I am writing a GUI game, and I want to wait for the game to finish, before returning the winner. However, since my Game manager class is separate from the class used to implement the game logic and detect a win, I want to know how I can make the game manager wait until the other class notifies it of a win, and then proceed to do other stuff. I have not really worked much with multithreading before, so I'm hoping someone could explain how I might achieve this.
Here is some relevant code from the GameManager class' main that I've tried:
...
Game game = new Game(mode);
String winner = game.getWinner();
...
And from the Game class:
public Game(Game.Mode mode){
this.board = new Board(7);
window = new BoardFrame(7, 7, mode, board); //Graphical interface
window.setVisible(true);
}
public String getWinner(){
synchronized(board.WINNER){
try {
board.WINNER.wait();
} catch (InterruptedException e) {}
}
return board.WINNER;
}
And the Board class:
public boolean update(int num){
if (isValidMove(CurrentPlayer, num)){
buttonClients.get(positions.get(CurrentPlayer)).clear();
positions.put(CurrentPlayer, num);
board[num] = 1;
buttonClients.get(num).performCallback(CurrentPlayer);
if ((WINNER = isGameFinished())!=""){
//Disable all further inputs
for (int i = 0; i<board.length; i++){
board[i] = 1;
}
synchronized (WINNER) {
WINNER.notify();
}
}
CurrentPlayer = (CurrentPlayer==PLAYER1)?PLAYER2:PLAYER1;
return true;
}
return false;
}
EDIT: So I have found the cause of the screen display issue, which is that all my code for the GameManager was in an EventQueue.invokeLater()
block. I have taken it out of that block for now, and the screen is displaying properly now. However, when I play until the end, and the synchronized(WINNER)
block is finally run, it seems like nothing happens? In other words, the game continues waiting on WINNER
.