Search code examples
javaalgorithmtic-tac-toe

TicTacToe suggested move


Things which cannot be changed:

enum CellLocation{TOP_LEFT,TOP_CENTER,TOP_RIGHT,CENTRE_LEFT, .. and so on}
enum CellState{OCCUPIED_BY_X,OCCUPIED_BY_O,EMPTY}

A gameboard interface, which only contain one method:

CellState getCellState(CellLocation cellLocation);

A Consultant interface, which also contain one method:

CellLocation suggest(GameBoard gameBoard);

My job is to create a class which implements the consultant interface and overwrite the given suggest method(the method also have to decide which player is the next -> the Cellocation output must have EMPTY state )

So, my problem is that I am not sure how to start. I was thinking about to create a temporary map inside the suggest method, and fill all the data, like this:

HashMap<CellLocation, CellState> temporaryBoard = new HashMap<>();

temporaryBoard.put(CellLocation.TOP_LEFT,gameBoard.getCellState(CellLocation.TOP_LEFT));
temporaryBoard.put(CellLocation.TOP_CENTRE,gameBoard.getCellState(CellLocation.TOP_CENTRE));
temporaryBoard.put(CellLocation.TOP_RIGHT,gameBoard.getCellState(CellLocation.TOP_RIGHT));
temporaryBoard.put(CellLocation.CENTRE_LEFT,gameBoard.getCellState(CellLocation.CENTRE_LEFT));
temporaryBoard.put(CellLocation.CENTRE_CENTRE,gameBoard.getCellState(CellLocation.CENTRE_CENTRE));
temporaryBoard.put(CellLocation.CENTRE_RIGHT,gameBoard.getCellState(CellLocation.CENTRE_RIGHT));
temporaryBoard.put(CellLocation.BOTTOM_LEFT,gameBoard.getCellState(CellLocation.BOTTOM_LEFT));
temporaryBoard.put(CellLocation.BOTTOM_CENTRE,gameBoard.getCellState(CellLocation.BOTTOM_CENTRE));
temporaryBoard.put(CellLocation.BOTTOM_RIGHT,gameBoard.getCellState(CellLocation.BOTTOM_RIGHT));

so I can easily operate with it. I am not sure that I should make a temporary gameboard for myself or not.

Any idea would be appreciated.


Solution

  • It is not totally clear from the question, but if the implementation is required to suggest a best possible move, this can be done with the Minimax algorithm, which aims at performing a possible move (thus creating a board with less possible moves for the other player) and recusively searches the game tree until a leaf is found. A leaf is then conceptually assigned a value of 1 (victory of player one), 0 (draw game) or -1 (victory of player two). For a non-leaf node, the value of a certain move is the maximum (or minimum, depending on which player's move it is) of its values. This definition is evaluated recursively; the algorithm would then suggest a move with maximum or minimum value.