javascript函数的第二部分没有运行?

时间:2017-06-24 20:41:09

标签: javascript

function blocksLogic(){

if(gameRunning == 0){
    var blocks = new Array(7);
    for(var i=0; i <7; i++){
        blocks[i] = new Array(7);
    }
    for(var x=0; x < 7; x++){
        for(var y=0; y < 7; y++){
            blocks[x][y] = false;
            console.log(blocks[x][y]);
        }
    }
}
console.log("gamerunning function ran");
// COLLISION!!!!!!!
for(var brickX = 0; x < 7; x++){
    console.log("for x has been run!");
    for( var brickY = 0; y < 7; y++){
            console.log("for y has been run!");
            var tempBrickX = brickX * 105 + 34;
            var tempBrickY = brickY * 25 - 10;
            //top collision
        if(ballY >= tempBrickX && ballX >= tempBrickX && ballX <= tempBrickX + BRICK_WIDTH){
            console.log("The top of this block has been hit!");
            ballSpeedX = -ballSpeedX;
            ballSpeedY = -ballSpeedY;
        }
            //bottom collision
        if(ballY <= tempBrickY + BRICK_HEIGHT && ballX >= tempBrickX  && ballX >= tempBrickX){
            console.log("The bottom of this brick has been hit!");
            ballSpeedX = -ballSpeedX;
            ballSpeedY = -ballSpeedY;
        }       
    }
}

https://pastebin.com/t2Zq79BG

功能blocksLogic没有运行注释“// COLLISION!”下面的代码。 它可能是非常简单但我刚刚开始用javascript进行编码(这就是为什么我的代码格式很糟糕) 我添加了很多调试console.logs来查看正在运行的内容和什么不是。

2 个答案:

答案 0 :(得分:2)

for(var brickX = 0; x < 7; x++)

x在此处未定义,这就是循环永远不会运行的原因(这看起来像是上面的复制粘贴错误)。确保使用brickX:

for(var brickX = 0; brickX < 7; brickX++)

答案 1 :(得分:1)

检查里面的变量for循环。为什么要声明brickX,然后检查x?改为

for(var x = 0; x < 7; x++){
console.log("for x has been run!");
for( var y = 0; y < 7; y++){
        console.log("for y has been run!");
        var tempBrickX = x * 105 + 34;
        var tempBrickY = y * 25 - 10;
        //top collision
    if(ballY >= tempBrickX && ballX >= tempBrickX && ballX <= tempBrickX + BRICK_WIDTH){
        console.log("The top of this block has been hit!");
        ballSpeedX = -ballSpeedX;
        ballSpeedY = -ballSpeedY;
    }
        //bottom collision
    if(ballY <= tempBrickY + BRICK_HEIGHT && ballX >= tempBrickX  && ballX >= tempBrickX){
        console.log("The bottom of this brick has been hit!");
        ballSpeedX = -ballSpeedX;
        ballSpeedY = -ballSpeedY;
    }       
}

}