首页 > 解决方案 > 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

标签: pythonpygame

解决方案


线

if event == pygame.quit():

没有做你期望它做的事情。pygame.quit()是一个函数,它会取消初始化所有 pygame 模块。函数返回None,因此条件失败。代码在尝试访问 pygame 模块的下一条指令处运行并崩溃。

将其更改为:

if event.type == pygame.QUIT:

对象的.type属性pygame.event.Event包含事件类型标识符。pygame.QUIT是一个枚举常量,用于标识退出事件。请参阅 的文档pygame.event


推荐阅读