James's blog

I've finally found out how to do collision detection for my new game Flappy Bird.

How to do it (the full code is on the arcade games page)

​CODE FOR MAKING A GROUP OF CLASS MEMBERS AND UPDATING THE GROUP

class Pipe (pygame.sprite.Sprite):

def __init__(self, image,[...]):

pygame.sprite.Sprite.__init__(self)

self.image = image

self.rect = self.image.get_rect()​

self.x = 5

self.y = 5

[...]

def update(self):

screen.blit(self.image, (self.x,self.y)

self.rect = Rect(self.x, self.y, 50,50)

​

def main():

pipe_image = image.load('pipe.png')

pipeGroup = pygame.sprite.group()

for x in range(3):

pipeGroup.add(Flappy_class(flappy_image, [...]))

while True:

pipeGroup.update()

​ pygame.display.update()

KEY

line 1. we create the class, inheriting from pygame.line 2. we "__init__" like usual. Note: "__init__" has 2 underscoresline 3. we call the pygame "__init__"​line 4. we load the image Note: I don't load it in the class because if we had 40 pipes it would be too slowline 5. we make a rect according to the imagelines 6&7. we create the x and y​line 10. I make a method called update Note: its name is important because it it one of the only methods that you can call for all the sprites in a group.line 11. we display the imageline 12. we create the rect(x pos, y pos, width, height) Note: using self.rect = Rect (...) for the updated image is important for collision detection line 15. we load the pipe image.line 16: we create a sprite groupline 18. we add members to the sprite groupline 20. we call the update method for all the sprites in the group

We would do a similar thing for flappy bird (including updating using self.rect = Rect (...) and store it in the bird object and then call these lines