forked from Cathesth/TRPG
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame_engine.py
More file actions
436 lines (351 loc) ยท 15.3 KB
/
game_engine.py
File metadata and controls
436 lines (351 loc) ยท 15.3 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
import random
import json
import logging
import os
import re
import difflib
from typing import TypedDict, List, Dict, Any
from langgraph.graph import StateGraph, END
from llm_factory import LLMFactory
from dotenv import load_dotenv
load_dotenv()
logger = logging.getLogger(__name__)
class PlayerState(TypedDict):
scenario: Dict[str, Any]
current_scene_id: str
player_vars: Dict[str, Any]
history: List[str]
last_user_choice_idx: int
last_user_input: str
parsed_intent: str
system_message: str
npc_output: str
narrator_output: str
critic_feedback: str
retry_count: int
chat_log_html: str
def normalize_text(text: str) -> str:
"""ํ
์คํธ ์ ๊ทํ (๊ณต๋ฐฑ ์ ๊ฑฐ, ์๋ฌธ์)"""
return text.lower().replace(" ", "")
# --- Nodes ---
def intent_parser_node(state: PlayerState):
"""
Node 1: ์ ์ ์
๋ ฅ ์๋ ํ์
- Fast-Track: ๋จ์ ์ ํ์ด๋ ํค์๋ ๋งค์นญ ์ LLM ์์ด ์ฆ์ ์ฒ๋ฆฌ
- Slow-Path: ์ ๋งคํ ์
๋ ฅ์ LLM์ด ํ๋จ
"""
user_input = state.get('last_user_input', '').strip()
norm_input = normalize_text(user_input)
logger.info(f"๐ข [USER INPUT]: {user_input}")
# 1. ์์คํ
์ ์ผ๋ก ์ด๋ฏธ ์ ํ๋ ๊ฒฝ์ฐ (UI ํด๋ฆญ ๋ฑ)
if state.get('last_user_choice_idx', -1) != -1:
state['parsed_intent'] = 'transition'
return state
scenario = state['scenario']
curr_scene_id = state['current_scene_id']
scenes = {s['scene_id']: s for s in scenario['scenes']}
curr_scene = scenes.get(curr_scene_id)
# 2. ์๋ฉ ์ฒดํฌ
endings = {e['ending_id']: e for e in scenario.get('endings', [])}
if curr_scene_id in endings:
state['parsed_intent'] = 'ending'
return state
transitions = curr_scene.get('transitions', []) if curr_scene else []
# ํธ๋์ง์
์์ผ๋ฉด ๋ฌด์กฐ๊ฑด ์ฑํ
if not transitions:
state['parsed_intent'] = 'chat'
return state
# 3. [Fast-Track] ํ
์คํธ ์ ์ฌ๋ ๋งค์นญ (LLM ์๋ต)
# ํ์ด์ฌ ์ฝ๋๋ก ์ง์ ๋น๊ตํ๋ฏ๋ก ์๋๊ฐ ๋งค์ฐ ๋น ๋ฆ (0.01์ด ๋ฏธ๋ง)
best_idx = -1
highest_ratio = 0.0
for idx, trans in enumerate(transitions):
trigger = trans.get('trigger', '').strip()
if not trigger: continue
norm_trigger = normalize_text(trigger)
# ์์ ์ผ์น ๋๋ ํฌํจ ๊ด๊ณ
if norm_input == norm_trigger or (
len(norm_input) > 2 and (norm_input in norm_trigger or norm_trigger in norm_input)):
logger.info(f"โก [FAST-TRACK] Direct Match: '{user_input}' matched '{trigger}'")
state['last_user_choice_idx'] = idx
state['parsed_intent'] = 'transition'
return state
# ์ ์ฌ๋ ๊ฒ์ฌ (์คํ ํ์ฉ)
similarity = difflib.SequenceMatcher(None, norm_input, norm_trigger).ratio()
if similarity > highest_ratio:
highest_ratio = similarity
best_idx = idx
# ์ ์ฌ๋๊ฐ 0.7(70%) ์ด์์ด๋ฉด AI ํธ์ถ ์์ด ๋ฐ๋ก ์ธ์
if highest_ratio >= 0.7:
logger.info(f"โก [FAST-TRACK] Fuzzy Match ({highest_ratio:.2f}): '{user_input}' -> Transtion {best_idx}")
state['last_user_choice_idx'] = best_idx
state['parsed_intent'] = 'transition'
return state
# 4. [Slow-Path] LLM ๊ธฐ๋ฐ ํ๋จ (์ตํ์ ์๋จ)
triggers_text = "\n".join([f"- {t['trigger']}" for t in transitions])
prompt = f"""
[TASK] Match user input to hidden triggers.
[TRIGGERS]
{triggers_text}
[INPUT] "{user_input}"
[OUTPUT JSON] {{"type": "transition"|"chat", "index": 1-based_index}}
"""
try:
api_key = os.getenv("OPENROUTER_API_KEY")
# ํ๋จ์ฉ ๊ฐ๋ฒผ์ด ๋ชจ๋ธ ์ฌ์ฉ
llm = LLMFactory.get_llm(api_key=api_key, model_name="openai/tngtech/deepseek-r1t2-chimera:free")
response = llm.invoke(prompt).content.strip()
# JSON ํ์ฑ ์๋
try:
if "```" in response:
response = response.split("```")[1].replace("json", "").strip()
result = json.loads(response)
if result.get('type') == 'transition':
idx = int(result.get('index', 0)) - 1
if 0 <= idx < len(transitions):
state['last_user_choice_idx'] = idx
state['parsed_intent'] = 'transition'
return state
except:
pass
except Exception as e:
logger.error(f"Intent Parser LLM Error: {e}")
# ๋งค์นญ ์คํจ ์ ๊ธฐ๋ณธ๊ฐ: ์ฑํ
state['parsed_intent'] = 'chat'
return state
def rule_node(state: PlayerState):
"""
Node 2: ๊ท์น ์์ง (์ดํํธ ์ ์ฉ ๋ฐ ์ฌ ์ด๋)
- ์์ดํ
ํ๋/๋ถ์ค
- ์คํฏ(HP, Sanity ๋ฑ) ๋ณ๊ฒฝ
"""
idx = state['last_user_choice_idx']
scenario = state['scenario']
curr_scene_id = state['current_scene_id']
all_scenes = {s['scene_id']: s for s in scenario['scenes']}
all_endings = {e['ending_id']: e for e in scenario.get('endings', [])}
sys_msg = []
curr_scene = all_scenes.get(curr_scene_id)
transitions = curr_scene.get('transitions', []) if curr_scene else []
# ํธ๋์ง์
์คํ ์กฐ๊ฑด ์ถฉ์กฑ ์
if state['parsed_intent'] == 'transition' and 0 <= idx < len(transitions):
trans = transitions[idx]
effects = trans.get('effects', [])
next_id = trans.get('target_scene_id')
trigger_desc = trans.get('trigger', 'ํ๋')
# --- [์ดํํธ ์ฒ๋ฆฌ ๋ก์ง ๋ณต๊ตฌ๋จ] ---
for eff in effects:
try:
if isinstance(eff, dict):
key = eff.get("target", "").lower()
operation = eff.get("operation", "add")
raw_val = eff.get("value", 0)
# ๊ฐ ํ์
๋ณํ
val = 0
if isinstance(raw_val, (int, float)):
val = int(raw_val)
elif isinstance(raw_val, str) and raw_val.isdigit():
val = int(raw_val)
# A. ์์ดํ
์ฒ๋ฆฌ (gain_item / lose_item)
if operation in ["gain_item", "lose_item"]:
item_name = str(eff.get("value", ""))
inventory = state['player_vars'].get('inventory', [])
if operation == "gain_item":
if item_name not in inventory:
inventory.append(item_name)
sys_msg.append(f"๐ฆ ์์ดํ
ํ๋: {item_name}")
elif operation == "lose_item":
if item_name in inventory:
inventory.remove(item_name)
sys_msg.append(f"๐๏ธ ์์ดํ
์ฌ์ฉ: {item_name}")
state['player_vars']['inventory'] = inventory
continue
# B. ์์น ๋ณ์ ์ฒ๋ฆฌ (HP, Sanity, Gold ๋ฑ)
if key:
current_val = state['player_vars'].get(key, 0)
if not isinstance(current_val, (int, float)): current_val = 0
if operation == "add":
new_val = current_val + val
sys_msg.append(f"{key.upper()} +{val}")
elif operation == "subtract":
new_val = max(0, current_val - val)
sys_msg.append(f"{key.upper()} -{val}")
elif operation == "set":
new_val = val
sys_msg.append(f"{key.upper()} = {new_val}")
else:
new_val = current_val
state['player_vars'][key] = new_val
except Exception as e:
logger.error(f"Effect Processing Error: {e}")
pass
# ์ฌ ID ๋ณ๊ฒฝ
if next_id:
state['current_scene_id'] = next_id
logger.info(f"๐ฃ [MOVE] {curr_scene_id} -> {next_id}")
# ์ด๋ ํ ์๋ฉ์ธ์ง ์ฒดํฌ
if state['current_scene_id'] in all_endings:
ending = all_endings[state['current_scene_id']]
state['parsed_intent'] = 'ending'
# ์๋ฉ ์ ๋๋ ์ดํฐ ์ถ๋ ฅ ๋ฏธ๋ฆฌ ์์ฑ
state['narrator_output'] = f"""
<div class="my-8 p-8 border-2 border-yellow-500/50 bg-gradient-to-b from-yellow-900/40 to-black rounded-xl text-center fade-in shadow-2xl relative overflow-hidden">
<h3 class="text-3xl font-black text-yellow-400 mb-4 tracking-[0.2em] uppercase drop-shadow-md">๐ ENDING ๐</h3>
<div class="w-16 h-1 bg-yellow-500 mx-auto mb-6 rounded-full"></div>
<div class="text-2xl font-bold text-white mb-4 drop-shadow-sm">"{ending.get('title')}"</div>
<p class="text-gray-200 leading-relaxed text-lg font-serif italic">
{ending.get('description')}
</p>
</div>
"""
state['system_message'] = " | ".join(sys_msg)
return state
def npc_node(state: PlayerState):
"""
Node 3: NPC ์ฑ๋ด (์ ์ ๊ฐ ์ฑํ
์ ์๋ํ์ ๋)
[๊ฐ์ ] ๋ํ ๋ด์ญ(History)์ ํ๋กฌํํธ์ ์ฃผ์
ํด์ ๋ฌธ๋งฅ ํ์
๊ฐ๋ฅํ๊ฒ ๋ณ๊ฒฝ
"""
if state.get('parsed_intent') != 'chat':
state['npc_output'] = ""
return state
scenario = state['scenario']
user_text = state['last_user_input']
curr_id = state['current_scene_id']
all_scenes = {s['scene_id']: s for s in scenario['scenes']}
curr_scene = all_scenes.get(curr_id)
npc_names = curr_scene.get('npcs', []) if curr_scene else []
if not npc_names:
state['npc_output'] = ""
return state
# ์ฒซ ๋ฒ์งธ NPC๊ฐ ๋๋ตํ๋ค๊ณ ๊ฐ์
target_npc_name = npc_names[0]
npc_info = f"Name: {target_npc_name}"
for npc in scenario.get('npcs', []):
if npc.get('name') == target_npc_name:
npc_info += f"\nPersonality: {npc.get('personality')}\nTone: {npc.get('dialogue_style')}"
break
# [์ถ๊ฐ๋จ] ๋ํ ๋ด์ญ ๊ฐ์ ธ์ค๊ธฐ (์ต๊ทผ 5ํด)
history = state.get('history', [])
history_context = "\n".join(history[-5:]) if history else "No previous conversation."
prompt = f"""
[ROLE] Act as the NPC '{target_npc_name}' in a TRPG.
[SCENE] Current Location: {curr_scene.get('title')}
[PROFILE] {npc_info}
[CONVERSATION HISTORY]
{history_context}
[USER SAID] "{user_text}"
[INSTRUCTION] Respond naturally in character. Keep it short (1-2 sentences). Use Korean.
"""
try:
api_key = os.getenv("OPENROUTER_API_KEY")
llm = LLMFactory.get_llm(api_key=api_key, model_name="openai/tngtech/deepseek-r1t2-chimera:free")
response = llm.invoke(prompt).content.strip()
state['npc_output'] = response
# [์ถ๊ฐ๋จ] ๋ํ ๋ด์ญ ์ ์ฅ
if 'history' not in state: state['history'] = []
state['history'].append(f"User: {user_text}")
state['history'].append(f"NPC({target_npc_name}): {response}")
except Exception as e:
logger.error(f"NPC LLM Error: {e}")
state['npc_output'] = "..."
return state
def narrator_node(state: PlayerState):
"""๋๋ ์ดํฐ ๋
ธ๋ (์ค์ ์์ฑ์ ์คํธ๋ฆฌ๋ฐ ํจ์์์ ์ฒ๋ฆฌํ๋ฏ๋ก ์ฌ๊ธฐ์ ํจ์ค)"""
return state
# --- Streaming Generators (SSE) ---
def prologue_stream_generator(state: PlayerState):
"""ํ๋กค๋ก๊ทธ ํ
์คํธ ์คํธ๋ฆฌ๋ฐ"""
scenario = state['scenario']
# ํ๋กค๋ก๊ทธ ํ
์คํธ ํค๊ฐ ๋ค๋ฅผ ์ ์์ด์ ์์ ํ๊ฒ ๊ฐ์ ธ์ด
prologue_text = scenario.get('prologue', scenario.get('prologue_text', ''))
if not prologue_text:
yield "์ด์ผ๊ธฐ๊ฐ ์์๋ฉ๋๋ค..."
return
# ํ ๋ฒ์ ๋ณด๋ด์ง ์๊ณ ์ฒญํฌ ๋จ์๋ก ๋์ด์ ๋ณด๋ด๊ฑฐ๋, ์ด๋ฏธ ์์ฑ๋ ํ
์คํธ๋ฉด ๊ทธ๋ฅ ๋ณด๋
# ์ฌ๊ธฐ์๋ ๋จ์ํ๊ฒ ์ ์ฒด ์ ์ก (LLM ์์ฑ์ด ์๋๋ฏ๋ก)
yield prologue_text
def scene_stream_generator(state: PlayerState):
"""
์ฌ ๋ฌ์ฌ ์คํธ๋ฆฌ๋ฐ (ํต์ฌ: ์ ํ์ง ๋ฏธ๋
ธ์ถ + ํํธ ์์ ์ ํฌํจ)
"""
scenario = state['scenario']
curr_id = state['current_scene_id']
all_scenes = {s['scene_id']: s for s in scenario['scenes']}
curr_scene = all_scenes.get(curr_id)
if not curr_scene:
yield "์ ์ ์๋ ์ฅ๋ฉด์
๋๋ค."
return
scene_title = curr_scene.get('title', 'Untitled')
scene_desc = curr_scene.get('description', '')
npc_names = curr_scene.get('npcs', [])
# ํํธ์ฉ ํธ๋ฆฌ๊ฑฐ ์ ๋ณด (์ถ๋ ฅ์ฉ ์๋, AI ํํธ์ฉ)
transitions = curr_scene.get('transitions', []) if curr_scene else []
trigger_hints = [t.get('trigger', '') for t in transitions if t.get('trigger')]
last_action = state.get('last_user_input', '')
# ๋๋ ์ด์
ํ๋กฌํํธ
prompt = f"""
You are a Game Master narrating a TRPG scene.
[CONTEXT]
Title: {scene_title}
Description: {scene_desc}
Last Action Player Took: "{last_action}"
NPCs Here: {', '.join(npc_names)}
[AVAILABLE HIDDEN ACTIONS (Do not list these directly!)]
{trigger_hints}
[INSTRUCTIONS]
1. Describe the scene vividly. Start by describing the result of the 'Last Action'.
2. Naturally weave **subtle hints** about the 'Available Hidden Actions' into the environment description.
- Use HTML <mark>keyword</mark> to slightly highlight interactable objects if needed.
- Example: "You see a <mark>rusty key</mark> on the table." (Implying user can take it)
3. **CRITICAL: DO NOT LIST CHOICES.** - Never write "1. Open door", "2. Run away".
- Never ask "What do you want to do?".
- Just describe the situation and let the player type their action.
4. Language: Korean (ํ๊ตญ์ด).
5. Length: 3-4 sentences.
"""
try:
api_key = os.getenv("OPENROUTER_API_KEY")
# ์คํธ๋ฆฌ๋ฐ ์ง์ ๋ชจ๋ธ ์ฌ์ฉ
llm = LLMFactory.get_llm(
api_key=api_key,
model_name="openai/tngtech/deepseek-r1t2-chimera:free",
streaming=True
)
for chunk in llm.stream(prompt):
if chunk.content:
yield chunk.content
except Exception as e:
logger.error(f"Scene Streaming Error: {e}")
# ์ค๋ฅ ์ ๊ธฐ๋ณธ ์ค๋ช
์ด๋ผ๋ ์ถ๋ ฅ
yield scene_desc if scene_desc else "..."
# --- Graph Construction ---
def create_game_graph():
"""LangGraph ์ํฌํ๋ก์ฐ ์์ฑ"""
workflow = StateGraph(PlayerState)
# ๋
ธ๋ ๋ฑ๋ก
workflow.add_node("intent_parser", intent_parser_node)
workflow.add_node("rule_engine", rule_node)
workflow.add_node("npc_actor", npc_node)
workflow.add_node("narrator", narrator_node)
# ์์์
workflow.set_entry_point("intent_parser")
# ์กฐ๊ฑด๋ถ ์ฃ์ง (๋ถ๊ธฐ ์ฒ๋ฆฌ)
def route_action(state):
intent = state.get('parsed_intent')
if intent == 'transition' or intent == 'ending':
return "rule_engine"
else:
return "npc_actor"
workflow.add_conditional_edges(
"intent_parser",
route_action,
{
"rule_engine": "rule_engine",
"npc_actor": "npc_actor"
}
)
# ํ๋ฆ ์ฐ๊ฒฐ
workflow.add_edge("rule_engine", "narrator")
workflow.add_edge("npc_actor", "narrator")
workflow.add_edge("narrator", END)
return workflow.compile()