Tic Tac Toe also known as Noughts and Crosses is a two-player paper-and-pencil game. Each player takes turns marking either an “X” or an “O” in one of the nine squares on a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical or diagonal row is the winner.
If all nine squares are filled and neither player has three in a row, the game is considered a draw. The game is simple yet can be challenging as each player tries to outsmart the other and get three in a row.
C++ Program to create a Tic Tac Toe Game
Now, Let’s look at the code below.
#include <iostream>
#include <string>
#include <array>
constexpr int kBoardSize = 3;
// Function to draw the board
void DrawBoard(const std::array<std::array<char, kBoardSize>, kBoardSize>& board) {
std::cout << "Tic Tac Toe\n\n";
for (int i = 0; i < kBoardSize; ++i) {
for (int j = 0; j < kBoardSize; ++j) {
std::cout << board[i][j] << " ";
}
std::cout << '\n';
}
std::cout << '\n';
}
// Function to check if the board is full
bool IsBoardFull(const std::array<std::array<char, kBoardSize>, kBoardSize>& board) {
for (int i = 0; i < kBoardSize; ++i) {
for (int j = 0; j < kBoardSize; ++j) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
// Function to check if a player has won
bool HasWon(const std::array<std::array<char, kBoardSize>, kBoardSize>& board, char player) {
// Check rows
for (int i = 0; i < kBoardSize; ++i) {
bool row_win = true;
for (int j = 0; j < kBoardSize; ++j) {
if (board[i][j] != player) {
row_win = false;
break;
}
}
if (row_win) {
return true;
}
}
// Check columns
for (int j = 0; j < kBoardSize; ++j) {
bool col_win = true;
for (int i = 0; i < kBoardSize; ++i) {
if (board[i][j] != player) {
col_win = false;
break;
}
}
if (col_win) {
return true;
}
}
// Check diagonal (top-left to bottom-right)
bool diag_win = true;
for (int i = 0; i < kBoardSize; ++i) {
if (board[i][i] != player) {
diag_win = false;
break;
}
}
if (diag_win) {
return true;
}
// Check diagonal (top-right to bottom-left)
diag_win = true;
for (int i = 0; i < kBoardSize; ++i) {
if (board[i][kBoardSize - i - 1] != player) {
diag_win = false;
break;
}
}
if (diag_win) {
return true;
}
return false;
}
DrawBoard: This function takes a 2D array of characters representing the Tic Tac Toe board and outputs it to the console.
IsBoardFull: This function takes a 2D array of characters representing the Tic Tac Toe board and returns true if all the squares are filled and false otherwise.
HasWon: This function takes a 2D array of characters representing the Tic Tac Toe board and a character representing a player (‘X’ or ‘O’) and returns true if the player has won and false otherwise.
The game board is represented as a 2D array of characters, with each square either filled with an ‘X’, ‘O’, or a space character representing an empty square. The functions check various win conditions (rows, columns, diagonals) to determine if a player has won.