【发布时间】:2023-03-24 21:40:01
【问题描述】:
我正在尝试在 p5.js 中制作经典的蛇游戏。我有一个蛇对象,我将其主体的位置存储在一个二维数组 this.data 中,其中每个元素存储一个 x 值和一个 y 值(分别在索引 0 和 1 处)。随着蛇的移动,我将新位置推入数组中。
当我试图检测蛇是否撞到自己时遇到了问题。我试图做的是使用 indexOf 测试它的当前位置是否已经在数组中,推理如果新位置是打开的,它只会在数组中出现一次,索引比数组的长度小一。否则,如果该位置已经存在于数组中的其他位置(表明蛇已经撞到自己),它将返回一个小于长度减一的值。
但是,这似乎没有发生。
function Snake()
{
this.x; //x-coordinate of head
this.y; //y-coordinate of head
this.dx; //velocity in x-direction
this.dy; //velocity in y-direction
this.length; //length of snake
this.data; //stores all locations snake occupies
this.alive = 1; //is the snake alive?
this.update = function(board)
{
if (this.alive)//update head position
{
this.x += this.dx;
this.y += this.dy;
let tempCoords = [this.x,this.y];
this.data.push(tempCoords);
while (this.data.length > this.length) //janky
{
this.data = this.data.slice(1);
}
if (this.data.indexOf(tempCoords) + 1 != this.data.length) //make sure snake hasn't hit itself
{
this.alive = 0;
}
}
}
}
即使蛇与自身相交,最后的 if 语句也总是评估为 false。从我所做的测试来看,这似乎是在多维数组上使用 indexOf 的问题。这个问题有什么解决办法?
【问题讨论】:
-
indexOf()将searchElement与使用严格相等的数组元素进行比较(与===或三等号运算符使用的方法相同)。这不适用于比较数组。请注意this.data包含具有一对值的数组。
标签: javascript multidimensional-array indexof