Python速成班-外来入侵-错误

时间:2019-05-15 13:43:31

标签: python pygame

我正在做Python Crash课程书中的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

1 个答案:

答案 0 :(得分:3)

if event == pygame.quit():

不执行您期望的操作。 pygame.quit()是一个函数,它会初始化所有pygame模块。该函数返回None,因此条件失败。该代码运行并在尝试访问pygame模块的下一条指令时崩溃。

将其更改为:

if event.type == pygame.QUIT:

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