Is there a better way to spawn enemy locations?

放肆的年华 提交于 2021-02-13 17:31:11

问题


I'm making a pygame, survive the hord type game. I have it set up to where enemy's will walk towards the player. If they hit the player, they take some of his health. if the player shoots them, they die/disappear, and the player gets a point or two.

I want the enemy's to all spawn off screen within a certain distance, and then walk onto screen so that you don't start the game with enemy's 5 pixels away, or on top of you.

I thought of trying to create an if statement, that only adds the enemy to the sprite list if they are not within a certain range, but then many sprites won't spawn at all, removing my ability to control the actual number of enemy's that spawn.

Below is the structure of how I am spawning enemy's. As you can see, some are spawing off screen as far as 200 pixels away in any direction, which is good, but they can also spawn right on top of my player.

In case you are wondering, the inputs for my Enemy_1pt class are (image,speed,health)

for i in range(10):
    enemy_1pt = Enemy_1pt(fire_drake_image,1.5,1)
    enemy_1pt.rect.x = random.randrange(-200,screen_width+200)
    enemy_1pt.rect.y = random.randrange(-200,screen_height+200)
    enemy_1pt_list.add(enemy_1pt)
    all_sprites_list.add(enemy_1pt)

回答1:


Use the application loop to spawn the enemies. Create a random position and try to place the enemy. If the enemy cannot spawn because it would be placed too close to another enemy, skip them and wait for the next frame. Try to spawn enemies as long as the number of enemies is less than the number of enemies requested:

import math
no_of_enemies = 10
minimum_distance = 100

# application loop
while True:

    if len(all_sprites_list.sprites()) < no_of_enemies:

        # try to spawn enemy  
        x = random.randrange(-200,screen_width+200)
        y = random.randrange(-200,screen_height+200) 

        spawn = True
        for enemy in enemy_1pt_list:
            ex, ey = enemy.rect.center
            distance = math.hypot(ex - x, ey - y)
            if distance < minimum_distance: 
                spawn = False
                break

        if spawn:
            enemy_1pt = Enemy_1pt(fire_drake_image,1.5,1)
            enemy_1pt.rect.center = x, y
            enemy_1pt_list.add(enemy_1pt)
            all_sprites_list.add(enemy_1pt)

    # [...]


来源:https://stackoverflow.com/questions/64838918/is-there-a-better-way-to-spawn-enemy-locations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!