Python实现奥赛罗(Reversi)游戏树生成功能报错求助
奥赛罗游戏树生成函数错误排查请求
我需要编写一个不依赖任何库的Python函数,用于生成奥赛罗(Reversi)的游戏树,最终输出元组(a,b,c):
a:黑棋获胜局面数b:白棋获胜局面数c:平局局面数
给定的棋盘以TXT文件形式提供,示例棋盘如下:
. . W W
. . B B
W W W B
W B B W
但当前代码输出与预期不符:示例预期输出为(2, 16, 0),实际得到(5, 7, 11)。以下是我的代码,无法定位错误,请求帮助排查。
def generate_game_tree(filename: str): # Load the board from the file board = [line.split() for line in open(filename)] # Initialize the game tree with the root node representing the current board state game_tree = [(board, 0)] black_count = 0 white_count = 0 draw_count = 0 # Generate the game tree by expanding the nodes in a breadth-first manner i = 0 while i < len(game_tree): node = game_tree[i] board, _ = node valid_moves = get_valid_moves(board) for move in valid_moves: new_board = make_move(board, move) game_tree.append((new_board, i)) i += 1 for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == "W": white_count += 1 if board[i][j] == "B": black_count += 1 else: draw_count += 1 return black_count, white_count, draw_count def make_move(board, move): flips = [] x, y = move curr_color = board[x][y] for dx, dy in [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]: x, y = move x += dx y += dy if not (0 <= x < len(board) and 0 <= y < len(board[0])): continue if board[x][y] != '.': continue while board[x][y] != curr_color: flips.append((x, y)) x += dx y += dy if not (0 <= x < len(board) and 0 <= y < len(board[0])): break return flips def get_valid_moves(board): valid_moves = [] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] != '.': continue flips = make_move(board, (i, j)) if flips: valid_moves.append((i, j)) return valid_moves
内容的提问来源于stack exchange,提问作者Jake Sparrow
相关产品推荐
相关产品推荐

