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
- The game can be played for n x n squares.
- The games rules should be separate from the rest of the application.
My approach :
- Tic tac toe is a board game (Game object, Board object)
- Board consists of an Array of Squares (Square object)
- Squares can be marked as X or O.
- Two players play the game( Human and Computer classes implements Player interface)
- 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
- If the game is still on, the other player is given his turn.
- 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
- Does the Player need to know about the GameEngine ?
- How to pass on the control to the next player if the game is still on. (How to implement takeTurn() )
- 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.