python - Pygame Sprite. How to create different enemies/images from same class? -
i building tiny platform based game pygame. want go having 1 graphic enemies, several different graphics. idea put them in array , draw randomly upon initing several sprites randomly picked graphics.
but result either enemy1.png or enemy2.png sprites. not sure if simple , not able see it, or if need extend enemy class each new graphic want enemies have?
i tried 2 things same, , same result both.
first idea:
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) in self.enemyarray: self.image = choice(self.enemyarray) self.rect = pygame.rect.rect(location, self.image.get_size()) self.direction = 1
second idea:
class enemy(pygame.sprite.sprite): enemyarray = [pygame.image.load('enemy.png'), pygame.image.load('bomb.png')] 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
i've used internet find guidance, can't find seems handle issue. helpful, ready made code snippets links might enlighten me.
update:
class game(object): def main(self, screen): ... self.enemies = tmx.spritelayer() enemy in self.tilemap.layers['triggers'].find('enemy'): enemy((enemy.px, enemy.py), self.enemies) self.tilemap.layers.append(self.enemies)
i use tilemap i've created in tiled, each enemy-trigger, there enemy spawning. enough?
in second idea have line:
image = choice(enemyarray)
this should not work because making local variable image, not stored enemy class @ all. don't have error in first idea. correct way set attribute this:
self.image = choice(enemyarray)
then can change:
in enemyarray: image = choice(enemyarray)
into:
image = choice(enemyarray)
because should make no difference, throwing dice 2 times when have 2 pictures in enemyarray.
Comments
Post a Comment