| 21 | |
| 22 | |
| 23 | class Bird(pygame.sprite.Sprite): |
| 24 | WIDTH = 32 # bird image width |
| 25 | HEIGHT = 32 # bird image height |
| 26 | DOWN_SPEED = 0.18 # pix per ms -y |
| 27 | UP_SPEED = 0.3 # pix per ms +y |
| 28 | UP_DURATION = 150 # time for which bird go up |
| 29 | |
| 30 | def __init__(self, x, y, ms_to_up, images): |
| 31 | super(Bird, self).__init__() |
| 32 | self.x, self.y = x, y |
| 33 | self.ms_to_up = ms_to_up |
| 34 | self._img_wingup, self._img_wingdown = images |
| 35 | self._mask_wingup = pygame.mask.from_surface(self._img_wingup) |
| 36 | self._mask_wingdown = pygame.mask.from_surface(self._img_wingdown) |
| 37 | |
| 38 | def update(self, delta_frames=1): |
| 39 | if self.ms_to_up > 0: |
| 40 | frac_climb_done = 1 - self.ms_to_up / Bird.UP_DURATION |
| 41 | self.y -= ( |
| 42 | Bird.UP_SPEED |
| 43 | * frames_to_msec(delta_frames) |
| 44 | * (1 - math.cos(frac_climb_done * math.pi)) |
| 45 | ) |
| 46 | self.ms_to_up -= frames_to_msec(delta_frames) |
| 47 | else: |
| 48 | self.y += Bird.DOWN_SPEED * frames_to_msec(delta_frames) |
| 49 | |
| 50 | @property |
| 51 | def image(self): |
| 52 | # to animate bird |
| 53 | if pygame.time.get_ticks() % 500 >= 250: |
| 54 | return self._img_wingup |
| 55 | else: |
| 56 | return self._img_wingdown |
| 57 | |
| 58 | @property |
| 59 | def mask(self): |
| 60 | # collision detection |
| 61 | if pygame.time.get_ticks() % 500 >= 250: |
| 62 | return self._mask_wingup |
| 63 | else: |
| 64 | return self._mask_wingdown |
| 65 | |
| 66 | @property |
| 67 | def rect(self): |
| 68 | # return birds params |
| 69 | return Rect(self.x, self.y, Bird.WIDTH, Bird.HEIGHT) |
| 70 | |
| 71 | |
| 72 | class PipePair(pygame.sprite.Sprite): |