-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
565 lines (495 loc) · 21.4 KB
/
Copy pathmain.py
File metadata and controls
565 lines (495 loc) · 21.4 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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
"""ARGUS-9 — a text adventure with pixel art.
Run with: python main.py
Controls:
Up / Down or mouse move the selection
Enter / Space confirm (and skip the typewriter effect)
1...9 jump straight to a choice
J journal of discoveries
L switch language (Russian / English)
F5 / F9 save / load
Esc quit
"""
import sys
from pathlib import Path
import pygame
import art
import i18n
import scenes
from state import MAX_HP, GameState
SAVE_PATH = Path(__file__).with_name("save.json")
# UI colors — taken from the same palette as the artwork.
C_BG = art.PAL["0"]
C_PANEL = art.PAL["1"]
C_LINE = art.PAL["3"]
C_TEXT = art.PAL["7"]
C_DIM = art.PAL["5"]
C_ACCENT = art.PAL["c"]
C_ACCENT_HI = art.PAL["C"]
C_WARN = art.PAL["a"]
C_BAD = art.PAL["r"]
C_OK = art.PAL["g"]
TYPE_SPEED = 2.2 # characters per frame
# Filled in by load_fonts() once pygame is up; None means pygame's built-in font.
# Kept in a dict so load_fonts() does not need the `global` statement.
FONTS = {"main": None, "bold": None}
class Ui:
"""Fonts and geometry, recomputed whenever the window is resized."""
def __init__(self, win_w, win_h):
self.resize(win_w, win_h)
def resize(self, win_w, win_h):
"""Recomputes every size that depends on the window dimensions."""
self.w, self.h = win_w, win_h
# integer pixel-art scale: fit the width, but no more than 52% of the height
self.scale = max(2, min(win_w // art.LOW_W, int(win_h * 0.52) // art.LOW_H))
self.art_w = art.LOW_W * self.scale
self.art_h = art.LOW_H * self.scale
self.art_x = (win_w - self.art_w) // 2
self.art_y = 0
self.status_y = self.art_h
self.status_h = max(26, self.scale * 7)
self.panel_y = self.status_y + self.status_h
# translucent scanlines: one dark line per pixel row of the artwork
self.scanlines = pygame.Surface((self.art_w, self.art_h), pygame.SRCALPHA)
for y in range(0, self.art_h, max(2, self.scale)):
pygame.draw.line(self.scanlines, (0, 0, 0, 46), (0, y),
(self.art_w, y))
base = max(15, self.scale * 4)
self.f_title = pygame.font.Font(FONTS["bold"], base + 5)
self.f_body = pygame.font.Font(FONTS["main"], base)
self.f_choice = pygame.font.Font(FONTS["main"], base)
self.f_small = pygame.font.Font(FONTS["main"], max(12, base - 4))
self.line_h = self.f_body.get_linesize() + 2
self.pad = max(14, self.scale * 4)
def load_fonts():
"""Monospaced font with Cyrillic support; falls back to pygame's built-in."""
FONTS["main"] = FONTS["bold"] = None
for name in ("menlo", "dejavusansmono", "couriernew", "monaco", "consolas"):
path = pygame.font.match_font(name)
if path:
FONTS["main"] = FONTS["bold"] = path
break
bold = pygame.font.match_font("menlo", bold=True) or \
pygame.font.match_font("couriernew", bold=True)
if bold:
FONTS["bold"] = bold
def wrap(font, text, max_w):
"""Wraps a string on word boundaries to fit the given width."""
words = text.split(" ")
lines, cur = [], ""
for word in words:
probe = word if not cur else cur + " " + word
if font.size(probe)[0] <= max_w or not cur:
cur = probe
else:
lines.append(cur)
cur = word
if cur:
lines.append(cur)
return lines
class Game:
"""The window, the input handling and the current scene on screen."""
def __init__(self):
pygame.init()
pygame.display.set_caption(i18n.ui("caption"))
load_fonts()
self.screen = pygame.display.set_mode((900, 820), pygame.RESIZABLE)
self.ui = Ui(*self.screen.get_size())
self.clock = pygame.time.Clock()
self.frame = 0
self.state = GameState()
self.messages = [] # popup notifications (text, frames left)
self.show_log = False
self.scroll = 0
self.selected = 0
self.typed = 0.0
# Filled in by refresh_text() / draw_panel(), declared here so the
# instance never carries half a set of attributes.
self.paragraphs = []
self.choices = []
self.total_chars = 0
self.choice_rects = []
self.enter_scene("start", first=True)
# ------------------------------------------------------------------
# transitions
# ------------------------------------------------------------------
def enter_scene(self, sid, first=False):
"""Moves to a scene, applying its entry effect and reloading its text."""
if sid == "__quit__":
self.quit()
if sid == "__finish__":
sid = scenes.choose_ending(self.state)
# unlit compartments are off limits without a flashlight
if (sid in scenes.DARK_SCENES and "power" not in self.state.flags
and not self.state.has(scenes.FLASHLIGHT)):
sid = "dark"
sc = scenes.SCENES[sid]
self.state.scene = sid
if not first:
self.state.turns += 1
self.note(self.state.apply(sc.get("on_enter")))
self.state.visited.add(sid)
if self.state.hp <= 0 and not sc.get("ending"):
self.enter_scene("death_hp")
return
self.selected = 0
self.scroll = 0
self.refresh_text(restart_typing=True)
def refresh_text(self, restart_typing=False):
"""Re-reads the current scene from the locale.
Deliberately does not touch the game state: this also runs when the
player switches language mid-scene, and re-applying "on_enter" there
would grant items or drain health a second time.
"""
sc = scenes.SCENES[self.state.scene]
done = not restart_typing and self.typed >= getattr(self, "total_chars", 0)
self.paragraphs = i18n.paragraphs(self.state.scene)
if sc.get("epilogue"):
self.paragraphs += [i18n.epilogue(e)
for e in scenes.epilogue_ids(self.state)]
self.choices = self.visible_choices(sc)
self.total_chars = sum(len(p) for p in self.paragraphs)
self.selected = min(self.selected, max(0, len(self.choices) - 1))
if restart_typing:
self.typed = 0.0
elif done:
self.typed = float(self.total_chars)
else:
self.typed = min(self.typed, float(self.total_chars))
def switch_lang(self):
"""Cycles to the next language, keeping the scene and the state."""
i18n.toggle()
pygame.display.set_caption(i18n.ui("caption"))
self.refresh_text()
self.note([i18n.ui("lang_switched")])
def visible_choices(self, sc):
"""Choices of a scene whose "if" condition currently holds."""
return [c for c in sc.get("choices", []) if self.state.check(c.get("if"))]
def pick(self, index):
"""Acts on the n-th visible choice, or reveals the text if still typing."""
if not self.choices or not 0 <= index < len(self.choices):
return
if self.typed < self.total_chars: # first finish typing the text
self.typed = self.total_chars
return
choice = self.choices[index]
if choice["id"] == "lang": # title-screen language toggle
self.switch_lang()
return
self.note(self.state.apply(choice.get("do")))
self.enter_scene(choice["to"])
def note(self, msgs):
"""Queues popup notifications above the artwork."""
for m in msgs or []:
self.messages.append([m, 150])
# ------------------------------------------------------------------
# input
# ------------------------------------------------------------------
def handle(self, event):
"""Dispatches one pygame event."""
if event.type == pygame.QUIT:
self.quit()
elif event.type == pygame.VIDEORESIZE:
size = (max(560, event.w), max(480, event.h))
self.screen = pygame.display.set_mode(size, pygame.RESIZABLE)
self.ui.resize(*size)
elif event.type == pygame.KEYDOWN:
self.on_key(event)
elif event.type == pygame.MOUSEMOTION:
hit = self.choice_at(event.pos)
if hit is not None:
self.selected = hit
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
hit = self.choice_at(event.pos)
if hit is None and self.typed < self.total_chars:
self.typed = self.total_chars
elif hit is not None:
self.pick(hit)
elif event.button == 4:
self.scroll = max(0, self.scroll - 1)
elif event.button == 5:
self.scroll += 1
def _move_selection(self, step):
"""Moves the highlight up or down, wrapping around."""
if self.choices:
self.selected = (self.selected + step) % len(self.choices)
def _save_game(self):
"""Writes the current state, and the language, to SAVE_PATH."""
SAVE_PATH.write_text(self.state.to_json(), encoding="utf-8")
self.note([i18n.ui("saved")])
def _load_game(self):
"""Restores the state from SAVE_PATH, if there is one."""
if not SAVE_PATH.exists():
self.note([i18n.ui("no_save")])
return
self.state = GameState.from_json(SAVE_PATH.read_text(encoding="utf-8"))
pygame.display.set_caption(i18n.ui("caption"))
self.enter_scene(self.state.scene, first=True)
self.note([i18n.ui("loaded")])
def _restart(self):
"""Starts a fresh run; only meaningful on an ending screen."""
if scenes.SCENES[self.state.scene].get("ending"):
self.state = GameState()
self.enter_scene("start", first=True)
def _toggle_log(self):
"""Opens or closes the journal overlay."""
self.show_log = not self.show_log
def _escape(self):
"""Closes the journal if it is open, otherwise leaves the game."""
if self.show_log:
self.show_log = False
else:
self.quit()
def _select_next(self):
"""Moves the highlight one row down."""
self._move_selection(1)
def _select_prev(self):
"""Moves the highlight one row up."""
self._move_selection(-1)
def _confirm(self):
"""Acts on the highlighted choice."""
self.pick(self.selected)
# Keys that work regardless of whether the journal is open.
ALWAYS_KEYS = {
pygame.K_ESCAPE: _escape,
pygame.K_j: _toggle_log,
pygame.K_TAB: _toggle_log,
pygame.K_l: switch_lang,
}
# Keys that only act on the scene underneath.
SCENE_KEYS = {
pygame.K_DOWN: _select_next,
pygame.K_s: _select_next,
pygame.K_UP: _select_prev,
pygame.K_w: _select_prev,
pygame.K_RETURN: _confirm,
pygame.K_KP_ENTER: _confirm,
pygame.K_SPACE: _confirm,
pygame.K_F5: _save_game,
pygame.K_F9: _load_game,
pygame.K_r: _restart,
}
def on_key(self, event):
"""Handles a key press."""
key = event.key
action = self.ALWAYS_KEYS.get(key)
if action:
action(self)
return
if self.show_log:
return
if pygame.K_1 <= key <= pygame.K_9:
self.pick(key - pygame.K_1)
return
action = self.SCENE_KEYS.get(key)
if action:
action(self)
def choice_at(self, pos):
"""Index of the choice row under a screen position, or None."""
for i, rect in enumerate(getattr(self, "choice_rects", [])):
if rect.collidepoint(pos):
return i
return None
def quit(self):
"""Shuts pygame down and exits the process."""
pygame.quit()
sys.exit(0)
# ------------------------------------------------------------------
# rendering
# ------------------------------------------------------------------
def draw(self):
"""Renders one frame."""
self.screen.fill(C_BG)
self.draw_art()
self.draw_status()
self.draw_panel()
self.draw_messages()
if self.show_log:
self.draw_log()
def draw_art(self):
"""Scene illustration, scaled up with scanlines over it."""
ui = self.ui
sc = scenes.SCENES[self.state.scene]
low = art.render(sc.get("art", "static"), self.frame)
big = pygame.transform.scale(low, (ui.art_w, ui.art_h))
self.screen.blit(big, (ui.art_x, ui.art_y))
self.screen.blit(ui.scanlines, (ui.art_x, ui.art_y))
pygame.draw.rect(self.screen, C_LINE,
(ui.art_x, ui.art_y, ui.art_w, ui.art_h), 1)
def draw_status(self):
"""Status bar: condition pips, state flags and the inventory."""
ui, s = self.ui, self.screen
rect = pygame.Rect(0, ui.status_y, ui.w, ui.status_h)
pygame.draw.rect(s, C_PANEL, rect)
pygame.draw.line(s, C_LINE, (0, ui.status_y), (ui.w, ui.status_y))
pygame.draw.line(s, C_LINE, (0, rect.bottom - 1), (ui.w, rect.bottom - 1))
cy = ui.status_y + ui.status_h // 2
# integrity gauge
label = ui.f_small.render(i18n.ui("status"), False, C_DIM)
s.blit(label, (ui.pad, cy - label.get_height() // 2))
x = ui.pad + label.get_width() + 8
cell = max(10, ui.scale * 4)
for i in range(MAX_HP):
box = pygame.Rect(x + i * (cell + 3), cy - cell // 3, cell, int(cell / 1.6))
if i < self.state.hp:
color = C_OK if self.state.hp > 2 else (C_WARN if self.state.hp > 1 else C_BAD)
pygame.draw.rect(s, color, box)
else:
pygame.draw.rect(s, C_LINE, box, 1)
x += MAX_HP * (cell + 3) + 12
if "infected" in self.state.flags:
warn = ui.f_small.render(i18n.ui("flag_infected"), False, art.PAL["m"])
s.blit(warn, (x, cy - warn.get_height() // 2))
x += warn.get_width() + 12
if "power" in self.state.flags:
lit = ui.f_small.render(i18n.ui("flag_power"), False, C_ACCENT)
s.blit(lit, (x, cy - lit.get_height() // 2))
x += lit.get_width() + 12
if "quarantine" in self.state.flags:
q = ui.f_small.render(i18n.ui("flag_quarantine"), False, C_BAD)
s.blit(q, (x, cy - q.get_height() // 2))
x += q.get_width() + 12
# inventory on the right
inv = (", ".join(i18n.item(i) for i in self.state.items)
or i18n.ui("inventory_empty"))
text = ui.f_small.render(inv, False, C_DIM)
max_w = ui.w - x - ui.pad
if text.get_width() > max_w > 40:
while text.get_width() > max_w and len(inv) > 4:
inv = inv[:-4] + "…"
text = ui.f_small.render(inv, False, C_DIM)
s.blit(text, (ui.w - ui.pad - text.get_width(), cy - text.get_height() // 2))
def _draw_title(self, y):
"""Scene heading with a rule under it; returns the next free y."""
ui, s = self.ui, self.screen
title = ui.f_title.render(i18n.title(self.state.scene), False, C_ACCENT_HI)
s.blit(title, (ui.pad, y))
rule = y + title.get_height() + 2
pygame.draw.line(s, C_LINE, (ui.pad, rule), (ui.w - ui.pad, rule))
return y + title.get_height() + ui.line_h // 2 + 6
def _draw_paragraphs(self, y):
"""Body text, revealed up to self.typed; returns the next free y."""
ui, s = self.ui, self.screen
max_w = ui.w - 2 * ui.pad
budget = int(self.typed)
for para in self.paragraphs:
for ln in wrap(ui.f_body, para[:max(0, budget)], max_w):
s.blit(ui.f_body.render(ln, False, C_TEXT), (ui.pad, y))
y += ui.line_h
budget -= len(para)
y += ui.line_h // 3
if budget <= 0:
break
return y
def _draw_choice(self, index, choice, y):
"""One choice row, with its hint when selected; returns its rectangle."""
ui, s = self.ui, self.screen
active = index == self.selected
marker = "▸" if active else " "
label = f"{marker} {index + 1}. {i18n.choice(self.state.scene, choice['id'])}"
surf = ui.f_choice.render(label, False, C_ACCENT_HI if active else C_TEXT)
row = pygame.Rect(ui.pad - 6, y - 3, ui.w - 2 * ui.pad + 12,
surf.get_height() + 6)
if active:
pygame.draw.rect(s, C_PANEL, row)
pygame.draw.line(s, C_ACCENT, (row.left, row.top), (row.left, row.bottom))
s.blit(surf, (ui.pad, y))
text = i18n.hint(self.state.scene, choice["id"])
if text and active:
hint = ui.f_small.render(f"— {text}", False, C_WARN)
hx = ui.pad + surf.get_width() + 10
if hx + hint.get_width() < ui.w - ui.pad:
s.blit(hint, (hx, y + (surf.get_height() - hint.get_height()) // 2))
return row
def draw_panel(self):
"""Text panel: title, typed-out paragraphs and the list of choices."""
ui, s = self.ui, self.screen
y = self._draw_paragraphs(self._draw_title(ui.panel_y + ui.pad))
self.choice_rects = []
if self.typed < self.total_chars:
hint = ui.f_small.render(i18n.ui("continue_hint"), False, C_LINE)
s.blit(hint, (ui.pad, ui.h - hint.get_height() - 8))
return
y = max(y + ui.line_h // 2,
ui.h - ui.pad - len(self.choices) * (ui.line_h + 6))
for i, choice in enumerate(self.choices):
self.choice_rects.append(self._draw_choice(i, choice, y))
y += ui.line_h + 6
# top-right corner of the panel: how to restart, or how to switch language
ending = scenes.SCENES[self.state.scene].get("ending")
corner = i18n.ui("restart_hint") if ending else i18n.ui("lang_hint")
tip = ui.f_small.render(corner, False, C_DIM)
s.blit(tip, (ui.w - ui.pad - tip.get_width(), ui.panel_y + 6))
def draw_messages(self):
"""Fading popup notifications in the corner of the artwork."""
ui, s = self.ui, self.screen
self.messages = [m for m in self.messages if m[1] > 0]
y = ui.art_y + 10
for msg, ttl in self.messages[-4:]:
surf = ui.f_small.render(msg, False, C_ACCENT_HI)
pad = 6
bg = pygame.Surface((surf.get_width() + pad * 2,
surf.get_height() + pad), pygame.SRCALPHA)
bg.fill((*C_PANEL, min(220, ttl * 4)))
s.blit(bg, (ui.art_x + ui.art_w - bg.get_width() - 10, y))
s.blit(surf, (ui.art_x + ui.art_w - bg.get_width() - 10 + pad,
y + pad // 2))
y += bg.get_height() + 4
for m in self.messages:
m[1] -= 1
def _log_heading(self, key, x, y):
"""Draws a small dim section heading; returns the next free y."""
self.screen.blit(self.ui.f_small.render(i18n.ui(key), False, C_DIM), (x, y))
return y + self.ui.line_h
def _log_records(self, x, y):
"""The records found so far, wrapped to the overlay width."""
ui, s = self.ui, self.screen
y = self._log_heading("journal_records", x, y)
if not self.state.log:
s.blit(ui.f_body.render(i18n.ui("journal_empty"), False, C_LINE), (x, y))
return y + ui.line_h
for entry in self.state.log:
for ln in wrap(ui.f_body, "• " + i18n.log(entry), ui.w - 4 * ui.pad):
s.blit(ui.f_body.render(ln, False, C_TEXT), (x, y))
y += ui.line_h
return y
def _log_items(self, x, y):
"""The inventory, by the names of the current language."""
ui, s = self.ui, self.screen
y = self._log_heading("journal_carried", x, y)
names = [i18n.item(i) for i in self.state.items]
for label in names or [i18n.ui("journal_nothing")]:
s.blit(ui.f_body.render("• " + label, False, C_TEXT), (x, y))
y += ui.line_h
return y
def draw_log(self):
"""Journal overlay: records found, inventory and statistics."""
ui, s = self.ui, self.screen
overlay = pygame.Surface((ui.w, ui.h), pygame.SRCALPHA)
overlay.fill((*C_BG, 235))
s.blit(overlay, (0, 0))
x, y = ui.pad * 2, ui.pad * 2
s.blit(ui.f_title.render(i18n.ui("journal"), False, C_ACCENT_HI), (x, y))
y += ui.line_h * 2
y = self._log_records(x, y) + ui.line_h
y = self._log_items(x, y) + ui.line_h
s.blit(ui.f_small.render(
i18n.ui("journal_stats", turns=self.state.turns,
places=len(self.state.visited)),
False, C_DIM), (x, y))
tip = ui.f_small.render(i18n.ui("journal_close"), False, C_DIM)
s.blit(tip, (ui.w - ui.pad * 2 - tip.get_width(), ui.h - ui.pad * 2))
# ------------------------------------------------------------------
def run(self):
"""Main loop: events, typewriter advance, draw, repeat at 60 fps."""
while True:
for event in pygame.event.get():
self.handle(event)
if self.typed < self.total_chars:
self.typed += TYPE_SPEED
self.draw()
pygame.display.flip()
self.frame += 1
self.clock.tick(60)
if __name__ == "__main__":
Game().run()