0

我正在创建一个Snake游戏(就像旧手机上的游戏一样)。我在下面有一段代码,它似乎显示了一个对象在各行之间改变其值的怪异行为。Javascript对象更改行间值

函数makeSnakeArray在游戏开始时或当蛇自身触及(游戏重新开始)时被调用。它返回一个新的蛇,它是一个xy属性的对象数组,存储在全局变量snakeArray中。

第一次被调用时,一切正常。但是,当它被称为重新启动游戏时,xy值在consoleLog1consoleLog2(请参阅代码注释)中有所不同。

consoleLog1中,xy的值与我在函数中计算的一样。但是,在consoleLog2中,tempArray会打印出snakeArray在要求重新启动游戏时的情况(并且在调用makeSnakeArray函数之前,我确定通过设置snakeArray = [];来清除snakeArray)。结果,蛇不像第一次那样在屏幕中间开始,但它似乎继续在它离开的地方。

为什么会发生这种情况?

功能:

function makeSnakeArray(){ 
    var tempArray = []; 

    //Get the position of the head of the snake 
    var halfWidth = Math.floor(canvasWidth/2) * blockSize; 
    var halfHeight = Math.floor(canvasHeight/2) * blockSize; 

    //Add in each block of the snake to the snake array, starting with the head 
    for (var i = 0; i < startingSnakeLength; i++){ 

    //Create and initialize the snakeBlock 
    var snakeBlock = { 
     x: halfWidth, 
     y: halfHeight + (i*blockSize), 
    } 

    console.log(snakeBlock); //consoleLog1 
    tempArray.push(snakeBlock); 
    } 

    console.log(tempArray);//consoleLog2 
    return tempArray; 
} 

输出示例:

consoleLog1

{x: 180, y: 180} 
{x: 180, y: 195} 
{x: 180, y: 210} 
{x: 180, y: 225} 
{x: 180, y: 240} 

consoleLog2

0:{x: 60, y: 270} 
1:{x: 60, y: 285} 
2:{x: 60, y: 300} 
3:{x: 60, y: 315} 
4:{x: 60, y: 330} 

这里是当前VERSI如果你想看到完整的代码:https://codepen.io/vrsivananda/pen/NvJyGJ?editors=0010

+0

这似乎是全球位置不正确复位,蛇似乎继续在那里。 –

+0

你是什么意思,我该如何重置全球职位? –

+0

对不起,我的意思是你的全球蛇阵列 –

回答

0

我用开发工具调试了你的代码,并且makeSnakeArray()函数似乎工作的很好。问题在于updateSnake()函数。

//Push this into the front of the snakeArray 
    snakeArray.unshift(newHead); 

    //If the head is the same place as the apple, then get a new apple and do not pop the tail off the snake 
    if(newHead.x == apple.x && newHead.y == apple.y){ 
    apple = placeRandomApple(); 
    } 
    else{ 
    //Delete the tail fo the snakeArray 
    snakeArray.pop(); 
    } 
    //Redraw the canvas 
    drawCanvas(); 

在这部分你不应该用新的头部更新蛇,如果你知道游戏刚刚重新启动。另外你也不应该在这种情况下切断尾巴。

最简单的事情将只是把一个return语句,你知道后,那场比赛中得到了重新启动:

for (var i = 0; i < snakeArray.length; i++){ 
    //If it is, restart the game 
    if(newHead.x == snakeArray[i].x && newHead.y == snakeArray[i].y){ 
     restartSnakeGame(); 
     return; 
     console.log("restarting"); 
    } 
    } 

为了避免所有的蛇体操纵

+1

你是对的!非常感谢你!我没有意识到在调用'restartSnakeGame()'之后,它会回到'updateSnake()'函数并继续进行蛇体操作。感谢所有的麻烦! :) –