1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import random from pygame.sprite import Sprite import pygame
SCREEN = pygame.Rect(0, 0, 400, 600) FRAME_SPD_SEC = 60 ENEMY_SHOW = pygame.USEREVENT
BULLET_SHOW = pygame.USEREVENT + 1
class Sprite_Class(Sprite): """定义的最基础的精灵类,包含常用方法,用于为其他类继承"""
def __init__(self, image, speed=0): super().__init__() self.image = pygame.image.load(image) self.rect = self.image.get_rect() self.speed = speed
def update(self, *args): self.rect.y += self.speed
class Background(Sprite_Class):
def __init__(self, is_alt=False): super().__init__('./images/bg/bg0.jpg', 1) if is_alt: self.rect.y = -self.rect.height
def update(self): super().update() if self.rect.y >= SCREEN.height: self.rect.y = -self.rect.height
class Enermy(Sprite_Class):
def __init__(self): super().__init__('./images/enemy/enemy.png') self.speed += random.randint(1, 3) self.rect.bottom = 0 self.rect.x = random.randint(0, SCREEN.width - self.rect.width) self.bullet_group = pygame.sprite.Group()
def update(self): super().update() self.rect.y += self.speed if self.rect.y > SCREEN.height: self.kill()
def __del__(self): pass
class Hero(Sprite_Class):
def __init__(self): super().__init__('./images/hero/hero.png') self.rect.centerx = SCREEN.centerx self.rect.bottom = SCREEN.bottom - 50 self.bullet_group = pygame.sprite.Group()
def update(self): self.rect.x += self.speed if self.rect.x < 0: self.rect.x = SCREEN.x elif self.rect.right > SCREEN.right: self.rect.right = SCREEN.right
def fire(self): bullet = Bullets() bullet.rect.centerx = self.rect.centerx bullet.rect.bottom = self.rect.y - 20 self.bullet_group.add(bullet)
class Bullets(Sprite_Class):
def __init__(self): super().__init__('./images/bullet/3.png', -5)
def update(self): super().update() if self.rect.bottom < 0: self.kill()
|