alien_invasion.py
import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from game_stats import GameStats
from ship import Ship
from alien import Alien
import game_functions as gf
def run_game():
#初始化游戏并创建一个屏幕对象
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
#创建一个用于存储游戏统计信息的实例
stats = GameStats(ai_settings)
#创建一艘飞船
ship = Ship(ai_settings, screen)
#创建一个存储子弹的编组
bullets = Group()
#创建一个外星人编组
aliens = Group()
#创建外星人群
gf.create_fleet(ai_settings, screen, ship, aliens)
#开始游戏的主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
run_game()
game_functions.py
import sys
from time import sleep
import pygame
from bullet import Bullet
from alien import Alien
def check_keydown_event(event, ai_settings, screen, ship, bullets):
#相应按键
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
ship.moving_down = True
elif event.key == pygame.K_SPACE:
#创建一颗子弹,并将其加入到编组bullets中
fire_bullet(ai_settings, screen, ship, bullets)
elif event.key == pygame.K_q:
sys.exit()
def check_keyup_event(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
if event.key == pygame.K_UP:
ship.moving_up = False
elif event.key == pygame.K_DOWN:
ship.moving_down = False
def check_events(ai_settings, screen, ship, bullets):
#监视键盘和鼠标事件
for event in pygame.event