2013-07-18 106 views
0

它的缺点是,我试图创建一个Snake JS实现。为了完成游戏的“弯曲”部分,我选择使用“转折点”来跟踪蛇的何时需要改变路线。为了跟踪点和方向,我使用了一个叫做turnPoint的对象:南/未定义的数字属性

var turnPoint = {x: 0, y: 0, direction: 0}; 

这是我正在开始编程的一门课。不知道为什么添加turnPoint.x和turnPoint.y会引发未定义的异常。当我用Number()函数包装时,我得到了一个N​​an。这是一个原型问题吗?

完整的源代码是在以上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(); 
} 
+3

为了澄清,术语JSON确实不适合这一点。这只是一个对象。 – Pointy

+0

没错,但是对象的语法是符合JSON的吗? –

+0

另外你还没有说明你到底发生了什么异常。如果你的一位初级程序设计专业的学生来找你说“我有个例外”,那么这不就是你问的第一件事吗? – Pointy

回答

3
for(var turn in turns){ 
    newLine.push(Number(turn.x)); 
    newLine.push(Number(turn.y)); 
} 

在JavaScript中,通过属性一个for ... in循环迭代名对象的,不财产。

for (var i = 0; i < turns.length; ++i) { 
    newLine.push(Number(turns[i].x)); 
    newLine.push(Number(turns[i].y)); 
} 

你真的不应该对阵列使用for ... in,除非你真的知道你需要做的。

+0

我不知道。我从Java编程中猜测到的坏习惯。 –

+0

@roguequery除了肤浅之外,Java和JavaScript几乎完全不同。 – Pointy