Skip to content
当前位置:🏠 首页  / 文章归档 / 2025

推箱子用js实现自动寻路

发布时间:2025-10-29 09:10:17

这两天给之前编的 推箱子 小游戏优化了优化,觉得有用的代码分享纪念一下。

我之前设置的点击按钮移动,我看到别的有点下直接自动移动过去的,自己就想也设置一下,于是就做了。

不停的修改优化,完美解决。下方是执行自动移动的相关函数

js
function moveTo(endX,endY) {
//点击地图执行的函数,endX,endY为目的坐标
    const steps = [];
    const [startX, startY] = [player.x,player.y];//player为玩家当前坐标
    const mapWidth = map[0].length - 1,mapHeight = map.length - 1;
//map为存储地图的二维数组,此处获取地图边界
    if (endX < 0 || endY < 0 || endX > mapWidth || endY > mapHeight) {return;}
     if(1==Math.abs(endX - startX)+Math.abs(endY - startY)){
//目的地相邻,不用计算,直接运行移动函数
    steps.push([endX-startX,endY-startY])}else{
    const queue = [[startX, startY, []]];
    const visited = new Set();
    visited.add(`${startX},${startY}`);
    const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
    while (queue.length > 0){
    const [currentX, currentY, path] = queue.shift();
    if (currentX === endX && currentY === endY) {steps.push(...path);break;}
        for (const [dx, dy] of directions) {
    const nextX = currentX + dx,nextY = currentY + dy,key = `${nextX},${nextY}`;
    if (nextX < 0 || nextY < 0 || nextX > mapWidth || nextY > mapHeight) {
continue;}
    if (visited.has(key)) {continue;}
        const isWall = walles.some(wall => wall.x === nextX && wall.y === nextY);
//障碍物坐标数组
        const isBox = boxes.some(box => box.x === nextX && box.y === nextY);
//也是障碍物坐标数组
        if (isBox||isWall) {continue;}else {visited.add(key);queue.push([nextX, nextY, [...path, [dx, dy]]])}}}
 }
     setime(steps)//执行多次移动的函数
}
function setime(arr) {
//一次一次的执行设置的移动路径
    if (arr.length === 0) {return;}
movePlayer(arr[0][0],arr[0][1]);
//这是移动的函数
drawGame();//渲染函数
arr.shift();//删除执行过的移动步骤
setTimeout(()=>{setime(arr);}, 200);
//每次移动设置200ms延迟,看上去好看点,也可以不用,直接用for循环执行,那样就像瞬移,感觉不太好看
}