Will this Dijkstra shortest path algorithm in the bge

Will this Dijkstra shortest path algorithm work in the bge
Dijkstra shortest path algorithm in python it is for 2017.

import sys


class Vertex:
    def __init__(self, node):
        self.id = node
        self.adjacent = {}
        # Set distance to infinity for all nodes
        self.distance = sys.maxint
        # Mark all nodes unvisited        
        self.visited = False  
        # Predecessor
        self.previous = None


    def add_neighbor(self, neighbor, weight=0):
        self.adjacent[neighbor] = weight


    def get_connections(self):
        return self.adjacent.keys()  


    def get_id(self):
        return self.id


    def get_weight(self, neighbor):
        return self.adjacent[neighbor]


    def set_distance(self, dist):
        self.distance = dist


    def get_distance(self):
        return self.distance


    def set_previous(self, prev):
        self.previous = prev


    def set_visited(self):
        self.visited = True


    def __str__(self):
        return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent])


class Graph:
    def __init__(self):
        self.vert_dict = {}
        self.num_vertices = 0


    def __iter__(self):
        return iter(self.vert_dict.values())


    def add_vertex(self, node):
        self.num_vertices = self.num_vertices + 1
        new_vertex = Vertex(node)
        self.vert_dict[node] = new_vertex
        return new_vertex


    def get_vertex(self, n):
        if n in self.vert_dict:
            return self.vert_dict[n]
        else:
            return None


    def add_edge(self, frm, to, cost = 0):
        if frm not in self.vert_dict:
            self.add_vertex(frm)
        if to not in self.vert_dict:
            self.add_vertex(to)


        self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
        self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)


    def get_vertices(self):
        return self.vert_dict.keys()


    def set_previous(self, current):
        self.previous = current


    def get_previous(self, current):
        return self.previous


def shortest(v, path):
    ''' make shortest path from v.previous'''
    if v.previous:
        path.append(v.previous.get_id())
        shortest(v.previous, path)
    return


import heapq


def dijkstra(aGraph, start):
    print '''Dijkstra's shortest path'''
    # Set the distance for the start node to zero 
    start.set_distance(0)


    # Put tuple pair into the priority queue
    unvisited_queue = [(v.get_distance(),v) for v in aGraph]
    heapq.heapify(unvisited_queue)


    while len(unvisited_queue):
        # Pops a vertex with the smallest distance 
        uv = heapq.heappop(unvisited_queue)
        current = uv[1]
        current.set_visited()


        #for next in v.adjacent:
        for next in current.adjacent:
            # if visited, skip
            if next.visited:
                continue
            new_dist = current.get_distance() + current.get_weight(next)
            
            if new_dist < next.get_distance():
                next.set_distance(new_dist)
                next.set_previous(current)
                print 'updated : current = %s next = %s new_dist = %s' \
                        %(current.get_id(), next.get_id(), next.get_distance())
            else:
                print 'not updated : current = %s next = %s new_dist = %s' \
                        %(current.get_id(), next.get_id(), next.get_distance())


        # Rebuild heap
        # 1. Pop every item
        while len(unvisited_queue):
            heapq.heappop(unvisited_queue)
        # 2. Put all vertices not visited into the queue
        unvisited_queue = [(v.get_distance(),v) for v in aGraph if not v.visited]
        heapq.heapify(unvisited_queue)




if __name__ == '__main__':


    g = Graph()


    g.add_vertex('a')
    g.add_vertex('b')
    g.add_vertex('c')
    g.add_vertex('d')
    g.add_vertex('e')
    g.add_vertex('f')


    g.add_edge('a', 'b', 7)  
    g.add_edge('a', 'c', 9)
    g.add_edge('a', 'f', 14)
    g.add_edge('b', 'c', 10)
    g.add_edge('b', 'd', 15)
    g.add_edge('c', 'd', 11)
    g.add_edge('c', 'f', 2)
    g.add_edge('d', 'e', 6)
    g.add_edge('e', 'f', 9)


    print 'Graph data:'
    for v in g:
        for w in v.get_connections():
            vid = v.get_id()
            wid = w.get_id()
            print '( %s , %s, %3d)'  % ( vid, wid, v.get_weight(w))


            
    dijkstra(g, g.get_vertex('a')) 


    target = g.get_vertex('e')
    path = [target.get_id()]
    shortest(target, path)
    print 'The shortest path : %s' %(path[::-1])
 

Yes, this will work, but you will need to write the code that sets up the graph, and then leverage it in your own code.

Are there any tutorials for setting up the graph?

How would i make a graph for a digging game with that?

Not really, it’s a specific problem.

I suggest you spend some time understanding what it does, and learn how to use Python to solve this :slight_smile:

Do you know about the benefits/disadvantages of Dijkstra over A*?
There are times when using this method of path-finding can be useful, but other times when it’s not.

I though it would be great for a digging game.

It’s great that you’re looking around, but I really suggest you actually understand what these things are before thinking you need them.

There are advantages and tradeoffs to all programs, algorithms and techniques, and so it is vital that you understand what their pros and cons are in order for you to be able to choose the appropriate one

That is what they used in a minecraft videogame so i thought it would be a good idea.

So why did they use it in minecraft? There’s a good reason for using different types of pathfinding.
Some are more efficient if you know the destination others if you know what you’re looking for but don’t know where the nearest one is because the route to the nearest one could be blocked or take longer than you think.
Others are good when you have one destination but multiple agents trying to get there (an influence map).

A* algorithm is Dijkstra + simple prediction. You can change the importance of heuristics to change Dijkstra -> A* -> Greedy pathfinding.

Now the difference is that Dijkstra will always find shortest path, A* is faster but will find shortest when the heuristics are done right, and greedy will most likely not find the shortest path which is why you cant stress the prediction heuristics too much.

Then again, i’m speaking out of my ass from practical experience.
Better read from here: http://theory.stanford.edu/~amitp/GameProgramming/

Yes, it is. Especially as all pathfinding algorithms are kinda Dijkstra with extra herbs and spices.

This makes me more confused than informed.

Short answer: Yes.

Long answer: Not right out of the box. You’re probably going to need to jiggle it around to make it work with your game.

To say that Dijkstra’s algorithm is the same as A* is like saying a bomb is the same as a gun. They both rely on the same mechanism but both have different applications.

From wikipedia;
“The algorithm exists in many variants; Dijkstra’s original variant found the shortest path between two nodes, but a more common variant fixes a single node as the “source” node and finds shortest paths from the source to all other nodes in the graph, producing a shortest-path tree.”

It CAN be used for point-to-point pathfinding, but it is not well suited to this task. Instead it can be used to create influence maps. This method allows you to pathfind for many agents with a single operation. Or find multiple paths to different goals for a single agent, then choose the best. It can be reversed to help enemies flee from the player or keep a certain distance away at all times.

It’s particularly useful in games where you have one player character and lots of enemies, or where the level layout can change often so you can’t take advantage of precalculated paths (a common trick in games to allow fast pathfinding).

There are other methods you can use, but be aware in each case “path finding” doesn’t always mean point-to-point.

How you build a graph will depend on whether you use a custom navigation mesh or tile based graph.

I was thinking -> generate whole world

have each path node store all the nodes in a radius to it,

have each agent get nodes from node they are occupying,

cull occupied nodes somehow

have each agent calc a path using the remaining nodes,
if no way exists, pathfind to obstruction and stand there.

Yes, that’s the basics. The usual result is to get a graph where each node has lower numbers the closer it is to the source. To pathfind you just “roll downhill” by choosing the neighboring tile with the lowest value. To pathfind away you can choose tge highest value.

The great thing is you only need to regenerate the graph if the source tile moves. Agents can continue to use the static graph for finding the next tile as long as the player stands still.

Here’s an example of then I actually tried using the system in a game:

(from 2014)

Is that anygood for a minecraft type digging videogame?

Why do you need pathfinding in your digging game? That would help us figure out what type of pathfinding algorithm you’ll need.

If your tiles/blocks are changing the terrain a lot, neither A* or Dijkstra’s algorithm will help you much (especially if there’s a large problem space).

I need it for the npc’s to nagivate over cubes the player places down and for them to navigate to the player as he makes tunnels.Pathfinding like what is in this video.https://www.youtube.com/watch?v=4e1oysgbjOMDoes it look cool?