我正在使用Python通过MiniMax算法创建无与伦比的TicTacToe游戏。我的代码似乎没有为每个职位输出正确的评估。据我了解,算法应该通过假设玩家发挥最佳状态来“测试”每个位置。但是,评估始终返回一个NoneType。
我尝试在评估函数中使用其他数字与else。但是,这样做似乎并不能返回正确的评估结果,至少,我认为这是不正确的。
board= ["O", 1, "X",
"X", 4, "X",
6, "O", "O"]
human = "O"
robot= "X"
#winning board combinations
def winning(board, player):
#horizontal tests
if((board[0] == player and board[1]==player and board[2]==player) or
(board[3]==player and board[4]==player and board[5]==player) or
(board[6]==player and board[7]==player and board[8]==player) or
#diagonal tests
(board[0]==player and board[4]==player and board[8]==player) or
(board[2]==player and board[4]==player and board[6]==player) or
#vertical tests
(board[0]==player and board[3]==player and board[6]==player) or
(board[1]==player and board[4]==player and board[7]==player) or
(board[2]==player and board[5]==player and board[8]==player)
):
return True
else:
return False
#evaluates the score of the game
def evaluation(board):
if (winning(board, human)):
return +10
elif (winning(board, robot)):
return -10
elif(len(empty_spots)==0):
return 0
#trying to get another value
# else:
# return 2
#this is to find the empty spots on the board
def empty_spots_func(board):
for i in board:
if(i!="X" and i!="O"):
empty_spots.append(i)
def minimax(spot, empty_spots, depth, maximizing_player):
if depth<=0:
eval= evaluation(board)
print(f'The evaluation function returns: {evaluation(board)}')
return eval
if maximizing_player:
maxEval= -1000000
#for each move in all possible moves
for spot in empty_spots:
#make the move
board[spot]=robot
#evaluate the outcome of the move
eval = minimax(spot, empty_spots, depth-1, False)
#then remove the move and replace it with the number
board[spot]=spot
maxEval= max(maxEval, eval)
# print(f'The maximum evaluation {maxEval}')
return maxEval
else:
minEval= +1000000
#for each move in all possible moves
for spot in empty_spots:
#make the move
board[spot]=human
#evaluate the outcome of the move
eval= minimax(spot, empty_spots, depth-1, True)
#then remove the spot
board[spot]=spot
#figure out the minimal evaluation
minEval=min(minEval, eval)
# print(f'The minimal evaluation is {minEval}')
return minEval
现在测试主要功能中的一个位置:
test_spot_eval=minimax(0, empty_spots, len(empty_spots), True)
empty_spots_func(board)
print(f'The spot eval is {test_spot_eval}')
在评估中没有最后一个“ else”的情况下,minimax仅返回一个NoneType。
答案 0 :(得分:0)
我制作了一个单独的程序来检查评估和获胜组合。原来,我犯的错误是:
在接受用户输入后,我没有将人工输入放在板上
我没有注意到我应该错误地使评估函数返回人类获胜时的正值,而机器人获胜时则应返回负值。
也许我还没有发现更多的错误。
错误1导致我的评估函数返回NoneType,因为在没有人工输入的情况下,该算法无法评估获胜位置。