最近比较空,想学学寻路算法,然后总和网上的的资料自己实现了一个简单的六边形网格地图的A*算法。
参考文章:
http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx
下面我把主要算法代码贴出来分享给大家:
/** * 寻路 */ public void searchRoute() { Hexagon nowHexagon = thisHexagon; nowHexagon.reset(); addToOpenList(nowHexagon); boolean finded = false; while(!finded) { openList.remove(nowHexagon);//将当前节点从openList中移除 closeList.add(nowHexagon);//将当前节点添加到关闭列表中 LinkedList<Hexagon> neighbors = nowHexagon.getNeighborList();//获取当前六边形的相邻六边形 System.out.println("当前相邻节点数----" + neighbors.size()); for(Hexagon neighbor : neighbors) { if(neighbor == targetHexagon) {//找到目标节点 System.out.println("找到目标点"); finded = true; neighbor.setFatherHexagon(nowHexagon); } if(isAtCloseList(neighbor) || !neighbor.canPass()) {//在关闭列表里 System.out.println("无法通过或者已在关闭列表"); continue; } if(isAtOpenlList(neighbor)) {//该节点已经在开启列表里 System.out.println("已在开启列表,判断是否更改父节点"); float assueGValue = neighbor.computeGValue(nowHexagon) + nowHexagon.getgValue();//计算假设从当前节点进入,该节点的g估值 if(assueGValue < neighbor.getgValue()) {//假设的g估值小于于原来的g估值 openList.remove(neighbor);//重新排序该节点在openList的位置 neighbor.setgValue(assueGValue);//从新设置g估值 addToOpenList(neighbor);//从新排序openList。 } } else {//没有在开启列表里 System.out.println("不在开启列表,添加"); neighbor.sethValue(neighbor.computeHValue(targetHexagon));//计算好他的h估值 neighbor.setgValue(neighbor.computeGValue(nowHexagon) + nowHexagon.getgValue());//计算该节点的g估值(到当前节点的g估值加上当前节点的g估值) addToOpenList(neighbor);//添加到开启列表里 neighbor.setFatherHexagon(nowHexagon);//将当前节点设置为该节点的父节点 } } if(openList.size() <= 0) { System.out.println("无法到达该目标"); break; } else { nowHexagon = openList.get(0);//得到f估值最低的节点设置为当前节点 } } openList.removeAll(openList); closeList.removeAll(closeList); if(finded) {//找到后将路线存入路线集合 route.removeAll(route); Hexagon hex = targetHexagon; while (hex != thisHexagon) { route.add(hex);//将节点添加到路径列表里 Hexagon fatherHex = hex.getFatherHexagon();//从目标节点开始搜寻父节点就是所要的路线 hex = fatherHex; } route.add(hex); liXiaoYao.setState(LiXiaoYao.STATE_MOVING); liXiaoYao.setStepIndex(route.size() - 1); } // resetMap(); }
代码写的比较粗糙,大家见谅。欢迎大家提出批评意见。
完整项目源码可以下载附件。