写一个黑白翻转棋 有ai 有人工对战
- User
写一个黑白翻转棋 有ai 有人工对战
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
写一个黑白翻转棋 有ai 有人工对战
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
好的,这里提供一个 Python 实现的黑白翻转棋(也称为奥赛罗)游戏,包含 AI 对战和人工对战功能。代码中包含详细的注释,方便理解。
import random
class Othello:
def __init__(self, board_size=8):
self.board_size = board_size
self.board = [['.' for _ in range(board_size)] for _ in range(board_size)]
self.board[board_size // 2 - 1][board_size // 2 - 1] = 'W' # 白色棋子
self.board[board_size // 2][board_size // 2] = 'W'
self.board[board_size // 2 - 1][board_size // 2] = 'B' # 黑色棋子
self.board[board_size // 2][board_size // 2 - 1] = 'B'
self.current_player = 'B' # 黑色先手
self.pass_count = 0 # 连续pass的次数
def print_board(self):
"""打印棋盘"""
print(" " + " ".join([chr(ord('a') + i) for i in range(self.board_size)]))
for i in range(self.board_size):
print(str(i + 1) + " " + " ".join(self.board[i]))
def get_valid_moves(self, player):
"""获取当前玩家的有效落子位置"""
moves = []
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] == '.':
if self.is_valid_move(row, col, player):
moves.append((row, col))
return moves
def is_valid_move(self, row, col, player):
"""判断落子位置是否有效"""
if self.board[row][col] != '.':
return False
directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
i, j = row + dr, col + dc
if 0 <= i < self.board_size and 0 <= j < self.board_size and self.board[i][j] == self.get_opponent(player):
while 0 <= i < self.board_size and 0 <= j < self.board_size and self.board[i][j] == self.get_opponent(player):
i += dr
j += dc
if 0 <= i < self.board_size and 0 <= j < self.board_size and self.board[i][j] == player:
return True
return False
def make_move(self, row, col, player):
"""落子并翻转棋子"""
self.board[row][col] = player
directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
i, j = row + dr, col + dc
if 0 <= i < self.board_size and 0 <= j < self.board_size and self.board[i][j] == self.get_opponent(player):
temp = []
while 0 <= i < self.board_size and 0 <= j < self.board_size and self.board[i][j] == self.get_opponent(player):
temp.append((i, j))
i += dr
j += dc
if 0 <= i < self.board_size and 0 <= j < self.board_size and self.board[i][j] == player:
for r, c in temp:
self.board[r][c] = player
def get_opponent(self, player):
"""获取对手的棋子颜色"""
return 'W' if player == 'B' else 'B'
def get_score(self):
"""计算双方的得分"""
black_score = 0
white_score = 0
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] == 'B':
black_score += 1
elif self.board[row][col] == 'W':
white_score += 1
return black_score, white_score
def is_game_over(self):
"""判断游戏是否结束"""
if not self.get_valid_moves('B') and not self.get_valid_moves('W'):
self.pass_count += 1
if self.pass_count >= 2:
return True
else:
return False
else:
self.pass_count = 0
return False
def ai_move(self, player):
"""AI 落子"""
valid_moves = self.get_valid_moves(player)
if not valid_moves:
return None # 没有有效落子位置
# 简单 AI:随机选择一个有效落子位置
# 可以根据需要实现更复杂的 AI 算法,例如 Minimax 算法
row, col = random.choice(valid_moves)
return row, col
def play_human_vs_human(self):
"""人机对战"""
while not self.is_game_over():
self.print_board()
if self.current_player == 'B':
print("黑色玩家的回合")
while True:
try:
move = input("请输入落子位置 (例如: a1): ")
col = ord(move[0]) - ord('a')
row = int(move[1]) - 1
if 0 <= row < self.board_size and 0 <= col < self.board_size and self.board[row][col] == '.' and self.is_valid_move(row, col, self.current_player):
break
else:
print("无效的落子位置,请重新输入。")
except (ValueError, IndexError):
print("无效的输入格式,请重新输入。")
self.make_move(row, col, self.current_player)
else:
print("白色玩家的回合")
while True:
try:
move = input("请输入落子位置 (例如: a1): ")
col = ord(move[0]) - ord('a')
row = int(move[1]) - 1
if 0 <= row < self.board_size and 0 <= col < self.board_size and self.board[row][col] == '.' and self.is_valid_move(row, col, self.current_player):
break
else:
print("无效的落子位置,请重新输入。")
except (ValueError, IndexError):
print("无效的输入格式,请重新输入。")
self.make_move(row, col, self.current_player)
self.current_player = self.get_opponent(self.current_player)
self.print_board()
black_score, white_score = self.get_score()
print("游戏结束!")
print("黑色棋子数量:", black_score)
print("白色棋子数量:", white_score)
if black_score > white_score:
print("黑色玩家获胜!")
elif white_score > black_score:
print("白色玩家获胜!")
else:
print("平局!")
def play_ai_vs_ai(self):
"""AI 对战 AI"""
while not self.is_game_over():
self.print_board()
if self.current_player == 'B':
print("黑色 AI 的回合")
else:
print("白色 AI 的回合")
move = self.ai_move(self.current_player)
if move is None:
# AI 没有有效落子位置,pass 一步
print("AI pass")
self.current_player = self.get_opponent(self.current_player)
continue
row, col = move
self.make_move(row, col, self.current_player)
self.current_player = self.get_opponent(self.current_player)
self.print_board()
black_score, white_score = self.get_score()
print("游戏结束!")
print("黑色棋子数量:", black_score)
print("白色棋子数量:", white_score)
if black_score > white_score:
print("黑色 AI 获胜!")
elif white_score > black_score:
print("白色 AI 获胜!")
else:
print("平局!")
def play_human_vs_ai(self):
"""人机对战"""
while not self.is_game_over():
self.print_board()
if self.current_player == 'B':
print("黑色玩家的回合")
while True:
try:
move = input("请输入落子位置 (例如: a1): ")
col = ord(move[0]) - ord('a')
row = int(move[1]) - 1
if 0 <= row < self.board_size and 0 <= col < self.board_size and self.board[row][col] == '.' and self.is_valid_move(row, col, self.current_player):
break
else:
print("无效的落子位置,请重新输入。")
except (ValueError, IndexError):
print("无效的输入格式,请重新输入。")
self.make_move(row, col, self.current_player)
else:
print("白色 AI 的回合")
move = self.ai_move(self.current_player)
if move is None:
# AI 没有有效落子位置,pass 一步
print("AI pass")
else:
row, col = move
self.make_move(row, col, self.current_player)
self.current_player = self.get_opponent(self.current_player)
self.print_board()
black_score, white_score = self.get_score()
print("游戏结束!")
print("黑色棋子数量:", black_score)
print("白色棋子数量:", white_score)
if black_score > white_score:
print("黑色玩家获胜!")
elif white_score > black_score:
print("白色 AI 获胜!")
else:
print("平局!")
# 主程序
if __name__ == "__main__":
game = Othello()
while True:
print("\n请选择游戏模式:")
print("1. 人机对战")
print("2. AI 对战 AI")
print("3. 人人对战")
print("4. 退出")
choice = input("请输入您的选择: ")
if choice == '1':
game.play_human_vs_ai()
elif choice == '2':
game.play_ai_vs_ai()
elif choice == '3':
game.play_human_vs_human()
elif choice == '4':
break
else:
print("无效的选择,请重新输入。")
代码解释:
Othello 类:
__init__(self, board_size=8): 初始化棋盘大小、棋盘状态、当前玩家和连续pass次数。print_board(self): 打印棋盘到控制台。get_valid_moves(self, player): 获取当前玩家所有有效的落子位置。is_valid_move(self, row, col, player): 检查指定位置是否为当前玩家的有效落子位置。make_move(self, row, col, player): 执行落子操作,并翻转被夹住的棋子。get_opponent(self, player): 获取当前玩家的对手。get_score(self): 计算黑白双方的得分。is_game_over(self): 检查游戏是否结束(双方都没有有效落子位置)。ai_move(self, player): AI 的落子逻辑(当前实现为随机选择)。play_human_vs_human(self): 实现人人对战的游戏流程。play_ai_vs_ai(self): 实现 AI 对战 AI 的游戏流程。play_human_vs_ai(self): 实现人机对战的游戏流程。主程序 (if __name__ == "__main__":):
Othello 类的实例。如何运行代码:
.py 文件(例如 othello.py)。python othello.py改进方向:
这个代码提供了一个基本的黑白翻转棋游戏框架,你可以根据自己的需求进行扩展和改进。 希望对你有所帮助!