Python Implementation of automatic Tic Tac Toe game using random number

This automatic Tic Tac Toe game simulates two players making random moves without human input. The game uses NumPy for board representation and random module for move selection, displaying the board after each turn until someone wins or the game draws.

Required Modules

The game requires NumPy for matrix operations and random for automated move selection ?

import numpy as np
import random
from time import sleep

Complete Implementation

Here's the complete automatic Tic Tac Toe game with proper error handling ?

import numpy as np
import random
from time import sleep

# Create an empty 3x3 board
def my_create_board():
    return np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])

# Find all empty positions on the board
def my_possibilities(board):
    empty_positions = []
    for i in range(len(board)):
        for j in range(len(board)):
            if board[i][j] == 0:
                empty_positions.append((i, j))
    return empty_positions

# Place player mark at random empty position
def my_random_place(board, my_player):
    selection = my_possibilities(board)
    current_loc = random.choice(selection)
    board[current_loc] = my_player
    return board

# Check for row wins
def my_row_win(board, my_player):
    for x in range(len(board)):
        win = True
        for y in range(len(board)):
            if board[x, y] != my_player:
                win = False
                break
        if win:
            return True
    return False

# Check for column wins
def my_col_win(board, my_player):
    for x in range(len(board)):
        win = True
        for y in range(len(board)):
            if board[y][x] != my_player:
                win = False
                break
        if win:
            return True
    return False

# Check for diagonal wins
def my_diag_win(board, my_player):
    # Main diagonal
    win = True
    for x in range(len(board)):
        if board[x, x] != my_player:
            win = False
            break
    if win:
        return True
    
    # Anti-diagonal
    win = True
    for x in range(len(board)):
        if board[x, len(board) - 1 - x] != my_player:
            win = False
            break
    return win

# Evaluate game state
def evaluate_game(board):
    my_winner = 0
    for my_player in [1, 2]:
        if (my_row_win(board, my_player) or
            my_col_win(board, my_player) or
            my_diag_win(board, my_player)):
            my_winner = my_player
            break
    
    # Check for draw
    if np.all(board != 0) and my_winner == 0:
        my_winner = -1
    return my_winner

# Main game function
def my_play_game():
    board = my_create_board()
    my_winner = 0
    counter = 1
    
    print("Initial Board:")
    print(board)
    sleep(1)
    
    while my_winner == 0:
        for my_player in [1, 2]:
            board = my_random_place(board, my_player)
            print(f"Board after move {counter} (Player {my_player}):")
            print(board)
            sleep(1)
            counter += 1
            my_winner = evaluate_game(board)
            if my_winner != 0:
                break
    
    return my_winner

# Run the game
result = my_play_game()
if result == -1:
    print("Game Result: Draw!")
else:
    print(f"Game Result: Player {result} wins!")

The output shows the game progression with random moves ?

Initial Board:
[[0 0 0]
 [0 0 0]
 [0 0 0]]
Board after move 1 (Player 1):
[[0 1 0]
 [0 0 0]
 [0 0 0]]
Board after move 2 (Player 2):
[[0 1 0]
 [0 0 0]
 [0 0 2]]
Board after move 3 (Player 1):
[[0 1 0]
 [0 0 0]
 [0 1 2]]
Board after move 4 (Player 2):
[[0 1 0]
 [0 0 2]
 [0 1 2]]
Board after move 5 (Player 1):
[[0 1 1]
 [0 0 2]
 [0 1 2]]
Board after move 6 (Player 2):
[[0 1 1]
 [2 0 2]
 [0 1 2]]
Board after move 7 (Player 1):
[[0 1 1]
 [2 1 2]
 [0 1 2]]
Game Result: Player 1 wins!

How It Works

The game follows this logic:

  • Board Creation: Creates a 3×3 NumPy array filled with zeros
  • Move Selection: Randomly selects from available empty positions
  • Win Detection: Checks rows, columns, and both diagonals for three in a row
  • Game Loop: Alternates between players 1 and 2 until someone wins or board fills
  • Draw Detection: Returns -1 if board is full with no winner

Conclusion

This automatic Tic Tac Toe demonstrates random gameplay simulation using NumPy arrays and Python's random module. The game runs completely autonomously, making it useful for testing game logic or creating AI training scenarios.

Updated on: 2026-03-25T05:00:14+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements