簡體   English   中英

如何在Pygame的子畫面中添加“矩形”或文本?

[英]How do I add 'Rect's or text to a sprite in Pygame?

我正在嘗試重新創建幻燈片拼圖 ,我需要將文本打印到先前繪制的矩形精靈上。 這是我設置它們的方式:

class Tile(Entity):
    def __init__(self,x,y):
        self.image = pygame.Surface((TILE_SIZE-1,TILE_SIZE-1))
        self.image.fill(LIGHT_BLUE)
        self.rect = pygame.Rect(x,y,TILE_SIZE-1,TILE_SIZE-1)
        self.isSelected = False
        self.font = pygame.font.SysFont('comicsansms',22) # Font for the text is defined

這就是我繪制它們的方式:

def drawTiles(self):
    number = 0
    number_of_tiles = 15

    x = 0
    y = 1

    for i in range(number_of_tiles):
        label = self.font.render(str(number),True,WHITE) # Where the label is defined. I just want it to print 0's for now.
        x += 1
        if x > 4:
            y += 1
            x = 1

        tile = Tile(x*TILE_SIZE,y*TILE_SIZE)
        tile.image.blit(label,[x*TILE_SIZE+40,y*TILE_SIZE+40]) # How I tried to print text to the sprite. It didn't show up and didn't error, so I suspect it must have been drawn behind the sprite.
        tile_list.append(tile) 

這是我嘗試添加Rect的方法(當用鼠標單擊時):

# Main program loop
for tile in tile_list:
    screen.blit(tile.image,tile.rect)
    if tile.isInTile(pos):
        tile.isSelected = True
        pygame.draw.rect(tile.image,BLUE,[tile.rect.x,tile.rect.y,TILE_SIZE,TILE_SIZE],2)
    else:
        tile.isSelected = False

isInTile:

def isInTile(self,mouse_pos):
    if self.rect.collidepoint(mouse_pos): return True

我究竟做錯了什么?

Pygame中的坐標是相對於正在繪制的表面的。 您當前在tile.image上繪制矩形的方式使其相對於tile.image的左上角在(tile.rect.x,tile.rect.y)處繪制。 大多數情況下tile.rect.x和tile.rect.y會大於圖塊的寬度和高度,因此將不可見。 您可能想要的是pygame.draw.rect(tile.image,BLUE,[0,0,TILE_SIZE,TILE_SIZE],2)。 這會在圖塊上從圖塊的左上角(0,0)到右下角(TILE_SIZE,TILE_SIZE)繪制一個矩形。

文本也是如此。 例如,如果TILE_SIZE為25,x為2,則在tile.image上將文本變暗的x坐標為2 * 25 + 40 =90。90大於tile.image的寬度(TILE_SIZE-1 = 24 ),因此它將繪制在表面的外部,使其不可見。 如果要在tile.image的左上角繪制文本,請執行tile.image.blit(label,[0,0])。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM