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 循环中的问题吗?
我尝试了你的程序,并在代码中遇到了一些功能错误,但它们很容易修复。以下是对您的程序的改编,并进行了一些修复。
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()
当您调用函数时。