Reputation: 11
I'm pretty new to python and I've been trying to write a minimax algorithm for tic-tac-toe. But I can't get my program to return the expected value and I'm not sure what's going on. My minimax method should be returning 1, but instead pretty much broken. I believe it's using the original list instead of creating a new one. I tried using copy() but it didn't work, unless I used it wrong. Here is my code:
import copy
def checkWin(board):
if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'y', 'x']]:
return 't'
if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'x', 'y']]:
return 'y'
return '0'
def minimax(board, player):
status = checkWin(board)
if status == 't':
return 0
if status == 'y':
return 1
if player == 'y':
value = -100000
for i in range(3):
for k in range(3):
if board[i][k] == '':
board2 = copy.deepcopy(board)
board2[i][k] == 'y'
bestMove = minimax(board2, 'x')
if bestMove > value:
value = bestMove
return value
else:
value = 100000
for i in range(3):
for k in range(3):
if board[i][k] == '':
board2 = copy.deepcopy(board)
board2[i][k] == 'x'
bestMove = minimax(board2, 'y')
if bestMove < value:
value = bestMove
return value
board = [
['y', 'x', 'y'],
['x', 'y', 'x'],
['x', 'x', '']
]
bestMove = minimax(board, 'y')
print(bestMove)
Any help is appreciated, thanks.
Edit. Thanks to the people who helped, I'm sorry I'm such an idiot. But I will make sure to learn how to debug my programs more carefully and thoroughly.
Upvotes: 0
Views: 48
Reputation: 139
You want to assign value not compare board2[i][k] == 'x'
should be board2[i][k] = 'x'
same with y.
import copy
def checkWin(board):
if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'y', 'x']]:
return 't'
if board == [['y', 'x', 'y'], ['x', 'y', 'x'], ['x', 'x', 'y']]:
return 'y'
return '0'
def minimax(board, player):
status = checkWin(board)
if status == 't':
return 0
if status == 'y':
return 1
if player == 'y':
value = -100000
for i in range(3):
for k in range(3):
if board[i][k] == '':
board2 = copy.deepcopy(board)
board2[i][k] = 'y'
bestMove = minimax(board2, 'x')
if bestMove > value:
value = bestMove
return value
else:
value = 100000
for i in range(3):
for k in range(3):
if board[i][k] == '':
board2 = copy.deepcopy(board)
board2[i][k] = 'x'
bestMove = minimax(board2, 'y')
if bestMove < value:
value = bestMove
return value
board = [
['y', 'x', 'y'],
['x', 'y', 'x'],
['x', 'x', '']
]
bestMove = minimax(board, 'y')
print(bestMove)
Upvotes: 1