i didn’t really understood what the A* brings in comparison with the one i learnt at university, the good old Dijkstra.
This is what my code does (summary to make it easy to read
, though not written with class)
my functions
## the core algo
def dijkstra (start, end, neigbours):
return path
## sub -core
def neigbours (s):
return graph[s]
## simple functon of mine to find the closest checkpoint to a (character)
def closest(character):
return checkpoint
the graph of checkpoints with a loop to auto-compute the distances (replacing the “0” by a xy distance). For example, “C1” can leads to “C2” and “C0” … So basically, in my game, i just posed 13 box-empties on the map and wrote the graph here below
graph = {
"C0": [ [0, "C1"] ],
"C1": [ [0, "C2"], [0, "C0"] ],
"C2": [ [0, "C3"], [0, "C1"], [0, "C0"] ],
"C3": [ [0, "C0"], [0, "C2"], [0, "C1"] , [0, "C4"] ],
"C4": [ [0, "C5"], [0, "C3"], [0, "C1"], [0, "C0"] ],
"C5": [ [0, "C6"], [0, "C8"], [0, "C4"] , [0, "C1"], [0, "C0"] ],
"C6": [ [0, "C7"], [0, "C5"] ],
"C7": [ [0, "C9"], [0, "C10"], [0, "C6"] ],
"C8": [ [0, "C9"], [0, "C5"], [0, "C0"], [0, "C1"] ],
"C9": [ [0, "C8"], [0, "C7"], [0, "C0"], [0, "C1"] ],
"C10": [ [0, "C7"], [0, "C11"] ],
"C11": [ [0, "C12"], [0, "C10"] ],
"C12": [ [0, "C11"], [0, "C13"] ],
"C13": [ [0, "C12"] ]
}
### compute the xy distance for each checkpoint couples
for i in graph.keys() :
for j in graph[i] :
j[0] = (scene.objects[i].worldPosition.xy - scene.objects[j[1]].worldPosition.xy).length
in game every 30 frame
npc['end'] = closest(player)
### check if the npc's closest checkpoint is the same than the player's one
if closest(npc) == npc['end'] :
npc['target'] = player ### go to the player
else :
npc['target'] = npc['check'] ### keep go to the next checkpoint
### if the npc collides with a checkpoint
if check.status == 1 :
### end of the path, the player must be around
if check.hitObject.name == npc["end"] :
### just a checkpoint, but let's recompute the path as the player
### might have moved since and lets go to the next checkpoint
elif check.hitObject.name == npc["check"] :
checks = dijkstra(npc["check"], npc['end'] , neighbours )
npc['target'] = npc["check"] = checks[1]
## you can collide by accideny with a checkpoint not on your current path
else :
print(" meh .. just another checkpoint")