配置类
import pygame
# 屏幕背景图的常量
SCREEN_RECT = pygame.Rect(0,0,480,700)
# 创建敌机的定时器常量
CREATE_ENEMY_EVENT = pygame.USEREVENT
# 英雄发射子弹事件
HERO_FIRE_EVENT = pygame.USEREVENT +1
class Settings():
"""存储所有的设置类"""
def __init__(self):
self.caption = "飞机大战"
主程序类:
import pygame
from plane_sprites import *
import Settings
import sys
from hero import Hero
class PlaneGame():
"""飞机大战主程序"""
def __init__(self):
self.screen = pygame.display.set_mode(Settings.SCREEN_RECT.size)
self.clock = pygame.time.Clock()
# 设置定时器
pygame.time.set_timer(Settings.CREATE_ENEMY_EVENT,1000)
pygame.time.set_timer(Settings.HERO_FIRE_EVENT, 500)
def __create_sprits(self):
# 创建敌机的精灵和精灵组
self.plane_group = pygame.sprite.Group()
# 创建英雄的精灵和精灵组
self.hero = Hero()
self.hero_group = pygame.sprite.Group(self.hero)
def start_game(self):
pygame.init()
pygame.display.set_caption(Settings.Settings().caption)
bg = pygame.image.load("./images/background.png")
bg_rect1 = pygame.Rect(0, 0, 480, 700)
bg_rect2 = pygame.Rect(0, -700, 480, 700)
self.screen.blit(bg, bg_rect1) # 将加载进去的图像显示在屏幕上,第二个参数指定的是位置
self.screen.blit(bg, bg_rect2)
# 创建精灵
self.__create_sprits()
# 绘制玩家飞机
# 游戏主循环
while True:
self.clock.tick(60)
# 背景图片的移动
# 先绘制背景图像就会避免残影
self.__background_scrool(bg, bg_rect1, bg_rect2)
# 监视键盘和鼠标事件
self.__event_handler()
# 碰撞检测
self.__check_collide()
# 调用精灵组
self.__update_sprites()
# 让最近绘制的屏幕可见
pygame.display.flip()
def __background_scrool(self, bg, bg_rect1, bg_rect2):
"""背景图像的移动"""
bg_rect1.y += 1
bg_rect2.y += 1
if bg_rect1.y >= 700:
bg_rect1.y = -700
elif bg_rect2.y >= 700:
bg_rect2.y = -700
self.screen.blit(bg, bg_rect1)
self.screen.blit(bg, bg_rect2)
def __event_handler(self):
"""监视键盘和鼠标事件"""
for event in pygame.event.get():
if event:
print(event)
# 判断事件类型是否是退出事件
if event.type == pygame.QUIT:
PlaneGame.__game_over()
elif event.type == Settings.CREATE_ENEMY_EVENT:
print("敌机---")
plane_path = "./images/enemy1.png"
plane = [GameSprites(plane_path) for i in range(10)]
self.plane_group.add(plane)
elif event.type == Settings.HERO_FIRE_EVENT:
self.hero.fire()
# elif event.type ==pygame.KEYDOWN and event.key == pygame.K_RIGHT:
# self.hero.speed = 2
# elif event.type ==pygame.KEYDOWN and event.key == pygame.K_LEFT:
# self.hero.speed = -2
# 使用键盘提供的东西获取按键元组(可以持续的向右移动)(推荐)
keys_press = pygame.key.get_pressed()
# 判断元组中对应按键的索引值
if keys_press[pygame.K_RIGHT] :
self.hero.speed = 2
elif keys_press[pygame.K_LEFT]:
self.hero.speed = -2
else:
self.hero.speed =0
def __check_collide(self):
"""碰撞检测"""
pygame.sprite.groupcollide(self.hero.bullets,self.plane_group,True,True)
enemies = pygame.sprite.spritecollide(self.hero, self.plane_group, True)
# 判断列表是否存在内容
if enemies:
# 让英雄牺牲
self.hero.kill()
self.__game_over()
def __update_sprites(self, ):
"""修改精灵组"""
self.plane_group.update()
self.plane_group.draw(self.screen)
self.hero_group.update()
self.hero_group.draw(self.screen)
self.hero.bullets.update()
self.hero.bullets.draw(self.screen)
@staticmethod
def __game_over():
"""游戏结束方法"""
pygame.quit()
sys.exit()
# 测试模块
if __name__ == '__main__':
PlaneGame().start_game()
# print(map(lambda x:x+1,[1,2,3]))
敌机精灵类
import pygame
import random
class GameSprites(pygame.sprite.Sprite):
"""飞机大战游戏精灵"""
def __init__(self, image_path, speed=1):
"""
初始化方法
:param image_path: 图片路径
:param speed: 移动速度
"""
super().__init__()
self.speed = random.randint(1,3)
self.image = pygame.image.load(image_path)
# x,y会被设置为0,size为图像的大小
self.rect = self.image.get_rect()
self.rect.x = random.randint(0,400)
self.rect.y = random.randint(-500,-self.rect.height)
# 销毁敌机对象
def __del__(self):
print("敌机挂了")
# 可以将精灵从所有的精灵组中移除
self.kill()
def update(self):
"""
重写update方法
"""
self.rect.y += self.speed
if self.rect.y >= 700:
print("del enemy")
self.__del__()
英雄类
import pygame
import random
from bullet import Bullet
class Hero(pygame.sprite.Sprite):
"""飞机大战英雄类"""
def __init__(self, speed=0):
"""
初始化方法
:param speed: 移动速度
"""
super().__init__()
self.speed = speed
self.image = pygame.image.load("./images/me1.png")
# x,y会被设置为0,size为图像的大小
self.rect = self.image.get_rect()
self.rect.centerx = 480 * 0.5
self.rect.bottom = 700 - 120
# 创建子弹的精灵组
self.bullets = pygame.sprite.Group()
# 销毁敌机对象
def __del__(self):
print("英雄挂了")
# 可以将精灵从所有的精灵组中移除
self.kill()
def update(self):
"""
重写update方法
"""
self.rect.x += self.speed
if self.rect.x >= 380:
self.rect.x = 380
elif self.rect.x <= 0:
self.rect.x = 0
# 发射子弹
def fire(self):
print("发射子弹...")
for i in range(3):
# 创建子弹精灵
bullet = Bullet()
# 设置精灵位置
bullet.rect.bottom = self.rect.y -i*20
bullet.rect.centerx = self.rect.centerx
self.bullets.add(bullet)
子弹类
import pygame
class Bullet(pygame.sprite.Sprite):
"""飞机大战子弹类"""
def __init__(self, speed=-2):
"""
初始化方法
:param speed: 移动速度
"""
super().__init__()
self.speed = speed
self.image = pygame.image.load("./images/bullet2.png")
# x,y会被设置为0,size为图像的大小
self.rect = self.image.get_rect()
def update(self):
"""
重写update方法
"""
self.rect.y += self.speed
# 判断子弹是否飞出屏幕
if self.rect.bottom <0:
self.__del__()
def __del__(self):
print("子弹被销毁")
self.kill()
关键点的理解: