Implementation of TicTacToe game (original) (raw)

Implementation of Tic-Tac-Toe game

Last Updated : 23 Jul, 2025

C++ `

#include #include #include

using namespace std;

// Set up the game board as an array vector board = {"-", "-", "-", "-", "-", "-", "-", "-", "-"};

// Define a function to print the game board void printBoard() { cout << board[0] << " | " << board[1] << " | " << board[2] << endl; cout << board[3] << " | " << board[4] << " | " << board[5] << endl; cout << board[6] << " | " << board[7] << " | " << board[8] << endl; }

// Define a function to handle a player's turn void takeTurn(string player) { cout << player << "'s turn." << endl; cout << "Choose a position from 1-9: "; int position; cin >> position; position -= 1; while (position < 0 || position > 8 || board[position] != "-") { cout << "Invalid input or position already taken. Choose a different position: "; cin >> position; position -= 1; } board[position] = player; printBoard(); }

// Define a function to check if the game is over string checkGameOver() { // Check for a win if ((board[0] == board[1] && board[1] == board[2] && board[0] != "-") || (board[3] == board[4] && board[4] == board[5] && board[3] != "-") || (board[6] == board[7] && board[7] == board[8] && board[6] != "-") || (board[0] == board[3] && board[3] == board[6] && board[0] != "-") || (board[1] == board[4] && board[4] == board[7] && board[1] != "-") || (board[2] == board[5] && board[5] == board[8] && board[2] != "-") || (board[0] == board[4] && board[4] == board[8] && board[0] != "-") || (board[2] == board[4] && board[4] == board[6] && board[2] != "-")) { return "win"; } // Check for a tie else if (count(board.begin(), board.end(), "-") == 0) { return "tie"; } // Game is not over else { return "play"; } }

// Define the main game loop int main() { printBoard(); string currentPlayer = "X"; bool gameOver = false; while (!gameOver) { takeTurn(currentPlayer); string gameResult = checkGameOver(); if (gameResult == "win") { cout << currentPlayer << " wins!" << endl; gameOver = true; } else if (gameResult == "tie") { cout << "It's a tie!" << endl; gameOver = true; } else { // Switch to the other player currentPlayer = currentPlayer == "X" ? "O" : "X"; } } return 0; }

Java

import java.util.Scanner;

public class TicTacToe { // Set up the game board as an array static String[] board = {"-", "-", "-", "-", "-", "-", "-", "-", "-"};

// Define a function to print the game board
static void printBoard() {
    System.out.println(board[0] + " | " + board[1] + " | " + board[2]);
    System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
    System.out.println(board[6] + " | " + board[7] + " | " + board[8]);
}

// Define a function to handle a player's turn
static void takeTurn(String player) {
    Scanner scanner = new Scanner(System.in);
    System.out.println(player + "'s turn.");
    System.out.print("Choose a position from 1-9: ");
    int position = scanner.nextInt() - 1;
    while (position < 0 || position > 8 || !board[position].equals("-")) {
        System.out.print("Invalid input or position already taken. Choose a different position: ");
        position = scanner.nextInt() - 1;
    }
    board[position] = player;
    printBoard();
}

// Define a function to check if the game is over
static String checkGameOver() {
    // Check for a win
    if ((board[0].equals(board[1]) && board[1].equals(board[2]) && !board[0].equals("-")) ||
            (board[3].equals(board[4]) && board[4].equals(board[5]) && !board[3].equals("-")) ||
            (board[6].equals(board[7]) && board[7].equals(board[8]) && !board[6].equals("-")) ||
            (board[0].equals(board[3]) && board[3].equals(board[6]) && !board[0].equals("-")) ||
            (board[1].equals(board[4]) && board[4].equals(board[7]) && !board[1].equals("-")) ||
            (board[2].equals(board[5]) && board[5].equals(board[8]) && !board[2].equals("-")) ||
            (board[0].equals(board[4]) && board[4].equals(board[8]) && !board[0].equals("-")) ||
            (board[2].equals(board[4]) && board[4].equals(board[6]) && !board[2].equals("-"))) {
        return "win";
    }
    // Check for a tie
    else if (!String.join("", board).contains("-")) {
        return "tie";
    }
    // Game is not over
    else {
        return "play";
    }
}

// Define the main game loop
public static void main(String[] args) {
    printBoard();
    String currentPlayer = "X";
    boolean gameOver = false;
    while (!gameOver) {
        takeTurn(currentPlayer);
        String gameResult = checkGameOver();
        if (gameResult.equals("win")) {
            System.out.println(currentPlayer + " wins!");
            gameOver = true;
        } else if (gameResult.equals("tie")) {
            System.out.println("It's a tie!");
            gameOver = true;
        } else {
            // Switch to the other player
            currentPlayer = currentPlayer.equals("X") ? "O" : "X";
        }
    }
}

}

Python

Set up the game board as a list

board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]

Define a function to print the game board

def print_board(): print(board[0] + " | " + board[1] + " | " + board[2]) print(board[3] + " | " + board[4] + " | " + board[5]) print(board[6] + " | " + board[7] + " | " + board[8])

Define a function to handle a player's turn

def take_turn(player): print(player + "'s turn.") position = input("Choose a position from 1-9: ") while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]: position = input("Invalid input. Choose a position from 1-9: ") position = int(position) - 1 while board[position] != "-": position = int(input("Position already taken. Choose a different position: ")) - 1 board[position] = player print_board()

Define a function to check if the game is over

def check_game_over(): # Check for a win if (board[0] == board[1] == board[2] != "-") or
(board[3] == board[4] == board[5] != "-") or
(board[6] == board[7] == board[8] != "-") or
(board[0] == board[3] == board[6] != "-") or
(board[1] == board[4] == board[7] != "-") or
(board[2] == board[5] == board[8] != "-") or
(board[0] == board[4] == board[8] != "-") or
(board[2] == board[4] == board[6] != "-"): return "win" # Check for a tie elif "-" not in board: return "tie" # Game is not over else: return "play"

Define the main game loop

def play_game(): print_board() current_player = "X" game_over = False while not game_over: take_turn(current_player) game_result = check_game_over() if game_result == "win": print(current_player + " wins!") game_over = True elif game_result == "tie": print("It's a tie!") game_over = True else: # Switch to the other player current_player = "O" if current_player == "X" else "X"

Start the game

play_game()

` JavaScript ``

// Set up the game board as an array let board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"];

// Define a function to print the game board function printBoard() { console.log(${board[0]} | <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>b</mi><mi>o</mi><mi>a</mi><mi>r</mi><mi>d</mi><mo stretchy="false">[</mo><mn>1</mn><mo stretchy="false">]</mo></mrow><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">{board[1]} | </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mopen">[</span><span class="mord">1</span><span class="mclose">]</span></span><span class="mord">∣</span></span></span></span>{board[2]}); console.log(${board[3]} | <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>b</mi><mi>o</mi><mi>a</mi><mi>r</mi><mi>d</mi><mo stretchy="false">[</mo><mn>4</mn><mo stretchy="false">]</mo></mrow><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">{board[4]} | </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mopen">[</span><span class="mord">4</span><span class="mclose">]</span></span><span class="mord">∣</span></span></span></span>{board[5]}); console.log(${board[6]} | <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>b</mi><mi>o</mi><mi>a</mi><mi>r</mi><mi>d</mi><mo stretchy="false">[</mo><mn>7</mn><mo stretchy="false">]</mo></mrow><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">{board[7]} | </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mopen">[</span><span class="mord">7</span><span class="mclose">]</span></span><span class="mord">∣</span></span></span></span>{board[8]}); }

// Define a function to handle a player's turn function takeTurn(player) { console.log(${player}'s turn.); let position = prompt("Choose a position from 1-9:"); position -= 1; while (position < 0 || position > 8 || board[position] !== "-") { position = prompt("Invalid input or position already taken. Choose a different position:"); position -= 1; } board[position] = player; printBoard(); }

// Define a function to check if the game is over function checkGameOver() { // Check for a win if ((board[0] === board[1] && board[1] === board[2] && board[0] !== "-") || (board[3] === board[4] && board[4] === board[5] && board[3] !== "-") || (board[6] === board[7] && board[7] === board[8] && board[6] !== "-") || (board[0] === board[3] && board[3] === board[6] && board[0] !== "-") || (board[1] === board[4] && board[4] === board[7] && board[1] !== "-") || (board[2] === board[5] && board[5] === board[8] && board[2] !== "-") || (board[0] === board[4] && board[4] === board[8] && board[0] !== "-") || (board[2] === board[4] && board[4] === board[6] && board[2] !== "-")) { return "win"; } // Check for a tie else if (!board.includes("-")) { return "tie"; } // Game is not over else { return "play"; } }

// Define the main game loop function main() { printBoard(); let currentPlayer = "X"; let gameOver = false; while (!gameOver) { takeTurn(currentPlayer); let gameResult = checkGameOver(); if (gameResult === "win") { console.log(${currentPlayer} wins!); gameOver = true; } else if (gameResult === "tie") { console.log("It's a tie!"); gameOver = true; } else { // Switch to the other player currentPlayer = currentPlayer === "X" ? "O" : "X"; } } }

// Start the game main();

``

**Rules of the Game

#include #include #include #include

using namespace std;

#define COMPUTER 1 #define HUMAN 2 #define SIDE 3 // Length of the board

// Computer will move with 'O' and human with 'X' #define COMPUTERMOVE 'O' #define HUMANMOVE 'X'

// Function to show the current board status void showBoard(char board[][SIDE]) { cout << endl << "\t\t\t " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl; cout << "\t\t\t--------------" << endl; cout << "\t\t\t " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl; cout << "\t\t\t--------------" << endl; cout << "\t\t\t " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl << endl; }

// Function to show the instructions void showInstructions() { cout << "\t\t\t Tic-Tac-Toe" << endl << endl; cout << "Choose a cell numbered from 1 to 9 as below and play" << endl << endl; cout << "\t\t\t 1 | 2 | 3" << endl; cout << "\t\t\t--------------" << endl; cout << "\t\t\t 4 | 5 | 6" << endl; cout << "\t\t\t--------------" << endl; cout << "\t\t\t 7 | 8 | 9" << endl << endl; cout << "-\t-\t-\t-\t-\t-\t-\t-\t-\t-" << endl << endl; }

// Function to initialise the game void initialise(char board[][SIDE], int moves[]) { srand(time(NULL)); for (int i = 0; i < SIDE; i++) { for (int j = 0; j < SIDE; j++) board[i][j] = ' '; } for (int i = 0; i < SIDE * SIDE; i++) moves[i] = i; random_shuffle(moves, moves + SIDE * SIDE); }

// Function to declare the winner of the game void declareWinner(int whoseTurn) { if (whoseTurn == COMPUTER) cout << "COMPUTER has won" << endl; else cout << "HUMAN has won" << endl; }

// Function to check if any row is crossed with the same player's move bool rowCrossed(char board[][SIDE]) { for (int i = 0; i < SIDE; i++) { if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') return true; } return false; }

// Function to check if any column is crossed with the same player's move bool columnCrossed(char board[][SIDE]) { for (int i = 0; i < SIDE; i++) { if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') return true; } return false; }

// Function to check if any diagonal is crossed with the same player's move bool diagonalCrossed(char board[][SIDE]) { if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') return true; if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ') return true; return false; }

// Function to check if the game is over bool gameOver(char board[][SIDE]) { return (rowCrossed(board) || columnCrossed(board) || diagonalCrossed(board)); }

// Function to play Tic-Tac-Toe void playTicTacToe(int whoseTurn) { char board[SIDE][SIDE]; int moves[SIDE * SIDE]; initialise(board, moves); showInstructions(); int moveIndex = 0, x, y; while (gameOver(board) == false && moveIndex != SIDE * SIDE) { if (whoseTurn == COMPUTER) { x = moves[moveIndex] / SIDE; y = moves[moveIndex] % SIDE; board[x][y] = COMPUTERMOVE; cout << "COMPUTER has put a " << COMPUTERMOVE << " in cell " << moves[moveIndex] + 1 << endl; showBoard(board); moveIndex++; whoseTurn = HUMAN; } else if (whoseTurn == HUMAN) { x = moves[moveIndex] / SIDE; y = moves[moveIndex] % SIDE; board[x][y] = HUMANMOVE; cout << "HUMAN has put a " << HUMANMOVE << " in cell " << moves[moveIndex] + 1 << endl; showBoard(board); moveIndex++; whoseTurn = COMPUTER; } } if (gameOver(board) == false && moveIndex == SIDE * SIDE) cout << "It's a draw" << endl; else { if (whoseTurn == COMPUTER) whoseTurn = HUMAN; else if (whoseTurn == HUMAN) whoseTurn = COMPUTER; declareWinner(whoseTurn); } }

// Driver program int main() { playTicTacToe(COMPUTER); return 0; }

Java

public class TicTacToe { private static final int COMPUTER = 1; private static final int HUMAN = 2; private static final int SIDE = 3; // Length of the board

// Computer will move with 'O' and human with 'X'
private static final char COMPUTERMOVE = 'O';
private static final char HUMANMOVE = 'X';

private char[][] board = new char[SIDE][SIDE];
private int[] moves = new int[SIDE * SIDE];

// Function to show the current board status
private void showBoard() {
    System.out.println("\n\t\t\t  " + board[0][0] + " | " + board[0][1] + " | " + board[0][2]);
    System.out.println("\t\t\t--------------");
    System.out.println("\t\t\t  " + board[1][0] + " | " + board[1][1] + " | " + board[1][2]);
    System.out.println("\t\t\t--------------");
    System.out.println("\t\t\t  " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + "\n");
}

// Function to show the instructions
private void showInstructions() {
    System.out.println("\t\t\t  Tic-Tac-Toe\n");
    System.out.println("Choose a cell numbered from 1 to 9 as below and play\n");
    System.out.println("\t\t\t  1 | 2 | 3");
    System.out.println("\t\t\t--------------");
    System.out.println("\t\t\t  4 | 5 | 6");
    System.out.println("\t\t\t--------------");
    System.out.println("\t\t\t  7 | 8 | 9\n");
    System.out.println("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n");
}

// Function to initialise the game
private void initialise() {
    for (int i = 0; i < SIDE; i++) {
        for (int j = 0; j < SIDE; j++)
            board[i][j] = ' ';
    }
    for (int i = 0; i < SIDE * SIDE; i++)
        moves[i] = i;
    // Shuffling moves
    java.util.Collections.shuffle(java.util.Arrays.asList(moves));
}

// Function to declare the winner of the game
private void declareWinner(int whoseTurn) {
    if (whoseTurn == COMPUTER)
        System.out.println("COMPUTER has won");
    else
        System.out.println("HUMAN has won");
}

// Function to check if any row is crossed with the same player's move
private boolean rowCrossed() {
    for (int i = 0; i < SIDE; i++) {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
            return true;
    }
    return false;
}

// Function to check if any column is crossed with the same player's move
private boolean columnCrossed() {
    for (int i = 0; i < SIDE; i++) {
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')
            return true;
    }
    return false;
}

// Function to check if any diagonal is crossed with the same player's move
private boolean diagonalCrossed() {
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
        return true;
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
        return true;
    return false;
}

// Function to check if the game is over
private boolean gameOver() {
    return (rowCrossed() || columnCrossed() || diagonalCrossed());
}

// Function to play Tic-Tac-Toe
public void playTicTacToe(int whoseTurn) {
    initialise();
    showInstructions();
    int moveIndex = 0, x, y;
    while (!gameOver() && moveIndex != SIDE * SIDE) {
        if (whoseTurn == COMPUTER) {
            x = moves[moveIndex] / SIDE;
            y = moves[moveIndex] % SIDE;
            board[x][y] = COMPUTERMOVE;
            System.out.println("COMPUTER has put a " + COMPUTERMOVE + " in cell " + (moves[moveIndex] + 1));
            showBoard();
            moveIndex++;
            whoseTurn = HUMAN;
        } else if (whoseTurn == HUMAN) {
            x = moves[moveIndex] / SIDE;
            y = moves[moveIndex] % SIDE;
            board[x][y] = HUMANMOVE;
            System.out.println("HUMAN has put a " + HUMANMOVE + " in cell " + (moves[moveIndex] + 1));
            showBoard();
            moveIndex++;
            whoseTurn = COMPUTER;
        }
    }
    if (!gameOver() && moveIndex == SIDE * SIDE)
        System.out.println("It's a draw");
    else {
        if (whoseTurn == COMPUTER)
            whoseTurn = HUMAN;
        else if (whoseTurn == HUMAN)
            whoseTurn = COMPUTER;
        declareWinner(whoseTurn);
    }
}

// Driver program
public static void main(String[] args) {
    TicTacToe game = new TicTacToe();
    game.playTicTacToe(COMPUTER);
}

}

Python3

import random import time

Constants for the game

COMPUTER = 1 HUMAN = 2 SIDE = 3 COMPUTERMOVE = 'O' HUMANMOVE = 'X'

Function to initialise the game / Tic-Tac-Toe board

def initialise(): board = [[' ' for _ in range(SIDE)] for _ in range(SIDE)] moves = [i for i in range(SIDE*SIDE)] random.shuffle(moves) return board, moves

Function to print the Tic-Tac-Toe board

def showBoard(board): print("\n\n") print("\t\t\t {} | {} | {} ".format(board[0][0], board[0][1], board[0][2])) print("\t\t\t--------------") print("\t\t\t {} | {} | {} ".format(board[1][0], board[1][1], board[1][2])) print("\t\t\t--------------") print("\t\t\t {} | {} | {} \n\n".format(board[2][0], board[2][1], board[2][2]))

Function to show the instructions

def showInstructions(): print("\t\t\t Tic-Tac-Toe\n\n") print("Choose a cell numbered from 1 to 9 as below and play\n\n") print("\t\t\t 1 | 2 | 3 ") print("\t\t\t--------------") print("\t\t\t 4 | 5 | 6 ") print("\t\t\t--------------") print("\t\t\t 7 | 8 | 9 \n\n") print("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n")

Function to declare the winner of the game

def declareWinner(whoseTurn): if whoseTurn == COMPUTER: print("COMPUTER has won") else: print("HUMAN has won")

Functions to check if any of the rows, columns, or diagonals have been crossed

def rowCrossed(board): for i in range(SIDE): if board[i][0] == board[i][1] and board[i][1] == board[i][2] and board[i][0] != ' ': return True return False

def columnCrossed(board): for i in range(SIDE): if board[0][i] == board[1][i] and board[1][i] == board[2][i] and board[0][i] != ' ': return True return False

def diagonalCrossed(board): if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[0][0] != ' ': return True if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[0][2] != ' ': return True return False

Function to check if the game is over

def gameOver(board): return rowCrossed(board) or columnCrossed(board) or diagonalCrossed(board)

Function to play Tic-Tac-Toe

def playTicTacToe(whoseTurn): board, moves = initialise() showInstructions() moveIndex = 0 while not gameOver(board) and moveIndex != SIDESIDE: if whoseTurn == COMPUTER: x = moves[moveIndex] // SIDE y = moves[moveIndex] % SIDE board[x][y] = COMPUTERMOVE print("COMPUTER has put a {} in cell {}".format(COMPUTERMOVE, moves[moveIndex]+1)) showBoard(board) moveIndex += 1 whoseTurn = HUMAN elif whoseTurn == HUMAN: x = moves[moveIndex] // SIDE y = moves[moveIndex] % SIDE board[x][y] = HUMANMOVE print("HUMAN has put a {} in cell {}".format(HUMANMOVE, moves[moveIndex]+1)) showBoard(board) moveIndex += 1 whoseTurn = COMPUTER if not gameOver(board) and moveIndex == SIDESIDE: print("It's a draw") else: if whoseTurn == COMPUTER: whoseTurn = HUMAN elif whoseTurn == HUMAN: whoseTurn = COMPUTER declareWinner(whoseTurn)

Driver function

if name == "main": # Let us play the game with COMPUTER starting first playTicTacToe(COMPUTER)

` JavaScript ``

const COMPUTER = 1; const HUMAN = 2; const SIDE = 3; // Length of the board

// Computer will move with 'O' and human with 'X' const COMPUTERMOVE = 'O'; const HUMANMOVE = 'X';

// Function to show the current board status function showBoard(board) { console.log(\n\t\t\t <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>b</mi><mi>o</mi><mi>a</mi><mi>r</mi><mi>d</mi><mo stretchy="false">[</mo><mn>0</mn><mo stretchy="false">]</mo><mo stretchy="false">[</mo><mn>0</mn><mo stretchy="false">]</mo></mrow><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">{board[0][0]} | </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mopen">[</span><span class="mord">0</span><span class="mclose">]</span><span class="mopen">[</span><span class="mord">0</span><span class="mclose">]</span></span><span class="mord">∣</span></span></span></span>{board[0][1]} | ${board[0][2]}); console.log(\t\t\t--------------); console.log(\t\t\t <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>b</mi><mi>o</mi><mi>a</mi><mi>r</mi><mi>d</mi><mo stretchy="false">[</mo><mn>1</mn><mo stretchy="false">]</mo><mo stretchy="false">[</mo><mn>0</mn><mo stretchy="false">]</mo></mrow><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">{board[1][0]} | </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mopen">[</span><span class="mord">1</span><span class="mclose">]</span><span class="mopen">[</span><span class="mord">0</span><span class="mclose">]</span></span><span class="mord">∣</span></span></span></span>{board[1][1]} | ${board[1][2]}); console.log(\t\t\t--------------); console.log(\t\t\t <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>b</mi><mi>o</mi><mi>a</mi><mi>r</mi><mi>d</mi><mo stretchy="false">[</mo><mn>2</mn><mo stretchy="false">]</mo><mo stretchy="false">[</mo><mn>0</mn><mo stretchy="false">]</mo></mrow><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">{board[2][0]} | </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">d</span><span class="mopen">[</span><span class="mord">2</span><span class="mclose">]</span><span class="mopen">[</span><span class="mord">0</span><span class="mclose">]</span></span><span class="mord">∣</span></span></span></span>{board[2][1]} | ${board[2][2]}\n); }

// Function to show the instructions function showInstructions() { console.log("\t\t\t Tic-Tac-Toe\n"); console.log("Choose a cell numbered from 1 to 9 as below and play\n"); console.log("\t\t\t 1 | 2 | 3"); console.log("\t\t\t--------------"); console.log("\t\t\t 4 | 5 | 6"); console.log("\t\t\t--------------"); console.log("\t\t\t 7 | 8 | 9\n"); console.log("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n"); }

// Function to initialise the game function initialise(board, moves) { for (let i = 0; i < SIDE; i++) { board[i] = []; for (let j = 0; j < SIDE; j++) board[i][j] = ' '; } for (let i = 0; i < SIDE * SIDE; i++) moves[i] = i; // Shuffling moves moves.sort(() => Math.random() - 0.5); }

// Function to declare the winner of the game function declareWinner(whoseTurn) { if (whoseTurn === COMPUTER) console.log("COMPUTER has won"); else console.log("HUMAN has won"); }

// Function to check if any row is crossed with the same player's move function rowCrossed(board) { for (let i = 0; i < SIDE; i++) { if (board[i][0] === board[i][1] && board[i][1] === board[i][2] && board[i][0] !== ' ') return true; } return false; }

// Function to check if any column is crossed with the same player's move function columnCrossed(board) { for (let i = 0; i < SIDE; i++) { if (board[0][i] === board[1][i] && board[1][i] === board[2][i] && board[0][i] !== ' ') return true; } return false; }

// Function to check if any diagonal is crossed with the same player's move function diagonalCrossed(board) { if (board[0][0] === board[1][1] && board[1][1] === board[2][2] && board[0][0] !== ' ') return true; if (board[0][2] === board[1][1] && board[1][1] === board[2][0] && board[0][2] !== ' ') return true; return false; }

// Function to check if the game is over function gameOver(board) { return (rowCrossed(board) || columnCrossed(board) || diagonalCrossed(board)); }

// Function to play Tic-Tac-Toe function playTicTacToe(whoseTurn) { const board = []; const moves = Array.from({length: SIDE * SIDE}); initialise(board, moves); showInstructions(); let moveIndex = 0, x, y; while (!gameOver(board) && moveIndex !== SIDE * SIDE) { if (whoseTurn === COMPUTER) { x = Math.floor(moves[moveIndex] / SIDE); y = moves[moveIndex] % SIDE; board[x][y] = COMPUTERMOVE; console.log(COMPUTER has put a <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>C</mi><mi>O</mi><mi>M</mi><mi>P</mi><mi>U</mi><mi>T</mi><mi>E</mi><mi>R</mi><mi>M</mi><mi>O</mi><mi>V</mi><mi>E</mi></mrow><mi>i</mi><mi>n</mi><mi>c</mi><mi>e</mi><mi>l</mi><mi>l</mi></mrow><annotation encoding="application/x-tex">{COMPUTERMOVE} in cell </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">COMP</span><span class="mord mathnormal" style="margin-right:0.10903em;">U</span><span class="mord mathnormal" style="margin-right:0.02778em;">TERMO</span><span class="mord mathnormal" style="margin-right:0.22222em;">V</span><span class="mord mathnormal" style="margin-right:0.05764em;">E</span></span><span class="mord mathnormal">in</span><span class="mord mathnormal">ce</span><span class="mord mathnormal" style="margin-right:0.01968em;">ll</span></span></span></span>{moves[moveIndex] + 1}); showBoard(board); moveIndex++; whoseTurn = HUMAN; } else if (whoseTurn === HUMAN) { x = Math.floor(moves[moveIndex] / SIDE); y = moves[moveIndex] % SIDE; board[x][y] = HUMANMOVE; console.log(HUMAN has put a <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>H</mi><mi>U</mi><mi>M</mi><mi>A</mi><mi>N</mi><mi>M</mi><mi>O</mi><mi>V</mi><mi>E</mi></mrow><mi>i</mi><mi>n</mi><mi>c</mi><mi>e</mi><mi>l</mi><mi>l</mi></mrow><annotation encoding="application/x-tex">{HUMANMOVE} in cell </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal" style="margin-right:0.10903em;">U</span><span class="mord mathnormal" style="margin-right:0.10903em;">M</span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.02778em;">NMO</span><span class="mord mathnormal" style="margin-right:0.22222em;">V</span><span class="mord mathnormal" style="margin-right:0.05764em;">E</span></span><span class="mord mathnormal">in</span><span class="mord mathnormal">ce</span><span class="mord mathnormal" style="margin-right:0.01968em;">ll</span></span></span></span>{moves[moveIndex] + 1}); showBoard(board); moveIndex++; whoseTurn = COMPUTER; } } if (!gameOver(board) && moveIndex === SIDE * SIDE) console.log("It's a draw"); else { if (whoseTurn === COMPUTER) whoseTurn = HUMAN; else if (whoseTurn === HUMAN) whoseTurn = COMPUTER; declareWinner(whoseTurn); } }

// Driver program playTicTacToe(COMPUTER);

``

Choose a cell numbered from 1 to 9 as below and play

          1 | 2  | 3    
        --------------  
          4 | 5  | 6    
        --------------  
          7 | 8  | 9  

COMPUTER has put a O in cell 6

            |    |      
        --------------  
            |    | O    
        --------------  
            |    |    

HUMAN has put a X in cell 7

            |    |      
        --------------  
            |    | O    
        --------------  
          X |    |    

COMPUTER has put a O in cell 5

            |    |      
        --------------  
            | O  | O    
        --------------  
          X |    |    

HUMAN has put a X in cell 1

          X |    |      
        --------------  
            | O  | O    
        --------------  
          X |    |    

COMPUTER has put a O in cell 9

          X |    |      
        --------------  
            | O  | O    
        --------------  
          X |    | O  

HUMAN has put a X in cell 8

          X |    |      
        --------------  
            | O  | O    
        --------------  
          X | X  | O  

COMPUTER has put a O in cell 4

          X |    |      
        --------------  
          O | O  | O    
        --------------  
          X | X  | O  

COMPUTER has won