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를 사용해야 합니다. 책에 써있었는데 무심코 무시했네요...