Python崩溃课程-外星人入侵- E

2024-03-29 01:43:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做Python速成教程中的外星人入侵项目。当我测试代码,看看飞船是否出现在屏幕上时,屏幕启动然后关闭。在

我已经查了好几个小时的代码,但没有找到原因。在

游戏:

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()

设置:

^{pr2}$

船舶:

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

Tags: therunrectimageimportselfgamesettings
1条回答
网友
1楼 · 发布于 2024-03-29 01:43:05

线

if event == pygame.quit():

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

更改为:

if event.type == pygame.QUIT:

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

相关问题 更多 >