Search code examples
javascriptminesweeper

Minesweeper FloodFill JavaScript


Got some problems with floodfill, i don't rly understand what is wrong with it as I tried to copy some code from someone other code, it was working for him, for me not. I have got a 9x9 double dimension array as border. First i wanted to display only fields horizontally, but the code goes infinity. With one FloodFill on it works good.

    function floodFill(x, y) {

    if (y < 0) {
        console.log("left border exceeded");
        return;
    }
    if (y > 8) {
        console.log("right border exceeded");
        return;
    }
    if (numberOfBombsAdjacentToField[x][y] > 0) {
        console.log("there are bombs nearly");
        return;
    }
    if (document.getElementById(((x).toString() + (y).toString())).style.backgroundColor == "darkGray") {
        console.log("already clicked");
        return;
    }
    document.getElementById(((x).toString() + (y).toString())).style.backgroundColor = "darkGray";
    floodFill(x, y + 1);
    floodFill(x, y - 1);
}

Solution

  • Ok the problem was with the browser. Google Chrome was reading the color of DarkGray as darkgray. After i renamed it everything is fine. In addition to this i improved my code and that is the final form:

    function floodFill(x, y) {
    
        if (y < 0) {
            console.log("left border exceeded");
            return;
        }
        if (y > 8) {
            console.log("right border exceeded");
            return;
        }
        if (x < 0) {
            console.log("top border exceeded");
            return;
        }
        if (x > 8) {
            console.log("bottom border exceeded");
            return;
        }
        if (board[x][y]) {
            console.log("bomb!");
            return;
        }
        if (document.getElementById(((x).toString() + (y).toString())).style.backgroundColor == "darkgray") {
            console.log("already clicked");
            return;
        }
        if (numberOfBombsAdjacentToField[x][y] > 0) {
            var divToChange = document.getElementById((x.toString() + y.toString()));
            divToChange.innerHTML = numberOfBombsAdjacentToField[x][y].toString();
            divToChange.style.backgroundColor = "darkGray";
            return;
        }
        else {
            document.getElementById(((x).toString() + (y).toString())).style.backgroundColor = "darkGray";
            document.getElementById(((x).toString() + (y).toString())).innerHTML = "";
        }
        floodFill(x, y - 1);
        floodFill(x, y + 1);
        floodFill(x + 1, y);
        floodFill(x - 1, y);
        floodFill(x - 1, y - 1);
        floodFill(x - 1, y + 1);
        floodFill(x + 1, y - 1);
        floodFill(x + 1, y + 1);
    }