[英]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.