使用 pygame 时,我的窗口在运行程序后立即关闭[关闭]

问题描述 投票:0回答:1
import sys
import pygame

from settings import Settings

class AlienInvasion:

    def __init__(self):
        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):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit
            
            self.screen.fill(self.settings.bg_color)
            pytgame.display.flip  

if __name__ == '__main__':
    ai = AlienInvasion()
    ai.run_game

为什么我的显示屏会在一瞬间关闭?我编辑了代码。它现在正在运行游戏,但窗口不会保持打开状态,这是我的 while true 循环中的问题吗?

python pygame
1个回答
1
投票

我尝试了你的程序,并在代码中遇到了一些功能错误,但它们很容易修复。以下是对您的程序的改编,并进行了一些修复。

import sys
import pygame

class AlienInvasion:

    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((400, 400))    # Substituted since I did not have the "Settings" file to import
        pygame.display.set_caption('Alien Invasion')

    def run_game(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()             # Added this to gently end the game
                    exit()

            self.screen.fill((50, 50, 150))   # Substituted since I did not have the "Settings" file to import
            pygame.display.flip() 

if __name__ == '__main__':
    ai = AlienInvasion()
    ai.run_game()           # One needs the parentheses to call this function

程序中闪烁屏幕的主要问题可能是程序中的最后一条语句缺少括号。而不是:

ai.run_game

一个人应该有:

ai.run_game()

当您调用函数时。

© www.soinside.com 2019 - 2024. All rights reserved.