Question: # Tic - Tac - Toe with Minimax Algorithm and Alpha - Beta Pruning import numpy as np # Initialize the board ( empty =
# TicTacToe with Minimax Algorithm and AlphaBeta Pruning
import numpy as np
# Initialize the board empty X O
def initializeboard:
return npzeros dtypeint
# Check for win condition for X for O for draw or incomplete
def checkwinnerboard:
for i in range:
# Check rows and columns
if abssumboardi ::
return boardi
if abssumboard: i:
return board i
# Check diagonals
if abssumboarddiagonal:
return board
if abssumnpfliplrboarddiagonal:
return board
# No winner
return
# Check if the board is full draw
def isboardfullboard:
return not board any
# Minimax function with AlphaBeta Pruning
def minimaxboard depth, alpha, beta, ismaximizing:
winner checkwinnerboard
if winner :
return winner # return the utility value: for X for O
if isboardfullboard:
return # Draw case
if ismaximizing: # Maximizing for X
maxeval npinf
for i in range:
for j in range:
if boardi j: # Check if the cell is empty
boardi j # X makes a move
eval minimaxboard depth alpha, beta, False
boardi j # Undo move
maxeval maxmaxeval, eval
alpha maxalpha eval
if beta alpha:
break # Beta cutoff
return maxeval
else: # Minimizing for O
mineval npinf
for i in range:
for j in range:
if boardi j: # Check if the cell is empty
boardi j # O makes a move
eval minimaxboard depth alpha, beta, True
boardi j # Undo move
mineval minmineval, eval
beta minbeta eval
if beta alpha:
break # Alpha cutoff
return mineval
# Best move for X Maximizing player
def bestmoveboard:
bestval npinf
move
for i in range:
for j in range:
if boardi j: # If cell is empty
boardi j # X makes a move
moveval minimaxboardnpinf, npinf, False
boardi j # Undo move
if moveval bestval:
move i j
bestval moveval
return move
# Display the board
def displayboardboard:
chars : X: O:
for row in board:
printjoincharscell for cell in row
print
# Simulate a game
def playgame:
board initializeboard
currentplayer # X starts
while checkwinnerboard and not isboardfullboard:
displayboardboard
if currentplayer : # Xs turn AI
i j bestmoveboard
printfX moves to ij
boardi j
else: # Os turn random play for demo purposes
i j nprandom.choicenpwhereboard nprandom.choicenpwhereboard
printfO moves to ij
boardi j
currentplayer # Switch players
displayboardboard
winner checkwinnerboard
if winner :
printX wins!"
elif winner :
printO wins!"
else:
printIts a draw!"
# Run the simulation
playgame
give the decision tree precisely according to the code and output for the code hand drawn according to these rules:
Decision Tree:
A handdrawn or digital decision tree that represents a full or partial game of TicTacToe.Clearly indicate where the Minimax algorithm evaluated game states and where Alphabeta pruning was applied.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
