Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2
Experiment No: 05
Program:
import math def minimax(board, depth, is_maximizing):
if check_winner(board, AI): # Constants for the players return 1 HUMAN = 'X' if check_winner(board, HUMAN): AI = 'O' return -1 EMPTY = '_' if is_draw(board): return 0 # Initialize the board board = [ if is_maximizing: [EMPTY, EMPTY, EMPTY], best_score = -math.inf [EMPTY, EMPTY, EMPTY], for i in range(3): [EMPTY, EMPTY, EMPTY] for j in range(3): ] if board[i][j] == EMPTY: board[i][j] = AI # Function to print the board score = minimax(board, depth + def print_board(board): 1, False) for row in board: board[i][j] = EMPTY print(' '.join(row)) best_score = max(score, print() best_score) return best_score # Function to check for a win else: def check_winner(board, player): best_score = math.inf for row in board: for i in range(3): if all([cell == player for cell in row]): for j in range(3): return True if board[i][j] == EMPTY: board[i][j] = HUMAN for col in range(3): score = minimax(board, depth + if all([board[row][col] == player for row 1, True) in range(3)]): board[i][j] = EMPTY return True best_score = min(score, best_score) return best_score if all([board[i][i] == player for i in # Function to find the best move range(3)]) or all([board[i][2 - i] == player for def best_move(board): i in range(3)]): best_score = -math.inf return True move = None for i in range(3): return False for j in range(3): if board[i][j] == EMPTY: # Function to check for a draw board[i][j] = AI def is_draw(board): score = minimax(board, 0, False) return all([cell != EMPTY for row in board board[i][j] = EMPTY if score > for cell in row]) best_score: best_score = score move = (i, j) # Minimax function to evaluate the board return move # Function for the AI to make a move # Game loop def ai_move(): def play_game(): move = best_move(board) print_board(board) if move: while True: board[move[0]][move[1]] = AI human_move() print_board(board) # Function for the human player to make a if check_winner(board, HUMAN): move print("You win!") def human_move(): break row, col = map(int, input("Enter row and if is_draw(board): column (0, 1, or 2): ").split()) print("It's a draw!") if board[row][col] == EMPTY: break board[row][col] = HUMAN ai_move() else: print_board(board) print("Cell is already occupied! Try if check_winner(board, AI): again.") print("AI wins!") human_move() break if is_draw(board): print("It's a draw!") break # Start the game play_game()