Pygame: <表面: (死显示)> 和Python的“with语句”
我正在用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.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))
你们觉得这个错误是怎么回事呢?
2 个回答
0
我也在尝试对pygame.Surface进行子类化,因为我想给它添加一些属性。下面的代码实现了这个目标。希望能对将来的朋友们有所帮助。
必须调用pygame.display.set_mode(),因为它会初始化所有与pygame.video相关的内容。看起来pygame.display就是最终会被绘制到屏幕上的那个表面。因此,我们需要把我们创建的任何表面绘制到pygame.display.set_mode()的返回值上(这个返回值其实也是一个pygame.Surface对象)。
import pygame from pygame.locals import * pygame.init() SCREEN_SIZE = (800, 600) font = pygame.font.SysFont('exocet', 16) class Screen(pygame.Surface): def __init__(self): pygame.Surface.__init__(self, SCREEN_SIZE) self.screen = pygame.display.set_mode((SCREEN_SIZE)) self.text = "ella_rox" My_Screen = Screen() text_surface = font.render(My_Screen.text, 1, (155, 0, 0)) while True: My_Screen.fill((255, 255, 255)) My_Screen.blit(text_surface, (50, 50)) My_Screen.screen.blit(My_Screen, (0, 0)) pygame.display.update()
0
这不是我技术上的答案,但问题在于,Surface 不能用 Python 的 super 来扩展。实际上,它应该被当作一种 Python 的旧式类来使用,像这样:
class ExtendedSurface(pygame.Surface):
def __init__(self, string):
pygame.Surface.__init__(self, (100, 100))
self.fill((220,22,22))
# ...
来源:http://archives.seul.org/pygame/users/Jul-2009/msg00211.html