Skip to content

Instantly share code, notes, and snippets.

@FriedGil
Created February 29, 2024 16:04
Show Gist options
  • Save FriedGil/ee4a96a4820d2e1c8beb6709962d5efe to your computer and use it in GitHub Desktop.
Save FriedGil/ee4a96a4820d2e1c8beb6709962d5efe to your computer and use it in GitHub Desktop.
#Instead of x and o players are 1 and -1
def eval(board): #returns 1 if player 1 wins, 0 if no player wins, -1 if player -1 wins
for i in range(3):
if board[i*3] == board [i*3 + 1] == board[i*3 +2] and board[i*3]!=0: #Horizontal
return board[i*3]
if board[i] == board[i+3] == board [i+6] and board[i*3]!=0: #Vertical
return board[i]
if board[0] == board[4] == board[8] and board[0]!=0: #Diagonal 1
return board[0]
if board[2] == board[4] == board[6] and board[2]!=0: #Diagonal 2
return board[2]
return 0 #Otherwise
def moves(board): #Gets all possible moves by index 0-8 inclusive
mv = []
for i in range(len(board)):
if (board[i] == 0):
mv.append(i)
return mv
def alphabeta(node, depth, a, b, player):
if len(moves(node)) == 0 or eval(node) !=0 or depth==9: #Terminal Conditions
return eval(node)
if player == 1:
value = -3 #Arbitrary, must be below -1 but doesn't really matter for tic tac toe.
for i in moves(node): #Try all moves
tboard = board.copy()
tboard[i] = player #Add move tp board
value = max(value, alphabeta(tboard, depth + 1, a, b, player*-1)) #Minimax type thing
if value > b: #Prune the tree
break
a = max(a, value)
return value
else:
value = 3
for i in moves(node):
tboard = board.copy()
tboard[i] = player
value = min(value, alphabeta(tboard, depth + 1, a, b, player*-1))
if value < a:
break
b = min(b, value)
return value
def ab_get_best_move(board,player):
t_score = -1
best_move = moves(board)[0]
for i in moves(board):
tboard = board.copy()
tboard[i] = player
score = alphabeta(tboard,0,-2,2,-player) * player
if score > t_score:
best_move = i
t_score = score
return best_move,t_score
board = [1,-1,0,
1,-1,0,
0 ,0,0]
ab_get_best_move(board,1)
@eoggod
Copy link

eoggod commented Mar 1, 2024

wow! amazing code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment