开发者

Pathfinding in Java

Let's say I use arrays to plot out my game map using this:

{ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 1开发者_运维知识库3, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1 },
{ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1, 1 }

I have an ArrayList<> of tile numbers that are BLOCKED while others are NOT BLOCKED. I can check by doing blocked(X,Y) and it will return true or false by checking the X and Y of that tile on the currentMap and then it will see if that tile is in the BLOCKED ArrayList<>. Anyways, what's the best method of pathfinding here?


You can use graph search algorithms, for example Breadth-first search. Implementations you can find in google, there is much examples.


I think by pathfinding you mean you want to find the shortest path from cell (x1,y1) to cell (x2,y2). Some more information is needed here. How do define adjacent cells - i.e. can I move from one cell to its 4 neightbours or 6 neighbours including diagonal movement? Is the cost of moving to any celll the same, or does it vary according to the type of cell or whether it is a row/coloumn move or diagonal move?

Assuming the cost of moving is the same for all cells and each cell is adjacent to the 4 cells it shares an edge with, this is basically a simple problem of finding the shortest path in a simple unweighted graph. For that you can use a breadth first search. The nodes of the graph are the cells and each cell (except for the ones at the top & bottom row and left and rightmost coloumns) have four edges(one for each adjacent cell). As we visit each node, we just skip over blocked nodes.

Pseudocode:

shortest path(start,end, blocked):
   cost=map of node:int
   visited=set of nodes
   dx=array {0,1,0,-1}
   dy=array {1,0,-1,0}
   Q=queue of nodes
   cost[start]=0
   add start to Q
   while Q is not empty:
       node=remove top from Q
       for i=0 until 4:
           next=new node with next.x=node.x+dx[i], next.y=node.y+dy[i]
           if (next is a valid node) and (next is not in visited) and (next is not in blocked):
              cost[next]=cost[node]+1
              add next to visited
              add next to Q
    if end is in visited:
       return cost[end]
    else:
       return -1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜