mardi 27 février 2018

JavaScript If-Statement Proved True But Outputs False

I am learning JavaScript by programming my first game (a simple laser-mirror-type game). The game operates in a grid and I want to determine if a cell holds an obstacle or not. So I call this function:

function updateGrid () {
for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
            for (let o = 0; o < obstacles.length; o++) {
                if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
                    grid[i][j].obstacle = true;
                } else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
                    //grid[i][j].obstacle = false;
                }
            }
            for (let m = mirrors.length - 1; m >= 0; m--) {
                if (grid[i][j].x + cellOffset.x== mirrors[m].x && grid[i][j].y + cellOffset.y == mirrors[m].y) {
                    grid[i][j].mirror = true;
                } else {
                    grid[i][j].mirror = false;
                }
            }
            if (grid[i][j].x + cellOffset.x == target.x && grid[i][j].y + cellOffset.y == target.y) {
                grid[i][j].target = true;
            } else {
                grid[i][j].target = false;
            }
            if (grid[i][j].x == laserPen.x && grid[i][j].y + (rowH / 2) - (cellOffset.y / 4) == laserPen.y) {
                grid[i][j].pen = true;
            } else {
                grid[i][j].pen = false;
            }
        }
    }
}

However the if-statement that determines if the cell contains an obstacle, seems to not work.

This works (sets grid[ i ][ j ].obstacle to true):

for (let o = 0; o < obstacles.length; o++) {
    if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
            grid[i][j].obstacle = true;
    } else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
        //grid[i][j].obstacle = false;
    }
}

This does not (sets grid[ i ][ j ].obstacle to false):

for (let o = 0; o < obstacles.length; o++) {
    if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
            grid[i][j].obstacle = true;
    } else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
        grid[i][j].obstacle = false;
    }
}

I actually added the else-if just for safety, but it failed to work with a simple else-statement as well.

I am using the p5.js library and any insight into what is happening here would be greatly appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire