0

简而言之,我正在尝试创建一个 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();
}
4

1 回答 1

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在数组上使用,除非你真的知道你需要这样做。

于 2013-07-18T01:20:13.250 回答