package tictactoe; public class Game implements GameInterface { private static final int XCHAR = 'X'; private static final int OCHAR = 'O'; private static final int EMPTYCHAR = ' '; private static final int DRAWCHAR = 'D'; private static final int BADCHAR = '!'; private int boardSize; private char[][] board; private UserInterface userX = null; private UserInterface userO = null; private UserInterface playerToMove = null; private char charToMove = XCHAR; private char winner = EMPTYCHAR; public Game(int boardSize) { this.boardSize = boardSize; board = new char[boardSize][boardSize]; for (int i = 0; i < boardSize; i++) for (int j = 0; j < boardSize; j++) board[i][j] = ' '; } // Tell userX to make a move public void startGame() { playerToMove = userX; userX.boardChanged(getBoardCopy()); userO.boardChanged(getBoardCopy()); userX.makeAMove(); } // return true on success, false on failure public void move(int row, int col, UserInterface user) { char[][] boardCopy; if (user != playerToMove) { user.inform("Sorry, it is not your move, wait for the other player ..."); return; } if (winner != EMPTYCHAR) { user.inform("The game is over, you must start another game"); return; } if (row < 0 || row >= boardSize || col < 0 || col >= boardSize || board[row][col] != EMPTYCHAR) { playerToMove.inform("Please try again to make a valid move:"); playerToMove.makeAMove(); return; } board[row][col] = charToMove; if (user == userX) { playerToMove = userO; charToMove = OCHAR; } else { playerToMove = userX; charToMove = XCHAR; } setWinner(); boardCopy = getBoardCopy(); userX.boardChanged(boardCopy); userO.boardChanged(boardCopy); if (winner == EMPTYCHAR) { playerToMove.inform(charToMove + ": Please make a move:"); playerToMove.makeAMove(); } else if (winner == XCHAR) { userX.inform("X won! Congratulations!"); userO.inform("X won, better luck next time!"); } else if (winner == OCHAR) { userO.inform("O won! Congratulations"); userX.inform("O won, better luck next time!"); } else { userX.inform("The game is a draw!"); userO.inform("The game is a draw!"); } return; } //inform the game of this user and find out if this s X or O public void joinGame(UserInterface user) { if (userX == null) { userX = user; user.setId((char)XCHAR); } else if (userO == null) { userO = user; user.setId((char)OCHAR); startGame(); } } private char[][] getBoardCopy() { char[][] copy = new char[boardSize][boardSize]; for (int i=0;i