简体   繁体   中英

Pygame Platformer- Randomly Spawning Enemies

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?

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM