开发者

Stackoverflow exception in java minesweeper game

开发者 https://www.devze.com 2023-03-19 12:01 出处:网络
I was trying to make a minesweeper game in Java, but I keep running into this error. This function sets the current square to clicked and any adjacent squares to be clicked and continues recursively.

I was trying to make a minesweeper game in Java, but I keep running into this error. This function sets the current square to clicked and any adjacent squares to be clicked and continues recursively. It should stop when it runs out of squares, but even when I set the field size to 2x2 with 0 mines, it overflows.

public void setCli开发者_如何学Ccked(boolean clicked){
    this.clicked = clicked;
    if(adjacentMines == 0)
        for(mine m : adjacent){
            if(!m.isClicked() && !m.isMine()){
                setClicked(true); //Should be m.setClicked(true);
            }
        }
}

Problem solved, I was missing the "m." in my method call. Thanks to everyone for your help.


You need to call setClicked on the adjacent mine, not on original mine, otherwise, you'll get setClicked(true) called over and over again for the source mine

public void setClicked(boolean clicked){
    this.clicked = clicked;
    if(adjacentMines == 0)
        for(mine m : adjacent){
            if(!m.isClicked() && !m.isMine()){
                m.setClicked(true); // setClicked should be called on the adjacent mine, not on itself!
            }
        }
}


You are calling setClicked on the same mine instead of the adjacent ones.

Change to:

public void setClicked(boolean clicked){
    this.clicked = clicked;
    if(adjacentMines == 0)
        for(mine m : adjacent){
            if(!m.isClicked() && !m.isMine()){
                //missing the "m."
                m.setClicked(true);
            }
        }
}


Well, I can only guess that setClicked() method is a member of mine, but shouldn't you be calling m.setClicked(true) inside your condition instead of just setClicked(true)?


Difficult to tell from your code snippet, but I would say you do not iterate over the cells. That means you are recursively checking the same cell over and over (to infinity and beyond woosh). The surrounding code would be very useful to see, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消