July 20, 2025/19 阅读
分数判定—井字棋
- 使用设置记录下输赢情况。赢表示1,输表示-1,平表示0
- 在创建节点功能中,节点数据新增一个分数键值对,默认值为None
- 创建get_state功能进行判断谁是赢者
# 获取棋盘状态
def get_state(board):
# 行相同
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] and board[i][0] != EMPTY:
# 返回赢家
return board[i][0]
# 列相同
for j in range(3):
if board[0][j] == board[1][j] == board[2][j] and board[0][j] != EMPTY:
# 返回赢家
return board[0][j]
# 对角线相同
if board[0][0] == board[1][1] == board[2][2] and board[1][1] != EMPTY:
# 返回赢家
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] and board[1][1] != EMPTY:
# 返回赢家
return board[0][2]
# 平局,返回'Draw'
if len(empty_pos(board)) == 0:
return 'Draw'
# 继续,返回'Continue'
return 'Continue'
- 'x'表示✖赢
- 'o'表示●赢
- 'Draw'表示平局
- 'Continue'表示继续下棋
- 获取棋盘状态
state = get_state(node['board'])
- 计算并设置叶子节点分数
if is_over(['board']) == True:
if state == 'Draw':
node['score'] = 0
elif state == X_CHESS:
node['score'] = 1
else:
node['score'] = -1
- 使用current_chess功能获取当前落子情况,并赋值给全局变量ai_chess
if state != 'Continue':
if state == 'Draw':
node['score'] = 0
elif state == ai_chess:
node['score'] = 1
else:
node['score'] = -1