[英]How can I unshift an array into each property of an object?
我正在尝试制作一个简单的蛇游戏,但不是在蛇吃一块食物时在蛇上添加一个积木,而是添加了多个积木。 我正在处理一些示例代码。 原始代码使用unshift()方法将蛇的尾巴放置在蛇的头部。
tail = {x: head_x , y: head_y};
snake_array.unshift(tail);
对象的尾部将移到snake_array中,以将新的x和y坐标添加到蛇的前面。 我想将两个x值和两个y值移入snake_array中,以使蛇在每次食用食物时增长两个单位。 我以为我可以为每个“尾巴”对象属性使用一个数组,但是每次我这样做时,蛇都会消失。
if(head_x == food.x && head_y == food.y){
if (direction == "right") var tail = {x: [head_x+1,head_x] , y: [head_y,head_y]};
snake_array.unshift(tail);
我不明白为什么会这样,我无法取消对象参数中的数组移动吗?
这是我的完整代码,为了方便阅读,我将head_x更改为nx,将head_y更改为ny。 我只关注蛇在此刻向左移动的情况,一旦我了解了unshift方法的工作原理,便可以确定其他方向。
if(nx == food.x && ny == food.y){
var tail;
if (d == "right") tail = {x: [nx+1,nx] , y: [ny,ny]}; //incremented to get new head position
else if(d == "left") tail = {x: nx-1,y: ny};
else if(d == "up") tail = {x: nx,y: ny-1};
else if(d == "down") tail = {x: nx,y: ny+1};
//Create new food
score++;
create_food();
}
else{
var tail = snake_array.pop();//pops out last cell
tail = {x: nx,y: ny};
}
snake_array.unshift(tail); //Puts back the tail as the first cell
因此,正如我在评论中所述,问题中的代码不起作用,因为该数组未正确转换为snake_array。 相反,我创建了一个称为“ tail”的1x2数组,每个索引都包含对象的各个属性及其值。 然后,我使用了MinusFour推荐的concat()方法。 我还将unshift()方法移至if语句的else部分。 我计划清理代码,以便如果我想在每种食物中添加5个块或10个块,则可以使用for循环轻松实现。 感谢Trincot指出如何使用控制台进行打印。
if (nx == food.x && ny == food.y) {
if (d == "right") tail = [{x: nx+1,y: ny},{x: nx,y: ny}];
else if (d == "left") tail = [{x: nx - 1,y: ny},{x: nx,y: ny}];
else if (d == "up") tail = [{x: nx,y: ny - 1},{x: nx,y: ny}];
else if (d == "down") tail = [{x: nx,y: ny + 1},{x: nx,y: ny}];
//Create new food
create_food();
snake_array = tail.concat(snake_array);
} else {
var tail = snake_array.pop(); //pops out last cell
tail = {x: nx,y: ny};
console.log(JSON.stringify(tail));
snake_array.unshift(tail); //Puts back the tail as the first cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.