Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

python - Is there a better way to spawn enemy locations?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

    # [...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...