<Python编程>
外星人入侵游戏编程练习
1.键盘不动事件
找了半天,找不到键盘按下,飞船不动是什么原因,然后仔细对照自己的代码和书上的代码,发现事件监听错误,如下:
game_functions:
import sys
import pygame
def check_events(ship):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.event == pygame.K_RIGHT:
# ship.rect.centerx += 100
ship.moving_right = True
elif event.event == pygame.K_LEFT:
ship.moving_left = True
elif event.type == pygame.KEYUP:
if event.event == pygame.K_RIGHT:
ship.moving_right = False
elif event.event == pygame.K_LEFT:
ship.moving_left = False
def update_screen(ai_settings, screen, ship):
screen.fill(ai_settings.bg_color)
ship.blitme()
pygame.display.flip()
错误原因分析:
在pygame中,键盘是否按下监听事件是通过 event.type 事件;
而具体按键事件是要通过 event.key事件;
并且在重构ship类代码时也犯了错误:
下面代码时正确的,之前犯的错误是在update()方法中,更新的仍是rect属性,而不是新加的center属性.
import pygame
class Ship():
def __init__(self, ai_settings, screen):
#初始化飞船位置
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
self.center = float(self.rect.centerx)
self.moving_right = False
self.moving_left = False
def update(self):
if self.moving_right:
self.center += self.ai_settings.ship_speed_factor
elif self.moving_left:
self.center -= self.ai_settings.ship_speed_factor
self.rect.centerx = self.center
def blitme(self):
self.screen.blit(self.image, self.rect)
网友评论