【 知你所想 】基于ernie-x1-turbo推理模型实现趣味猜心游戏

🌟 项目特点

  • 🤖 智能AI:基于文心一言大模型,具有强大的推理能力
  • 🎯 实时思考:展示AI的思考过程,让你了解AI是如何推理的
  • 🎮 互动性强:通过简单的"是/否"问答,让游戏更加有趣
  • 📊 计分系统:记录AI和人类的得分,增加游戏竞技性
  • 🎨 精美界面:采用现代化的UI设计,提供流畅的游戏体验

🎯 游戏规则

  1. 玩家在心中想一个物体
  2. AI会通过最多20个"是/否"问题来猜测这个物体
  3. 玩家需要诚实回答每个问题
  4. 如果AI在20个问题内猜对,AI得1分
  5. 如果AI没有猜对,人类得1分
  6. 游戏结束后可以重新开始,继续挑战

💡 特色功能

  • 实时思考展示:AI会展示它的思考过程,让你了解它是如何推理的
  • 智能问题生成:AI会根据之前的回答,生成更有针对性的问题
  • 容错机制:考虑到玩家可能回答错误的情况,AI会进行更全面的推理
  • 分数统计:记录游戏得分,增加竞技性
  • 轮数显示:清晰显示当前问题轮数,让游戏进度一目了然

🎮 如何开始

  1. 在输入框中输入你想让AI猜的物体
  2. 点击"设置目标物体"按钮开始游戏
  3. 回答AI提出的"是/否"问题
  4. 等待AI的最终猜测
  5. 查看结果并开始新的游戏

🎯 游戏技巧

  • 选择具体的物体,避免抽象概念
  • 诚实回答每个问题
  • 观察AI的思考过程,了解它的推理方式
  • 尝试选择一些不常见的物体,增加游戏难度

🎨 界面预览

游戏界面采用现代化的设计风格,包含:

  • 清晰的游戏标题和说明
  • 醒目的轮数计数器
  • 实时更新的分数显示
  • 优雅的输入框和按钮
  • 流畅的动画效果

import os
import gradio as gr
from openai import OpenAI
import time# 初始化OpenAI客户端
client = OpenAI(api_key="填写你的密钥",base_url="https://aistudio.baidu.com/llm/lmapi/v3"
)# 游戏状态
class GameState:def __init__(self):self.questions_asked = 0self.max_questions = 20self.game_history = []self.target_object = Noneself.is_game_over = Falseself.current_question = Noneself.is_game_started = Falseself.ai_score = 0self.human_score = 0game_state = GameState()def stream_response(response, history_text):"""流式输出响应"""full_response = ""for chunk in response:if chunk.choices[0].delta.content:full_response += chunk.choices[0].delta.contentyield full_response, history_textreturn full_response, history_textdef set_target_object(target):"""设置目标物体并开始游戏"""if not target.strip():return "请输入目标物体!", "", "", "0/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""game_state.target_object = target.strip()game_state.is_game_started = Truegame_state.questions_asked = 0game_state.game_history = []game_state.is_game_over = Falsegame_state.current_question = None# 让AI提出第一个问题prompt = """你正在玩20问游戏。请提出第一个问题来猜测玩家心中的物体。
问题应该是一个简单的"是/否"问题,比如"它是活物吗?"、"它比汽车大吗?"等。
请先思考一下,然后只输出问题,不要输出其他内容。"""try:yield "游戏开始!", "\n".join(game_state.game_history), "", "0/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", "AI正在思考第一个问题..."response = client.chat.completions.create(model="ernie-x1-turbo-32k",messages=[{"role": "user", "content": prompt}],temperature=0.7,max_tokens=100,stream=True)first_question = ""thinking_process = "AI正在思考第一个问题...\n\n"for chunk in response:if hasattr(chunk.choices[0].delta, 'reasoning_content') and chunk.choices[0].delta.reasoning_content:thinking_process += chunk.choices[0].delta.reasoning_contentyield "游戏开始!", "\n".join(game_state.game_history), "", "0/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", thinking_processif chunk.choices[0].delta.content:first_question += chunk.choices[0].delta.contentgame_state.current_question = first_question.strip()game_state.game_history.append(f"AI问题 {game_state.questions_asked + 1}: {first_question.strip()}")yield f"游戏开始!\nAI的第一个问题:{first_question.strip()}", "\n".join(game_state.game_history), "", "0/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", thinking_process + "\n\n思考完成!"except Exception as e:yield f"发生错误: {str(e)}", "", "", "0/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""def answer_question(answer):"""处理玩家的回答"""if not game_state.is_game_started:return "请先设置目标物体!", "", "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""if game_state.is_game_over:return "游戏已结束,请开始新游戏!", "", "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""if not answer.strip():return "请输入你的回答!", "", "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""# 记录玩家的回答game_state.game_history.append(f"玩家回答: {answer}")game_state.questions_asked += 1# 如果是最后一轮,让AI进行最终猜测if game_state.questions_asked >= game_state.max_questions:game_state.is_game_over = True# 让AI进行最终猜测guess_prompt = f"""基于之前的对话:
{chr(10).join(game_state.game_history)}这是最后一轮了,请根据所有信息,给出你的最终猜测。
请先分析一下已有的信息,然后给出你的猜测。
只输出一个具体的物体名称,不要输出其他内容。"""try:yield "游戏即将结束...", "\n".join(game_state.game_history), "", "20/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", "AI正在分析所有信息并做出最终猜测..."guess_response = client.chat.completions.create(model="ernie-x1-turbo-32k",messages=[{"role": "user", "content": guess_prompt}],temperature=0.7,max_tokens=50,stream=True)guess = ""thinking_process = "AI正在分析所有信息并做出最终猜测...\n\n"for chunk in guess_response:if hasattr(chunk.choices[0].delta, 'reasoning_content') and chunk.choices[0].delta.reasoning_content:thinking_process += chunk.choices[0].delta.reasoning_contentyield "游戏即将结束...", "\n".join(game_state.game_history), "", "20/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", thinking_processif chunk.choices[0].delta.content:guess += chunk.choices[0].delta.contentguess = guess.strip()game_state.game_history.append(f"AI最终猜测: {guess}")# 判断AI的猜测是否正确if guess.lower().strip() == game_state.target_object.lower().strip():game_state.ai_score += 1result = f"AI猜对了!目标物体就是:{game_state.target_object}\nAI得1分!"else:game_state.human_score += 1result = f"AI猜错了!目标物体是:{game_state.target_object}\n人类得1分!"history_text = "\n".join(game_state.game_history)yield result, history_text, "", "20/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", thinking_process + "\n\n思考完成!"returnexcept Exception as e:yield f"发生错误: {str(e)}", "", "", "20/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""return# 如果不是最后一轮,让AI继续提问next_prompt = f"""基于之前的对话:
{chr(10).join(game_state.game_history)}请分析这些问答,提出下一个问题来猜测玩家心中的物体。
问题应该是一个简单的"是/否"问题,要基于之前的回答来缩小范围,但也要注意,有时玩家并不知道这个物体应该选是还是否,可能会出现回答错误,因此要考虑这种情况。
请先思考一下,然后只输出问题,不要输出其他内容。"""try:yield "AI正在思考...", "\n".join(game_state.game_history), "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", f"AI正在分析第{game_state.questions_asked}轮的回答并思考下一个问题..."next_response = client.chat.completions.create(model="ernie-x1-turbo-32k",messages=[{"role": "user", "content": next_prompt}],temperature=0.7,max_tokens=100,stream=True)next_question = ""thinking_process = f"AI正在分析第{game_state.questions_asked}轮的回答并思考下一个问题...\n\n"for chunk in next_response:if hasattr(chunk.choices[0].delta, 'reasoning_content') and chunk.choices[0].delta.reasoning_content:thinking_process += chunk.choices[0].delta.reasoning_contentyield "AI正在思考...", "\n".join(game_state.game_history), "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", thinking_processif chunk.choices[0].delta.content:next_question += chunk.choices[0].delta.contentnext_question = next_question.strip()game_state.current_question = next_questiongame_state.game_history.append(f"AI问题 {game_state.questions_asked + 1}: {next_question}")history_text = "\n".join(game_state.game_history)yield f"AI的问题 {game_state.questions_asked + 1}/20: {next_question}", history_text, "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", thinking_process + "\n\n思考完成!"except Exception as e:yield f"发生错误: {str(e)}", "", "", f"{game_state.questions_asked}/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", ""def reset_game():"""重置游戏"""game_state.questions_asked = 0game_state.game_history = []game_state.is_game_over = Falsegame_state.target_object = Nonegame_state.current_question = Nonegame_state.is_game_started = Falsereturn "游戏已重置!请设置新的目标物体。", "", "", "0/20", f"AI: {game_state.ai_score} - 人类: {game_state.human_score}", "游戏已重置,等待开始新游戏..."# 自定义CSS样式
custom_css = """
.round-counter {font-size: 24px !important;font-weight: bold !important;color: #4a90e2 !important;padding: 10px 20px !important;background-color: #f5f5f5 !important;border-radius: 10px !important;box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;margin-left: auto !important;
}.score-counter {font-size: 20px !important;font-weight: bold !important;color: #2c3e50 !important;padding: 8px 16px !important;background-color: #ecf0f1 !important;border-radius: 8px !important;box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;margin-left: 20px !important;
}.thinking {color: #666 !important;font-style: italic !important;
}.ai-thinking {font-family: 'Courier New', monospace !important;background-color: #f8f9fa !important;padding: 15px !important;border-radius: 8px !important;border-left: 4px solid #4a90e2 !important;margin: 10px 0 !important;white-space: pre-wrap !important;font-size: 14px !important;line-height: 1.5 !important;
}
"""# 创建Gradio界面
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:with gr.Row():gr.Markdown("# 🎮 知你所想")round_counter = gr.Markdown("0/20", elem_classes=["round-counter"])score_counter = gr.Markdown("AI: 0 - 人类: 0", elem_classes=["score-counter"])gr.Markdown("### 20个问题,猜中你所想的东西,来挑战一下吧!")with gr.Row():with gr.Column(scale=1):target_input = gr.Textbox(label="输入你想让AI猜的物体",placeholder="例如:长颈鹿",lines=2)set_target_button = gr.Button("设置目标物体", variant="primary")with gr.Column(scale=1):answer_input = gr.Textbox(label="回答AI的问题",placeholder="输入:是、否、或不知道",lines=2)answer_button = gr.Button("回答", variant="primary")with gr.Row():reset_button = gr.Button("开始新游戏", variant="stop")with gr.Row():ai_thinking = gr.Textbox(label="AI思考过程",lines=5,elem_classes=["ai-thinking"],interactive=False)with gr.Row():output = gr.Textbox(label="游戏状态", lines=10)history = gr.Textbox(label="游戏历史", lines=10)error = gr.Textbox(label="错误信息", lines=10)# 设置事件处理set_target_button.click(set_target_object,inputs=[target_input],outputs=[output, history, error, round_counter, score_counter, ai_thinking],queue=True)answer_button.click(answer_question,inputs=[answer_input],outputs=[output, history, error, round_counter, score_counter, ai_thinking],queue=True)reset_button.click(reset_game,outputs=[output, history, error, round_counter, score_counter, ai_thinking])if __name__ == "__main__":demo.queue().launch() 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/pingmian/83911.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Excel 模拟分析之单变量求解简单应用

正向求解 利用公式根据贷款总额、还款期限、贷款利率,求每月还款金额 反向求解 根据每月还款能力,求最大能承受贷款金额 参数: 目标单元格:求的值所在的单元格 目标值:想要达到的预期值 可变单元格:变…

关于easyexcel动态下拉选问题处理

前些日子突然碰到一个问题,说是客户的导入文件模版想支持部分导入内容的下拉选,于是我就找了easyexcel官网寻找解决方案,并没有找到合适的方案,没办法只能自己动手并分享出来,针对Java生成Excel下拉菜单时因选项过多导…

【Qt】之【Get√】【Bug】通过值捕获(或 const 引用捕获)传进 lambda,会默认复制成 const

通过值捕获&#xff08;或 const 引用捕获&#xff09;传进 lambda&#xff0c;会默认复制成 const。 背景 匿名函数外部定义 QSet<QString> nameSet,需要传入匿名函数使用修改 connect(dlg, ..., [nameSet](...) {nameSet.insert(name); // ❌ 这里其实是 const QSet…

css元素的after制作斜向的删除线

<div class"price_div"></div>.price_div{position: relative; } ::after{content: ;position: absolute;left: 0;top: 50%;width: 100%;height: 2px;background: #FF186B;transform: rotate(-5deg); }

uniapp map组件的基础与实践

UniApp 中的 map 组件用于在应用中展示地图,并且支持在地图上添加标记、绘制线条和多边形等功能。以下是一些基本用法: 1. 基本结构 首先,确保你在页面的 .vue 文件中引入了 map 组件。以下是创建一个简单地图的基本代码结构: <template><view class="con…

深入理解PHP安全漏洞:文件包含与SSRF攻击全解析

深入理解PHP安全漏洞&#xff1a;文件包含与SSRF攻击全解析 前言 在Web安全领域&#xff0c;PHP应用程序的安全问题一直备受关注。本文将深入探讨两种常见的PHP安全漏洞&#xff1a;文件包含漏洞和服务器端请求伪造(SSRF)&#xff0c;帮助开发者理解漏洞原理、利用方式以及防…

MS358A 低功耗运算放大器 车规

MS358A 低功耗运算放大器 车规 产品简述 MS358A 是双通道运算放大器&#xff0c;具有低功耗、宽电源电压范围、高单位增益带宽的特性。在特定情况下&#xff0c;压摆率可以达到0.4V/μs 。每个通道的静态电流 (5V) 只有 430μA 。 MS358A输入共模范围可以到地&#xff0c;同时…

n8n + AI Agent:AI 自动化生成测试用例并支持导出 Excel

n8n + AI Agent:AI 自动化生成测试用例并支持导出 Excel 最终成果展示一、准备工作二、手把手搭建工作流第一步:创建手动触发器 (Chat Trigger)第二步:创建 AI Agent 节点第三步:为 AI Agent 植入 DeepSeek AI 模型第四步:解析AI的响应 (Code)第五步:生成Excel文件 (Conv…

5.1 HarmonyOS NEXT系统级性能调优:内核调度、I/O优化与多线程管理实战

HarmonyOS NEXT系统级性能调优&#xff1a;内核调度、I/O优化与多线程管理实战 在HarmonyOS NEXT的全场景生态中&#xff0c;系统级性能调优是构建流畅、高效应用的关键。通过内核调度精细化控制、存储与网络I/O深度优化&#xff0c;以及多线程资源智能管理&#xff0c;开发者…

​线性注意力 vs. 传统注意力:效率与表达的博弈新解

​核心结论​&#xff1a;线性注意力用计算复杂度降维换取全局建模能力&#xff0c;通过核函数和结构优化补足表达缺陷 一、本质差异&#xff1a;两种注意力如何工作&#xff1f; ​特性​传统注意力&#xff08;Softmax Attention&#xff09;线性注意力&#xff08;Linear At…

github中main与master,master无法合并到main

文章目录 遇到问题背景怎么做 遇到问题 上传 github 时候&#xff0c;发现传上去的是 master&#xff0c;但是 github 竟然还有一个 main 背景 github 采用 main 替代 master 作为主分支不是出于技术背景&#xff0c;而是出于 2020 年全球范围内兴起的 “Black Lives Matter…

使用矩阵乘法+线段树解决区间历史和问题的一种通用解法

文章目录 前言P8868 [NOIP2022] 比赛CF1824DP9990/2020 ICPC EcFinal G 前言 一般解决普通的区间历史和&#xff0c;只需要定义辅助 c h s − t ⋅ a chs-t\cdot a chs−t⋅a&#xff0c; h s hs hs是历史和&#xff0c; a a a是区间和&#xff0c; t t t是时间戳&#xff0c…

RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)

RabbitMQ 一、RabbitMQ概述 RabbitMQ RabbitMQ最初由LShift和CohesiveFT于2007年开发&#xff0c;后来由Pivotal Software Inc.&#xff08;现为VMware子公司&#xff09;接管。RabbitMQ 是一个开源的消息代理和队列服务器&#xff0c;用 Erlang 语言编写。广泛应用于各种分布…

Python Copilot【代码辅助工具】 简介

粉丝爱买鳕鱼肠深海鳕鱼肉鱼肉香肠盼盼麦香鸡味块卡乐比&#xff08;Calbee&#xff09;薯条三兄弟 独立小包美丽雅 奶茶杯一次性饮料杯好时kisses多口味巧克力糖老金磨方【黑金系列】黑芝麻丸郑新初网红郑新初烤鲜牛肉干超人毛球修剪器去球器剃毛器衣服去毛器优惠券宁之春 红黑…

VBA进度条ProgressForm1

上一章《VBA如何使用ProgressBar进度条控件》介绍了ProgressBar控件的使用方法&#xff0c;今天我给大家介绍ProgressForm1进度条的使用方法&#xff0c;ProgressForm1是集成ProgressBar控件和Label控件的窗体&#xff0c;可以同时显示进度条和百分比&#xff0c;如下图&#x…

快速部署和启动Vue3项目

快速入门Vue3 一、安装 Node.js 和 npm Vue 3 是基于 JavaScript 的框架&#xff0c;Node.js 提供了 JavaScript 运行环境&#xff0c;npm 是 Node.js 的包管理工具&#xff0c;用于安装和管理 Vue 3 及相关依赖。访问 Node.js 官方网站&#xff08;https://nodejs.org/&…

[TIP] Ubuntu 22.04 配置多个版本的 GCC 环境

问题背景 在 Ubuntu 22.04 中安装 VMware 虚拟机时&#xff0c;提示缺少 VMMON 和 VMNET 模块 编译这两个模块需要 GCC 的版本大于 12.3.0&#xff0c;而 Ubuntu 22.04 自带的 GCC 版本为 11.4.0 因此需要安装对应的 GCC 版本&#xff0c;但为了不影响其他程序&#xff0c;需…

【西门子杯工业嵌入式-4-什么是外部中断】

西门子杯工业嵌入式-4-什么是外部中断 一、中断的基本概念1. 什么是中断2. 生活中的中断示例3. MCU 中的中断机制 二、NVIC 嵌套向量中断控制器1. NVIC 简介2. NVIC 的作用3. 中断向量表 三、中断优先级机制1. 中断优先级的含义2. 抢占与响应优先级3. 优先级分组配置 四、外部中…

Blocked aria-hidden on an element because its descendant retained focus.

问题出在 Element UI 的 el-table 组件 全选功能上&#xff0c;这是一个常见的无障碍&#xff08;a11y&#xff09;问题。这个错误提示与网页 accessibility&#xff08;无障碍访问&#xff09;相关&#xff0c;涉及 aria-hidden 属性的不当使用。 问题原因分析 1. Element U…

App/uni-app 离线本地存储方案有哪些?最推荐的是哪种方案?

以下是 UniApp 离线本地存储方案的详细介绍及推荐方案分析&#xff1a; 一、UniApp 离线本地存储方案分类 1. 基于 uni.storage 系列 API&#xff08;跨端基础方案&#xff09; API 及特点&#xff1a; 提供 uni.setStorage&#xff08;异步存储&#xff09;、uni.getStorag…