[英]Pygame: <Surface: (Dead Display)> and Python's “with statement”
因此,我正在使用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))
是否对导致此错误的原因有任何想法?
我也试图继承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()
从技术上讲,这不是我的答案,但问题是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.