【问题标题】:Generating a new surface with a filled square and text string in pygame在pygame中生成一个带有填充正方形和文本字符串的新表面
【发布时间】:2014-02-16 09:42:56
【问题描述】:

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

方块(当前)显示游戏中用户的颜色,文本是玩家姓名。在从一组相似表面计算位置后,我将在屏幕上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

【问题讨论】:

  • @jonrsharpe 什么都没有。如果我将屏幕表面作为参数传递给类,我可以创建矩形,但正如我在问题中提到的那样;我不想那样做。我想把所有的位置计算留到以后。我还查看了subsurface 函数;但同样,我必须在初始化课程之前计算我的放置位置。

标签: python pygame rectangles pygame-surface


【解决方案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 类的更多实例的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多