# Minimax算法和跳棋游戏

##### 问题描述投票：0回答：1

``````def run_game(board):
players = board.players
is_move_possible = True
move = 0
while is_move_possible:
is_move_possible = move_piece_minimax(board, players[move % 2])
move += 1
``````

``````def move_piece_minimax(board, player):
best_move = minimax(copy.deepcopy(board), player, 0)
if best_move.score == +infinity or best_move.score == -infinity:
return False
move_single_piece(board.fields, player, best_move)
return True
``````

``````def minimax(board, player, depth):
best_move = Move(-1, -1, -infinity if player.name == PLAYER_NAMES['P1'] else +infinity)

if depth == MAX_SEARCH_DEPTH or game_over(board):
score = evaluate(board)
return Move(-1, -1, score)

for correct_move in get_all_correct_moves(player, board.fields):
x, y, piece = correct_move.x, correct_move.y, correct_move.piece
move_single_piece(board.fields, player, correct_move)
player_to_move = get_player_to_move(board, player)
move = minimax(board, player_to_move, depth + 1)    # <--- here is a recursion
move.x = x
move.y = y
move.piece = piece

if player.name == PLAYER_NAMES['P1']:
if move.score > best_move.score:
best_move = move  # max value
else:
if move.score < best_move.score:
best_move = move  # min value

return best_move
``````

``````class Move:
def __init__(self, x, y, score, piece=None):
self.x = x
self.y = y
self.score = score
self.piece = piece
``````

python algorithm recursion artificial-intelligence minimax
0