-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck.py
More file actions
397 lines (341 loc) · 15.9 KB
/
Copy pathcheck.py
File metadata and controls
397 lines (341 loc) · 15.9 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
"""Content and artwork checks: runs headless.
python check.py
Catches typos in scene ids, unreachable locations, unknown conditions/effects,
gaps between the locales and crashes inside the drawing functions.
"""
import os
import sys
# SDL must not reach for a real display: these checks run in CI with no screen.
# The variable has to be set before pygame is imported for the first time,
# which is why the imports below cannot sit at the top of the file.
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
# pylint: disable=wrong-import-position
import pygame
import art
import i18n
import locales
import main as game_main
import scenes
from state import GameState
# pylint: enable=wrong-import-position
SPECIAL = {"__quit__", "__finish__"}
errors, warnings = [], []
def as_list(val):
"""Wraps a bare value into a list, leaving lists and tuples alone."""
return list(val) if isinstance(val, (list, tuple)) else [val]
def effects_of(sc):
"""Every effect dict a scene can apply: on entry and on each choice."""
return [e for e in [sc.get("on_enter")]
+ [c.get("do") for c in sc.get("choices", [])] if e]
# --------------------------------------------------------------------------
# Structure
# --------------------------------------------------------------------------
def check_scenes():
"""Per-scene fields, choice ids and the validity of conditions/effects."""
ids = set(scenes.SCENES)
for sid, sc in scenes.SCENES.items():
if sc.get("art") not in art.SCENES:
errors.append(f"{sid}: unknown image {sc.get('art')!r}")
if not sc.get("choices") and not sc.get("ending"):
errors.append(f"{sid}: no choices and not marked as an ending")
if sc.get("ending") and sc.get("choices"):
warnings.append(f"{sid}: ending scene with choices")
seen_ids = set()
for i, ch in enumerate(sc.get("choices", [])):
where = f"{sid}.choices[{i}]"
if "id" not in ch or "to" not in ch:
errors.append(f"{where}: fields id and to are required")
continue
if ch["id"] in seen_ids:
errors.append(f"{where}: duplicate choice id {ch['id']!r}")
seen_ids.add(ch["id"])
if ch["to"] not in ids and ch["to"] not in SPECIAL:
errors.append(f"{where}: jump to a non-existent scene {ch['to']!r}")
_probe(where, ch.get("if"), ch.get("do"))
_probe(f"{sid}.on_enter", None, sc.get("on_enter"))
def _probe(where, cond, eff):
"""Runs a condition and an effect against a blank state to catch bad keys."""
for call, arg in ((GameState().check, cond), (GameState().apply, eff)):
if arg is None:
continue
try:
call(arg)
except KeyError as exc:
errors.append(f"{where}: {exc}")
def check_reachability():
"""Warns about scenes no chain of choices can lead to."""
seen, queue = {"start"}, ["start"]
while queue:
for ch in scenes.SCENES[queue.pop()].get("choices", []):
nxt = ch["to"]
if nxt in SPECIAL or nxt in seen:
continue
seen.add(nxt)
queue.append(nxt)
# endings behind __finish__ and the "dark" scenes are not reached by a
# direct link but through choose_ending / the darkness check
seen.update(("ending_witness", "ending_alone", "ending_beacon",
"ending_escape_quarantine", "death_infected", "death_hp",
"dark", "death_dark"))
for sid in sorted(set(scenes.SCENES) - seen):
warnings.append(f"{sid}: unreachable scene")
def check_requirements():
"""No condition may require an item or flag that is never granted."""
given_items, given_flags = set(), set()
for sc in scenes.SCENES.values():
for eff in effects_of(sc):
given_items.update(as_list(eff.get("item+", [])))
given_flags.update(as_list(eff.get("flag+", [])))
conds = [(sid, ch.get("if") or {}) for sid, sc in scenes.SCENES.items()
for ch in sc.get("choices", [])]
conds += [("EPILOGUE." + eid, cond) for eid, cond in scenes.EPILOGUE]
for sid, cond in conds:
for key, pool, what in (("item", given_items, "item"),
("no_item", given_items, "item"),
("flag", given_flags, "flag"),
("any_flag", given_flags, "flag")):
for need in as_list(cond.get(key, [])):
if need and need not in pool:
errors.append(f"{sid}: requires {what} {need!r}, "
"which is never granted anywhere")
# --------------------------------------------------------------------------
# Locales
# --------------------------------------------------------------------------
def wanted_ids():
"""The id sets every locale is expected to cover."""
logs = set()
for sc in scenes.SCENES.values():
for eff in effects_of(sc):
logs.update(as_list(eff.get("log+", [])))
items = {v for k, v in vars(scenes).items()
if k.isupper() and isinstance(v, str) and not k.startswith("_")}
return {"scene": set(scenes.SCENES), "item": items, "log": logs,
"epilogue": {eid for eid, _ in scenes.EPILOGUE}}
def check_locale_coverage():
"""Each locale must define exactly the ids the game refers to."""
want = wanted_ids()
ui_keys = {code: set(mod.UI) for code, mod in locales.MODULES.items()}
reference = ui_keys[i18n.DEFAULT]
for code, mod in locales.MODULES.items():
tag = f"locale {code}"
have = {"scene": set(mod.SCENES), "item": set(mod.ITEMS),
"log": set(mod.LOG), "epilogue": set(mod.EPILOGUE)}
for label, ids in want.items():
for missing in sorted(ids - have[label]):
errors.append(f"{tag}: no {label} {missing!r}")
for extra in sorted(have[label] - ids):
warnings.append(f"{tag}: unused {label} {extra!r}")
for missing in sorted(reference - ui_keys[code]):
errors.append(f"{tag}: no UI string {missing!r}")
for extra in sorted(ui_keys[code] - reference):
warnings.append(f"{tag}: unused UI string {extra!r}")
def check_locale_scenes():
"""Every scene entry needs a title, body text and all of its choices."""
for code, mod in locales.MODULES.items():
tag = f"locale {code}"
for sid, sc in scenes.SCENES.items():
entry = mod.SCENES.get(sid)
if entry is None:
continue
if not entry.get("title"):
errors.append(f"{tag}: {sid} has no title")
if not entry.get("text"):
errors.append(f"{tag}: {sid} has no text")
want_ids = {ch["id"] for ch in sc.get("choices", [])}
have_ids = set(entry.get("choices", {}))
for missing in sorted(want_ids - have_ids):
errors.append(f"{tag}: {sid} has no choice {missing!r}")
for extra in sorted(have_ids - want_ids):
warnings.append(f"{tag}: {sid} has an unused choice {extra!r}")
for hid in sorted(set(entry.get("hints", {})) - want_ids):
warnings.append(f"{tag}: {sid} hints at an unknown choice {hid!r}")
# hints are a deliberate authoring choice: warn when the locales disagree
for sid in sorted(scenes.SCENES):
marked = [code for code, mod in locales.MODULES.items()
if mod.SCENES.get(sid, {}).get("hints")]
if marked and len(marked) != len(locales.MODULES):
warnings.append(f"{sid}: hints present only in {marked}")
# --------------------------------------------------------------------------
# Artwork
# --------------------------------------------------------------------------
def check_art():
"""Every illustration renders at the right size, from palette colours only."""
pygame.init()
pygame.display.set_mode((64, 64))
for name in art.SCENES:
for frame in (0, 7, 33, 91):
surf = art.render(name, frame)
if surf.get_size() != (art.LOW_W, art.LOW_H):
errors.append(f"art {name}: wrong size {surf.get_size()}")
for var in dir(art):
if var.startswith("SPR_"):
for row in getattr(art, var):
for ch in row:
if ch not in art.PAL and ch not in art.SKIP:
errors.append(f"{var}: character {ch!r} outside the palette")
# --------------------------------------------------------------------------
# Playing
# --------------------------------------------------------------------------
# The route is written in choice ids, so it is language-independent.
ROUTE = [
("cryo", "locker"), ("cryo_locker", "take_light"),
("cryo", "term"), ("cryo_term", "back"),
("cryo", "corridor"),
("corridor", "medbay"),
("medbay", "cabinet"), ("medbay_cabinet", "close"),
("medbay", "terminal"), ("medbay_log", "close"),
("medbay", "sheet"), ("medbay_body", "take_crystal"),
("medbay_crystal", "back"), ("medbay", "back"),
("corridor", "quarters"),
("quarters", "locker"), ("quarters_locker", "close"),
("quarters", "back"),
("corridor", "comms"),
("comms", "take_fuse"), ("comms_fuse", "to_engine"),
("engine", "panel"), ("engine_panel", "restore"),
("power_on", "reply"),
("engine", "cutter"), ("engine_cutter", "belt"),
("engine", "back"),
("corridor", "cryo"),
("cryo", "pod"), ("cryo_pod", "thaw"),
("cryo_wake_mor", "know"), ("cryo_mor_talk", "leave"),
("corridor", "comms"),
("comms", "transmit"), ("comms_send", "report"),
("comms_report", "to_shuttle"),
("shuttle_door", "enter_code"),
("shuttle", "wait_mor"), ("shuttle_wait", "pilot_seat"),
("shuttle", "launch"), ("launch", "burn"),
]
def check_playthrough():
"""Plays through to the best ending along a predefined route."""
st = GameState(scene="start")
st.apply(scenes.SCENES["start"].get("on_enter"))
st.scene = "cryo" # the "begin" choice
st.apply(scenes.SCENES[st.scene].get("on_enter"))
for expect, cid in ROUTE:
if st.scene != expect:
errors.append(f"playthrough: expected scene {expect}, "
f"but the game is in {st.scene}")
return
options = [c for c in scenes.SCENES[st.scene].get("choices", [])
if st.check(c.get("if"))]
match = next((c for c in options if c["id"] == cid), None)
if match is None:
errors.append(f"playthrough: {st.scene} has no available choice {cid!r}. "
f"Available: {[c['id'] for c in options]}")
return
st.apply(match.get("do"))
nxt = match["to"]
if nxt == "__finish__":
nxt = scenes.choose_ending(st)
if (nxt in scenes.DARK_SCENES and "power" not in st.flags
and not st.has(scenes.FLASHLIGHT)):
nxt = "dark"
st.scene = nxt
st.apply(scenes.SCENES[nxt].get("on_enter"))
if st.hp <= 0 and not scenes.SCENES[nxt].get("ending"):
errors.append(f"playthrough: died of exhaustion in {nxt}")
return
if st.scene != "ending_witness":
errors.append("playthrough: expected the ending ending_witness, "
f"got {st.scene}")
elif not scenes.epilogue_ids(st):
warnings.append("playthrough: ending with no epilogues")
else:
print(f" route completed: {st.scene}, condition {st.hp}/4, "
f"epilogues {len(scenes.epilogue_ids(st))}")
# --------------------------------------------------------------------------
# Interface
# --------------------------------------------------------------------------
def check_ui():
"""UI smoke test: draws every scene and handles every key, in each language."""
game = game_main.Game()
for code in locales.CODES:
i18n.set_lang(code)
for sid in scenes.SCENES:
game.enter_scene(sid, first=True)
game.typed = game.total_chars
for frame in (0, 25):
game.frame = frame
try:
game.draw()
# a smoke test wants to report any failure, not just expected ones
except Exception as exc: # pylint: disable=broad-exception-caught
errors.append(f"drawing scene {sid} [{code}]: {exc!r}")
break
i18n.set_lang(i18n.DEFAULT)
keys = [pygame.K_DOWN, pygame.K_UP, pygame.K_j, pygame.K_j, pygame.K_F5,
pygame.K_F9, pygame.K_1, pygame.K_SPACE, pygame.K_r, pygame.K_TAB,
pygame.K_TAB, pygame.K_l, pygame.K_l]
game.enter_scene("corridor", first=True)
for key in keys:
try:
game.on_key(pygame.event.Event(pygame.KEYDOWN, key=key))
game.draw()
except SystemExit:
errors.append(f"key {key}: unexpected exit from the game")
except Exception as exc: # pylint: disable=broad-exception-caught
errors.append(f"key {key}: {exc!r}")
game.handle(pygame.event.Event(pygame.VIDEORESIZE, w=640, h=520, size=(640, 520)))
game.draw()
game.handle(pygame.event.Event(
pygame.MOUSEBUTTONDOWN, button=1, pos=(20, game.ui.h - 30)))
game.draw()
def check_darkness():
"""The dark-scene gate in main.py must agree with the flags scenes.py sets."""
for flags, items, expect in (
(set(), [], "dark"), # no light at all
({"power"}, [], "medbay"), # reactor running
(set(), [scenes.FLASHLIGHT], "medbay"), # carrying the flashlight
):
game = game_main.Game()
game.state.flags = set(flags)
game.state.items = list(items)
game.enter_scene("medbay", first=True)
if game.state.scene != expect:
errors.append(f"darkness: flags={flags or '{}'} items={items} -> "
f"{game.state.scene}, expected {expect}")
def check_lang_switch():
"""Switching language mid-scene must not touch the game state."""
i18n.set_lang("ru")
game = game_main.Game()
game.enter_scene("cryo_locker", first=True)
game.typed = game.total_chars
game.pick(0) # picks up the flashlight
before = (game.state.hp, sorted(game.state.items), sorted(game.state.flags),
game.state.turns, game.state.scene)
for _ in range(4):
game.switch_lang()
after = (game.state.hp, sorted(game.state.items), sorted(game.state.flags),
game.state.turns, game.state.scene)
if before != after:
errors.append(f"language switch changed the state: {before} -> {after}")
if i18n.current() != "ru":
errors.append(f"four switches did not return to ru: {i18n.current()}")
# the title-screen toggle must not count as a move either
game.enter_scene("start", first=True)
game.typed = game.total_chars
turns = game.state.turns
lang_at = next(i for i, c in enumerate(game.choices) if c["id"] == "lang")
game.pick(lang_at)
if game.state.turns != turns:
errors.append("the title-screen language toggle counted as a move")
if game.state.scene != "start":
errors.append(f"the language toggle left the title screen: {game.state.scene}")
i18n.set_lang(i18n.DEFAULT)
CHECKS = (check_scenes, check_reachability, check_requirements,
check_locale_coverage, check_locale_scenes, check_art,
check_playthrough, check_ui, check_darkness, check_lang_switch)
def main():
"""Runs every check and reports the result."""
for check in CHECKS:
check()
print(f"Scenes: {len(scenes.SCENES)}, images: {len(art.SCENES)}, "
f"languages: {', '.join(locales.CODES)}")
for warning in warnings:
print(" WARNING:", warning)
for error in errors:
print(" ERROR:", error)
print("Done." if not errors else f"Errors: {len(errors)}")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())