VOOZH about

URL: https://www.geeksforgeeks.org/python/python-implementation-automatic-tic-tac-toe-game-using-random-number/

⇱ Automatic Tic Tac Toe Game using Random Number - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Automatic Tic Tac Toe Game using Random Number - Python

Last Updated : 28 Jul, 2025

Tic-Tac-Toe is a simple and fun game. In this article, we’ll build an automatic version using Python. The twist is that the game plays itself, no user input needed! Players randomly place their marks on the board and the winner is declared when three in a row is achieved.

We’ll use:

  • NumPy for managing the 3x3 board.
  • random module for placing marks randomly.

Game Implementation

A Python program that:

  • Initializes a 3x3Tic-Tac-Toe board.
  • Lets player 1 and 2 take turns placing marks randomly.
  • Checks for win conditions (rows, columns, diagonals).
  • Prints the board after each move.
  • Announces the winner or a draw when the game ends.

Note: Run this code in a local Python environment to ensure smooth execution of the required modules.

Code:

Output:

[[0 0 0]
[0 0 0]
[0 0 0]]

Board after move 1:
[[0 0 0]
[0 0 0]
[0 1 0]]

Board after move 2:
[[0 0 0]
[0 0 0]
[2 1 0]]

Board after move 3:
[[0 0 0]
[1 0 0]
[2 1 0]]

Board after move 4:
[[0 0 0]
[1 0 2]
[2 1 0]]

Board after move 5:
[[0 1 0]
[1 0 2]
[2 1 0]]

Board after move 6:
[[0 1 0]
[1 0 2]
[2 1 2]]

Board after move 7:
[[1 1 0]
[1 0 2]
[2 1 2]]

Board after move 8:
[[1 1 2]
[1 0 2]
[2 1 2]]

Winner is: 2

Code Breakdown:

  • create_board(): Initializes the Board, creates a 3x3 grid filled with zeros using NumPy where 0 means an empty cell.
  • random_place(): Selects a random empty spot on the board and places the player’s number (1 or 2):
  • Win Check Functions: row_win(), col_win(), diag_win() -These functions verify if a player has a winning line:
  • evaluate(): Determines Game Status by checking if any player has won, or if the board is full (draw). Returns 1 or 2 if a player wins, -1 for draw and 0 if the game is still on.
  • play_game(): It creates the game loop, i.e. it handles turn-taking, board updates and win/draw detection

Note: Everytime we will run this code, we will get a different ouput because the games is played randomly

Related Articles:

Comment
Article Tags:
Article Tags: