-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoc_gradio_bot.py
More file actions
504 lines (400 loc) · 18.2 KB
/
Copy pathcoc_gradio_bot.py
File metadata and controls
504 lines (400 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# coc_gradio_bot.py - 修复版(添加自动投骰按钮、修复循环bug)
import gradio as gr
import sys
import io
import json
from contextlib import redirect_stdout
from typing import Dict, Optional, Tuple, List
import os
# 导入你的 CoC Agent
from coc_agent import CoCAgent, ZHIPUAI_API_KEY, PREGEN_CHARACTERS, SAVE_GAME_DIR
from character_sheet import Investigator, Characteristics, InvestigatorSkills
# --- 全局状态管理 ---
class GameSession:
def __init__(self):
self.agent: Optional[CoCAgent] = None
self.initialized = False
self.waiting_for_roll = False
self.waiting_for_character = True
# --- 捕获 Agent 输出 ---
def capture_agent_output(func, *args, **kwargs):
"""捕获函数执行时的所有 print 输出"""
f = io.StringIO()
with redirect_stdout(f):
result = func(*args, **kwargs)
output = f.getvalue()
return output, result
# --- 提取 KP 回复(修复版:支持 emoji)---
def extract_kp_response(output: str) -> str:
"""从输出中提取 KP 的回复"""
# 查找 KP 凛的发言
if 'KP 凛' in output:
# 找到第一个包含 "KP 凛" 的位置
idx = output.find('KP 凛')
if idx != -1:
# 从这个位置开始,找冒号
colon_idx = output.find(':', idx)
if colon_idx == -1:
colon_idx = output.find(':', idx)
if colon_idx != -1:
# 提取冒号后的所有内容
response = output[colon_idx + 1:].strip()
# 移除调试信息(以 🤖 🎲 等开头的行)
lines = response.split('\n')
clean_lines = []
for line in lines:
if line.strip() and not any(
line.startswith(prefix) for prefix in ['🤖', '🎲', '🧠', '---', '💥', '⚔️', '📍']):
clean_lines.append(line)
elif not line.strip():
clean_lines.append(line) # 保留空行用于段落分隔
result = '\n'.join(clean_lines).strip()
if result:
return result
return output.strip()
# --- 初始化角色(修复版:防止循环)---
def initialize_character(choice: str, session: GameSession) -> Tuple[str, GameSession]:
"""根据用户选择初始化角色"""
if choice not in PREGEN_CHARACTERS:
return "❌ 无效的角色选择,请重新选择", session
try:
# 创建 Agent
session.agent = CoCAgent(api_key=ZHIPUAI_API_KEY)
# 加载预设角色
char_data_copy = PREGEN_CHARACTERS[choice].copy()
char_data_copy['characteristics'] = Characteristics(**char_data_copy['characteristics'])
if 'skills' in char_data_copy and 'values' in char_data_copy['skills']:
char_data_copy['skills'] = InvestigatorSkills(values=char_data_copy['skills']['values'])
else:
char_data_copy.pop('skills', None)
session.agent.investigator = Investigator(**char_data_copy)
session.agent.investigator._calculate_derived_attributes()
session.agent.investigator._initialize_base_skills()
# 添加系统提示
session.agent.messages.insert(0, {"role": "system", "content": session.agent.system_prompt})
# 生成角色卡摘要
char_summary = session.agent._get_character_summary()
session.initialized = True
session.waiting_for_character = False
# 让 KP 开始叙述(修复版:使用更明确的指令)
session.agent.game_state.current_location = "莱德贝特旅馆房间"
init_prompt = f"""请用简洁专业的语言描述开场场景:{session.agent.investigator.name}在莱德贝特旅馆房间。
要求:
1. 简短描述环境(2-3句)
2. 不要使用重复的动作描写
{session.agent._get_current_status_prompt()}"""
session.agent.messages.append({
"role": "user",
"content": init_prompt
})
# 调用 next_turn
session.agent.next_turn()
# 从 messages 中获取最后一条 assistant 消息
kp_response = ""
for msg in reversed(session.agent.messages):
if msg.get("role") == "assistant" and msg.get("content"):
kp_response = msg["content"]
break
if not kp_response:
kp_response = "那么,开始吧。你想做什么?"
welcome_msg = f"✅ 你选择了 **{session.agent.investigator.name}**\n\n"
welcome_msg += "--- 角色卡 ---\n```\n" + char_summary + "\n```\n\n"
welcome_msg += "🎙️ **[KP 凛]:** " + kp_response
return welcome_msg, session
except Exception as e:
import traceback
traceback.print_exc()
return f"❌ 初始化角色失败: {e}", session
# --- 处理用户输入 ---
def process_message(message: str, history: List, session: GameSession) -> Tuple[str, GameSession]:
"""处理用户的游戏输入"""
# 如果还没初始化角色
if not session.initialized or session.waiting_for_character:
return "⚠️ 请先选择你的角色!", session
# 检查是否在等待投骰
if session.agent.pending_roll or session.agent.pending_san_check:
# 尝试解析为投骰结果
try:
message_clean = message.strip().lower()
# 支持自动投骰命令
if message_clean in ['auto', 'autoroll', '自动', '自动投骰', '']:
roll_value = session.agent._auto_roll_dice()
else:
roll_value = int(message)
if not (1 <= roll_value <= 100):
return "⚠️ 请输入 1-100 之间的数字,或发送 'auto' 自动投骰", session
# 处理 SAN Check
if session.agent.pending_san_check:
outcome_str, san_loss_val, madness_bool = session.agent.resolve_sanity_check(
roll_value,
session.agent.pending_san_check.success_loss,
session.agent.pending_san_check.failure_loss
)
session.agent.pending_san_check = None
output, _ = capture_agent_output(
session.agent.next_turn,
san_check_outcome=outcome_str,
san_loss=san_loss_val,
madness_flag=madness_bool
)
# 处理技能检定
else:
outcome_str, outcome_lvl = session.agent.resolve_skill_check(
roll_value,
session.agent.pending_roll.skill_name,
session.agent.pending_roll.difficulty
)
session.agent.pending_roll = None
output, _ = capture_agent_output(
session.agent.next_turn,
roll_outcome=outcome_str,
roll_outcome_level=outcome_lvl
)
response = extract_kp_response(output)
# 检查是否又有新的检定请求
if session.agent.pending_roll:
response += f"\n\n🎲 **需要进行检定:** {session.agent.pending_roll.skill_name} ({session.agent.pending_roll.difficulty})\n"
response += f"当前技能值:{session.agent.investigator.get_skill_value(session.agent.pending_roll.skill_name)}\n"
response += "请输入 d100 结果 (1-100),或点击'自动投骰'按钮"
elif session.agent.pending_san_check:
response += f"\n\n🧠 **需要进行理智检定:** {session.agent.pending_san_check.reason}\n"
response += f"当前 SAN 值:{session.agent.investigator.current_sanity}\n"
response += "请输入 d100 结果 (1-100),或点击'自动投骰'按钮"
return response, session
except ValueError:
return "⚠️ 请输入有效的数字 (1-100),或点击'自动投骰'按钮", session
# 正常游戏输入
output, _ = capture_agent_output(session.agent.next_turn, player_input=message)
response = extract_kp_response(output)
# 检查是否有检定请求
if session.agent.pending_roll:
response += f"\n\n🎲 **需要进行检定:** {session.agent.pending_roll.skill_name} ({session.agent.pending_roll.difficulty})\n"
response += f"当前技能值:{session.agent.investigator.get_skill_value(session.agent.pending_roll.skill_name)}\n"
response += "请输入 d100 结果 (1-100),或点击'自动投骰'按钮"
elif session.agent.pending_san_check:
response += f"\n\n🧠 **需要进行理智检定:** {session.agent.pending_san_check.reason}\n"
response += f"当前 SAN 值:{session.agent.investigator.current_sanity}\n"
response += "请输入 d100 结果 (1-100),或点击'自动投骰'按钮"
return response, session
# --- 查看状态 ---
def view_status(session: GameSession) -> str:
"""查看当前角色状态"""
if not session.initialized or not session.agent or not session.agent.investigator:
return "⚠️ 请先选择角色"
return "📊 **当前状态**\n```\n" + session.agent._get_current_status_prompt() + "\n```"
# --- 查看完整角色卡 ---
def view_character_sheet(session: GameSession) -> str:
"""查看完整角色卡"""
if not session.initialized or not session.agent or not session.agent.investigator:
return "⚠️ 请先选择角色"
return "📋 **角色卡**\n```\n" + session.agent._get_character_summary() + "\n```"
# --- 存档 ---
def save_game(session: GameSession) -> str:
"""保存游戏进度"""
if not session.initialized or not session.agent:
return "⚠️ 没有可保存的游戏"
try:
output, _ = capture_agent_output(session.agent.save_game, "web_save")
return "✅ 游戏已保存!"
except Exception as e:
return f"❌ 存档失败: {e}"
# --- 读档 ---
def load_game(session: GameSession) -> Tuple[str, GameSession]:
"""加载最新的存档"""
try:
save_files = sorted(
[f for f in os.listdir(SAVE_GAME_DIR) if f.endswith(".json")],
reverse=True
) if os.path.exists(SAVE_GAME_DIR) else []
if not save_files:
return "⚠️ 没有找到存档文件", session
filepath = os.path.join(SAVE_GAME_DIR, save_files[0])
# 创建新的 agent 并加载
new_agent = CoCAgent(api_key=ZHIPUAI_API_KEY)
output, _ = capture_agent_output(new_agent.load_game, filepath)
session.agent = new_agent
session.initialized = True
session.waiting_for_character = False
return f"✅ 已加载存档: {save_files[0]}\n\n" + view_status(session), session
except Exception as e:
import traceback
traceback.print_exc()
return f"❌ 读档失败: {e}", session
# --- Gradio 界面 ---
def create_ui():
with gr.Blocks(title="CoC 7th 单人跑团 - KP 凛", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# 🎲 克苏鲁的呼唤 7版 - 单人跑团
## 你的守秘人:KP 凛
欢迎来到克苏鲁的世界。选择你的调查员,开始你的冒险...
**功能说明:**
- 完整的 CoC 7版规则(技能检定、战斗、理智检定)
- 战斗系统(攻击、闪避、伤害计算、NPC 管理)
- SAN Check 与临时疯狂
- KP 好感度系统(凛会记住你的行为)
- 存档/读档功能
""")
# 状态管理
session_state = gr.State(GameSession())
with gr.Row():
with gr.Column(scale=3): # 改大对话区域
# 角色选择
with gr.Group() as char_select_group:
gr.Markdown("### 📋 选择你的调查员")
char_choice = gr.Radio(
choices=[
("1. 约翰·史密斯 (私家侦探)", "1"),
("2. 艾米丽·卡特 (学者)", "2")
],
label="角色",
value=None
)
init_btn = gr.Button("🎮 开始游戏", variant="primary")
init_output = gr.Markdown()
# 聊天界面
chatbot = gr.Chatbot(
label="游戏对话",
height=700, # 加大高度
show_label=True,
type="messages",
value=[] # 初始化为空列表
)
with gr.Row():
msg_input = gr.Textbox(
label="你的行动",
placeholder="描述你想做什么,或输入投骰结果 (1-100)...",
scale=3,
lines=2
)
with gr.Column(scale=1):
submit_btn = gr.Button("发送", variant="primary")
auto_roll_btn = gr.Button("🎲 自动投骰", variant="secondary")
with gr.Column(scale=1):
gr.Markdown("### 🎮 游戏控制")
status_btn = gr.Button("📊 查看状态")
status_output = gr.Markdown()
char_sheet_btn = gr.Button("📋 完整角色卡")
char_sheet_output = gr.Markdown()
save_btn = gr.Button("💾 保存游戏")
load_btn = gr.Button("📂 加载游戏")
save_output = gr.Markdown()
gr.Markdown("""
### 💡 使用提示
**投骰:**
- 直接输入数字 (1-100)
- 或点击 **🎲 自动投骰** 按钮
**战斗:**
- "我攻击那个怪物"(KP 会要求攻击检定)
- 成功后自动计算伤害
- 敌人回合 KP 会要求你闪避检定
**理智检定:**
- 遇到恐怖事件时自动触发
- 根据成功/失败损失不同 SAN 值
- 一次损失 ≥5 点会触发临时疯狂
**与 KP 互动:**
- 幽默、机智、高级奉承 → 可能增加好感度
- 恶俗笑话、恶意刁难 → 可能降低好感度
- 高好感度时 KP 会更温柔
### 🎲 示例行动
- "我想搜索房间"
- "我尝试说服他"
- "我用手枪攻击那个怪物"
- "我闪避这次攻击"
""")
# --- 事件绑定 ---
# 初始化角色
def init_char_and_update(choice, session):
result, new_session = initialize_character(choice, session)
# 将结果添加到聊天历史(修复:单层列表)
return new_session, [{"role": "assistant", "content": result}], ""
init_btn.click(
fn=init_char_and_update,
inputs=[char_choice, session_state],
outputs=[session_state, chatbot, init_output]
)
# 处理消息
def respond(message, history, session):
if not message.strip():
return history, "", session
response, new_session = process_message(message, history, session)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response})
return history, "", new_session
submit_btn.click(
fn=respond,
inputs=[msg_input, chatbot, session_state],
outputs=[chatbot, msg_input, session_state]
)
msg_input.submit(
fn=respond,
inputs=[msg_input, chatbot, session_state],
outputs=[chatbot, msg_input, session_state]
)
# 自动投骰
def auto_roll(history, session):
"""自动投骰处理"""
if not session.initialized:
history.append({"role": "assistant", "content": "⚠️ 请先开始游戏"})
return history, "", session
# 检查是否需要投骰
if not session.agent.pending_roll and not session.agent.pending_san_check:
history.append({"role": "assistant", "content": "⚠️ 当前不需要投骰"})
return history, "", session
# 执行自动投骰
response, new_session = process_message("auto", history, session)
history.append({"role": "user", "content": "🎲 自动投骰"})
history.append({"role": "assistant", "content": response})
return history, "", new_session
auto_roll_btn.click(
fn=auto_roll,
inputs=[chatbot, session_state],
outputs=[chatbot, msg_input, session_state]
)
# 查看状态
status_btn.click(
fn=view_status,
inputs=[session_state],
outputs=[status_output]
)
# 查看角色卡
char_sheet_btn.click(
fn=view_character_sheet,
inputs=[session_state],
outputs=[char_sheet_output]
)
# 存档
save_btn.click(
fn=save_game,
inputs=[session_state],
outputs=[save_output]
)
# 读档
def load_and_update(session):
result, new_session = load_game(session)
return new_session, result
load_btn.click(
fn=load_and_update,
inputs=[session_state],
outputs=[session_state, save_output]
)
return demo
# --- 启动 ---
if __name__ == "__main__":
print("🚀 正在启动 CoC Gradio Bot...")
print("⚠️ 请确保 RAG API 已在 http://127.0.0.1:8000 运行")
print("\n📋 功能列表:")
print(" ✅ 完整技能检定系统")
print(" ✅ 战斗系统(攻击/闪避/伤害)")
print(" ✅ SAN Check & 临时疯狂")
print(" ✅ NPC/敌人管理")
print(" ✅ KP 好感度系统")
print(" ✅ 存档/读档")
print(" ✅ 自动投骰按钮")
print("\n正在启动...\n")
demo = create_ui()
demo.launch(
share=True,
server_name="0.0.0.0",
server_port=7862,
show_error=True
)