
只要周末有空闲时间,我就喜欢编写一些小而愚蠢的东西。其中一个想法变成了一款命令行国际象棋游戏,您可以在其中与 openai 对抗。我将其命名为“skakibot”,灵感来自“skaki”,希腊语中的国际象棋单词。
优秀的 python-chess 库负责所有的国际象棋机制。我们的目标不是从头开始构建一个国际象棋引擎,而是展示 openai 如何轻松地集成到这样的项目中。
让我们深入研究代码,看看它们是如何组合在一起的!
我们将首先设置一个基本的游戏循环,该循环接受用户输入并为国际象棋逻辑奠定基础。
def main():
while true:
user_input = input("enter your next move: ").strip()
if user_input.lower() == 'exit':
print("thanks for playing skakibot. goodbye!")
break
if not user_input:
print("move cannot be empty. please try again.")
continue
print(f"you entered: {user_input}")
此时,代码并没有做太多事情。它只是提示用户输入、验证并打印它:
enter your next move: e2e4 you entered: e2e4 enter your next move: exit thanks for playing skakibot. goodbye!
接下来,我们引入 python-chess,它将处理棋盘管理、移动验证和游戏结束场景。
pip install chess
安装库后,我们可以初始化棋盘并在提示用户输入之前打印它:
import chess
def main():
board = chess.board()
while not board.is_game_over():
print(board)
user_input = input("enter your next move (e.g., e2e4): ").strip()
if user_input.lower() == 'exit':
print("thanks for playing skakibot. goodbye!")
break
为了使游戏正常运行,我们需要验证用户输入并向棋盘应用合法的移动。 uci(通用国际象棋接口)格式用于移动,您可以在其中指定起始和结束方格(例如,e2e4)。
def main():
board = chess.board()
while not board.is_game_over():
# ...
try:
move = chess.move.from_uci(user_input)
if move in board.legal_moves:
board.push(move)
print(f"move '{user_input}' played.")
else:
print("invalid move. please enter a valid move.")
except valueerror:
print("invalid move format. use uci format like 'e2e4'.")
我们现在可以处理游戏结束的场景,例如将死或僵局:
def main():
board = chess.board()
while not board.is_game_over():
# ...
if board.is_checkmate():
print("checkmate! the game is over.")
elif board.is_stalemate():
print("stalemate! the game is a draw.")
elif board.is_insufficient_material():
print("draw due to insufficient material.")
elif board.is_seventyfive_moves():
print("draw due to the seventy-five-move rule.")
else:
print("game ended.")
在这个阶段,你为双方效力。您可以通过尝试 fool's mate 来测试它,并按照 uci 格式执行以下动作:
立即学习“Python免费学习笔记(深入)”;
这会导致快速将死。
现在是时候让人工智能接管一边了。 openai 将评估董事会的状态并提出最佳举措。
我们首先从环境中获取 openai api 密钥:
# config.py
import os
def get_openai_key() -> str:
key = os.getenv("openai_api_key")
if not key:
raise environmenterror("openai api key is not set. please set 'openai_api_key' in the environment.")
return key
接下来,我们编写一个函数来将棋盘状态(以 forsyth-edwards notation (fen) 格式)发送到 openai 并检索建议的走法:
def get_openai_move(board):
import openai
openai.api_key = get_openai_key()
board_fen = board.fen()
response = openai.chatcompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": (
"you are an expert chess player and assistant. your task is to "
"analyse chess positions and suggest the best move in uci format."
)},
{"role": "user", "content": (
"the current chess board is given in fen notation:\n"
f"{board_fen}\n\n"
"analyse the position and suggest the best possible move. respond "
"with a single uci move, such as 'e2e4'. do not provide any explanations."
)}
])
suggested_move = response.choices[0].message.content.strip()
return suggested_move
提示很简单,但它可以很好地生成有效的动作。它为 openai 提供了足够的上下文来了解董事会状态并以 uci 格式的合法举措进行响应。
棋盘状态以 fen 格式发送,它提供了游戏的完整快照,包括棋子位置、轮到谁、易位权和其他详细信息。这是理想的,因为 openai 的 api 是无状态的,并且不会保留请求之间的信息,因此每个请求必须包含所有必要的上下文。
目前,为了简单起见,该模型被硬编码为 gpt-3.5-turbo,但最好从环境中获取它,就像我们对 api 密钥所做的那样。这将使以后更容易更新或使用不同的模型进行测试。
最后,我们可以将人工智能集成到主游戏循环中。 ai 在每个用户移动后评估棋盘并播放其响应。
def main():
board = chess.Board()
while not board.is_game_over():
clear_display()
print(board)
user_input = input("Enter your next move (e.g., e2e4): ").strip()
if user_input.lower() == 'exit':
print("Thanks for playing SkakiBot. Goodbye!")
break
try:
move = chess.Move.from_uci(user_input)
if move in board.legal_moves:
board.push(move)
print(f"Move '{user_input}' played.")
else:
print("Invalid move. Please enter a valid move.")
continue
except ValueError:
print("Invalid move format. Use UCI format like 'e2e4'.")
continue
try:
ai_move_uci = get_openai_move(board)
ai_move = chess.Move.from_uci(ai_move_uci)
if ai_move in board.legal_moves:
board.push(ai_move)
print(f"OpenAI played '{ai_move_uci}'.")
else:
print("OpenAI suggested an invalid move. Skipping its turn.")
except Exception as e:
print(f"Error with OpenAI: {str(e)}")
print("The game is ending due to an error with OpenAI. Goodbye!")
break
就是这样!现在您已经有了一个功能齐全的国际象棋游戏,您可以在其中与 openai 对抗。代码还有很大的改进空间,但它已经可以玩了。有趣的下一步是让两个人工智能相互对抗,让他们一决胜负。
代码可在 github 上获取。祝实验愉快!
以上就是使用 Python 和 OpenAI 构建国际象棋游戏的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号