在JavaScript上解决非循环迷宫

时间:2014-02-11 20:39:14

标签: javascript algorithm

我正在尝试找到一种能够始终解决随机生成的非循环迷宫的算法,我正在使用以下代码但它仍然卡住了。有什么建议吗?

function makeMove()
{   
    if(isWall("Right") == true)
    {
        move("Forward");
    }
    else if(isWall("Right") == false)
    {
        move("Right");
    }
    else if(isWall("Right") == true && isWall("Forward") == true)
    {
        move("Left");
    }
}

3 个答案:

答案 0 :(得分:1)

你可能会因为你的寻路算法无法回溯而陷入困境。如果你最终走到了死胡同(即你的前面,你的左边,你的右边),怎么办?你需要能够回溯。

从我看到的,你正在检查右边的路是否被阻挡。如果是这样,你就前进了。但是你需要检查一下是否可以继续前进。仅仅因为通往右翼的道路受阻,并不意味着前进的道路是开放的!

此外,您的第三个条件永远不会被执行,因为第一个条件将为此报告为true,因此该if块中的代码将被执行。

答案 1 :(得分:1)

你需要一些条件来转动光标。想想就像把你的右手不停地放在迷宫的墙上一样,如果你到达前方有一堵墙的地方,那么你就转过来(这就是当你把手放在上面时会发生的事情)右墙)。

如此有效

var up = 1;
function makeMove()
{   
    if(isWall("Right", up) && !isWall("Forward", up))
    {
        move("Forward", up);
    }
    else if(!isWall("Right", up))
    {
        move("Right", up);
    }
    else
    {
        up = !up; makeMove();
    }
}

在回复您的评论时,您可以使用一些简单的系统来跟踪方向:

function move( direction, up ) {
    if ( ! up ) {
        if (direction == "Forward") { direction = "Backward"; }
        else if ( direction == "Backward" ) { direction = "Forward"; }
        else if ( direction == "Right" ) { direction = "Left"; }
        else { direction = "Right"; }
    }

    … Your current code
}

修改:添加了一个用于“转身”的模拟开关。相同的代码也应位于isWall()

的顶部

答案 2 :(得分:-2)

这应该解决任何迷宫......最终。

var direction = ['Left', 'Forward', 'Right', 'Back'];
var isWall = function () {
    return Math.floor(Math.random() * 2);
};

function makeMove() {
    var dir = Math.floor(Math.random() * 4);
    dir = direction[dir];
    alert(dir);

    if (!isWall(dir)) move(dir);
    else makeMove();
}

function move(dir) {
    // Go places
    if (!confirm('You moved, continue?')) return;

    if ("places" === "exit") alert("FREEEEDOOM!");
    else makeMove();
}

makeMove();

<强> DEMO

<强> DEMO WITH MAZE

相关问题