【发布时间】:2018-10-16 00:01:26
【问题描述】:
我的 minimax 算法 tic tac toe AI 的代码似乎无法正常工作,我不知道为什么。如果移动导致损失,recursion 方面似乎有问题并返回负值;它不区分防御性动作和进攻性动作。
它没有选择将 X 放置在位置 6 以阻止对手连续达到 3,而是将其放置在另一个图块上
board = [
"X", "X", "O",
"O", "O", "X",
"-", "-", "-",
]
opp = "O"
plyr = "X"
def getOpenPos(board):
openPos = []
for index, state in enumerate(board):
if state == "-":
openPos.append(index)
return openPos
def winning(board, plyr):
if ((board[0] == plyr and board[1] == plyr and board[2] == plyr) or
(board[3] == plyr and board[4] == plyr and board[5] == plyr) or
(board[6] == plyr and board[7] == plyr and board[8] == plyr) or
(board[0] == plyr and board[4] == plyr and board[8] == plyr) or
(board[1] == plyr and board[4] == plyr and board[7] == plyr) or
(board[2] == plyr and board[4] == plyr and board[6] == plyr) or
(board[0] == plyr and board[3] == plyr and board[6] == plyr) or
(board[2] == plyr and board[5] == plyr and board[8] == plyr)):
return True
else:
return False
def minimax(board, turn, FIRST):
possibleMoves = getOpenPos(board)
#check if won
if (winning(board, opp)):
return -10
elif (winning(board, plyr)):
return 10
scores = []
#new board created for recursion, and whoevers turn it is
for move in possibleMoves:
newBoard = board
newBoard[move] = turn
if (turn == plyr):
scores.append( [move,minimax(newBoard, opp, False)] )
elif (turn == opp):
scores.append( [move, minimax(newBoard, plyr, False)] )
#collapse recursion by merging all scores to find optimal position
#see if there is a negative value (loss) and if there is its a -10
if not FIRST:
bestScore = 0
for possibleScore in scores:
move = possibleScore[0]
score = possibleScore[1]
if score == -10:
return -10
else:
if score > bestScore:
bestScore = score
return bestScore
else:
bestMove, bestScore = 0, 0
for possibleScore in scores:
move = possibleScore[0]
score = possibleScore[1]
if score > bestScore:
bestMove = move
bestScore = score
#returns best position
return bestMove
print(minimax(board, plyr, True))
【问题讨论】:
标签: python algorithm artificial-intelligence minimax