Design Tic-Tac-Toe
Explore how to design a TicTacToe game struct that supports moves and winning conditions on an n by n board. Learn to track game state effectively, handle player moves, and determine the winner through horizontal, vertical, and diagonal checks. This lesson helps you implement game logic critical for coding interviews.
We'll cover the following...
Statement
Suppose that two players are playing a tic-tac-toe game on an board. They’re following specific rules to play and win the game:
- A move is guaranteed to be valid if a mark is placed on an empty block.
- No more moves are allowed once a winning condition is reached.
- A player who succeeds in placing of their marks in a horizontal, vertical, or diagonal row wins the game.
Implement a TicTacToe struct, which will be used by two players to play the game and win fairly.
Keep in mind the following functionalities that need to be implemented:
- NewTicTacToe(), initializes an object of
TicTacToe, allowing the players to play on a board of size . - move(row, col, player) indicates that the player with the ID,
player, places their mark on the cell (row,col). The move is guaranteed to be a valid move. At each move, this function returns the player ID if the current player wins and returns if no one wins.
Constraints:
-
-
playershould be either1or2. -
row,col -
Every call to
move()will be with a uniquerow,colcombination. -
The
move()function will be called at most times.
Examples
Understanding the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:
Design Tic-Tac-Toe
We are given the current state of a game on a board, showing the moves made so far, where Player 1’s moves are denoted by a cross, and Player 2’s moves are denoted by a circle.
The following moves are now made by the players:
move(0, 2, 2)
move(1, 0, 1)
What would the result be?
Player 1 wins the game.
Player 2 wins the game.
No one wins the game.
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: This puzzle relates only to the function,
move(). The data structures that are set up in the constructor,NewTicTacToe, have been mentioned in the first card.
Try it yourself
Implement your solution in the following coding playground.
package maintype TicTacToe struct {// Write your code here}// Constructor will be used to initialize TicTacToe data membersfunc (this *TicTacToe) NewTicTacToe(n int) {// Write your code here}// move will be used to play a move by a specific player and identify who// wins at each movefunc (this *TicTacToe) move(row int, col int, player int) int {// Replace this placeholder return statement with your codereturn -1}