2014-04-09 51 views
0

我试图重新创建一个slide puzzle,我需要打印到以前绘制的矩形精灵的文本。这是我如何设置它们:如何在Pygame中将Rect或文本添加到Sprite中?

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 

我做错了什么?

+0

欢迎来到SO!不幸的是,你没有足够的信息来回答你的问题。你只提供当前的代码,但为了回答你的问题,我们需要知道3件事情。 1:究竟是什么错误,是不是显示正确,抵消,而不是? 2.代码是否正确运行,I.E.不会崩溃。和3.你有什么尝试过,以及它没有奏效。请考虑这些因素,然后相应地编辑您的问题。干杯! – KodyVanRy

+0

我推荐你这本书[用python制作游戏](http://inventwithpython.com/pygame/)我读过那个,用pygame学习编程。我不确定它是第6章还是第7章,但有一个幻灯片拼图示例源代码很好解释(您可以在该链接免费下载pdf,对pygame库非常有用) – AlvaroAV

+0

@ DuhProgrammer13,我认为它我很清楚我在问什么。我想知道如何将pygame.Rects和文本添加到矩形小精灵中。我在代码中评论了我认为问题正在发生以及我认为是错误的地方。 – Alexdr5398

回答

0

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上文本是blit的x坐标是2 * 25 + 40 = 90. 90比tile.image的宽度大(这是TILE_SIZE-1 = 24 ),所以它会吸引到表面之外,使其不可见。如果要在tile.image的左上角绘制文本,请执行tile.image.blit(label,[0,0])。

相关问题