主文件alien_invasion:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
def __init__(self):
# 初始化游戏并创建游戏资源
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
# 游戏窗口标题
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
# 开始游戏的主循环
while True:
# 监视键盘和鼠标事件
self._check_events()
self.ship.update()
self._update_screen()
def _check_events(self):
# 响应按键和鼠标事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN: # 获取键盘按下
self._check_keydown_events(event)
elif event.type == pygame.KEYUP: # 获取键盘松手
self._check_keyup_events(event)
def _check_keydown_events(self, event):
# 按下
if event.key == pygame.K_RIGHT: # 向右移动飞船
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q: # 可以按Q结束游戏
sys.exit()
def _check_keyup_events(self, event):
# 松开
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _update_screen(self):
# 更新屏幕上的图像,并切换到新屏幕
# 每次循环都重绘屏幕
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
# 让最近绘制的屏幕可见
pygame.display.flip()
if __name__ == "__main__":
# 创建游戏实例并允许游戏
ai = AlienInvasion()
ai.run_game()
设置文件settings:
class Settings:
# 存储游戏中所有设置的类
def __init__(self):
# 初始化游戏设置
# 屏幕设置
# 游戏窗口:宽1200,高800像素
self.screen_width = 1200
self.screen_height = 800
# 设置背景颜色
self.bg_color = (230, 230, 230)
# 飞船设置
self.ship_speed = 1.5
飞船文件:
import pygame
class Ship:
def __init__(self, ai_game):
# 初始化飞船并设置其初始位置
self.screen = ai_game.screen # 屏幕赋给ship一个属性,以便在这个类所有方法中轻松访问
self.settings = ai_game.settings
# 访问屏幕属性rect,赋给self.screen_rect 获取外接矩形
self.screen_rect = ai_game.screen.get_rect()
# 加载飞船图像并获取其外接矩形
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
# 对于每一艘新飞船,都讲其放在屏幕底部的中央
self.rect.midbottom = self.screen_rect.midbottom
# 在飞船的属性x中存储数值
self.x = float(self.rect.x)
# 移动标志
self.moving_right = False
self.moving_left = False
def update(self):
# 根据移动标志调整飞船的位置
if self.moving_right and self.rect.right < self.screen_rect.right: # 限制活动范围
self.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.ship_speed
# 根据self.x更新rect对象
self.rect.x = self.x
def blitme(self):
# 在指定的self.rect绘制飞船
self.screen.blit(self.image, self.rect)