即使已初始化,视频系统也未初始化错误

时间:2018-08-05 10:49:11

标签: python pygame init

我知道已经报告过几次此错误,但是已经检查过并正确安装了pygame并正确进行了初始化,因此我只能猜测我的编程中根本看不到任何错误(对于过去2周..)。有人可以帮我看看为什么在运行以下代码时出现错误吗?:

import sys

import pygame

from settings import Settings

def run_game():
    # Initialize game and create a 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")


    # Start 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()

        # Redraw Screen during each pass through.
        screen.fill(ai_settings.bg_color)

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

run_game()

1 个答案:

答案 0 :(得分:0)

您已经定义了一个函数,其主体为:

def run_game():
    # Initialize game and create a 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")

然后您将看到一个循环:

while True:
    #Watch for keyboard and mouse events.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        # Redraw Screen during each pass through.
        screen.fill(ai_settings.bg_color)

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

这里的问题是上面的循环位于run_game范围的外部范围内,它是在全局范围内定义的,因此它在调用run_game()之前就已执行。结果pygame和screen都没有初始化,这就是为什么您会收到初始化错误的原因。

您假设调用run_game将初始化pygame并执行mainloop,但不会...在python缩进中很重要。我建议您确保首先了解python如何解释这些行,然后这些类型的问题将变得非常清楚。

这是一本不错的书,https://docs.python.org/3/reference/lexical_analysis.html#lexical-analysis