我试图重新创建一个slide puzzle,我需要打印到以前绘制的矩形精灵的文本。这就是我设置它们的方式:
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
我做错了什么?
答案 0 :(得分:0)
Pygame中的坐标是相对于正在绘制的表面。你当前在tile.image上绘制rects的方式使得它相对于tile.image的tople从(tile.rect.x,tile.rect.y)绘制。大多数时候,tile.rect.x和tile.rect.y将大于tile的宽度和高度,因此它将是不可见的。你可能想要的是pygame.draw.rect(tile.image,BLUE,[0,0,TILE_SIZE,TILE_SIZE],2)。这会在图块上从图块的topleft(0,0)到右下角(TILE_SIZE,TILE_SIZE)绘制一个矩形。
同样适用于文本。例如,如果TILE_SIZE为25且x为2,则tile.image上文本为blit的x坐标为2 * 25 + 40 = 90. 90大于tile.image的宽度(TILE_SIZE-1 = 24 ),因此它会在表面之外绘制,使其不可见。如果要在tile.image的左上角绘制文本,请执行tile.image.blit(label,[0,0])。