【问题标题】:Pygame screen output not displayingPygame屏幕输出不显示
【发布时间】:2020-04-19 04:10:38
【问题描述】:

我正在使用 Pygame 开发一个游戏项目。我才刚刚开始从事这个项目,我有点卡住了。我制作了三个文件,每个文件都包含执行不同功能的代码。第一个文件 - “alien_apocalypse.py”包含类“AlienApocalypse”,用于启动和监控游戏中的用户事件,并包含一些导入的模块,例如游戏设置 (这是第二个文件 - 'game_settings.py')和一个包含游戏角色“knight.py”之一的所有属性的类文件。我正在尝试运行“alien_apocalypse.py”,它旨在显示我的角色骑士和显示屏的底部中间,但没有显示任何内容。我在带有 macOS Mojave 的 Mac 上运行它,IDE 是 PyCharm。以下是文件:

  • 文件 1 - “alien_apocalypse.py”:
import sys
import os
import pygame
from game_settings import GameSettings
from knight import Knight


class AlienApocalypse:
    """Overall class to manage game assets and behaviour"""

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

        drivers = ['directfb', 'fbcon', 'svgalib']

        found = False
        for driver in drivers:
            if not os.getenv('SDL_VIDEODRIVER'):
                os.putenv('SDL_VIDEODRIVER', driver)
            try:
                pygame.display.init()
            except pygame.error:
                print('Driver: {0} failed.'.format(driver))
                continue
            found = True
            break

        if not found:
            raise Exception('No suitable video driver found!')

        self.screen_window = pygame.display.set_mode((2880, 1800))
        pygame.display.set_caption("Alien Apocalypse")

        """Setting background color"""
        self.background_color = (230, 230, 255)

        self.knight = Knight(self)

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

            # Redraw the screen during each pass through the loop.
            self.screen_window.fill(self.settings.background_color)
            self.knight.blitme()

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


if __name__ == "__main__":
    """Make a game instance, and run the game"""
    ac = AlienApocalypse()
    ac.run_game()


  • 文件 2 - game_settings.py
class GameSettings:
    """This class stores all the game settings"""

    def __init__(self):
        """Initialize the game's settings attributes"""
        # Screen settings
        self.screen_width = 2880
        self.screen_height = 1800
        self.background_color = (230, 230, 255)

  • 文件 3 knight.py
import pygame


class Knight:
    """A class that manages the character knight"""

    def __init__(self, ac_game):
        """Initialize the knight and set its starting position."""
        self.screen_window = ac_game.screen_window
        self.screen_window_rect = ac_game.screen_window.get_rect()

        # Load the character - Knight image and get its rect.
        image_file = "/Users/johnphillip/Downloads/craftpix-891165-assassin" \
                     "-mage-viking-free-pixel-art-game-heroes/PNG/Knight" \
                     "/knight.bmp "
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()

        # Start each new character at the bottom center of the screen.
        self.rect.midbottom = self.screen_window_rect.midbottom

    def blitme(self):
        """Draw the character at its current location."""
        self.screen_window.blit(self.image, self.rect)

【问题讨论】:

  • 嗨!我认为问题在于您必须设置正确的驱动程序(os.putenv('SDL_VIDEODRIVER',驱动程序)并初始化显示(pygame.display.init())。看看这个:@ 987654321@。如果你正在运行在 Windows 上,使用这个:drivers = ['windib', 'directx']

标签: python python-3.x macos pygame pygame-surface


【解决方案1】:

到目前为止我检测到的问题(现在显示窗口):

  • 您必须设置正确的视频驱动程序

  • 那你要初始化pygame.display

  • 您在类 (ac.run_game()) 中调用 run_game() 函数,而不是另一个。

  • 类中的 run_game() 什么都不做(通过)

  • 您必须将当前类内的 run_game() 替换为类外的类,这样您就可以访问变量和函数等“自己的东西”。

  • 如果 self 不存在,则不能将其等于 None 作为默认值(self 是类本身及其包含的所有内容,因此,如果将其等于 None,您就是在“杀死”自己(类)!!! )

您的 alien_apocalypse.py 可能如下所示:

import pygame
from game_settings import GameSettings
from knight import Knight

class AlienApocalypse:
"""Overall class to manage game assets and behaviour"""

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

    drivers = ['windib', 'directx']

    found = False
    for driver in drivers:
        if not os.getenv('SDL_VIDEODRIVER'):
            os.putenv('SDL_VIDEODRIVER', driver)
        try:
            pygame.display.init()
        except pygame.error:
            print('Driver: {0} failed.'.format(driver))
            continue
        found = True
        break

    if not found:
        raise Exception('No suitable video driver found!')

    self.screen_window = pygame.display.set_mode((2880, 1800))
    pygame.display.set_caption("Alien Apocalypse")

    """Setting background color"""
    self.background_color = (230, 230, 255)

    self.knight = Knight(self)

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

        # Redraw the screen during each pass through the loop.
        self.screen_window.fill(self.settings.background_color)
        self.knight.blitme()

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

if __name__ == "__main__":
    """Make a game instance, and run the game"""
    ac = AlienApocalypse()
    ac.run_game()

【讨论】:

  • 仍然对我不起作用。我想我只需要在 linux 虚拟机上制作这个项目。不过还是谢谢。
  • 我现在在 Windows 上!我可以建议您插入一些 print() 消息以了解问题所在吗? (不是最好的方法,而是最简单的方法)。除此之外,如果您遇到任何错误,请将其粘贴到此处以便我们提供帮助。
  • 所以我在 __init__() 方法和 run_game() 方法中添加了打印语句,并且只有 __init__() 方法中的打印语句有效。我还尝试调用 run_game() 方法并得到一个 AttributeError。 ``` ```
  • 看你的代码,还有其他地方不对。您有两个 run_game() 函数,一个在类内不执行任何操作(通过),另一个在类外尝试使用 self...self 仅在类内可用!除此之外,您不能将 self 等同于 None ...这意味着您正在“杀死自己(班级)。只需擦除班级内部的 run_game() 函数,然后将其替换为班级外部的函数即可,并让“self”单独作为参数,而不是 self=None。我希望它足够清楚。无论如何我都会编辑我的答案。
  • 我已经做到了。我会更新我的问题中的代码。
猜你喜欢
  • 1970-01-01
  • 2017-02-16
  • 2018-05-18
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多