1

I am currently having an issue when trying to randomly spawn enemies into my platformer game. I have an enemy class class Enemy(pygame.sprite.Sprite): that has an __init__ and move(self) function. Currently i have each instance of the enemy defined individually:

 enemy1 = Enemy(210,515,"Enemy.png")
 enemy2 = Enemy(705,515,"Enemy.png")
 enemy3 = Enemy(1505,515,"Enemy.png")

During the main game loop i append each instance to a group:

enemy_list = pygame.sprite.Group()
        enemy_list.add(enemy1)
        enemy_list.add(enemy2)
        enemy_list.add(enemy3)

However i would rather that the enemeies spawned at random times in a random position so i hought i could do a check like this:

if random.randrange(0,100) < 1:
                spawnEnemy = Enemy(400, 515, "Enemy.png")

My issue is that i do not know how to now append the random eney to the enemy_list. Any ideas?

sloth
  • 99,095
  • 21
  • 171
  • 219

1 Answers1

0

if im correct the coordinates are being passed into class Enemy(pygame.sprite.Sprite): for instantiation

in that case the random positioning could be done by:

enemy4 = Enemy(random.randrange(100,1000),random.randrange(100,1000),"Enemy.png")
enemy_list.add(enemy4)

if you cannot hardcode enemy identifier, try directly adding to the enemy group list without assingment:

enemy_list.add(Enemy(random.randrange(100,1000),random.randrange(100,1000),"Enemy.png"))
Zulfiqaar
  • 603
  • 1
  • 6
  • 12
  • Thanks, I added the `enemy_list.add(Enemy(random.randrange(100,1000),random.randrange(100,1000),"Enemy.png"))` just underneath my `if random.randrange(0,100) <1:` code and it does randomly spawn however it only shows up for a second before it re-spawns elsewhere. I imagine that its just modifying the same instance opposed to creating a new one each time, therefore the single instance is just being randomly redrawn. Not sure how to fix this, but its progress. Any ideas? – Jack Harrison Apr 01 '19 at 17:01
  • Incase its not clear: Id like it to constantly add new instances so that over time i can make it so that more and more enemies spawn as the player score increases, rather than having a set number of enemies. – Jack Harrison Apr 01 '19 at 17:02
  • im actually not too sure on why instantiating a new `Enemy()` overwrites the previous one if you dont assign it to a specific variable, im not too familiar with the module itself. hope you can sort that out – Zulfiqaar Apr 02 '19 at 15:01