本文实例讲述了JS/HTML5游戏常用算法之路径搜索算法 A*寻路算法。分享给大家供大家参考,具体如下:
原理可参考:https://www.jb51.net/article/152744.htm
完整实例代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <meta charset="UTF-8"> <title>A*寻路算法</title> <style> #stage { border: 1px solid lightgray; } </style> </head> <body> <canvas id="stage"></canvas> </body> <script> window.onload = function () { var stage = document.querySelector('#stage'), ctx = stage.getContext('2d'); stage.width = 600; stage.height = 600; var row = 7, column = 7, r = 40; //取区域随机数x>=min && x<max function randInt(min, max) { max = max || 0; min = min || 0; var step = Math.abs(max - min); var st = (arguments.length < 2) "black"); } } } //绘制开始方块 createRect(startRect.x, startRect.y, r, "red"); if (endRect.hasCreate) { //绘制跟随方块 createRect(endRect.pos()[0], endRect.pos()[1], r, "blue"); endPoint = mapSCPos(endRect.pos()[1], endRect.pos()[0]); if(path === null){ var ASmap = convertArrToAS(mapArr); path = findPathA(ASmap, startPoint, endPoint, ASmap.length, ASmap.length); }else{ next = path.pop(); startRect.y = next.x * r; startRect.x = next.y * r; if(path.length===0){ startPoint = mapSCPos(startRect.pos()[1], startRect.pos()[0]); path = null; endRect.hasCreate = false; } } } requestAnimationFrame(update); } update(); stage.addEventListener('click', function () { //标准的获取鼠标点击相对于canvas画布的坐标公式 var x = event.clientX - stage.getBoundingClientRect().left, y = event.clientY - stage.getBoundingClientRect().top; var endRectPos = mapSCPos(y, x);//[i,j] endRect.x = endRectPos[1]*r; endRect.y = endRectPos[0]*r; if (mapHasRect(mapArr, endRectPos[0], endRectPos[1])) { console.log('这个位置已经有方块啦!'); } else { endRect.pos(); endRect.hasCreate = true; } }) }; </script> </html>
使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun,测试运行上述代码,可得到如下运行效果:
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。