Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
941 lines (881 loc) · 36 KB
/
Copy pathgame.js
File metadata and controls
941 lines (881 loc) · 36 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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
// graphgram play engine.
//
// Inputs (loaded as earlier <script> tags on the page):
// window.GRAPH — the dungeon graph, in graphlib JSON shape.
// Generated by `make play/graph.js SEED=N`.
// window.DEFAULT_TEXT — the default phrasebook (play/phrasebook.js).
// window.TEXT — optional user overrides (sibling play/text.js).
// Merged over DEFAULT_TEXT at load time.
//
// Output: a CYOA-style traversal in the DOM, driven by clicks on
// hyperlink affordances printed at the end of each node's description.
(function () {
'use strict'
// ------------------------------------------------------------------
// Graph indexing.
// ------------------------------------------------------------------
if (!window.GRAPH || !window.GRAPH.nodes || !window.GRAPH.edges) {
showError('Missing window.GRAPH. Regenerate play/graph.js.')
return
}
if (!window.DEFAULT_TEXT) {
showError('Missing window.DEFAULT_TEXT. Is play/phrasebook.js loaded?')
return
}
const GRAPH = window.GRAPH
// Merge user-supplied text over the defaults.
const TEXT = mergeText(window.DEFAULT_TEXT, window.TEXT || {})
const nodeById = {} // host id -> label object
for (const n of GRAPH.nodes) nodeById[n.v] = n.value || {}
const nodeIdToHostId = {} // label.nodeId -> host id (for prereq.visited lookups)
for (const n of GRAPH.nodes) {
const nid = (n.value || {}).nodeId
if (nid) nodeIdToHostId[nid] = n.v
}
// Index edges by source.
const outgoing = {}
for (const e of GRAPH.edges) {
if (!outgoing[e.v]) outgoing[e.v] = []
outgoing[e.v].push({ v: e.v, w: e.w, label: e.value || {} })
}
// All edgeIds that actually exist (for prereq.traversed validation).
const allEdgeIds = new Set()
for (const e of GRAPH.edges) {
const eid = (e.value || {}).edgeId
if (eid) allEdgeIds.add(eid)
}
// Find the start node: prefer label.type === 'start', fallback to
// label.nodeId === 'start', fallback to first node.
function findStart () {
for (const n of GRAPH.nodes) if ((n.value || {}).type === 'start') return n.v
for (const n of GRAPH.nodes) if ((n.value || {}).nodeId === 'start') return n.v
return GRAPH.nodes[0].v
}
// ------------------------------------------------------------------
// Player state.
// ------------------------------------------------------------------
const state = {
currentNode: findStart(),
playerHP: 1,
monsterHP: null, // null when not in a battle
inBattleGroup: null, // monster group-id (shared by battle nodes)
visited: new Set(), // set of label.nodeId values the player has visited
traversed: new Set(), // set of label.edgeId values the player has traversed
moves: 0,
score: null, // set on win
gameOver: false,
// Full per-step trace: alternating node/edge events from start to
// current. Used for the dump-trace debug affordance.
history: []
}
// A battle is delimited by a set of nodes created in one rule application.
// The monsterBattle primitive names its nodes with suffixes "_N" where N is
// the rule application iter; we pull that iter out as the battle id.
function battleGroup (label) {
const t = label && label.type
if (t !== 'choice' && t !== 'random' && t !== 'death') return null
// Parse iter suffix off the nodeId — e.g. battle_normal_3 -> 3.
const nid = label.nodeId || ''
const m = nid.match(/_(\d+)$/)
return m ? ('battle_' + m[1]) : null
}
// ------------------------------------------------------------------
// Edge accessibility.
// ------------------------------------------------------------------
function edgeAccessible (edge) {
// oneTime edges are locked out after first traversal: used for
// set-piece entry and decline affordances so they don't reappear
// when the player loops back via some other cycle.
if (edge.label.oneTime && edge.label.edgeId && state.traversed.has(edge.label.edgeId)) {
return false
}
const prereq = edge.label.prereq
if (!prereq) return true
if (prereq.pairId) {
// Player must have visited the key with this pairId.
for (const n of GRAPH.nodes) {
const lab = n.value || {}
if (lab.type === 'key' && lab.pairId === prereq.pairId) {
if (state.visited.has(lab.nodeId)) return true
}
}
return false
}
if (prereq.traversed) return state.traversed.has(prereq.traversed)
if (prereq.visited) return state.visited.has(prereq.visited)
return true
}
// ------------------------------------------------------------------
// Text lookup with template substitution.
// ------------------------------------------------------------------
function lookupText (bucket, label, field) {
const dict = TEXT[bucket]
const byId = label[bucket === 'node' ? 'nodeId' : 'edgeId']
const byType = label.type
let entry = null
if (byId && dict[byId] && dict[byId][field] != null) entry = dict[byId][field]
else if (byType && dict[byType] && dict[byType][field] != null) entry = dict[byType][field]
else if (dict._default && dict._default[field] != null) entry = dict._default[field]
if (entry == null) return null
return interpolate(entry, label)
}
function interpolate (tmpl, label) {
// Dotted paths resolve through nested objects, so templates can read
// e.g. {prereq.after} from a locked edge's prereq block. Missing any
// link in the chain yields '' (same as the flat-key case).
return String(tmpl).replace(/\{([a-zA-Z0-9_.]+)\}/g, function (_, k) {
const parts = k.split('.')
let v = label
for (let i = 0; i < parts.length; i++) {
if (v == null) return ''
v = v[parts[i]]
}
if (v == null) return ''
if (typeof v === 'number') {
const leaf = parts[parts.length - 1]
if (leaf === 'healValue' || leaf === 'playerDamage' || leaf === 'monsterDamage') {
return Math.round(v * 100) + '%'
}
}
return String(v)
})
}
// ------------------------------------------------------------------
// Rendering: text pane, status line, graph.
// ------------------------------------------------------------------
function appendEvent (html, cls) {
const pane = document.getElementById('text-pane')
const div = document.createElement('div')
div.className = 'event ' + (cls || '')
div.innerHTML = html
pane.appendChild(div)
pane.scrollTop = pane.scrollHeight
return div
}
function appendLinks (links) {
if (!links.length) return
const pane = document.getElementById('text-pane')
const container = document.createElement('div')
container.className = 'links event'
links.forEach(function (l) {
const a = document.createElement('a')
a.href = '#'
a.className = l.cls || ''
a.textContent = l.text
a.addEventListener('click', function (ev) {
ev.preventDefault()
// Strip all currently-active links so the player can only act once.
document.querySelectorAll('#text-pane .links').forEach(function (el) {
el.parentNode.removeChild(el)
})
l.onClick()
})
container.appendChild(a)
})
pane.appendChild(container)
pane.scrollTop = pane.scrollHeight
}
function appendDivider () {
document.getElementById('text-pane').appendChild(
Object.assign(document.createElement('div'), { className: 'divider' }))
}
function renderStatus () {
const status = document.getElementById('status')
const chips = []
const hpPct = Math.max(0, Math.round(state.playerHP * 100))
chips.push('<span class="chip ' + (hpPct <= 0 ? 'dead' : '') + '">HP: ' + hpPct + '</span>')
if (state.monsterHP != null) {
const m = Math.max(0, Math.round(state.monsterHP * 100))
chips.push('<span class="chip mon">Monster: ' + m + '</span>')
}
chips.push('<span class="chip moves">Moves: ' + state.moves + '</span>')
if (state.score != null) chips.push('<span class="chip score">Score: ' + state.score + '</span>')
// Visited nodes with a `status` text become inventory chips.
const inv = []
state.visited.forEach(function (nid) {
const hostId = nodeIdToHostId[nid]
if (!hostId) return
const label = nodeById[hostId]
const s = lookupText('node', label, 'status')
if (s) inv.push(s)
})
if (inv.length) {
chips.push('<span class="chip inv">' + inv.map(escapeHtml).join(', ') + '</span>')
}
chips.push('<a class="chip debug" href="#" id="dump-trace">dump trace</a>')
status.innerHTML = chips.join('')
document.getElementById('dump-trace').addEventListener('click', function (ev) {
ev.preventDefault()
dumpTrace()
})
}
// Shallow-clone a label so that snapshots into the history don't share
// references with live graph objects (and don't carry the `dot` subtree,
// which is pure presentation bloat).
function shallowLabel (label) {
if (!label || typeof label !== 'object') return label
const out = {}
for (const k of Object.keys(label)) if (k !== 'dot') out[k] = label[k]
return out
}
// Diagnostic dump: the full history of node / edge visits from start
// to the current position, plus outgoing edges with access status and
// per-edge reasons for any blocks. Prints to the text pane, logs to
// console, and triggers a download of the whole state as JSON.
function dumpTrace () {
const curLabel = nodeById[state.currentNode] || {}
const curOut = outgoing[state.currentNode] || []
const outgoingReport = curOut.map(function (edge) {
const access = edgeAccessible(edge)
const p = edge.label.prereq || null
const report = {
v: edge.v, w: edge.w,
type: edge.label.type, edgeId: edge.label.edgeId || null,
accessible: access,
prereq: p
}
if (!access && p) {
if (p.traversed != null) {
report.block = {
needs: 'traversed', value: p.traversed,
present: state.traversed.has(p.traversed),
existsInGraph: allEdgeIds.has(p.traversed)
}
} else if (p.visited != null) {
report.block = {
needs: 'visited', value: p.visited,
present: state.visited.has(p.visited),
existsInGraph: !!nodeIdToHostId[p.visited]
}
} else if (p.pairId != null) {
report.block = { needs: 'key with pairId', value: p.pairId }
}
}
return report
})
const summary = {
time: new Date().toISOString(),
currentHostId: state.currentNode,
currentLabel: shallowLabel(curLabel),
playerHP: state.playerHP,
monsterHP: state.monsterHP,
moves: state.moves,
score: state.score,
inBattleGroup: state.inBattleGroup,
visited: Array.from(state.visited).sort(),
traversed: Array.from(state.traversed).sort(),
outgoing: outgoingReport,
history: state.history
}
// On-screen: a compact tabular rendering of the full trace + a short
// outgoing-edges audit.
const lines = ['--- trace (' + state.history.length + ' steps) ---']
for (const ev of state.history) {
if (ev.kind === 'node') {
const l = ev.label || {}
const name = l.nodeId || l.type || ev.hostId
const firstTag = ev.firstVisit ? ' *' : ''
lines.push(pad(ev.step, 3) + '. node ' + pad(ev.hostId, 5)
+ ' [' + (l.type || '?') + '] ' + name + firstTag
+ ' HP=' + round(ev.playerHP * 100)
+ (ev.monsterHP != null ? ' mHP=' + round(ev.monsterHP * 100) : ''))
} else {
const l = ev.label || {}
lines.push(pad(ev.step, 3) + '. edge ' + pad(ev.v, 5) + ' -> ' + pad(ev.w, 5)
+ ' [' + (l.type || '?') + ']'
+ (l.edgeId ? ' edgeId=' + l.edgeId : '')
+ (l.playerDamage ? ' pd=' + l.playerDamage : '')
+ (l.monsterDamage ? ' md=' + l.monsterDamage : '')
+ (l.correct != null ? ' correct=' + l.correct : ''))
}
}
lines.push('')
lines.push('--- current outgoing (' + outgoingReport.length + ') ---')
for (const r of outgoingReport) {
let line = (r.accessible ? '+' : '-') + ' '
+ pad(r.v, 5) + ' -> ' + pad(r.w, 5)
+ ' [' + (r.type || '?') + ']'
+ (r.edgeId ? ' edgeId=' + r.edgeId : '')
if (r.block) {
line += ' blocked: needs ' + r.block.needs + '=' + r.block.value
+ (r.block.present != null ? ' present=' + r.block.present : '')
+ (r.block.existsInGraph != null ? ' existsInGraph=' + r.block.existsInGraph : '')
}
lines.push(line)
}
const text = lines.join('\n')
console.log(text)
console.log('full trace JSON:', summary)
appendEvent('<pre class="trace">' + escapeHtml(text) + '</pre>')
// Download the whole summary as a JSON file for offline inspection.
const ts = summary.time.replace(/[:.]/g, '-')
downloadJSON('graphgram-trace-' + ts + '.json', summary)
}
function pad (s, n) {
s = String(s)
while (s.length < n) s = ' ' + s
return s
}
function round (n) { return Math.round(n) }
function downloadJSON (filename, data) {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url; a.download = filename
document.body.appendChild(a); a.click(); document.body.removeChild(a)
setTimeout(function () { URL.revokeObjectURL(url) }, 1000)
}
// ------------------------------------------------------------------
// Core transitions.
// ------------------------------------------------------------------
function start () {
renderStatus()
renderGraph()
enterNode(state.currentNode, /*viaEdge*/ null)
}
// Arrive at a node: apply node-entry effects, print its text, offer its
// outgoing affordances. May short-circuit via random-node auto-roll.
function enterNode (nodeId, viaEdge) {
const label = nodeById[nodeId] || {}
const wasFirstVisit = !state.visited.has(label.nodeId)
state.currentNode = nodeId
// Record the step in the trace BEFORE applying effects, so that the
// history reads as alternating node/edge/node/... and each node
// entry reflects the player's HP / monster HP at arrival time.
state.history.push({
kind: 'node', step: state.history.length,
hostId: nodeId, label: shallowLabel(label),
playerHP: state.playerHP, monsterHP: state.monsterHP, moves: state.moves,
firstVisit: wasFirstVisit
})
// Node-entry effects.
applyNodeEntryEffects(label, wasFirstVisit)
if (label.nodeId) state.visited.add(label.nodeId)
// Track battle group: entering a battle node sets monsterHP to 1.0,
// leaving resets.
const bg = battleGroup(label)
if (bg && state.inBattleGroup !== bg) {
state.inBattleGroup = bg
state.monsterHP = 1
} else if (!bg && state.inBattleGroup) {
state.inBattleGroup = null
state.monsterHP = null
}
renderStatus()
renderGraph()
// Death / win short-circuits.
if (label.type === 'death' || state.playerHP <= 0) {
appendEvent('<div class="death">' + escapeHtml(lookupText('node', label, 'verbose') || 'You have died.') + '</div>')
state.gameOver = true
return
}
if (label.type === 'win') {
state.score = state.moves
appendEvent('<div class="victory">' + escapeHtml(lookupText('node', label, 'verbose') || 'You have won!') + ' Final score: ' + state.score + ' moves.</div>')
state.gameOver = true
return
}
// Random node: engine rolls immediately.
if (label.type === 'random') {
rollAtRandom(nodeId)
return
}
// Normal node: show text + offer affordances.
const verbose = lookupText('node', label, wasFirstVisit ? 'verbose' : 'brief') || ''
const klass = wasFirstVisit ? 'verbose' : 'brief'
appendEvent('<div class="' + klass + '">' + escapeHtml(verbose) + '</div>')
// Offer the "look" affordance on repeat visits to see verbose text again.
const accessible = accessibleOutgoing(nodeId)
const links = accessible.map(function (edge) {
return {
text: linkTextFor(edge),
cls: linkClassFor(edge),
onClick: function () { takeEdge(edge) }
}
})
if (!wasFirstVisit) {
const repeatVerbose = lookupText('node', label, 'verboseRepeat') || lookupText('node', label, 'verbose') || verbose
links.unshift({
text: 'Look', cls: 'look',
onClick: function () {
appendEvent('<div class="verbose">' + escapeHtml(repeatVerbose) + '</div>')
renderNodeAffordances() // re-render the same links
}
})
}
appendLinks(links)
}
// Re-render current node's outgoing links without printing new node text
// (used by the "look" affordance).
function renderNodeAffordances () {
const accessible = accessibleOutgoing(state.currentNode)
appendLinks(accessible.map(function (edge) {
return {
text: linkTextFor(edge),
cls: linkClassFor(edge),
onClick: function () { takeEdge(edge) }
}
}))
}
function accessibleOutgoing (nodeId) {
const label = nodeById[nodeId] || {}
const out = outgoing[nodeId] || []
// `random` nodes have only consequence edges; the engine will roll,
// never the player.
if (label.type === 'random') return []
return out.filter(edgeAccessible)
}
function linkTextFor (edge) {
// Prefer explicit user/text-dict link text by edgeId -> type.
const t = lookupText('edge', edge.label, 'link')
if (t) return t
// Next: dot.label (often the most descriptive, e.g. 'attack', 'defend').
if (edge.label.dot && edge.label.dot.label) return edge.label.dot.label
// Fallback: type name.
return edge.label.type || 'Go'
}
function linkClassFor (edge) {
return edge.label.type || ''
}
function applyNodeEntryEffects (label, firstVisit) {
// Heal if potion and first visit.
if (label.type === 'potion' && firstVisit && typeof label.healValue === 'number') {
const before = state.playerHP
state.playerHP = Math.min(1, state.playerHP + label.healValue)
const gained = Math.round((state.playerHP - before) * 100)
if (gained > 0) {
appendEvent('<span class="heal">+' + gained + ' HP</span>')
}
}
}
// Player traverses an edge.
function takeEdge (edge) {
state.moves++
if (edge.label.edgeId) state.traversed.add(edge.label.edgeId)
state.history.push({
kind: 'edge', step: state.history.length,
v: edge.v, w: edge.w, label: shallowLabel(edge.label)
})
// Print narrative text for the edge.
const firstTime = edge.label.edgeId
? !state.traversedOnce || !state.traversedOnce.has(edge.label.edgeId)
: true
const narrative = lookupText('edge', edge.label,
firstTime ? 'initial' : 'repeat') || lookupText('edge', edge.label, 'initial')
if (narrative && narrative !== '...') {
appendEvent('<div class="narrative">' + escapeHtml(narrative) + '</div>')
}
if (!state.traversedOnce) state.traversedOnce = new Set()
if (edge.label.edgeId) state.traversedOnce.add(edge.label.edgeId)
// Apply damage encoded on the edge.
applyEdgeDamage(edge.label)
renderStatus()
// If player died mid-edge, route directly to the nearest death node
// (prefer one in the current battle group).
if (state.playerHP <= 0) {
goToDeathNode()
return
}
// If the monster died, force victory route.
if (state.monsterHP != null && state.monsterHP <= 0) {
const victory = findVictoryTarget(edge.v)
if (victory) {
appendEvent('<div class="narrative">Your final blow lands. The monster falls.</div>')
enterNode(victory, edge)
return
}
}
enterNode(edge.w, edge)
}
// Engine picks an outgoing edge at a random node by `weight`; if the
// rolled edge carries lethal damage, reroute to death/victory as needed.
function rollAtRandom (nodeId) {
const edges = (outgoing[nodeId] || []).filter(function (e) {
return e.label.type === 'consequence'
})
if (!edges.length) return // malformed graph
const total = edges.reduce(function (s, e) { return s + (e.label.weight || 0) }, 0)
let r = Math.random() * total
let picked = edges[edges.length - 1]
for (const e of edges) {
r -= (e.label.weight || 0)
if (r <= 0) { picked = e; break }
}
// Short description of what happened.
const role = picked.label.role || 'the die is cast'
appendEvent('<div class="narrative"><em>' + escapeHtml(role.replace(/-/g, ' ')) + '</em></div>')
takeEdge(picked)
}
function applyEdgeDamage (label) {
if (typeof label.playerDamage === 'number' && label.playerDamage > 0) {
state.playerHP = Math.max(0, state.playerHP - label.playerDamage)
appendEvent('<span class="damage">-' + Math.round(label.playerDamage * 100) + ' HP</span>')
}
if (typeof label.monsterDamage === 'number' && label.monsterDamage > 0
&& state.monsterHP != null) {
state.monsterHP = Math.max(0, state.monsterHP - label.monsterDamage)
appendEvent('<span class="damage">Monster -' + Math.round(label.monsterDamage * 100) + ' HP</span>')
}
}
function findVictoryTarget (fromNodeId) {
// Victory consequence edges target a non-death, non-choice, non-random
// node; in the monsterBattle expansion that's `b`.
const ns = outgoing[fromNodeId] || []
for (const e of ns) {
if (e.label.type === 'consequence') {
const tt = (nodeById[e.w] || {}).type
if (tt !== 'death' && tt !== 'choice' && tt !== 'random') return e.w
}
}
return null
}
function goToDeathNode () {
// Find a death node reachable from the current battle neighborhood.
for (const n of GRAPH.nodes) {
if ((n.value || {}).type === 'death') {
enterNode(n.v, null)
return
}
}
// No death node? Just end the game.
appendEvent('<div class="death">You have died.</div>')
state.gameOver = true
}
// ------------------------------------------------------------------
// Dagre-based graph rendering: compute a layered DAG layout in pure JS,
// then draw the resulting SVG ourselves so we can keep full control over
// shapes and styling. No WASM, no external layout binary.
// ------------------------------------------------------------------
// Radius (in edges) of the neighborhood to show around the current node.
// 1 = just current node + immediate neighbors; 2 = also two-hop nodes.
let graphRadius = 2
// Compute the visible subgraph: BFS from the current node on undirected
// adjacency, out to `graphRadius`. Returns { nodes: Map<hostId, dist>,
// edges: [{v,w,label}] } plus stub annotations for off-screen neighbors.
function visibleSubgraph () {
const center = state.currentNode
const distance = new Map()
distance.set(center, 0)
const queue = [center]
while (queue.length) {
const v = queue.shift()
const d = distance.get(v)
if (d >= graphRadius) continue
const neighbors = new Set()
for (const e of (outgoing[v] || [])) neighbors.add(e.w)
for (const e of GRAPH.edges) if (e.w === v) neighbors.add(e.v)
for (const u of neighbors) {
if (!distance.has(u)) {
distance.set(u, d + 1)
queue.push(u)
}
}
}
const edges = []
for (const e of GRAPH.edges) {
if (distance.has(e.v) && distance.has(e.w)) {
edges.push({ v: e.v, w: e.w, label: e.value || {} })
}
}
// Count hidden neighbors per frontier node.
const stubs = [] // {kind:'out'|'in', at: hostId, count: N}
for (const [v, d] of distance) {
if (d !== graphRadius) continue
let hOut = 0, hIn = 0
for (const e of (outgoing[v] || [])) if (!distance.has(e.w)) hOut++
for (const e of GRAPH.edges) if (e.w === v && !distance.has(e.v)) hIn++
if (hOut) stubs.push({ kind: 'out', at: v, count: hOut })
if (hIn) stubs.push({ kind: 'in', at: v, count: hIn })
}
return { distance, edges, stubs }
}
// Approximate pixel width of a label rendered at `fontSize` in Helvetica.
// Used so dagre can lay nodes out with a sensible size.
function approxTextWidth (s, fontSize) {
return Math.max(4, String(s).length) * fontSize * 0.6
}
const NODE_FONT = 10
const NODE_VPAD = 10 // vertical padding around text
const NODE_HPAD = 14 // horizontal padding
function labelText (label, fallback) {
return (label.dot && label.dot.label) || label.type || fallback || ''
}
function renderGraph () {
if (typeof dagre === 'undefined') return // script still loading
const pane = document.getElementById('graph-pane')
pane.innerHTML = ''
const sub = visibleSubgraph()
// Build the dagre graph.
const g = new dagre.graphlib.Graph({ multigraph: false })
g.setGraph({ rankdir: 'LR', nodesep: 24, ranksep: 40, marginx: 12, marginy: 12 })
g.setDefaultEdgeLabel(function () { return {} })
for (const [v] of sub.distance) {
const label = nodeById[v] || {}
const text = labelText(label, v)
const w = approxTextWidth(text, NODE_FONT) + NODE_HPAD * 2
const h = NODE_FONT + NODE_VPAD * 2
g.setNode(v, { text, w, h, width: w, height: h, hostId: v, labelObj: label })
}
// Stub nodes for off-screen neighbors.
sub.stubs.forEach(function (s, i) {
const text = s.kind === 'out' ? ('+' + s.count + ' →') : ('← +' + s.count)
const id = '__stub_' + i
const w = approxTextWidth(text, NODE_FONT) + 8
const h = NODE_FONT + 8
g.setNode(id, { text, w, h, width: w, height: h, stub: true })
if (s.kind === 'out') g.setEdge(s.at, id, { stub: true })
else g.setEdge(id, s.at, { stub: true })
})
for (const e of sub.edges) {
g.setEdge(e.v, e.w, { labelObj: e.label, text: (e.label.dot || {}).label || '' })
}
dagre.layout(g)
// Compute SVG viewBox from the layout bounds.
const gInfo = g.graph()
const width = Math.max(100, gInfo.width || 0)
const height = Math.max(100, gInfo.height || 0)
const svgNS = 'http://www.w3.org/2000/svg'
const svg = document.createElementNS(svgNS, 'svg')
svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height)
svg.setAttribute('width', width)
svg.setAttribute('height', height)
svg.setAttribute('class', 'graph')
// <defs> with a reusable arrow marker.
const defs = document.createElementNS(svgNS, 'defs')
defs.innerHTML =
'<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" ' +
'markerWidth="7" markerHeight="7" orient="auto">' +
'<path d="M0,0 L10,5 L0,10 z" fill="#555"/></marker>' +
'<marker id="arrow-traversed" viewBox="0 0 10 10" refX="9" refY="5" ' +
'markerWidth="7" markerHeight="7" orient="auto">' +
'<path d="M0,0 L10,5 L0,10 z" fill="#2a6"/></marker>'
svg.appendChild(defs)
// Edges first so nodes sit on top.
const edgeLayer = document.createElementNS(svgNS, 'g')
edgeLayer.setAttribute('class', 'edges')
svg.appendChild(edgeLayer)
g.edges().forEach(function (eid) {
const data = g.edge(eid)
const pts = data.points
if (!pts || pts.length < 2) return
const d = pathFromPoints(pts)
const group = document.createElementNS(svgNS, 'g')
const classes = ['edge']
const label = data.labelObj || {}
const dot = label.dot || {}
if (data.stub) classes.push('stub')
if (label.type) classes.push('et-' + label.type)
if (label.edgeId && state.traversed.has(label.edgeId)) classes.push('traversed')
group.setAttribute('class', classes.join(' '))
const path = document.createElementNS(svgNS, 'path')
path.setAttribute('d', d)
path.setAttribute('fill', 'none')
const stroke = data.stub ? '#aaa'
: (classes.indexOf('traversed') >= 0 ? '#2a6' : (dot.color || '#555'))
path.setAttribute('stroke', stroke)
path.setAttribute('stroke-width', classes.indexOf('traversed') >= 0 ? 2 : 1.2)
if (data.stub || (dot.style || '').indexOf('dashed') >= 0) path.setAttribute('stroke-dasharray', '4 3')
else if ((dot.style || '').indexOf('dotted') >= 0) path.setAttribute('stroke-dasharray', '1 3')
path.setAttribute('marker-end',
classes.indexOf('traversed') >= 0 ? 'url(#arrow-traversed)' : 'url(#arrow)')
group.appendChild(path)
if (data.text) {
const mid = pts[Math.floor(pts.length / 2)]
const t = document.createElementNS(svgNS, 'text')
t.setAttribute('x', mid.x)
t.setAttribute('y', mid.y - 2)
t.setAttribute('text-anchor', 'middle')
t.setAttribute('font-size', 9)
t.setAttribute('font-family', 'Helvetica,sans-serif')
t.setAttribute('fill', dot.color || '#444')
t.setAttribute('class', 'edge-label')
t.textContent = data.text
group.appendChild(t)
}
edgeLayer.appendChild(group)
})
// Nodes.
const nodeLayer = document.createElementNS(svgNS, 'g')
nodeLayer.setAttribute('class', 'nodes')
svg.appendChild(nodeLayer)
g.nodes().forEach(function (v) {
const data = g.node(v)
const label = data.labelObj || {}
const dot = label.dot || {}
const group = document.createElementNS(svgNS, 'g')
group.setAttribute('transform', 'translate(' + data.x + ',' + data.y + ')')
const classes = ['node']
if (data.stub) classes.push('stub')
if (label.type) classes.push('nt-' + label.type)
if (v === state.currentNode) classes.push('current')
if (label.nodeId && state.visited.has(label.nodeId)) classes.push('visited')
const dist = sub.distance.get(v)
if (dist != null && dist >= graphRadius && !data.stub) classes.push('frontier')
group.setAttribute('class', classes.join(' '))
if (!data.stub) {
appendShape(group, dot.shape || 'ellipse', data.w, data.h, dot.color)
}
const t = document.createElementNS(svgNS, 'text')
t.setAttribute('text-anchor', 'middle')
t.setAttribute('dominant-baseline', 'middle')
t.setAttribute('font-size', NODE_FONT)
t.setAttribute('font-family', 'Helvetica,sans-serif')
t.setAttribute('fill', data.stub ? '#888' : '#222')
t.textContent = data.text
group.appendChild(t)
nodeLayer.appendChild(group)
})
pane.appendChild(svg)
}
function pathFromPoints (pts) {
if (pts.length === 2) {
return 'M' + pts[0].x + ',' + pts[0].y + ' L' + pts[1].x + ',' + pts[1].y
}
// Smooth interior with a quadratic through each interior point.
let d = 'M' + pts[0].x + ',' + pts[0].y
for (let i = 1; i < pts.length - 1; i++) {
const p = pts[i], q = pts[i + 1]
const mx = (p.x + q.x) / 2, my = (p.y + q.y) / 2
d += ' Q' + p.x + ',' + p.y + ' ' + mx + ',' + my
}
const last = pts[pts.length - 1]
d += ' L' + last.x + ',' + last.y
return d
}
// Draw a shape centered at (0,0) with given width/height. Matches the
// Graphviz shape names used in dungeon-primitives.js dot attrs.
function appendShape (group, shape, w, h, fillHint) {
const svgNS = 'http://www.w3.org/2000/svg'
const rx = w / 2, ry = h / 2
const stroke = fillHint || '#555'
let el
switch (shape) {
case 'box':
case 'rect':
el = document.createElementNS(svgNS, 'rect')
el.setAttribute('x', -rx); el.setAttribute('y', -ry)
el.setAttribute('width', w); el.setAttribute('height', h)
break
case 'diamond':
el = document.createElementNS(svgNS, 'polygon')
el.setAttribute('points',
'0,' + (-ry) + ' ' + rx + ',0 0,' + ry + ' ' + (-rx) + ',0')
break
case 'house':
el = document.createElementNS(svgNS, 'polygon')
el.setAttribute('points',
(-rx) + ',' + ry + ' ' +
(-rx) + ',' + (-ry * 0.5) + ' ' +
'0,' + (-ry) + ' ' +
rx + ',' + (-ry * 0.5) + ' ' +
rx + ',' + ry)
break
case 'invtriangle':
el = document.createElementNS(svgNS, 'polygon')
el.setAttribute('points',
(-rx) + ',' + (-ry) + ' ' + rx + ',' + (-ry) + ' 0,' + ry)
break
case 'octagon': {
const k = 0.414 // tan(pi/8)
const insetX = rx * k / (1 + k)
const insetY = ry * k / (1 + k)
el = document.createElementNS(svgNS, 'polygon')
el.setAttribute('points',
(-rx + insetX) + ',' + (-ry) + ' ' +
(rx - insetX) + ',' + (-ry) + ' ' +
rx + ',' + (-ry + insetY) + ' ' +
rx + ',' + (ry - insetY) + ' ' +
(rx - insetX) + ',' + ry + ' ' +
(-rx + insetX) + ',' + ry + ' ' +
(-rx) + ',' + (ry - insetY) + ' ' +
(-rx) + ',' + (-ry + insetY))
break
}
case 'doublecircle': {
const outer = document.createElementNS(svgNS, 'ellipse')
outer.setAttribute('rx', rx); outer.setAttribute('ry', ry)
outer.setAttribute('fill', 'white'); outer.setAttribute('stroke', stroke)
group.appendChild(outer)
const inner = document.createElementNS(svgNS, 'ellipse')
inner.setAttribute('rx', rx - 3); inner.setAttribute('ry', ry - 3)
inner.setAttribute('fill', 'white'); inner.setAttribute('stroke', stroke)
group.appendChild(inner)
return
}
case 'plain':
return // no shape, text only
default:
el = document.createElementNS(svgNS, 'ellipse')
el.setAttribute('rx', rx); el.setAttribute('ry', ry)
}
el.setAttribute('fill', 'white')
el.setAttribute('stroke', stroke)
el.setAttribute('stroke-width', '1.2')
group.appendChild(el)
}
// ------------------------------------------------------------------
// Helpers.
// ------------------------------------------------------------------
function escapeHtml (s) {
return String(s)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"')
}
function dotEscape (s) {
return String(s).replace(/"/g, '\\"').replace(/\n/g, '\\n')
}
function showError (msg) {
const el = document.getElementById('error')
el.style.display = 'block'
el.textContent = msg
}
function mergeText (base, over) {
const out = { node: Object.assign({}, base.node), edge: Object.assign({}, base.edge) }
for (const k of Object.keys(over.node || {})) {
out.node[k] = Object.assign({}, out.node[k] || {}, over.node[k])
}
for (const k of Object.keys(over.edge || {})) {
out.edge[k] = Object.assign({}, out.edge[k] || {}, over.edge[k])
}
return out
}
// ------------------------------------------------------------------
// Zoom controls.
// ------------------------------------------------------------------
function setupZoomControls () {
const pane = document.getElementById('graph-pane')
const bar = document.createElement('div')
bar.id = 'zoom-bar'
bar.innerHTML =
'<button id="zoom-out">–</button>' +
'<span id="zoom-level">radius ' + graphRadius + '</span>' +
'<button id="zoom-in">+</button>'
pane.parentNode.insertBefore(bar, pane)
document.getElementById('zoom-in').addEventListener('click', function () {
graphRadius = Math.min(6, graphRadius + 1)
document.getElementById('zoom-level').textContent = 'radius ' + graphRadius
renderGraph()
})
document.getElementById('zoom-out').addEventListener('click', function () {
graphRadius = Math.max(1, graphRadius - 1)
document.getElementById('zoom-level').textContent = 'radius ' + graphRadius
renderGraph()
})
}
// ------------------------------------------------------------------
// Kick off. Script is at end of <body>, so the DOM is ready; no need
// to wait for DOMContentLoaded (and it may well have already fired).
// ------------------------------------------------------------------
setupZoomControls()
start()
// dagre is a synchronous script; if it wasn't ready on the initial
// start() call (e.g. script still loading), schedule a single retry.
if (typeof dagre === 'undefined') {
const retry = setInterval(function () {
if (typeof dagre !== 'undefined') {
clearInterval(retry)
renderGraph()
}
}, 50)
}
})()