繁体   English   中英

尽管条件失败,为什么项目被推入数组?

[英]why items are being pushed into array, despite failing conditional?

我正在 node.js 中编写一个终端游戏,它会生成一个由以下组成的随机字段

const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';

玩家需要穿过迷宫并找到他们的帽子。 字段表示为

randomArr

因为数组是随机的,所以生成的字段可能无法通过,因为帽子被孔包围,玩家根本无法到达那里,所以我正在制作一个算法首先检查是否可能的功能获胜(基本上是迷宫生成器)。 我有一个应该可以工作的代码,但它无法正确执行,因为它陷入了无限循环。 它遇到了 conditional ,需要满足条件才能将双元素数组添加到嵌套数组中(条件是:相邻方格必须是字段元素并且该方格之前没有被访问过)。 尽管不满足第二个条件,算法会一遍又一遍地将相同的元素添加到数组中。

这是循环的开始:

while (true) {           
    //checking if next move is a winning move
    if (randomArr?.[p[0]]?.[p[1] + 1] === hat || randomArr?.[p[0]]?.[p[1] - 1] === hat || randomArr?.[p[0] + 1]?.[p[1]] === hat || randomArr?.[p[0] - 1]?.[p[1]] === hat) {
        console.table(visited, visitedTwice, visited3x, visited4x, visited5x);
        console.log(`solution found, reached postion ${p}`)
        return randomArr;
    }          
    //checking if neighbouring square hasn't been visited, if no, go there
    else if (randomArr?.[p[0]]?.[p[1] + 1] === fieldCharacter && !visited.includes([ p[0], p[1] + 1 ])) {
        p = [p[0], p[1] + 1];
        visited.push([p[0], p[1]]);
        //console.log(visited.includes([ p[0], p[1] + 1 ]), 0);
        //console.log(visited);
    } else if (randomArr?.[p[0]]?.[p[1] - 1] === fieldCharacter && !visited.includes([ p[0], p[1] - 1 ])) {
        p = [p[0], p[1] - 1];
        visited.push([p[0], p[1]]);
        //console.log(visited.includes([ p[0], p[1] - 1 ]), 1);
        //console.log(visited);
    } else if (randomArr?.[p[0] + 1]?.[p[1]] === fieldCharacter && !visited.includes([ p[0] + 1, p[1] ])) {
        p = [p[0] + 1, p[1]];
        visited.push([p[0], p[1]]);
        //console.log(!visited.includes([ p[0] + 1, p[1] ]), 2);
        //console.log(visited);
    } else if (randomArr?.[p[0] - 1]?.[p[1]] === fieldCharacter && !visited.includes([ p[0] - 1, p[1] ])) {
        p = [p[0] - 1, p[1]];
        visited.push([p[0], p[1]]);
        //console.log(!visited.includes([ p[0] - 1, p[1] ]), 3);
        //console.log(visited);

这段代码继续遍历前 2 个 else if 语句,并不断向visited的数组添加相同的元素。 (注释掉的console.log语句是让我检查发生了什么)。

您不能使用!visited.includes([ p[0], p[1] + 1 ]) 数组是通过身份匹配的,而不是通过比较内容,所以这永远不会是真的。

利用

!visited.some(([el1, el2]) => el1 == p[0] && el2 == p[1]+1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM