hex棋人机对战代码实现
时间: 2023-07-30 20:10:37 浏览: 802
以下是一个简单的hex棋人机对战代码实现,主要使用了minimax算法和alpha-beta剪枝。
```python
import random
# 坐标转换函数
def to_index(row, col, size):
return row * size + col
def to_row_col(index, size):
return (index // size, index % size)
# 定义棋盘类
class HexBoard:
def __init__(self, size):
self.size = size
self.board = [0] * (size * size)
# 棋子是否在边缘
def is_edge(self, index):
row, col = to_row_col(index, self.size)
return row == 0 or row == self.size - 1 or col == 0 or col == self.size - 1
# 检查是否有玩家获胜
def is_winner(self, player):
visited = [False] * (self.size * self.size)
for i in range(self.size):
if self.board[to_index(0, i, self.size)] == player:
if self.dfs(0, i, visited, player):
return True
return False
# dfs搜索函数
def dfs(self, row, col, visited, player):
if self.board[to_index(row, col, self.size)] != player:
return False
if self.is_edge(to_index(row, col, self.size)):
return True
visited[to_index(row, col, self.size)] = True
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
new_row, new_col = row + i, col + j
if new_row < 0 or new_row >= self.size or new_col < 0 or new_col >= self.size:
continue
if visited[to_index(new_row, new_col, self.size)]:
continue
if self.dfs(new_row, new_col, visited, player):
return True
return False
# 检查是否有空位
def is_full(self):
return all(self.board)
# 返回所有可用的位置
def available_moves(self):
return [i for i in range(self.size * self.size) if self.board[i] == 0]
# 下棋函数
def play_move(self, index, player):
if self.board[index] != 0:
return False
self.board[index] = player
return True
# 打印棋盘
def print_board(self):
p = {0: '.', 1: 'x', -1: 'o'}
for i in range(self.size):
print(' ' * i, end='')
for j in range(self.size):
print(p[self.board[to_index(i, j, self.size)]], end=' ')
print()
# 定义玩家类
class HumanPlayer:
def __init__(self, player):
self.player = player
def get_move(self, board):
while True:
try:
move = int(input(f"Player {self.player}, enter your move: "))
if move not in board.available_moves():
print("Invalid move! Please try again.")
continue
return move
except ValueError:
print("Invalid input! Please enter a number.")
# 定义AI类
class AIPlayer:
def __init__(self, player, depth):
self.player = player
self.depth = depth
# 估值函数
def evaluate(self, board):
if board.is_winner(self.player):
return 100
if board.is_winner(-self.player):
return -100
return 0
# minimax算法
def minimax(self, board, depth, alpha, beta, maximizing_player):
if depth == 0 or board.is_full():
return self.evaluate(board)
if maximizing_player:
max_eval = float('-inf')
for move in board.available_moves():
board.play_move(move, self.player)
eval = self.minimax(board, depth - 1, alpha, beta, False)
board.board[move] = 0
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
return max_eval
else:
min_eval = float('inf')
for move in board.available_moves():
board.play_move(move, -self.player)
eval = self.minimax(board, depth - 1, alpha, beta, True)
board.board[move] = 0
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval
# alpha-beta剪枝算法
def alpha_beta_pruning(self, board):
best_move = None
max_eval = float('-inf')
alpha = float('-inf')
beta = float('inf')
for move in board.available_moves():
board.play_move(move, self.player)
eval = self.minimax(board, self.depth - 1, alpha, beta, False)
board.board[move] = 0
if eval > max_eval:
best_move = move
max_eval = eval
alpha = max(alpha, eval)
return best_move
def get_move(self, board):
print(f"Player {self.player} is thinking...")
return self.alpha_beta_pruning(board)
# 游戏主函数
def play_game():
size = 5
board = HexBoard(size)
human_player = HumanPlayer(1)
ai_player = AIPlayer(-1, 3)
players = [human_player, ai_player]
random.shuffle(players)
current_player = players[0]
while not board.is_full() and not board.is_winner(1) and not board.is_winner(-1):
board.print_board()
move = current_player.get_move(board)
board.play_move(move, current_player.player)
current_player = players[(players.index(current_player) + 1) % 2]
board.print_board()
if board.is_winner(1):
print("Player 1 wins!")
elif board.is_winner(-1):
print("Player 2 wins!")
else:
print("It's a tie!")
if __name__ == '__main__':
play_game()
```
运行以上代码可以进行人机对战,玩家使用数字输入坐标进行下棋。AI使用alpha-beta剪枝算法进行决策,可以通过调整depth参数来控制AI的难度。
阅读全文