Windows / Python pygame.error:添加pygame.init()后未初始化视频系统

时间:2018-01-16 21:30:06

标签: python pygame

我在我的pygame游戏和pygame.init()中添加了一些音乐,以便在调用视频系统之前对其进行初始化,但我认为代码非常混乱,即使将所有内容移动到正确位置之后也没有任何内容它需要的地方。由于这个添加,我现在在添加pygame.init()后仍然出现此错误:

Traceback (most recent call last): 
  File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\My First game ERROR.py", line 31, 
     in for event in pygame.event.get(): 
pygame.error: video system not initialized

这是我写的代码:

# This just imports all the Pygame modules
import pygame

pygame.init()

class Game(object):
    def main(self, screen):

        if __name__ == '__main__':
            pygame.init()
            screen = pygame.display.set_mode((640, 480))
            pygame.display.set_caption('St.Patrick game')
            Game().main(screen)

clock = pygame.time.Clock()

while 1:
    clock.tick(30)     
    for event in pygame.event.get():
        if event.type == pygame.quit():
            pygame.quit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            pygame.quit()

pygame.mixer.init(44100, -16,2,2048)

import time
pygame.mixer.music.load('The Tonight Show Star Wars The Bee Gees Stayin Alive Shortened.mp3')
pygame.mixer.music.play(-1, 0.0)

#class Player(pygame.sprite.Sprite):
   # def __init__(self, *groups):
       # super(Player, self.__init__(*groups)
        #self.image = pygame.image.load('Sprite-01.png')
       # self.rect = pygame.rect.Rect((320, 240), self.image.get_size())

    #def update(self):
       # key = pygame

image = pygame.image.load('Sprite-01.png')
# initialize variables
image_x = 0
image_y = 0

image_x += 0
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
        image_x -= 10
if key[pygame.K_RIGHT]:
        image_x += 10
if key[pygame.K_UP]:
        image_y -= 10
if key[pygame.K_DOWN]:
        image_y += 10

screen.fill((200, 200, 200))
screen.blit(image, (image_x, image_y))
pygame.display.flip()

pygame.mixer.music.stop(52)

1 个答案:

答案 0 :(得分:3)

您的问题可能在pygame.quit()循环内while

pygame.quit()取消初始化使用pygame.init()初始化的模块 - 但它不会在循环中退出,因此while-loop会尝试在下一个循环中使用event.get()。然后你会因为未初始化的模块而遇到问题。

此外,没有任何意义

if event.type == pygame.quit():

必须是

if event.type == pygame.QUIT:

pygame.quit()是结束pygame.init()开始的函数。

pygame.QUIT是固定值 - 尝试print(pygame.QUIT) - 您可以将其与event.type进行比较。

我们使用UPPER_CASE_NAMES作为常量值。阅读:PEP 8 -- Style Guide for Python Code

最后,你需要

running = True
while running:
    clock.tick(30)     
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False

因此它退出循环,但它不会初始化您在其余代码中需要的模块。

相关问题