Skip to content

Commit 01657ff

Browse files
coderabbitai[bot]hyperpolymatharena-agent
authored
Add and document the SOP bunker sim with expeditions and save/load (#340)
Add the playable Standard Operating Psychopathy browser game with utility-driven inmate AI, construction and wiring, power and gas simulation, disasters, CRT-style rendering, and audio. Include surface expeditions, newcomer arrivals, autosave/manual save/load and JSON import/export, plus smoke and DOM test harnesses. Document AI, world, rendering, UI, audio, and persistence functions. Validate world saves, normalize restored statistics, defer expedition returns when the gate is blocked, and bind the development server to localhost. Scope exceeds the task title “Generate docstrings for PR #339”: the eight-commit range adds the entire game alongside documentation and fixes. Validation: commit history reports four 28,800-tick smoke runs and a passing DOM boot test. Validation was not rerun for this metadata task. [View coding task](https://app.coderabbit.ai/code/tasks/676f663e-e460-5a48-bec4-57d17db1c73b?source=coding_agent_github_pr_description) --------- Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com> Co-authored-by: hyperpolymath <6759885+hyperpolymath@users.noreply.github.com> Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent c25e0ac commit 01657ff

5 files changed

Lines changed: 125 additions & 11 deletions

File tree

‎game/ai.js‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
window.SOP = window.SOP || {};
77

88
SOP.InmateAI = class InmateAI {
9+
/** Create an idle inmate at tile coordinates (x, y) with randomised initial needs. */
910
constructor(name, trait, x, y) {
1011
this.name = name;
1112
this.trait = trait;
@@ -36,6 +37,10 @@ SOP.InmateAI = class InmateAI {
3637
}
3738

3839
/* ---------------- UTILITY EVALUATOR ---------------- */
40+
/**
41+
* Choose the highest-scoring drive for a living inmate. Reset progress and movement
42+
* when the action changes or has no goal; otherwise retain the current goal.
43+
*/
3944
evaluateDrives(world) {
4045
if (this.dead) return;
4146
const A = this.affective;
@@ -153,7 +158,7 @@ SOP.InmateAI = class InmateAI {
153158
this.logConativeState(best);
154159
}
155160

156-
/* Is this device on the same wired component as any dispenser? */
161+
/** Return whether dev is connected to any dispenser, including the dispenser itself. */
157162
onDispenserGrid(world, dev) {
158163
const starts = world.devices.filter(d => d.kind === 'dispenser');
159164
if (!starts.length) return false;
@@ -171,13 +176,15 @@ SOP.InmateAI = class InmateAI {
171176
return seen.has(dev.id);
172177
}
173178

179+
/** Return a random sabotage goal for a wired device other than a gas vent, or null. */
174180
pickSabotageTarget(world) {
175181
const linked = world.devices.filter(d => d.links.length > 0 && d.kind !== 'gas_vent');
176182
if (!linked.length) return null;
177183
const d = linked[Math.floor(Math.random() * linked.length)];
178184
return { kind: 'device', dev: d, act: 'sabotage' };
179185
}
180186

187+
/** Return a walkable wander goal, or null if none is found in 20 random attempts. */
181188
randomWanderGoal(world) {
182189
for (let tries = 0; tries < 20; tries++) {
183190
const x = Math.floor(Math.random() * world.W);
@@ -187,6 +194,10 @@ SOP.InmateAI = class InmateAI {
187194
return null;
188195
}
189196

197+
/**
198+
* Return the nearest device matching pred by Manhattan distance, or null.
199+
* Reachability is not checked; errors thrown by pred propagate to the caller.
200+
*/
190201
nearestDevice(world, pred) {
191202
let best = null, bd = Infinity;
192203
for (const d of world.devices) {
@@ -197,6 +208,10 @@ SOP.InmateAI = class InmateAI {
197208
return best;
198209
}
199210

211+
/**
212+
* Return the nearest dirt dig mark with a walkable neighbour, preferring unclaimed
213+
* marks, or null if none qualifies. Distance is Manhattan; no path is checked.
214+
*/
200215
nearestDigMark(world) {
201216
const taken = new Set();
202217
for (const o of world.inmates) {
@@ -216,6 +231,10 @@ SOP.InmateAI = class InmateAI {
216231
return best || bestTaken;
217232
}
218233

234+
/**
235+
* Return the nearest empty tile with gas at most 10 and oxygen at least 30
236+
* on their 0–100 scales, or null. Use Manhattan distance without checking a path.
237+
*/
219238
nearestClearAir(world) {
220239
let best = null, bd = Infinity;
221240
for (let y = 0; y < world.H; y++) for (let x = 0; x < world.W; x++) {
@@ -227,6 +246,7 @@ SOP.InmateAI = class InmateAI {
227246
return best;
228247
}
229248

249+
/** Return the display thought for an action name, falling back to an em dash. */
230250
thoughtFor(action) {
231251
const T = {
232252
'ESSEN FASSEN': 'Ausgabe. Jetzt.',
@@ -245,11 +265,16 @@ SOP.InmateAI = class InmateAI {
245265
return T[action] || '—';
246266
}
247267

268+
/** Release all devices in world operated by this inmate. */
248269
releaseCrank(world) {
249270
for (const d of world.devices) if (d.operatedBy === this.id) d.operatedBy = null;
250271
}
251272

252273
/* ---------------- PER-TICK EXECUTION ---------------- */
274+
/**
275+
* Advance needs, health, movement and actions by one simulation tick; ignore dead inmates.
276+
* Deliver action events synchronously to onEvent; callback errors propagate.
277+
*/
253278
tick(world, onEvent) {
254279
if (this.dead) return;
255280
// dynamo ownership sanity: a cranker who switched goals frees the cranks
@@ -309,6 +334,10 @@ SOP.InmateAI = class InmateAI {
309334
if (this.sayCooldown > 0) this.sayCooldown--;
310335
}
311336

337+
/**
338+
* Return whether tile (x, y) is close enough to execute the current goal.
339+
* Flee and hide tile goals require an exact match; other goals allow one orthogonal step.
340+
*/
312341
isGoalTile(x, y) {
313342
const g = this.goal;
314343
if (!g) return false;
@@ -319,6 +348,10 @@ SOP.InmateAI = class InmateAI {
319348
return false;
320349
}
321350

351+
/**
352+
* Replace the route to the current goal or an adjacent standing tile.
353+
* Abandon the goal if no standing tile or path is available.
354+
*/
322355
repath(world) {
323356
const g = this.goal;
324357
if (!g) { this.path = []; return; }
@@ -339,13 +372,22 @@ SOP.InmateAI = class InmateAI {
339372
if (!p) this.goal = null; // unreachable — re-evaluate next round
340373
}
341374

375+
/**
376+
* Return the first walkable neighbour in east, west, south, north order, or null.
377+
* Inmate occupancy and reachability from the current position are not checked.
378+
*/
342379
adjacentStand(world, x, y) {
343380
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) {
344381
if (world.walkable(x + dx, y + dy)) return { x: x + dx, y: y + dy };
345382
}
346383
return null;
347384
}
348385

386+
/**
387+
* Advance the current action when within reach, otherwise request a route if needed.
388+
* May change needs, resources, terrain or devices and clear the goal.
389+
* Deliver action events synchronously to onEvent; callback errors propagate.
390+
*/
349391
execute(world, onEvent) {
350392
const g = this.goal;
351393
if (!g) return;
@@ -445,6 +487,10 @@ SOP.InmateAI = class InmateAI {
445487
}
446488
}
447489

490+
/**
491+
* Mark this inmate dead with the display cause, end sleep and release operated devices
492+
* in SOP.World.
493+
*/
448494
die(cause) {
449495
this.dead = true;
450496
this.deadCause = cause;
@@ -454,6 +500,10 @@ SOP.InmateAI = class InmateAI {
454500
}
455501

456502
/* ---------------- SAVE / LOAD ---------------- */
503+
/**
504+
* Return save data with rounded health and copied needs and expedition state.
505+
* Omit the current goal, route, sleep state and action progress.
506+
*/
457507
serialize() {
458508
return {
459509
id: this.id, name: this.name, trait: this.trait,
@@ -465,6 +515,7 @@ SOP.InmateAI = class InmateAI {
465515
};
466516
}
467517

518+
/** Restore an inmate from save data with idle action state; reuse d.away when present. */
468519
static fromData(d) {
469520
const i = new SOP.InmateAI(d.name, d.trait, d.tx, d.ty);
470521
i.id = d.id || d.name;
@@ -477,6 +528,7 @@ SOP.InmateAI = class InmateAI {
477528
return i;
478529
}
479530

531+
/** Retain the scored action by reference as lastScored. */
480532
logConativeState(action) {
481533
this.lastScored = action;
482534
}

‎game/audio.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,11 @@ SOP.Audio = (() => {
7272
}
7373
}
7474

75-
/** Start or stop the sequencer; return whether playback is running. */
75+
/**
76+
* Start or stop scheduling notes; return whether the sequencer is running.
77+
* Return false if Web Audio is unavailable; audio initialisation errors propagate.
78+
* Stopping leaves already scheduled notes to finish.
79+
*/
7680
function toggle() {
7781
init();
7882
if (!ctx) return false;

‎game/main.js‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,10 @@ SOP.Main = (() => {
275275
};
276276
}
277277

278-
/** Save the current snapshot to localStorage and return success; silent suppresses logs. */
278+
/**
279+
* Save the current snapshot to localStorage and return success; silent suppresses logs.
280+
* Return false when storage is unavailable or serialisation or writing fails.
281+
*/
279282
function saveGame(silent) {
280283
const st = storage();
281284
if (!st) { if (!silent) UI.log('STORAGE BLOCKIERT. NUTZE EXPORT.', 'alert'); return false; }
@@ -289,7 +292,10 @@ SOP.Main = (() => {
289292
}
290293
}
291294

292-
/** Restore a version-1 snapshot and resume play; return false on format or load errors. */
295+
/**
296+
* Restore a version-1 snapshot and resume play; return true on success or false on format
297+
* or load errors. Failed loads do not roll back changes already applied to the game.
298+
*/
293299
function loadGame(data) {
294300
try {
295301
if (!data || data.v !== 1) { UI.log('AKTE UNLESBAR (FALSCHES FORMAT).', 'alert'); return false; }
@@ -343,7 +349,11 @@ SOP.Main = (() => {
343349
}
344350
}
345351

346-
/** Read a File as text, parse its JSON, and attempt to restore the saved game. */
352+
/**
353+
* Read a File as text asynchronously and attempt to restore its JSON snapshot.
354+
* JSON parse errors are caught and load errors become loadGame's false result.
355+
* Synchronous FileReader errors propagate; asynchronous read errors have no handler.
356+
*/
347357
function importSave(file) {
348358
const r = new FileReader();
349359
r.onload = () => {

‎game/ui.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ SOP.UI = (() => {
2626
let logLines = [];
2727

2828
/* ---------------- EVENT LOG ---------------- */
29+
/**
30+
* Prepend a day-stamped message to the display, retaining at most 70 entries.
31+
* msg is inserted as HTML; cls selects the l-* CSS class and defaults to ok.
32+
*/
2933
function log(msg, cls) {
3034
const day = SOP.Main ? SOP.Main.day() : 0;
3135
logLines.push({ msg, cls: cls || 'ok', day });
@@ -35,14 +39,20 @@ SOP.UI = (() => {
3539
).reverse().join('');
3640
}
3741

42+
/** Display an alert message and sound the alarm when audio is on. */
3843
function alert(msg) {
3944
log(msg, 'alert');
4045
if (SOP.Audio.on) SOP.Audio.alarm();
4146
}
4247

48+
/** Display a message with the wiring event style. */
4349
function wire(msg) { log(msg, 'wire'); }
4450

4551
/* ---------------- TICKER ---------------- */
52+
/**
53+
* Replace ticker text with the standard lines, optionally prefixed by extra.
54+
* An extra announcement highlights the ticker and schedules a reset after six seconds.
55+
*/
4656
function setTicker(extra) {
4757
const lines = extra ? [extra, ...SOP.TICKER_LINES] : SOP.TICKER_LINES;
4858
el.ticker.textContent = lines.join(' /// ') + ' /// ';
@@ -53,6 +63,7 @@ SOP.UI = (() => {
5363
}
5464

5565
/* ---------------- BUILD MENU ---------------- */
66+
/** Populate build controls and hints; call onSelect(kind) when an item is clicked. */
5667
function initBuildMenu(onSelect) {
5768
let html = '';
5869
for (const kind of SOP.BUILDABLE) {
@@ -80,17 +91,23 @@ SOP.UI = (() => {
8091
el.buildHint.textContent = 'MODUL WÄHLEN, DANN IM HOHLRAUM PLATZIEREN. ESC BRICHT AB.';
8192
}
8293

94+
/** Return a German cost label from resource quantities, or GRATIS for an empty cost. */
8395
function costText(cost) {
8496
const parts = [];
8597
for (const k in cost) parts.push(cost[k] + ' ' + k.toUpperCase());
8698
return parts.length ? 'KOSTET ' + parts.join(', ') : 'GRATIS';
8799
}
88100

101+
/** Remove selection styling from build buttons. */
89102
function clearBuildSelection() {
90103
el.buildMenu.querySelectorAll('.build-item').forEach(x => x.classList.remove('selected'));
91104
}
92105

93106
/* ---------------- SYSTEM PANEL ---------------- */
107+
/**
108+
* Refresh the HUD with the day, power, resources, living inmate count and atmosphere
109+
* averaged over empty tiles.
110+
*/
94111
function updateSystem(world, day) {
95112
el.sysDay.textContent = day;
96113
const p = world.power;
@@ -119,6 +136,10 @@ SOP.UI = (() => {
119136
/* ---------------- SUBJECT INSPECTOR ---------------- */
120137
const NEED_LABEL = { stress: 'STRESS', hunger: 'HUNGER', exhaustion: 'ERSCHÖPFUNG', paranoia: 'ARGWOHN', o2: 'O₂-MANGEL' };
121138

139+
/**
140+
* Show the selected inmate’s needs and action, or an empty, dead or away state.
141+
* world is unused.
142+
*/
122143
function updateInspector(world, selected) {
123144
if (!selected || selected.dead) {
124145
el.inspector.innerHTML = `<div class="panel-title">SUBJEKT-INSPEKTOR</div>
@@ -163,6 +184,11 @@ SOP.UI = (() => {
163184
/* ---------------- DEVICE INSPECTOR (crosslink / airlock) ---------------- */
164185
let devSig = '';
165186

187+
/**
188+
* Refresh device details and controls when tracked display state changes.
189+
* mode selects the empty-panel hint; ticksNow is elapsed simulation ticks
190+
* used for expedition estimates and defaults to zero when omitted.
191+
*/
166192
function updateDevicePanel(world, dev, mode, ticksNow) {
167193
const awaySig = world.inmates.filter(i => !i.dead && i.away)
168194
.map(i => i.name + ':' + i.away.returnTick).join(',')
@@ -232,13 +258,15 @@ SOP.UI = (() => {
232258
});
233259
}
234260

261+
/** Toggle a device’s enabled state, releasing its operator when disabling a dynamo. */
235262
function toggleDevice(dev) {
236263
dev.enabled = dev.enabled === false ? true : false;
237264
if (dev.kind === 'dynamo' && dev.enabled === false) dev.operatedBy = null;
238265
log(`${SOP.OBJ[dev.kind].label} ${dev.enabled === false ? 'ABGESCHALTET' : 'EINGESCHALTET'}.`, 'dim');
239266
}
240267

241268
/* ---------------- OVERLAYS ---------------- */
269+
/** Show the intro and bind its start button to hide it and call onStart. */
242270
function showIntro(onStart) {
243271
el.overlayIntro.classList.add('show');
244272
$('btn-start').addEventListener('click', () => {
@@ -249,6 +277,7 @@ SOP.UI = (() => {
249277
});
250278
}
251279

280+
/** Show stats as HTML in the game-over overlay; bind restart to hide it and call onRestart. */
252281
function showGameOver(stats, onRestart) {
253282
el.overStats.innerHTML = stats;
254283
el.overlayOver.classList.add('show');

0 commit comments

Comments
 (0)