1
\$\begingroup\$

I need to find a method using which I can ensure that random enemies and objects don't spawn just near the player. In fact, if they do, the player will be more likely to collide with them and lose.

These enemies and objects spawn relatively to the player's score and to some userevents.

I've tried to use a recursive function in these objects' classes in order to check whether the object's coordinates obey to the condition that they shouldn't be near the player's coordinates and if they are valid (they obey to that condition), I can blit their images to the screen.

But I found that this idea isn't a good one and demands lots of code so I abandonned it.

So is there any other method to implement that ?

NOTE :

Enemies coordinates are generated randomly like this:

self.x = random.randrange(2, 502, 20)
self.y = random.randrange(2, 502, 20)

Then, they're blitted to the screen at these coordinates :

screen.blit(myenemy.img, (self.x, self.y))
\$\endgroup\$
2
  • 3
    \$\begingroup\$ Currently, how do you generate those enemies? What are the other constraints for spawning? \$\endgroup\$
    – Vaillancourt
    Jul 12 at 17:51
  • \$\begingroup\$ @Vaillancourt, their coordinates are generated randomly and then these enemies are blitted to the screen at these coordinates. So new enemies are added to the screen every random n seconds or when the score is high \$\endgroup\$
    – Salem
    Jul 12 at 19:36
3
\$\begingroup\$

The simplest system I can think of consists in testing the position of the new enemy before your screen.blit(), like so:

def distance_square(a, b):
    return (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - b.y)

def init_enemy(min_distance):
    while True:
        self.x = random.randrange(2, 502, 20)
        self.y = random.randrange(2, 502, 20)
        if distance_square(self, player) > (min_distance * min_distance):
            break
    # Then blit the enemy, etc.

I left the distance squared as a slight optimization, since it is faster to compute a simple multiplication.

The logic is very simple here: rather than seeking a specific algorithm to generate a random number that meets your conditions, it is probably simpler (and perhaps faster) to just generate a new random number. Here, I generate forever until I find a position that meets your requirements.

However, you may want to set some safety net to avoid a very, very unlikely but possible loop that run for a long time. And you can of course implement this loop right into your game loop depending on how you designed it. It's all up to you and as it depends on the specific needs of your project. This is just a template.

\$\endgroup\$
1
  • \$\begingroup\$ good idea, thank you ! \$\endgroup\$
    – Salem
    Jul 13 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.