我正在使用 Pygame 构建一个基于平台的小型游戏。我想从为我的敌人提供一个图形到几个不同的图形。我的想法是将它们全部放在一个数组中,并在初始化时从中随机绘制,以获得几个带有随机选择图形的精灵。
但结果是我得到了所有精灵的enemy1.png 或enemy2.png。我不确定这是否真的很简单并且我只是看不到它,或者我是否需要为我希望敌人拥有的每个新图形扩展敌人类?
我尝试了两件本质上相同的事情,并且我从两者中得到了相同的结果。
第一个想法:
class Enemy(pygame.sprite.Sprite):
enemyArray = [pygame.image.load('enemy1.png'), pygame.image.load('enemy2.png')]
def __init__(self, location, *groups):
super(Enemy, self).__init__(*groups)
for i in self.enemyArray:
self.image = choice(self.enemyArray)
self.rect = pygame.rect.Rect(location, self.image.get_size())
self.direction = 1
第二个想法:
class Enemy(pygame.sprite.Sprite):
enemyArray = [pygame.image.load('enemy.png'), pygame.image.load('bomb.png')]
for i in enemyArray:
image = choice(enemyArray)
def __init__(self, location, *groups):
super(Enemy, self).__init__(*groups)
self.rect = pygame.rect.Rect(location, self.image.get_size())
self.direction = 1
我已经使用互联网找到了一些指导,但我找不到任何似乎可以解决这个问题的东西。任何东西都是有帮助的,从现成的代码片段到可能启发我的链接。
更新:
class Game(object):
def main(self, screen):
...
self.enemies = tmx.SpriteLayer()
for enemy in self.tilemap.layers['triggers'].find('enemy'):
Enemy((enemy.px, enemy.py), self.enemies)
self.tilemap.layers.append(self.enemies)
我使用我在 Tiled 中创建的瓷砖地图,因此对于每个敌人触发,都会产生一个敌人。这够了吗?