它的缺点是,我试图创建一个Snake JS实现。为了完成游戏的“弯曲”部分,我选择使用“转折点”来跟踪蛇的何时需要改变路线。为了跟踪点和方向,我使用了一个叫做turnPoint的对象:南/未定义的数字属性
var turnPoint = {x: 0, y: 0, direction: 0};
这是我正在开始编程的一门课。不知道为什么添加turnPoint.x和turnPoint.y会引发未定义的异常。当我用Number()函数包装时,我得到了一个Nan。这是一个原型问题吗?
完整的源代码是在以上GitHub
var turns = new Array();
function move(key){
if(lastKeyPressed == null){
lastKeyPressed = currentKey;
}
var delta = moveRate;
if(currentKey == leftArrow || currentKey == upArrow){
delta *= -1;
}
//only change direction if the key isn't the same, and not the opposite key up vs down, left vs right
if(currentKey != lastKeyPressed && Math.abs(lastKeyPressed-currentKey) != 2){
//lets create a container to hold the turning point
var turnPoint = {x: 0, y: 0, direction: 0};
if(lastKeyPressed == leftArrow || currentKey == leftArrow) //from left, going up or down
{
turnPoint = {x: Number(snakePoints[0]), y: Number(snakePoints[1]), direction: currentKey};
}else if(lastKeyPressed == rightArrow || currentKey == rightArrow)
{
turnPoint = {x: Number(snakePoints[2]), y: Number(snakePoints[3]), direction:currentKey};
}
if(turnPoint != null){
turns.push(turnPoint);
console.log(turns);
}
}
if(currentKey == leftArrow){
snakePoints[0] += delta;
}else if(currentKey == rightArrow){
snakePoints[2] += delta;
}else if(currentKey == upArrow){
snakePoints[1] += delta;
}else{
snakePoints[3] += delta;
}
var newLine = new Array();
newLine.push(snakePoints[0]);
newLine.push(snakePoints[1]);
for(var turn in turns){
newLine.push(Number(turn.x));
newLine.push(Number(turn.y));
}
newLine.push(snakePoints[2]);
newLine.push(snakePoints[3]);
console.log(newLine);
lastKeyPressed = currentKey;
snake.setPoints(newLine);
drawGame();
}
为了澄清,术语JSON确实不适合这一点。这只是一个对象。 – Pointy
没错,但是对象的语法是符合JSON的吗? –
另外你还没有说明你到底发生了什么异常。如果你的一位初级程序设计专业的学生来找你说“我有个例外”,那么这不就是你问的第一件事吗? – Pointy