马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
大佬,求解:
alien_invasion:import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
"""管理游戏资源和行为的类"""
def __init__(self):
#初始化游戏并创建游戏资源
pygame.init()[code]import pygame
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)
# 设置背景色
self.bg_color = (230, 230, 230)
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:
pygame.quit()
sys.exit(0)
elif event.type == pygame.KEYDOWN:
_check_keydown_events(event)
elif event.type == pygame.KEYUP:
_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:
pygame.quit()
sys.exit(0)
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):
"""初始化游戏的设置"""
# 屏幕设置
self.screen_width = 1200
self.screen_height = 700
self.bg_color = (230, 230, 230)
ship:class Ship:
"""管理飞船的类"""
def __init__(self, ai_game):
# 初始化飞船并设置其初始位置
self.screen = ai_game.screen
self.settings = ai_game.settings
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):
"""根据移动标志调整飞船的位置"""
# 更新飞船而不是rect对象的x值
if self.moving_right and self.rect.right < self.screen_rect.right:
self.rect.x += 1
if self.moving_left and self.rect.left > 0:
self.rect.x -= 1
def blitme(self):
"""在指定位置绘制飞船"""
self.screen.blit(self.image, self.rect)
错误信息:Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\Alien_Invasion\alien_invasion.py", line 73, in <module>
ai.run_game()
File "C:\Users\Administrator\Desktop\Alien_Invasion\alien_invasion.py", line 28, in run_game
self._check_events()
File "C:\Users\Administrator\Desktop\Alien_Invasion\alien_invasion.py", line 39, in _check_events
_check_keydown_events(event)
NameError: name '_check_keydown_events' is not defined
|