【 知你所想 】基于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
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/83911.shtml
英文地址,請注明出處:http://en.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…