0

0

使用 Python 和 OpenAI 构建国际象棋游戏

聖光之護

聖光之護

发布时间:2024-11-24 22:21:01

|

923人浏览过

|

来源于dev.to

转载

使用 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 格式执行以下动作:

立即学习Python免费学习笔记(深入)”;

科大讯飞-AI虚拟主播
科大讯飞-AI虚拟主播

科大讯飞推出的移动互联网智能交互平台,为开发者免费提供:涵盖语音能力增强型SDK,一站式人机智能语音交互解决方案,专业全面的移动应用分析;

下载
  • 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开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

749

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

635

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

758

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

618

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1262

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

577

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

705

2023.08.11

PPT交互图表教程大全
PPT交互图表教程大全

本专题整合了PPT交互图表相关教程汇总,阅读专题下面的文章了解更多详细内容。

39

2026.01.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 3万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号