Review my design : Tic tac toe game using OO methodology

Vinoth Kumar C M picture Vinoth Kumar C M · Jul 4, 2011 · Viewed 10.5k times · Source

This was asked as an interview question.

Design a tic tac toe using object oriented principles. The interviewer said he is not interested in the logic and he wants only the design. I gave the design as below but I was not completely satisfied. Please let me know if there are any suggestions/improvements.

The interviewer was very particular about two things

  1. The game can be played for n x n squares.
  2. The games rules should be separate from the rest of the application.

My approach :

  1. Tic tac toe is a board game (Game object, Board object)
  2. Board consists of an Array of Squares (Square object)
  3. Squares can be marked as X or O.
  4. Two players play the game( Human and Computer classes implements Player interface)
  5. Once X or O is placed, the GameEngine (GameEngine object) decides if the game is over(draw or the player won) or it's still on
  6. If the game is still on, the other player is given his turn.
  7. For the Computer player , GameEngine figures out where to locate the next piece.

Rough sketch of classes.

 interface Player {
    Player takeTurn();
  void markNextBox();
  }

.

 public class TicTacToeGameEngine implements GameRule{
@Override
public Boolean isWinner(Game game) {
        // Check winner logic
        return false;
}

@Override
public Square locateSquareToMark(Game game) {
    List<Square> squares= game.getBoard().getFilledSquares();
    //go through the list of squares and figure out a square to mark
    return square;
    }
 }

.

  public class Computer implements Player {
GameRule g = new TicTacToeGameEngine();
@Override
public void markNextBox() {
    g.locateSquareToMark(game);
}
@Override
public Player takeTurn() {
    // TODO Auto-generated method stub
    return null;
}
 }

.

 public interface GameRule {
    Boolean isWinner(Game game);
    Square locateSquareToMark(Game game);
     }

//Similar implementation for Human

Now the difficulties I found in this design is

  1. Does the Player need to know about the GameEngine ?
  2. How to pass on the control to the next player if the game is still on. (How to implement takeTurn() )
  3. I initially decided that the Game object should hold the state. If you look at the Computer class, I pass the game object to the GameEngine. Is it good to do it here? I feel something better can be done about it.

Any flaws, improvements to design will be appreciated.

Answer