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!
inf = 1000 bo = [["x", "o", "o"], [" ", "o", " "], [" ", "x", "x"]] def bestMove(board): bestScore = -inf bestMove = None for i in range(3): for j in range(3): if(board[i][j]==" "): board[i][j]=getTurn(board) score = minimax(board, searchdepth, True) board[i][j]=" " if score > bestScore: bestScore = score bestMove = [i, j] print("nnn") return bestMove searchdepth = 10 def minimax(node, depth, maxP): resultat = win(node) if resultat=="x": return 1 if resultat=="o": return -1 if resultat=="tie": return 0 if depth == 0: return 0 if maxP==True: value = -inf for i in range(3): for j in range(3): if node[i][j] == " ": node[i][j] = getTurn(node) newval = minimax(node, depth - 1, False) node[i][j] = " " value = max(newval, value) return value if maxP==False: value = inf for i in range(3): for j in range(3): if node[i][j] == " ": node[i][j] = getTurn(node) newval = minimax(node, depth - 1, True) node[i][j] = " " value = min(newval, value) return value print(bestMove(bo))
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.