Pygame 敌击类
class Enemy(GameBase):
def __init__(self):
# 随机图片
enemy_pic = ["images/enemy1.png", "images/enemy2.png", "images/enemy3.png"]
self.img_path = random.choice(enemy_pic)
# 随机速度
speed_y = random.randint(2, 3)
super().__init__(self.img_path, 0, speed_y)
# 敌机的初始化位置
self.rect.bottom = 0
self.rect.x = random.randint(0, SCREEN_SIZE.width - self.rect.width)
self.update_count = 0
self.using = "images/enemy3.png"
def update(self, screen: Surface):
super().update(screen)
if self.img_path == "images/enemy3.png":
self.update_head()
if self.rect.top >= SCREEN_SIZE.bottom:
self.kill()
def update_head(self):
self.update_count += 1
if self.update_count >= 20:
if self.using == "images/enemy3.png":
self.using = "images/enemy3_n2.png"
else:
self.using = "images/enemy3.png"
self.update_count = 0
self.img = pygame.image.load(self.using)
class Bullet(GameBase):
def __init__(self, hero_rect: Rect, speed_x):
img_path = "images/bomb.png"
super().__init__(img_path, speed_x, -3)
# 初始化位置
self.rect.centerx = hero_rect.centerx
self.rect.bottom = hero_rect.top
def update(self, screen: Surface):
super().update(screen)
# 边界检测:飞出屏幕底边就释放资源
if (self.rect.bottom <= SCREEN_SIZE.top or
self.rect.left <= SCREEN_SIZE.left or
self.rect.right >= SCREEN_SIZE.right):
self.kill()