Javascript对象更改行间值
我正在创建一个Snake游戏(就像旧手机上的游戏一样)。我在下面有一段代码,它似乎显示了一个对象在各行之间改变其值的怪异行为。Javascript对象更改行间值
函数makeSnakeArray
在游戏开始时或当蛇自身触及(游戏重新开始)时被调用。它返回一个新的蛇,它是一个x
和y
属性的对象数组,存储在全局变量snakeArray
中。
第一次被调用时,一切正常。但是,当它被称为重新启动游戏时,x
和y
值在consoleLog1
和consoleLog2
(请参阅代码注释)中有所不同。
在consoleLog1
中,x
和y
的值与我在函数中计算的一样。但是,在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
我用开发工具调试了你的代码,并且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");
}
}
为了避免所有的蛇体操纵
你是对的!非常感谢你!我没有意识到在调用'restartSnakeGame()'之后,它会回到'updateSnake()'函数并继续进行蛇体操作。感谢所有的麻烦! :) –
这似乎是全球位置不正确复位,蛇似乎继续在那里。 –
你是什么意思,我该如何重置全球职位? –
对不起,我的意思是你的全球蛇阵列 –