Sorry to dump my code like this, but I’ve been pulling my hair out the last hours trying to figure out where my minimax algorithm in python is going wrong. Any help is greatly appreciated!
JavaScript
x
50
50
1
inf = 1000
2
bo = [["x", "o", "o"],
3
[" ", "o", " "],
4
[" ", "x", "x"]]
5
6
def bestMove(board):
7
bestScore = -inf
8
bestMove = None
9
for i in range(3):
10
for j in range(3):
11
if(board[i][j]==" "):
12
board[i][j]=getTurn(board)
13
score = minimax(board, searchdepth, True)
14
board[i][j]=" "
15
if score > bestScore:
16
bestScore = score
17
bestMove = [i, j]
18
print("nnn")
19
return bestMove
20
21
searchdepth = 10
22
def minimax(node, depth, maxP):
23
resultat = win(node)
24
if resultat=="x": return 1
25
if resultat=="o": return -1
26
if resultat=="tie": return 0
27
if depth == 0: return 0
28
29
if maxP==True:
30
value = -inf
31
for i in range(3):
32
for j in range(3):
33
if node[i][j] == " ":
34
node[i][j] = getTurn(node)
35
newval = minimax(node, depth - 1, False)
36
node[i][j] = " "
37
value = max(newval, value)
38
return value
39
if maxP==False:
40
value = inf
41
for i in range(3):
42
for j in range(3):
43
if node[i][j] == " ":
44
node[i][j] = getTurn(node)
45
newval = minimax(node, depth - 1, True)
46
node[i][j] = " "
47
value = min(newval, value)
48
return value
49
print(bestMove(bo))
50
Output: [1, 0] Expected output: [2, 0]
Advertisement
Answer
You are always sending a 1 in case ‘X’ wins, this is not correct. This means that if it is O:s turn it will think it is good if X wins. The easiest way would be to give a different value depending on who’s turn it is, that is give a score of 1 if YOURSELF win, -1 if OPPONENT wins and 0 if draw.