forked from johnny603/lux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
343 lines (290 loc) · 11.6 KB
/
Copy pathcli.py
File metadata and controls
343 lines (290 loc) · 11.6 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
from typing import Dict, List, Optional, Sequence, Set
import storage
def difficulty_key(d: str) -> int:
# lower is easier
if not d:
return 99
d = d.lower()
if d == "easy":
return 0
if d == "medium":
return 1
if d == "hard":
return 2
return 99
def sort_levels(levels: List[Dict], solved: Set[str] = None) -> List[Dict]:
solved = solved or set()
def key(level):
return (
level.get("id") in solved,
difficulty_key(level.get("difficulty")),
(level.get("category") or "").lower(),
(level.get("title") or "").lower(),
level.get("id") or "",
)
ordered = sorted(levels, key=key)
return ordered
def _level_matches_text(level: Dict, query: str) -> bool:
haystack = " ".join(
str(level.get(field, ""))
for field in ("id", "title", "description", "category", "difficulty")
).lower()
return query in haystack
def _level_matches_tags(level: Dict, tags: Optional[Set[str]]) -> bool:
if not tags:
return True
level_tags = {tag.lower() for tag in level.get("tags", [])}
return tags.issubset(level_tags)
def _level_matches_filters(
level: Dict,
*,
category: Optional[str],
difficulty: Optional[str],
query: Optional[str],
tag_set: Optional[Set[str]],
) -> bool:
if category and (level.get("category") or "").lower() != category:
return False
if difficulty and (level.get("difficulty") or "").lower() != difficulty:
return False
if query and not _level_matches_text(level, query):
return False
return _level_matches_tags(level, tag_set)
def filter_levels(
levels: Sequence[Dict],
*,
category: Optional[str] = None,
difficulty: Optional[str] = None,
query: Optional[str] = None,
tags: Optional[Sequence[str]] = None,
) -> List[Dict]:
category = category.lower().strip() if category else None
difficulty = difficulty.lower().strip() if difficulty else None
query = query.lower().strip() if query else None
tag_set = {tag.lower().strip() for tag in tags} if tags else None
return [
level
for level in levels
if _level_matches_filters(
level,
category=category,
difficulty=difficulty,
query=query,
tag_set=tag_set,
)
]
def format_level_line(level: Dict, solved: Set[str] = None) -> str:
solved = solved or set()
marker = "[x]" if level.get("id") in solved else "[ ]"
tags = ", ".join(level.get("tags", []))
attempts = level.get("attempts")
attempt_text = f" · attempts {attempts}" if attempts else ""
return (
f"{marker} {level.get('id')}: {level.get('title')} "
f"({level.get('difficulty', '?')}) - {level.get('category', '?')}"
f"{attempt_text}"
f"{' - ' + tags if tags else ''}"
)
def format_progress_summary(state: Dict, levels: Optional[List[Dict]] = None) -> str:
summary = storage.get_progress_summary(state, levels)
pieces = [f"Solved {summary['solved_count']}"]
if summary.get("total_levels"):
pieces.append(f"of {summary['total_levels']}")
if summary.get("percent_complete") is not None:
pieces.append(f"({summary['percent_complete']}%)")
pieces.append(
f"streak {summary.get('current_streak', 0)} / best {summary.get('longest_streak', 0)}"
)
pieces.append(f"attempts {summary.get('total_attempts', 0)}")
recent = summary.get("recent_solved") or []
if recent:
pieces.append("recent " + ", ".join(recent[:3]))
return " | ".join(pieces)
def format_room_atmosphere(room: Dict) -> str:
if not room:
return "Chamber atmosphere details unavailable."
rname = room.get("name", "Unknown Chamber")
rid = room.get("id", "")
theme = room.get("theme", "industrial-facility")
atmosphere = room.get("atmosphere") or {}
ambient = atmosphere.get("ambient_text", room.get("description", ""))
sights = atmosphere.get("sights", "Minimal lighting with active console terminals.")
sounds = atmosphere.get("sounds", "Faint mechanical hum and cooling fans.")
smells = atmosphere.get("smells", "Static electricity and warm electronics.")
ascii_art = atmosphere.get("ascii_art", "")
lines = [
f"🌌 === Atmosphere & Observation: {rname} [{rid}] ===",
f"🏷️ Theme: {theme}",
f"📖 Ambient: {ambient}",
f"👁️ Sights: {sights}",
f"👂 Sounds: {sounds}",
f"👃 Smells: {smells}",
]
if ascii_art:
lines.append("\n🗺️ Room Map / Layout:")
lines.append(ascii_art)
objs = room.get("objects", [])
if objs:
lines.append("\n📦 Visible Interactive Items:")
for obj in objs:
take_tag = "[Takeable]" if obj.get("is_pickupable") else "[Fixed]"
lines.append(
f" * {obj.get('name')} ({obj.get('id')}) {take_tag} - {obj.get('description')}"
)
return "\n".join(lines)
def format_room_objects(objects: Sequence[Dict]) -> str:
if not objects:
return "No interactive objects found in this chamber."
lines = ["Chamber Objects:"]
for obj in objects:
pickup_tag = "[pickupable]" if obj.get("is_pickupable") else "[static]"
lines.append(
f" * {obj.get('name', 'Unknown')} ({obj.get('id', '')}) {pickup_tag}: "
f"{obj.get('description', '')}"
)
return "\n".join(lines)
def examine_object(obj: Dict) -> str:
if not obj:
return "Object not found."
lines = [
f"=== {obj.get('name')} ===",
f"ID: {obj.get('id')}",
f"Pickupable: {'Yes' if obj.get('is_pickupable') else 'No'}",
f"Description: {obj.get('description')}",
]
hint = obj.get("interaction_hint")
if hint:
lines.append(f"Hint: {hint}")
triggers = obj.get("triggers", [])
if triggers:
lines.append("Actions:")
for t in triggers:
lines.append(f" - [{t.get('action')}]: {t.get('message')}")
return "\n".join(lines)
def format_inventory(inventory_items: Sequence[Dict]) -> str:
if not inventory_items:
return "Inventory is empty."
lines = ["🎒 Player Inventory:"]
for item in inventory_items:
usable = ""
if item.get("usable_on"):
usable = f" (Usable on: {', '.join(item.get('usable_on', []))})"
name = item.get("name", item.get("id", "Unknown"))
oid = item.get("id", "")
desc = item.get("description", "")
lines.append(f" * {name} [{oid}]{usable}: {desc}")
return "\n".join(lines)
def format_room_timer(timer_info: Optional[Dict]) -> str:
if not timer_info or not timer_info.get("time_limit_seconds"):
return "No active countdown limit."
limit = timer_info.get("time_limit_seconds")
rem = timer_info.get("remaining_seconds", 0)
if timer_info.get("is_expired"):
return f"⏱️ TIME EXPIRED! ({limit}s limit exceeded. Reset room to retry)."
return f"⏱️ {rem}s remaining (Time limit: {limit}s)"
def format_adaptive_hints(hints_data: Optional[Dict]) -> str:
if not hints_data or not hints_data.get("hints"):
return "No hints available for this chamber."
rname = hints_data.get("room_name", "Room")
unlocked_cnt = hints_data.get("unlocked_hints_count", 0)
total_cnt = hints_data.get("total_hints_count", 0)
failed = hints_data.get("failed_attempts", 0)
header = (
f"💡 Adaptive Hints for {rname} "
f"({unlocked_cnt}/{total_cnt} unlocked | failed attempts: {failed}):"
)
lines = [header]
for h in hints_data.get("hints", []):
lvl = h.get("level", 1)
lvl_tag = {1: "Subtle Clue", 2: "Directional Guidance", 3: "Direct Solution"}.get(
lvl, f"Level {lvl}"
)
if h.get("is_unlocked"):
lines.append(f" [Level {lvl} - {lvl_tag}] ✅ {h.get('text')}")
else:
cond = h.get("unlock_condition")
lines.append(f" [Level {lvl} - {lvl_tag}] 🔒 {h.get('text')} (Unlock: {cond})")
return "\n".join(lines)
def format_room_map(map_data: Dict) -> str:
"""Format an ASCII representation of the facility room layout and player location."""
if not map_data or not map_data.get("rooms"):
return "Facility map unavailable."
rooms_list = map_data.get("rooms", [])
current_id = map_data.get("current_room_id")
escaped_set = set(map_data.get("escaped_rooms", []))
lines = [
"🗺️ === Facility Navigation Map ===",
f"📍 Current Location: {current_id} | Escaped: {len(escaped_set)}/{len(rooms_list)} Chambers",
"",
]
# Render node chain representation
node_blocks = []
for r in sorted(rooms_list, key=lambda x: (x.get("is_secret", False), x.get("position", {}).get("x", 0))):
rid = r.get("id", "")
rname = r.get("name", "Chamber")
is_cur = rid == current_id
is_esc = rid in escaped_set
is_unl = r.get("is_unlocked", False)
is_exp = r.get("is_expired", False)
is_secret = r.get("is_secret", False)
if is_esc:
badge = "✅ ESCAPED"
elif is_cur:
badge = "📍 YOU ARE HERE"
elif is_exp:
badge = "⏱️ EXPIRED"
elif is_unl:
badge = "🔓 UNLOCKED"
else:
badge = "🔒 LOCKED"
if is_secret:
badge = f"✨ {badge}"
pos = r.get("position", {})
pos_tag = f"({pos.get('x', 0)},{pos.get('y', 0)})"
node_blocks.append(
f"+--------------------------------+\n"
f"| [{rid}] {rname[:20]:<20} |\n"
f"| Grid: {pos_tag:<6} Status: {badge:<13} |\n"
f"+--------------------------------+"
)
# Join with directional corridor connectors
corridor = " ||\n \\/ [Corridor]\n ||\n"
lines.append(corridor.join(node_blocks))
# Add Connections Summary and Legend
lines.append("\n🔗 Room Corridors / Links:")
for conn in map_data.get("connections", []):
lines.append(f" • {conn.get('from')} <===> {conn.get('to')}")
lines.append("\n🏷️ Legend: [📍 Current Room] [✅ Escaped] [🔓 Unlocked] [🔒 Locked] [⏱️ Expired] [✨ Secret Chamber]")
return "\n".join(lines)
def format_secret_room_discovery(room: Dict) -> str:
"""Format notification message when player discovers a hidden chamber / easter egg."""
rname = room.get("name", "Secret Chamber")
rid = room.get("id", "secret-room")
desc = room.get("description", "")
return (
f"✨🎉 EASTER EGG FOUND! Secret Chamber Unlocked: '{rname}' [{rid}]! 🎉✨\n"
f"📝 {desc}\n"
f"Use /api/v1/rooms/{rid} or explore via map to enter!"
)
def format_sequence_submission(result: Dict) -> str:
"""Format the result of an audio tone sequence submission."""
success = result.get("success", False)
rid = result.get("room_id", "")
msg = result.get("message", "")
seq = result.get("sequence_submitted", [])
if success:
return (
f"🎶 [SUCCESS] Harmonic Resonance Achieved in [{rid}]!\n"
f"🎵 Sequence Played: {' -> '.join(seq)}\n"
f"✨ {msg}\n"
f"🏆 Chamber Escaped (+{result.get('xp_awarded', 150)} XP)"
)
else:
matched = result.get("matched_tones_count", 0)
expected_len = result.get("expected_length", 0)
return (
f"❌ [DISSONANCE] Harmonic Sequence Failed in [{rid}]:\n"
f"🎵 Sequence Played: {' -> '.join(seq) if seq else '(empty)'}\n"
f"🔍 Matched {matched}/{expected_len} initial tones.\n"
f"⚠️ {msg}"
)