如何在Pygame中给精灵添加'Rect'或文本?
我正在尝试制作一个滑动拼图,我需要在之前画好的矩形精灵上打印文字。以下是我设置它们的方式:
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)
这是我尝试添加矩形的方法(当用鼠标点击时):
# 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
我哪里做错了?
1 个回答
0
Pygame中的坐标是相对于你正在绘制的表面来说的。你现在在tile.image上绘制矩形的方式是根据(tile.rect.x, tile.rect.y)来定位的,这个位置是相对于tile.image的左上角的。通常情况下,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])。