python - Python 速成课程 - 外星人入侵 - 错误
问题描述
我正在 Python Crash Course 书中做 Alien Invasion 项目。当我测试代码以查看船舶是否出现在屏幕上时,屏幕会启动然后关闭。
我已经浏览了几个小时的代码,却没有找出原因。
游戏:
import sys
import pygame
from settings import Settings
from ship import Ship
def run_game():
# Initialize pygame, settings, and screen object
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Make a ship
ship = Ship(screen)
# Set background color
bg_color = (230, 230, 230)
# Start the main loop for the game
while True:
# Watch for keyboard and mouse events
for event in pygame.event.get():
if event == pygame.quit():
sys.exit()
# Redraw the screen during each pass through the loop
screen.fill(ai_settings.bg_color)
ship.blitme()
# Make most recently drawn screen visible
pygame.display.flip()
run_game()
设置:
class Settings():
def __init__(self):
"""Initialize the game's settings."""
# Screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
船:
import pygame
class Ship():
def __init__(self, screen):
self.screen = screen
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# Start each new ship at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
def blitme(self):
self.screen.blit(self.image, self.rect)
这是出现的错误
"C:\Users\My Name\Desktop\Mapper\Python'\Scripts\python.exe" "C:/Users/My Name/Desktop/Mapper/Python/Projects/alien invasion/alien_invasion.py"
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:/Users/My Name/Desktop/Mapper/Python/Projects/alien invasion/alien_invasion.py", line 37, in <module>
run_game()
File "C:/Users/My Name/Desktop/Mapper/Python/Projects/alien invasion/alien_invasion.py", line 30, in run_game
screen.fill(ai_settings.bg_color)
pygame.error: display Surface quit
Process finished with exit code 1
解决方案
线
if event == pygame.quit():
没有做你期望它做的事情。pygame.quit()
是一个函数,它会取消初始化所有 pygame 模块。函数返回None
,因此条件失败。代码在尝试访问 pygame 模块的下一条指令处运行并崩溃。
将其更改为:
if event.type == pygame.QUIT:
对象的.type
属性pygame.event.Event
包含事件类型标识符。pygame.QUIT
是一个枚举常量,用于标识退出事件。请参阅 的文档pygame.event
。
推荐阅读
- android - AWS S3 安卓开发工具包 2.11.0
- c - 简单的客户端/服务器出现问题,文件打印错误
- eclipse - 如何从 Eclipse 32 位传递到 64 位?
- javascript - 将输入放入 JavaScript 表中
- python - 仿射warp_matrix里面有什么(如何分解)
- angular - 角度拖放传递附加参数以输入谓词
- c# - 在 iText5 中将生成的 PDF 页面上的所有文本向上或向下移动指定量 - C#
- spring-boot - Spring Boot Servlet 注册
- python - 如何在 mosek.fusion.Model 中提取表达式?
- angularjs - angularjs 材料多余的行和长字会创建错误的布局