如何在Pygame中让多坐标生成的食物图片居中?
Pygame吃豆人游戏:食物图片无法居中显示问题
我用Python的Pygame库制作自定义吃豆人游戏,通过以下数组创建地图:
WORLD_MAP = [ ['x','x','x','x','x'], ['x',' ',' ',' ',' '], ['x',' ',' ',' ',' '], ['x',' ',' ',' ',' '], ['x','x','x','x','x'], ]
接着编写了创建地图的函数,将数组中空位设置为食物图片:
def create_map(self): for row_index, row in enumerate(WORLD_MAP): for col_index, col in enumerate(row): x = col_index * TILESIZE y = row_index * TILESIZE if col == ' ': self.food = Food((x,y),[self.visible_sprites, self.obstacles_sprites])
随后创建了Food类:
class Food(pygame.sprite.Sprite): def __init__(self,pos,groups): width = TILESIZE/3 height = TILESIZE/3 super().__init__(groups) self.image = pygame.transform.scale(pygame.image.load(os.path.join('images', 'circle.png')), (width, height)) self.rect = self.image.get_rect(topleft = pos).center
问题在于运行程序时,circle.png始终显示在每个空位的左上角,修改topleft为center、bottomleft等参数也无法让图片居中。我需要让每个circle.png居中显示在数组中col == ' '对应的每个格子区域的中心。
问题原因
你的代码里self.rect = self.image.get_rect(topleft = pos).center这行逻辑错误:get_rect()返回的是Pygame的Rect对象,访问.center会得到一个(x,y)坐标元组,把这个元组直接赋值给self.rect,相当于把Rect对象替换成了普通坐标,Pygame绘制精灵时依赖Rect对象的位置属性,自然无法正确计算图片位置。
修复方案
调整Food类的__init__方法,正确设置图片Rect的中心为对应格子的中心:
方案一:直接设置Rect的center属性
class Food(pygame.sprite.Sprite): def __init__(self, pos, groups): width = TILESIZE / 3 height = TILESIZE / 3 super().__init__(groups) # 加载并缩放图片 self.image = pygame.transform.scale( pygame.image.load(os.path.join('images', 'circle.png')), (width, height) ) # 计算格子的中心坐标:格子左上角pos加上半个格子边长 tile_center = (pos[0] + TILESIZE // 2, pos[1] + TILESIZE // 2) # 设置图片Rect的中心为格子中心 self.rect = self.image.get_rect(center=tile_center)
方案二:先创建Rect再调整中心
class Food(pygame.sprite.Sprite): def __init__(self, pos, groups): width = TILESIZE / 3 height = TILESIZE / 3 super().__init__(groups) self.image = pygame.transform.scale( pygame.image.load(os.path.join('images', 'circle.png')), (width, height) ) # 先获取图片的Rect对象 self.rect = self.image.get_rect() # 调整Rect的中心到格子中心 self.rect.center = (pos[0] + TILESIZE//2, pos[1] + TILESIZE//2)
两种方案都能让食物图片准确居中显示在对应格子的中心位置。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

