我正在为西洋跳棋软件开发一个 minimax 算法,我的算法崩溃了,因为它一直说没有可用的动作,而实际上有。手动播放时不会发生这种情况。
我的算法如下:
def _minimax(self, board_state : Board, depth : int, max_player : bool, game : Game):
if depth == 0 or game.end_game:
return board_state._evaluate(), board_state
best_move = None
if max_player: #if AI
best = -math.inf
all_moves = self.get_all_moves(board_state, "B", game) #get simulated moves
for piece, move, new_board in all_moves:
eval, _ = self._minimax(new_board, depth - 1, False, game)
if eval > best:
best = eval
best_move = (piece, move, new_board)
else: #if random or human
best = math.inf
all_moves = self.get_all_moves(board_state, "R", game)
for piece, move, new_board in all_moves:
eval, _ = self._minimax(new_board, depth - 1, True, game)
if eval < best:
best = eval
best_move = (piece, move, new_board)
return best, best_move
我对
simulate_move
方法的实现如下:
def simulate_move(self, piece, move, game):
game.move(piece, move)
return game.board
我对
get_all_moves
方法的实现如下:
def get_all_moves(self, board, color, game):
#get all possible moves that we can make from a board
moves = []
all_moves = game.player_all_moves(board, color)
for _,move,piece in all_moves:
#make a copy of the current board state
temp_game = deepcopy(game)
new_board = self.simulate_move(piece, move, temp_game)
moves.append((piece, move, new_board))
return moves
suggest_move
方法内部调用了minimax算法,即:
def suggest_move(self):
eval, best_move = self._minimax(self._board, 2, True, self._game)
piece, sug_move, new_board = best_move
return piece, sug_move, new_board
最后,这是我模拟游戏的方式(这是在一个更大的函数中,不需要发布整个函数):
piece, move, new_board = current.suggest_move()
game.move(piece, move)
game.board = new_board
**编辑: 错误回溯是:
Traceback (most recent call last):
File "bots.py", line 289, in <module>
cmd()
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 1137, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 1062, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.8/dist-packages/click/core.py", line 763, in invoke
return __callback(*args, **kwargs)
File "bots.py", line 213, in cmd
simulate(game, num_games, bots)
File "bots.py", line 184, in simulate
piece, move, new_game = current.suggest_move()
File "bots.py", line 68, in suggest_move
piece, sug_move, new_game = best_move
TypeError: cannot unpack non-iterable NoneType object
请让我知道我的代码可能有什么问题!谢谢。
我尝试过手动测试,在我的模拟中模拟西洋跳棋游戏的开始,看看是否会出现同样的错误。手动播放时我没有收到错误消息——我可以移动到棋盘上的可用空间。同样奇怪的是,当我打印游戏中每一轮的可用动作时,它说代码错误时没有动作。