所以我正在开发一个使用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))
有关导致错误的原因的任何想法吗?
答案 0 :(得分:0)
从技术上来说,这不是我的答案,但问题是Surface不能用Python的超级扩展。相反,它应该被称为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
答案 1 :(得分:0)
我还试图将pygame.Surface子类化,因为我希望能够为其添加属性。以下完成。我希望它能帮助未来的人们。
必须调用pygame.display.set_mode(),因为它会包含所有pygame.video内容。似乎pygame.display是最终被绘制到屏幕的表面。因此我们需要将我们创建的任何表面blit到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()