有没有更好的方法来产生敌人的位置? [英] Is there a better way to spawn enemy locations?

查看:62
本文介绍了有没有更好的方法来产生敌人的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个 pygame,在部落类型的游戏中幸存下来.我已将其设置为敌人将走向玩家的位置.如果他们击中玩家,他们会损失一些他的生命值.如果玩家射击它们,它们就会死亡/消失,并且玩家会得到一两分.

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.

我希望敌人在一定距离内全部出现在屏幕外,然后走到屏幕上,这样你就不会在敌人 5 像素远或在你上方时开始游戏.

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.

我想尝试创建一个 if 语句,如果敌人不在一定范围内,它只会将敌人添加到精灵列表中,但是许多精灵根本不会产生,从而消除了我控制实际数量的能力产生的敌人.

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.

以下是我如何生成敌人的结构.正如您所看到的,有些在屏幕外向任何方向产生 200 像素远,这很好,但它们也可以在我的播放器正上方产生.

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.

如果您想知道,我的 Enemy_1pt 类的输入是 (image,speed,health)

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)

推荐答案

使用应用程序循环来生成敌人.创建一个随机位置并尝试放置敌人.如果敌人因为离另一个敌人太近而无法生成,请跳过它们并等待下一帧.只要敌人数量少于请求的敌人数量,就尝试生成敌人:

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)

    # [...]

这篇关于有没有更好的方法来产生敌人的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆