所以我正在使用 Pygame 开发一个游戏,并试图抽象出很多代码。不过,在此过程中,我遇到了一些奇怪的错误。也就是说,当我运行 main.py 时,我得到了这个跟踪:
>>>
initializing pygame...
initalizing screen...
initializing background...
<Surface(Dead Display)> #Here I print out the background instance
Traceback (most recent call last):
File "C:\Users\Ceasar\Desktop\pytanks\main.py", line 19, in <module>
background = Background(screen, BG_COLOR)
File "C:\Users\Ceasar\Desktop\pytanks\background.py", line 8, in __init__
self.fill(color)
error: display Surface quit
我想这与我在我的 main 中使用上下文来管理屏幕有关。
#main.py
import math
import sys
import pygame
from pygame.locals import *
...
from screen import controlled_screen
from background import Background
BATTLEFIELD_SIZE = (800, 600)
BG_COLOR = 100, 0, 0
FRAMES_PER_SECOND = 20
with controlled_screen(BATTLEFIELD_SIZE) as screen:
background = Background(screen, BG_COLOR)
...
#screen.py
import pygame.display
import os
#The next line centers the screen
os.environ['SDL_VIDEO_CENTERED'] = '1'
class controlled_screen:
def __init__(self, size):
self.size = size
def __enter__(self):
print "initializing pygame..."
pygame.init()
print "initalizing screen..."
return pygame.display.set_mode(self.size)
def __exit__(self, type, value, traceback):
pygame.quit()
#background.py
import pygame
class Background(pygame.Surface):
def __init__(self, screen, color):
print "initializing background..."
print screen
super(pygame.Surface, self).__init__(screen.get_width(),
screen.get_height())
print self
self.fill(color)
self = self.convert()
screen.blit(self, (0, 0))
关于这里导致错误的原因有什么想法吗?