[font=Arial,][color=#000000]I am working on a simple 2d game where many enemies continually spawn and chase the player or players in python + pygame. A problem I ran into, and one many people that have programmed this type of game have run into is that the enemies converge very quickly. I have made a temporary solution to this problem with a function that pushes any two enemies randomly apart if they are too close to each other. This works well but is about an O(n^2) algorithm which severely slows the program down.[/font]
When my program runs with this function the enemies seem to form a round object I nicknamed a "clump". The clump seems to usually be egg-shaped with the small tip in the direction of the player. I do like the way the clump behaves, however it currently uses a O(n^2) algorithm. Is there a way to calculate the clump all at once, perhaps as a polygon (straight edges are fine it doesn't have to be exactly round) with a O(n) or better algorithm (n being the number of enemies inside).
Currently all enemies move toward the player and then the clump function is used. Here are the two functions for this.
def moveEnemy(enemy, player, speed):
a = player.left-enemy.left
b = player.top-enemy.top
r = speed/math.hypot(a,b)
return enemy.move(r*a, r*b)
def clump(enemys):
for p in range(len(enemys)):
for q in range(len(enemys)-p-1):
a = enemys
b = enemys[p+q+1]
if abs(a.left-b.left)+abs(a.top-b.top)<CLUMP:
xChange = (random.random()-.5)*CLUMP
yChange = ((CLUMP/2)**2-xChange**2)**.5
enemys
= enemys
.move(int(xChange+.5), int(yChange + .5))
enemys[p+q+1] = enemys[p+q+1].move(-int(xChange+.5),-int(yChange+.5))
return enemys
I also posted this question of stack overflow:http://stackoverflow...enemies-at-once however no one there knew how to make the algorithm less than O(n^2) which is what is needed for high number of enemies