Устранение проблем с черным экраном Pygame: Alien Invasion - PullRequest
2 голосов
/ 14 марта 2020

Я следил за проектом курса Python Cra sh, чтобы создать игру космических захватчиков. Я был в состоянии кодировать до точки, где окно игры откроется, но вместо того, чтобы получить фон с моим изображением в середине нижней части экрана, меня встречает черный экран. Я новичок в кодировании и видел, что это было аналогичной проблемой и для других. Я использую Python 3.8 и успешно загрузил правильную установку pip (https://ehmatthes.github.io/pcc_2e/updates/python3_8/#pygame -on- python -38 ).

Вот код для Alien Invasion:

import sys

import pygame

class AlienInvasion:
    """Overall Class to manage game assests and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()

        self.screen = pygame.display.set_mode((1100, 700))
        pygame.display.set_caption("Alien Invasion")

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            # Watch for keyboard and mouse events.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            # Make the most recently drawn screen Visible
            pygame.display.flip()

if __name__ == "__main__":
    # Make a game instance, and run the game.
    ai = AlienInvasion()
    ai.run_game()

def __init__(self):
    pygame.display.set_caption("Alien Invasion")

    # Set the Background Color
    self.bg_color = (230, 230, 230)

def run_game(self):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    #redraw the screen during each pass through the loop
    self.screen.fill(self.bg_color)

    #make the most recently drawn screen visible.
    pygame.display.flip()

import pygame

from settings import Settings

class AlienInvasion:
    """Overall Class to manage game assets and behavior"""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

    def run_game(self):
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)

        #make most recently drawn screen visible.
        pygame.display.flip()

from settings import Settings
from ship import Ship

class AlienInvasion:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        pygame.display.set_caption("Alien Invasion")

        self.ship = Ship(self)

    def run_game(self):
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()

        # Make most recently drawn screen visible
        pygame.display.flip()

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()
            # Redraw the screen during each pass through the loop
            break

    def _check_events(self):
        """Respond to keypress and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            self._check_events()
            self._update_screen()

    def _check_events(self):
        --snip--

    def _update_sceen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()

        pygame.display.flip()

Настройки

 class Settings:
    """A class to store all settings for Alien Invasion."""

    def __init__(self):
        """Initialize the game's static settings."""
        # Screen settings.
        self.screen_width = 1100
        self.screen_height = 700
        self.bg_color = (230, 230, 230)

Космический корабль:

  import pygame

class Ship:
    """A class to manage the ship."""

    def __init__(self, ai_game):
        """Initialize the ship and set its starting position."""
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()

        # Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        # Start each new ship at the bottom center of the screen
        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        """Draw the ship at current location"""
        self.screen.blit(self.image, self.rect)

Любая помощь с благодарностью! В настоящее время я использую Python Cra sh Учебник Эри c Matthes.

1 Ответ

0 голосов
/ 14 марта 2020

У вас есть базовое c недоразумение. Похоже, вы пытались распространить чертеж на несколько реализаций класса с именем AlienInvasion. Прочитайте о Class : "Классы предоставляют средства для объединения данных и функциональности вместе." . Класс - это тип, который вы должны поместить в один «класс». На самом деле каждый из классов AlienInvasion в вашей реализации - это отдельный тип в отдельном модуле. Невозможно распределить реализацию класса и методы класса по разным модулям.

Создание экземпляров Settings и Ship в классе AlienInvasion:

self.settings = Settings()
self.ship = Ship(self)

Метод экземпляра run_game класса AlienInvasion реализует основное приложение l oop. Основное приложение l oop должно:

  • обрабатывать события либо pygame.event.pump(), либо pygame.event.get().
  • обновить игровое состояние и положение объектов в зависимости от входных событий и времени (соответственно, фреймов)
  • очистить весь экран или нарисовать фон
  • нарисовать всю сцену (blit все объекты )
  • обновить отображение с помощью pygame.display.update() или pygame.display.flip()

, например:

import pygame
from settings import Settings
from ship import Ship

class AlienInvasion:
    """Overall Class to manage game assests and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()

        self.screen = pygame.display.set_mode((1100, 700))
        pygame.display.set_caption("Alien Invasion")

        self.settings = Settings()
        self.ship = Ship(self)

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            # Watch for keyboard and mouse events.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            # clear display
            self.screen.fill(self.settings.bg_color)  

            # draw scene
            self.ship.blitme()      

            # Make the most recently drawn screen Visible
            pygame.display.flip()

if __name__ == "__main__":
    # Make a game instance, and run the game.
    ai = AlienInvasion()
    ai.run_game()
...