|
| 1 | +import pygame |
| 2 | +from pygame.constants import K_LEFT, K_a, K_RIGHT, K_d |
| 3 | + |
| 4 | + |
| 5 | +class BaseObject(pygame.sprite.Sprite): |
| 6 | + def __init__(self, ipath, position, scale=0.5): |
| 7 | + pygame.sprite.Sprite.__init__(self) |
| 8 | + |
| 9 | + img = pygame.image.load(ipath) |
| 10 | + rect = img.get_rect(center=position) |
| 11 | + w, h = rect.size[0], rect.size[1] |
| 12 | + w, h = int(w * scale), int(h * scale) |
| 13 | + self.image = pygame.transform.scale(img, (w, h)) |
| 14 | + self.rect = self.image.get_rect(center=position) |
| 15 | + self.should_kill = False |
| 16 | + |
| 17 | + def get_center(self): |
| 18 | + return self.rect.center |
| 19 | + |
| 20 | + def draw(self, surface, **kwargs): |
| 21 | + raise NotImplementedError('Not yet implemented') |
| 22 | + |
| 23 | + |
| 24 | +class Bullet(BaseObject): |
| 25 | + def __init__(self, position, scale=1.0): |
| 26 | + BaseObject.__init__(self, './images/bullet.png', position, scale) |
| 27 | + |
| 28 | + def draw(self, surface, **kwargs): |
| 29 | + if self.should_kill: |
| 30 | + return |
| 31 | + |
| 32 | + x, y = self.rect.center |
| 33 | + self.rect.center = x, y - 1 |
| 34 | + |
| 35 | + surface.blit(self.image, self.rect.center) |
| 36 | + |
| 37 | + if y <= 0: |
| 38 | + self.should_kill = True |
| 39 | + |
| 40 | + |
| 41 | +class Rock(BaseObject): |
| 42 | + def __init__(self, position, scale=1.0): |
| 43 | + BaseObject.__init__(self, './images/rock.png', position, scale) |
| 44 | + |
| 45 | + def draw(self, surface, **kwargs): |
| 46 | + if self.should_kill: |
| 47 | + return |
| 48 | + |
| 49 | + x, y = self.rect.center |
| 50 | + self.rect.center = x, y + 1 |
| 51 | + |
| 52 | + surface.blit(self.image, self.rect.center) |
| 53 | + |
| 54 | + if y >= kwargs['height']: |
| 55 | + self.should_kill = True |
| 56 | + |
| 57 | + |
| 58 | +class Ship(BaseObject): |
| 59 | + def __init__(self, position, scale=1.0): |
| 60 | + BaseObject.__init__(self, './images/ship.png', position, scale) |
| 61 | + |
| 62 | + def draw(self, surface, **kwargs): |
| 63 | + width, height = kwargs['width'], kwargs['height'] |
| 64 | + x, y = self.rect.center |
| 65 | + w, h = self.rect.size |
| 66 | + |
| 67 | + if 'event' in kwargs: |
| 68 | + event = kwargs['event'] |
| 69 | + if event.key in (K_LEFT, K_a): |
| 70 | + if x - w / 2.0 >= 0: |
| 71 | + x -= 10 |
| 72 | + elif event.key in (K_RIGHT, K_d): |
| 73 | + if x + w / 2.0 <= width: |
| 74 | + x += 10 |
| 75 | + |
| 76 | + self.rect.center = x, y |
| 77 | + |
| 78 | + surface.blit(self.image, self.rect.center) |
0 commit comments