Python实现飞机大战小游戏
Python实现飞机大战小游戏
附上详细代码↓,代码里都有详细的注释,最后有运行效果↓
创建两个py文件:plane_main.py || plane_sprites.py
plane_main.py:
import pygame
from plane_sprites import *
class PlaneGame(object):
"""飞机大战祝游戏"""
def __init__(self):
print("游戏初始化")
# 1. 创建游戏的窗口
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
# 2. 创建游戏的失踪
self.clock = pygame.time.Clock()
# 3. 调用私有方法, 精灵和精灵组的创建
self.__create_sprites()
# 4. 设置定时器事件 - 创建敌机 1s
pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
pygame.time.set_timer(HERO_FIRE_EVENT, 500)
def __create_sprites(self):
"""创建精灵组"""
# 创建背景精灵和精灵组
bg1 = Background()
bg2 = Background(True)
self.back_group = pygame.sprite.Group(bg1, bg2)
# 创建敌机的精灵组
self.enemy_group = pygame.sprite.Group()
# 创建英雄的精灵和精灵组
self.hero = Hero()
self.hero_group = pygame.sprite.Group(self.hero)
def start_game(self):
"""开始游戏"""
print("游戏开始...")
while True:
# 1. 设置刷新帧率
self.clock.tick(FRAME_PER_SEC)
# 2. 事件监听
self.__event_handler()
# 3. 碰撞检测
self.__check_collide()
# 4. 更新/绘制精灵组
self.__update_sprites()
# 5. 更新显示
pygame.display.update()
def __event_handler(self


1万+





