Ускоренный курс Python - Вторжение пришельцев - Ошибка - PullRequest
4 голосов
/ 15 мая 2019

Я делаю проект Alien Invasion из книги Python Crash Course.Когда я проверяю код, чтобы увидеть, появляется ли корабль на экране, экран запускается, а затем выключается.

Я часами просматривал код, не выясняя, почему.

Игра:

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 Ответ

3 голосов
/ 15 мая 2019

Линия

if event == pygame.quit():

не делает то, что вы ожидаете. pygame.quit() - это функция, которая неинициализирует все модули Pygame. Функция возвращает None, поэтому условие не выполняется. Код запускается и вылетает при следующей инструкции, которая пытается получить доступ к модулю pygame.

Измените его на:

if event.type == pygame.QUIT:

Свойство .type объекта pygame.event.Event содержит идентификатор типа события. pygame.QUIT является константой перечислителя, которая идентифицирует событие quit . См. Документацию pygame.event.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...