使用 Python 和 OpenAI 构建国际象棋游戏
来源:dev.to
时间:2024-12-02 11:00:55 430浏览 收藏
一分耕耘,一分收获!既然打开了这篇文章《使用 Python 和 OpenAI 构建国际象棋游戏》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

只要周末有空闲时间,我就喜欢编写一些小而愚蠢的东西。其中一个想法变成了一款命令行国际象棋游戏,您可以在其中与 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 格式执行以下动作:
- f2f3
- e7e5
- g2g4
- d8h4
这会导致快速将死。
集成 openai
现在是时候让人工智能接管一边了。 openai 将评估董事会的状态并提出最佳举措。
获取 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
ai移动生成
接下来,我们编写一个函数来将棋盘状态(以 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 构建国际象棋游戏》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
245 收藏
-
211 收藏
-
204 收藏
-
147 收藏
-
467 收藏
-
333 收藏
-
365 收藏
-
446 收藏
-
464 收藏
-
417 收藏
-
299 收藏
-
412 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习