You are on page 1of 2

def max_alpha_beta(self, alpha, beta):

maxv = -2
#intialize the x and y coordinates to the maximum value

px = None
py = None

# Check if the game has ended


result = self.is_end()

#check if either X or O have won and assign a score accordingly


if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)

for i in range(0, 3):


for j in range(0, 3):

#check if the cell is empty and place an O


if self.current_state[i][j] == '.':
self.current_state[i][j] = 'O'
(m, min_i, min_j) = self.min_alpha_beta(alpha, beta) # Call
min_alpha_beta for the opponent

#update the maximum value if the user's score is higher than the one we
have
if m > maxv:
maxv = m

#update the x and y coordinates of the maximum value


px = i
py = j

# Reset the cell to empty


self.current_state[i][j] = '.'

#perform pruning if alpha is greater than beta


if maxv >= beta:
return (maxv, px, py)

#update alpha with the maximum value where alpha changes beta
if maxv > alpha:
alpha = maxv
return (maxv, px, py)

#the following function computes beta


def min_alpha_beta(self, alpha, beta):
minv = 2
qx = None
qy = None
result = self.is_end()

#check if either X or O have won and assign a score accordingly


if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)

for i in range(0, 3):


for j in range(0, 3):
if self.current_state[i][j] == '.':
self.current_state[i][j] = 'X'
(m, max_i, max_j) = self.max_alpha_beta(alpha, beta)

#if minimum is greater than m update m with the beta value


if m < minv:
minv = m
qx = i
qy = j
self.current_state[i][j] = '.'

#perform pruning if minimum score is less than or equal to alpha


if minv <= alpha:
return (minv, qx, qy)

#update beta with the minimum value ifthe mimumum value is less than beta
if minv < beta:
beta = minv
return (minv, qx, qy)

You might also like