我有一个尽可能简单的negamax算法,用于评估Tic Tac Toe中的位置。游戏的状态存储为numpy中的数组,X的部分用1表示,而O的部分用4表示。
我刚刚测试了这个,发现:
a = np.zeros(9).reshape(3,3)
negaMax(a, 6, 1) # Returned zero as it should
negaMax(a, 7, 1) # Returns 100
这意味着我的算法认为它已经找到了一种方法让X在Tic Tac Toe的游戏中赢得七层,这对于体面的游戏来说显然是不可能的。我无法弄清楚如何打印它找到的最佳动作,所以在调试时遇到了麻烦。我做错了什么?
def winCheck(state):
"""Takes a position, and returns the outcome of that game"""
# Sums which correspond to a line across a column
winNums = list(state.sum(axis=0))
# Sums which correspond to a line across a row
winNums.extend(list(state.sum(axis=1)))
# Sums which correspond to a line across the main diagonal
winNums.append(state.trace())
# Sums which correspond to a line across the off diagonal
winNums.append(np.flipud(state).trace())
if Square.m in winNums:
return 'X'
elif (Square.m**2 + Square.m) in winNums:
return 'O'
elif np.count_nonzero(state) == Square.m**2:
return 'D'
else:
return None
def moveFind(state):
"""Takes a position as an nparray and determines the legal moves"""
moveChoices = []
# Iterate over state, to determine which squares are empty
it = np.nditer(state, flags=['multi_index'])
while not it.finished:
if it[0] == 0:
moveChoices.append(it.multi_index)
it.iternext()
return moveChoices
def moveSim(state, move, player):
"""Create the state of the player having moved without interfering with the board"""
simState = state.copy()
if player == 1:
simState[move] = 1
else:
simState[move] = gamecfg.n + 1
return simState
def positionScore(state):
"""The game is either won or lost"""
if winCheck(state) == 'X':
return 100
elif winCheck(state) == 'O':
return -100
else:
return 0
def negaMax(state, depth, colour):
"""Recursively find the best move via a negamax search"""
if depth == 0:
return positionScore(state) * colour
highScore = -100
moveList = moveFind(state)
for move in moveList:
score = -negaMax(moveSim(state, move, colour), depth -1, colour * -1)
highScore = max(score, highScore)
return highScore
答案 0 :(得分:2)
当制作一行3个符号时,您的代码不会认为游戏停止。
这意味着它正在玩一个tic-tac-toe的变体,如果O在3行之后即使在3行之后也会获胜。
对于这个变种,程序已经正确地发现X可能总是赢!
(我遇到了同样的情况,我制作了一个国际象棋程序,计算机很乐意牺牲它的国王,如果它稍后会达到将军......)