How to create a simple AI for Tic Tac Toe

 



How to Create a Simple AI for Tic Tac Toe


Tic Tac Toe is a classic game that serves as a great starting point for learning game development and artificial intelligence (AI). In this guide, we’ll walk through the process of creating a simple AI for Tic Tac Toe, using a step-by-step approach.


By the end of this tutorial, you will understand:

✅ The rules of Tic Tac Toe

✅ How to implement a basic game board

✅ How to create a simple AI opponent

✅ How to improve the AI with the Minimax algorithm


Let’s dive in!



---


Understanding the Rules of Tic Tac Toe


Tic Tac Toe is a two-player game played on a 3x3 grid. The objective is to get three marks in a row (horizontally, vertically, or diagonally) before your opponent does.


Each player takes turns placing an "X" or "O" on the grid. The game ends when:


One player wins by getting three in a row.


The board is full, resulting in a draw.



A simple AI for Tic Tac Toe needs to:

✔️ Detect winning and losing positions.

✔️ Prevent the opponent from winning.

✔️ Make intelligent moves to win or force a draw.



---


Step 1: Creating the Tic Tac Toe Board


Before implementing AI, we need a way to represent the Tic Tac Toe board in code.


Python Code for the Game Board


# Tic Tac Toe Board Representation

board = [

    [" ", " ", " "],

    [" ", " ", " "],

    [" ", " ", " "]

]


# Function to Print the Board

def print_board(board):

    for row in board:

        print("|".join(row))

        print("-" * 5)


# Example Usage

print_board(board)


This simple function prints the Tic Tac Toe grid, helping us visualize the game state.



---


Step 2: Implementing Player Moves


To play the game, we need a function that allows the player to place their move.


# Function to Check if a Move is Valid

def is_valid_move(board, row, col):

    return board[row][col] == " "


# Function to Make a Move

def make_move(board, row, col, player):

    if is_valid_move(board, row, col):

        board[row][col] = player

        return True

    return False


How it Works


✅ is_valid_move() ensures a move is made in an empty space.

✅ make_move() updates the board with the player's move.



---


Step 3: Checking for a Winner


To determine if the game is over, we need a function to check for winning conditions.


# Function to Check for a Winner

def check_winner(board, player):

    # Check Rows & Columns

    for i in range(3):

        if all(board[i][j] == player for j in range(3)) or \

           all(board[j][i] == player for j in range(3)):

            return True

    

    # Check Diagonals

    if all(board[i][i] == player for i in range(3)) or \

       all(board[i][2 - i] == player for i in range(3)):

        return True


    return False


How it Works


✔️ Checks rows, columns, and diagonals for three matching marks.

✔️ Returns True if a player wins.



---


Step 4: Implementing a Basic AI (Random Moves)


Now, let's create a basic AI that plays randomly.


import random


# Function for AI Move (Random)

def ai_move(board):

    empty_cells = [(i, j) for i in range(3) for j in range(3) if board[i][j] == " "]

    return random.choice(empty_cells)


How it Works


✅ Finds all available moves.

✅ Picks a random move from the available spaces.


This AI is not very smart but serves as a starting point.



---


Step 5: Improving the AI (Blocking Moves)


A smarter AI should block the opponent from winning.


# Function to Check for Winning Move

def find_winning_move(board, player):

    for i in range(3):

        for j in range(3):

            if board[i][j] == " ":

                board[i][j] = player  # Simulate Move

                if check_winner(board, player):

                    board[i][j] = " "  # Undo Move

                    return i, j

                board[i][j] = " "  # Undo Move

    return None


How it Works


✔️ Simulates all possible moves to find a winning move.

✔️ Returns the best move if available.


Now, we update the AI move function to include blocking.


# Smarter AI Move Function

def ai_smart_move(board):

    # Check if AI can win

    move = find_winning_move(board, "O")

    if move:

        return move

    

    # Block opponent's win

    move = find_winning_move(board, "X")

    if move:

        return move

    

    # Otherwise, pick a random move

    return ai_move(board)



---


Step 6: Implementing the Minimax Algorithm (Unbeatable AI)


For a perfect AI, we use the Minimax algorithm, which evaluates all possible moves and picks the best one.


# Minimax Algorithm for Best Move

def minimax(board, depth, is_maximizing):

    # Check for terminal states

    if check_winner(board, "O"):

        return 10 - depth

    if check_winner(board, "X"):

        return depth - 10

    if all(board[i][j] != " " for i in range(3) for j in range(3)):

        return 0  # Draw

    

    # Maximizing player (AI "O")

    if is_maximizing:

        best_score = -float("inf")

        for i in range(3):

            for j in range(3):

                if board[i][j] == " ":

                    board[i][j] = "O"

                    score = minimax(board, depth + 1, False)

                    board[i][j] = " "

                    best_score = max(best_score, score)

        return best_score

    

    # Minimizing player (Human "X")

    else:

        best_score = float("inf")

        for i in range(3):

            for j in range(3):

                if board[i][j] == " ":

                    board[i][j] = "X"

                    score = minimax(board, depth + 1, True)

                    board[i][j] = " "

                    best_score = min(best_score, score)

        return best_score


Now, use Minimax AI to pick the best move.


def best_move(board):

    best_score = -float("inf")

    move = None

    for i in range(3):

        for j in range(3):

            if board[i][j] == " ":

                board[i][j] = "O"

                score = minimax(board, 0, False)

                board[i][j] = " "

                if score > best_score:

                    best_score = score

                    move = (i, j)

    return move



---


Final Thoughts


You've now built a simple Tic Tac Toe AI that:

✔️ Plays random moves (beginner AI).

✔️ Blocks the opponent from winning (intermediate AI).

✔️ Uses Minimax to play perfectly (unbeatable AI).


This project is an excellent introduction to game AI and can be extended by:


Adding a GUI for better interaction.


Implementing difficulty levels (easy, medium, hard).


Extending the Minimax for larger board games.



Now, challenge yourself to play against your AI and see how well it performs! 🚀


Comments

Popular posts from this blog

Strategies

Strategy

Best gaming laptop