game_functions.py
import pygame
import sys
def check_enents(ship):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event == pygame.QUIT:
sys.exit()
elif event == pygame.KEYDOWN:
if event == pygame.K_d:
ship.rect.centerx+=10
def update_screen(ai_settings,screen,ship):
"""更新屏幕上的图像"""
# 重绘屏幕
screen.fill(ai_settings.bg_color)
ship.blitme()
pygame.display.flip()
alien_invasion.py
import pygame
from settings import Settings
from ship import Ship
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))
ship=Ship(screen)
pygame.display.set_caption("Alien Invasion")
# 开始游戏主循环
while True:
gf.check_enents(ship)
gf.update_screen(ai_settings,screen,ship)
run_game()
只能强行终止进程,按红叉无法退出,按d后也没办法向右移动,代码和书上基本一样,求教是哪里错了,和OS X系统有关系么?
找到问题所在了,pygame.QUIT、pygame.KEYDOWN都得用event.tpye,pygame.K_d是表示键盘按下的d,要使用event.key。书上有写但是粗心忽略了……