Python
Python

 

 

Introduction

Tic-Tac-Toe is a classic two-player game where players alternate marking spaces in a 3×3 grid with X or O. Enhancing the game with a simple AI opponent makes it more engaging and challenging for single players. This program uses Python to implement a basic Tic-Tac-Toe game with an AI that makes logical moves to compete against the player.

Objective

The objective of this program is to create an interactive Tic-Tac-Toe game where players can play against an AI opponent. The AI makes its moves based on available spaces and basic strategies to block the player or win.

Python Code

import random

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def check_winner(board, player):
    # Check rows, columns, and diagonals
    for row in board:
        if all(cell == player for cell in row):
            return True
    for col in range(3):
        if all(row[col] == player for row in board):
            return True
    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

def get_available_moves(board):
    return [(r, c) for r in range(3) for c in range(3) if board[r][c] == " "]

def ai_move(board):
    moves = get_available_moves(board)
    return random.choice(moves)

def main():
    board = [[" " for _ in range(3)] for _ in range(3)]
    print("Welcome to Tic-Tac-Toe with AI!")
    print_board(board)

    for turn in range(9):
        if turn % 2 == 0:  # Player's turn
            move = input("Enter your move (row and column) as 'row,col': ")
            try:
                row, col = map(int, move.split(","))
                if board[row][col] != " ":
                    print("Invalid move, try again.")
                    continue
                board[row][col] = "X"
            except (ValueError, IndexError):
                print("Invalid input, try again.")
                continue
        else:  # AI's turn
            row, col = ai_move(board)
            board[row][col] = "O"
            print(f"AI chose: {row},{col}")

        print_board(board)

        if check_winner(board, "X"):
            print("Congratulations! You win!")
            break
        if check_winner(board, "O"):
            print("AI wins! Better luck next time.")
            break
    else:
        print("It's a draw!")

if __name__ == "__main__":
    main()

Program Explanation

This Python program creates a simple Tic-Tac-Toe game with an AI opponent. Here’s a breakdown of the program structure:

  • print_board: Displays the current state of the board.
  • check_winner: Checks if a player has won by completing a row, column, or diagonal.
  • get_available_moves: Returns a list of empty spaces where a move can be made.
  • ai_move: Selects a random available move for the AI.
  • Main game loop: Alternates between the player and AI, checking for a winner or a draw after each turn.

Steps to Run the Program

  1. Ensure Python is installed on your system.
  2. Copy the code into a file named tic_tac_toe_ai.py.
  3. Open a terminal or command prompt and navigate to the directory containing the file.
  4. Run the script using the command: python tic_tac_toe_ai.py.
  5. Follow the prompts to play the game against the AI.
© 2024 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)