【问题标题】:How can I unshift an array into each property of an object?如何将数组转换为对象的每个属性?
【发布时间】:2016-02-22 05:27:09
【问题描述】:

我正在尝试制作一个简单的蛇游戏,但不是在蛇吃一块食物时添加一个块,而是添加多个块。我正在处理一些示例代码。原代码使用unshift()方法将蛇的尾块放在蛇的头部。

tail = {x: head_x , y: head_y};

snake_array.unshift(tail);

对象尾部被移动到snake_array 中,以将新的x 和y 坐标添加到snake 的前面。我想将两个 x 值和两个 y 值移到蛇数组中,这样蛇每次吃食物时都会增长两个单位。我以为我可以为每个“尾巴”对象属性使用一个数组,但每次我这样做时,蛇都会消失在遗忘中。

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

【问题讨论】:

  • 为什么不连接数组而不是取消所有内容?
  • 您发布的代码似乎没问题。您是否在 unshift 后调试并打印了数组,例如 console.log(JSON.stringify(snake_array));?这种调试习惯对于确定问题发生的何处至关重要。我认为它在您的代码中的其他地方。
  • 我不能使用 concat() 方法,因为我的语句的 else 部分需要一个方向条件。在其他部分,我将弹出蛇的尾端,然后将其移至蛇的开头。打印控制台是一个很好的提示,谢谢!我发现当调用 unshift 方法时,我将一个数组插入到对象参数中:"[{'x':[2,1],'y':[10,10]},{'x':0,'y':10},{'x':0,'y':9},....等等所以我所做的就是将上面的代码更改为以下代码:if (d == "right") tail = [{x: nx+1 , y: ny},{x: nx , y: ny}];跨度>
  • 这样做的问题是我开始为 x 参数获取空值,这很奇怪。

标签: javascript arrays


【解决方案1】:

所以正如我在 cmets 中描述的那样,问题中的代码不起作用,因为数组没有正确转换为蛇数组。相反,我创建了一个名为“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
}

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2012-09-18
    相关资源
    最近更新 更多