0

我正在创建一个类,它将返回一个带有正方形的表面和如下所示的文本:

表面

方块(当前)显示游戏的用户颜色,文本是玩家姓名。在从一组相似表面计算位置后,我将blit在屏幕上显示这些表面。

我能够text轻松地生成表面。我不想将屏幕表面传递给班级pygame.draw.rect;而是单独创建矩形;合并矩形和文本表面,然后返回这个分组表面。我当前的类定义很简单:

from pygame.locals import *
from pygame import font as pyfont, event as pyevent, display as pydisplay
from sys import exit

class Info:
    GRAY = ( 214, 171, 127 )
    def __init__( self, name, colour ):
        pyfont.init()
        self.name = name
        self.colour = colour
        self.font = pyfont.Font( None, 36 )

    def generate( self ):
        text = self.font.render( self.name, True, self.GRAY )
        # The rectangle surface to be drawn here
        return text
4

1 回答 1

1

在阅读了更多 pygame 文档之后,我将类更新为:

import pygame
from pygame.locals import *
from pygame import font as pyfont, event as pyevent, display as pydisplay
from sys import exit

class Info:
    GRAY = ( 214, 171, 127 )
    def __init__( self, surface, name, colour ):
        pyfont.init()
        self.surface = surface
        self.name = name
        self.colour = colour
        self.font = pyfont.Font( None, 36 )

    def generate( self ):
        t = pygame.Rect( 5, 5, 32, 32 )
        pygame.draw.rect( self.surface, self.colour, t, 0 )
        text = self.font.render( self.name, True, self.GRAY )
        return self.surface.blit( text, (50, 5) )

它可以按如下方式使用:

if __name__ == "__main__":
    x = pygame.Rect( 50, 50, 250, 100 )
    screen = pydisplay.set_mode( (1024, 576) )
    pydisplay.set_caption( "Title goes" )
    srf = screen.subsurface( x )
    x = Info( srf, "hjpotter92", (230, 150, 51) )
    c = pygame.time.Clock()
    screen.fill( (255, 255, 255) )
    while True:
        pydisplay.update()
        c.tick( 1 )
        print x.generate()
        for event in pyevent.get():
            if event.type == QUIT:
                exit( 0 )
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    exit( 0 )

但这是对问题的肮脏/肮脏的解决方案,并产生如下内容:

电流输出

我愿意改变当前的设计。否则我将不得不提前计算更多Info类实例的位置。

于 2014-02-16T17:32:25.463 回答