Tic Tac Toe — An Object Oriented Design

Came across some dusty old school notebooks while cleaning today. Upon opening them, I wasn’t surprised to see random games of tic-tac-toe between notes.
And so, I got my “real world thing” for today.
Noughts and Crosses
A game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner.
Let’s get crackin’
Whenever it comes to board games, the first thing that comes to mind is ways to win.
To say it in one word; strategy.
In order to win, a player will have to choose a strategy and more often than not switch to another strategy based on the opponent’s move and board setting.
How might we play this game?
- Play in an open square
- Play to an open corner
How can we stay in the game?
- Block the opponent from winning
How can we win the game?
- Place a third piece in a row to win
Based on this behaviour of the system, we can incorporate the Strategy Pattern
Strategy Design Pattern
Strategy is a behavioural design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.

- Context stories a reference to one of the concrete strategies and communicates with this object only via the strategy interface
- Strategy interface is common to all concrete strategies. It declares a method the context uses to execute a strategy.
- Concrete Strategies implement different variations of an algorithm the context uses
- Context calls the execution method on the linked strategy object each time it needs to run the algorithm and doesn’t know what type of strategy it works with or how the algorithm is executed
- Client creates a specific strategy object and passes it to the context. The context exposes a setter which lets clients replace the strategy associated with the context at runtime
Classes and Objects
The classes for our design will be:
- TicTacToeStrategy — The interface used by all strategies
- Player — The player serves as the context and executes the strategy
- Classes for concrete strategies — AnyOpenSquare, AnyOpenCorner BlockOpponent, PlayToWin
- TicTacToeBoard — Class to represent the game board state
- Position — Class to represent position of a piece

The Code
Classes to represent the game board and piece position
Strategy interface and concrete classes for various game playing strategies
Player as context with the ability to set and execute strategies
This is how this system will function
# Create a game board
board = TicTacToeBoard.new# Create player and set strategy for their first moves
player1 = Player.new(AnyOpenCorner.new)
player2 = Player.new(AnyOpenSquare.new)# Players change strategies as the game progresses
player1.strategy = AnyOpenSquare.new
player1.execute_strategy(board)# ... game continues
# player1 at the verge of winning
player2 = Player.new(BlockOpponent.new)