Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
2381 lines (2336 loc) · 137 KB
/
Copy pathgame.js
File metadata and controls
2381 lines (2336 loc) · 137 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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// =====================================================================
// State
// =====================================================================
const SPELLS = {
'1': {id:'fire', name:'Fire', cost:4, range:9, col:[1.0,.5,.15], stopAtEnt:1},
'2': {id:'lightning', name:'Lightning', cost:5, range:12, col:[.6,.8,1.0]},
'3': {id:'frost', name:'Frost', cost:4, range:8, col:[.55,.9,1.0]},
'4': {id:'holy', name:'Holy', cost:6, range:10, col:[1.0,.9,.55], stopAtEnt:1},
};
const cost = k => Math.max(1, SPELLS[k].cost - (state.costDown || 0));
const knows = k => !!state.spells[SPELLS[k].id];
const spellKey = id => Object.keys(SPELLS).find(k => SPELLS[k].id === id);
// ---- weapons: three kinds, and Eli's stock gets better on every floor
const WEAPONS = {
dagger: {name:'dagger', lo:1, hi:4, hit:3, crit:18, mult:2, style:'stab', price:10, note:'quick and precise · crits on 18-20'},
sword: {name:'sword', lo:2, hi:6, hit:1, crit:19, mult:2, style:'cleave', price:16, note:'balanced · crits on 19-20'},
axe: {name:'axe', lo:3, hi:8, hit:-1, crit:20, mult:3, style:'cleave', price:20, note:'heavy and wild · crits hit ×3'},
};
const TIERS = ['', 'old', 'iron', 'steel', 'dwarf-forged', 'starmetal'];
function weaponStats(w = state.weapon){
if (!w) return {name:'bare hands and tail', lo:1, hi:3, hit:0, crit:20, mult:2, style:'whip', note:'better than nothing, barely'};
const B = WEAPONS[w.type], t = w.tier;
return {name:`${TIERS[t]} ${B.name}`, lo:B.lo + 2 * (t - 1), hi:B.hi + 2 * (t - 1), hit:B.hit + (t - 1), crit:B.crit, mult:B.mult,
style:B.style, note:B.note, price:Math.round(B.price * (1 + 1.6 * (t - 1)))};
}
const PLAYER_HIT = 4;
const playerHit = () => PLAYER_HIT + weaponStats().hit;
// ---- armour: no dodging, just a number your enemies have to beat
const GIFTS = [null,
{slot:'body', name:'leather jerkin', ac:2},
{slot:'head', name:'fur-lined hood', ac:1},
{slot:'body', name:'chain shirt', ac:4},
{slot:'head', name:'iron helm', ac:2},
{slot:'cloak', name:'starweave cloak', ac:3},
];
const SLOTS = ['body', 'head', 'cloak'];
const playerAC = () => 10 + (state.acBonus || 0) + SLOTS.reduce((a, k) => a + (state.gear[k]?.ac || 0), 0);
const PRICES = {potion:12, mana:10};
const POTION_HEAL = 15, MANA_GAIN = 12;
let farv, fire, elecT, frostT, seen, vis, lumS, lr, lg, lb, snowAcc, danger;
let ents, player, npc, items, parts, wparts, bolts, projs, flashes, lights, msgs, state, dying, flies, slashes, pillars = [];
let level = null;
let shakeAmp = 0, phosphor = 0, hitStop = 0, screenFlashT = -1e9;
const PHOS = [ {name:'COLOR', tint:[1,1,1], mono:0} ];
let hover = null, hoverAny = null;
const W = {rain:0, snow:0, wind:0, dir:1}; // smoothed weather intensities
function mkEnt(type, x, y, extra){
const d = MONS[type], lv = state?.floor || 1;
const e = {type, ch:d.ch, name:d.name, col:d.col.slice(), hp:d.hp, maxhp:d.hp, dmg:d.dmg,
x, y, vx:x, vy:y, anim:null, act:null, knock:null, hitT:-1e9, burning:0, frozen:0, poison:0, dead:false, seen:null,
face:rnd() < .5 ? 1 : -1, seed:rnd() * 100, sz:1, s:d.s || 1, ac:d.ac ?? 9 + lv, hit:d.hit ?? 1 + lv,
tf:{ox:0, oy:0, rot:0, sx:1, sy:1}};
if (d.boss) { e.boss = true; e.sz = e.s > 1 ? 2 : 1.3; e.pt = 4; e.cd = 2; if (d.hydra) { e.heads = 3; e.stumps = 0; } }
else if (!extra) {
// individual variety
const r = rnd();
if (r < .2) { e.name = 'big ' + e.name; e.hp = e.maxhp = Math.ceil(d.hp * 1.5); e.dmg = d.dmg + 1; e.sz = 1.16; }
else if (r < .35) { e.name = 'scrawny ' + e.name; e.hp = e.maxhp = Math.max(1, Math.floor(d.hp * .7)); e.sz = .88; }
}
const v = .88 + rnd() * .24; if (!d.boss) e.col = e.col.map((c, i) => clamp(c * (i === 1 ? v : 2 - v), 0, 1));
if (extra) Object.assign(e, extra);
return e;
}
// ---- a whole new run
function init(){
dlg = null; inspect = null; packOpen = false;
state = {turn:0, floor:1, seed:(rnd() * 1e9) | 0, targeting:null, dead:false, won:false, gold:20, travel:null, zone:-1,
costDown:0, acBonus:0, belief:false, spells:{}, inv:{potion:1, mana:0}, keys:{}, weapon:null, gear:{}, quest:{}, eggs:0,
weather:{type:'clear', until:30}, thunderT:-1e9,
mem:{name:'friend', ch:0, lastTalk:-99, met:false, visited:{}, kills:0, idleI:0, echoUsed:{}, nextEcho:0, called:false}};
msgs = [];
player = mkEnt('rat', 0, 0);
Object.assign(player, {ch:'@', name:'you', col:[1,1,.85], hp:24, maxhp:24, mp:20, maxmp:20, dmg:0, sz:1, s:1, isPlayer:true});
log('AFTERGLOW // somewhere below, a stone that never dies', [.6,1,.7]);
log('Move: keys/click. Right-click inspects. I: pack', [.55,.7,.55]);
enterLevel(1);
}
// what you carry from floor to floor; also what comes back when you fall and try the floor again
const SNAP_KEYS = ['gold', 'costDown', 'acBonus', 'belief', 'spells', 'inv', 'keys', 'weapon', 'gear', 'quest', 'mem', 'prayed', 'eggs'];
function snapshot(){
const P = player, o = {p:{hp:P.hp, maxhp:P.maxhp, mp:P.mp, maxmp:P.maxmp}, s:{}};
for (const k of SNAP_KEYS) o.s[k] = state[k];
state.snap = JSON.stringify(o);
}
function retryFloor(){
const o = JSON.parse(state.snap);
Object.assign(state, o.s, {dead:false, travel:null, targeting:null});
player = mkEnt('rat', 0, 0);
Object.assign(player, {ch:'@', name:'you', col:[1,1,.85], dmg:0, sz:1, s:1, isPlayer:true}, o.p);
inspect = null; dlg = null; packOpen = false;
log('You wake at the top of the stairs, aching, alive. Again.', [1,.85,.6]);
enterLevel(state.floor, true);
}
// fresh per-floor buffers (shared by a new floor and a loaded save)
function allocLevel(n){
const N = MW * MH, z = n - 1;
zone = new Uint8Array(N).fill(z);
fire = new Int8Array(N); elecT = new Float64Array(N).fill(-1e9); frostT = new Float64Array(N).fill(-1e9);
seen = new Uint8Array(N); vis = new Uint8Array(N); farv = new Uint8Array(N); lumS = new Float32Array(N); danger = new Uint8Array(N);
lr = new Float32Array(N); lg = new Float32Array(N); lb = new Float32Array(N);
snowAcc = new Float32Array(N);
if (z === Z.PASS) snowAcc.fill(.85);
parts = []; wparts = []; bolts = []; projs = []; flashes = []; dying = []; flies = []; slashes = []; pillars = [];
}
function enterLevel(n, retry){
state.floor = n;
level = buildLevel(n, state.seed);
allocLevel(n);
const P = player;
[P.x, P.y] = level.start; P.vx = P.x; P.vy = P.y; P.anim = P.act = P.knock = null;
P.burning = P.frozen = P.poison = P.webbed = 0; P.dead = false;
npc = mkEnt('rat', ...level.npc);
Object.assign(npc, {ch:'@', name:'old man', col:[.86,.8,1], hp:99, maxhp:99, sz:1, s:1, npc:true, face:-1, home:level.npc.slice()});
ents = [player, npc];
for (const [t, x, y, ex] of level.spawns) ents.push(mkEnt(t, x, y, ex));
items = level.items.map(o => ({...o}));
altars = {}; for (const a of level.altars) altars[idx(a.x, a.y)] = a.deity;
state.zone = -1; state.targeting = null; state.travel = null; state.bossSeen = false;
if (!state.quest || state.quest.floor !== n) state.quest = {floor:n, stage:0};
CX = clamp(P.x + .5 - WVW / 2, 0, MW - WVW); CY = clamp(P.y + .5 - WVH / 2, 0, MH - WVH);
if (!retry) snapshot();
rebuildLights(); computeFOV(); checkZone();
saveGame();
if (n > 1 && !retry) log(state.mem.knowsName ? 'Eli is already here, warming his hands. Of course he is.' : 'The old man is already here, warming his hands. Of course he is.', [.85,.8,1]);
}
// ---- the run lives in this browser's localStorage, so a refresh picks up where you left off
const SAVE_KEY = 'afterglow.save.v1';
const EPHEMERAL = {anim:1, act:1, knock:1, tf:1};
function saveGame(){
if (!state || !level || !map) return;
try {
const fl = []; for (let i = 0; i < fire.length; i++) if (fire[i]) fl.push(i, fire[i]);
const strip = e => { const o = {}; for (const k in e) if (!EPHEMERAL[k]) o[k] = e[k]; return o; };
localStorage.setItem(SAVE_KEY, JSON.stringify({v:1, state:{...state, travel:null, targeting:null}, level, map, under, fire:fl,
seen:Array.from(seen).join(''), ents:ents.filter(e => !e.dead || e.isPlayer).map(strip), items, altars, msgs:msgs.slice(-12)}));
} catch (e) { /* private mode or full storage: just don't save */ }
}
function clearSave(){ try { localStorage.removeItem(SAVE_KEY); } catch (e) {} }
function loadGame(){
let d; try { d = JSON.parse(localStorage.getItem(SAVE_KEY)); } catch (e) { return false; }
if (!d || d.v !== 1) return false;
try {
state = Object.assign(d.state, {thunderT:-1e9, npcSpark:0}); level = d.level;
allocLevel(level.n);
map = d.map; under = d.under;
for (let k = 0; k < d.fire.length; k += 2) fire[d.fire[k]] = d.fire[k + 1];
for (let i = 0; i < d.seen.length; i++) seen[i] = d.seen.charCodeAt(i) === 49 ? 1 : 0;
ents = d.ents.map(e => ({...e, vx:e.x, vy:e.y, anim:null, act:null, knock:null, hitT:-1e9, tf:{ox:0, oy:0, rot:0, sx:1, sy:1}}));
player = ents.find(e => e.isPlayer); npc = ents.find(e => e.npc);
if (!player || !npc) throw new Error('bad save');
items = d.items; altars = d.altars; msgs = d.msgs || [];
dlg = null; inspect = null; packOpen = false;
CX = clamp(player.x + .5 - WVW / 2, 0, MW - WVW); CY = clamp(player.y + .5 - WVH / 2, 0, MH - WVH);
rebuildLights(); computeFOV(); computeDanger();
log('You pick up where you left off.', [.6,1,.7]);
return true;
} catch (e) { console.warn('could not load save', e); clearSave(); return false; }
}
addEventListener('pagehide', saveGame);
function log(text, col = [.7,.85,.7]){ msgs.push({text, col}); if (msgs.length > 40) msgs.shift(); }
function healPlayer(n, quiet){
const P = player, before = P.hp; P.hp = Math.min(P.maxhp, P.hp + n);
if (P.hp > before) part(P.x, P.y - .3, 0, -1.2, .9, '+' + (P.hp - before), [.5,1,.6], 1);
if (!quiet && P.hp > before) Snd.potion();
}
function quaff(kind){
const P = player;
if (state.dead || state.won || projs.length) return;
if (!(state.inv[kind] > 0)) { Snd.error(); log(kind === 'potion' ? 'You have no healing potions.' : 'You have no mana potions.', [.8,.5,.5]); return; }
state.inv[kind]--;
if (kind === 'potion') { healPlayer(POTION_HEAL, true); P.poison = 0; log('You drink a healing potion. Warmth spreads to your fingertips.', [1,.5,.6]); }
else { P.mp = Math.min(P.maxmp, P.mp + MANA_GAIN); part(P.x, P.y - .3, 0, -1.2, .9, '+' + MANA_GAIN, [.5,.7,1], 1); log('You drink a mana potion. Your thoughts fizz.', [.6,.7,1]); }
Snd.potion(); packOpen = false;
endTurn();
}
// =====================================================================
// Weather
// =====================================================================
const WEATHERS = [['clear',.34],['rain',.2],['snow',.13],['wind',.15],['storm',.1],['blizzard',.08]];
const WTARGET = {clear:{}, rain:{rain:1}, snow:{snow:1}, wind:{wind:1}, storm:{rain:1, wind:.85}, blizzard:{snow:1, wind:.9}};
const WMSG = {clear:'The sky clears.', rain:'A soft rain begins to fall.', snow:'Snow begins to drift down.', wind:'The wind picks up.',
storm:'Thunder rumbles. A storm rolls in.', blizzard:'A blizzard howls in.'};
function tickWeather(){
const w = state.weather;
if (state.turn < w.until) return;
let r = rnd(), next = 'clear';
for (const [n, p] of WEATHERS) { if ((r -= p) < 0) { next = n; break; } }
if (next === w.type) next = 'clear';
w.type = next; w.until = state.turn + ri(35, 75); W.dir = rnd() < .5 ? -1 : 1;
const z = zone[idx(player.x, player.y)];
if (ZONES[z].outdoor) log(WMSG[next], [.7,.8,.9]);
}
// intensities as felt in a given zone
function localW(z){
if (!ZONES[z].outdoor) return {rain:0, snow:0, wind:0};
if (z === Z.PASS) return {rain:0, snow:Math.max(.22, W.snow, W.rain * .9), wind:Math.max(.25, W.wind)};
if (z === Z.MIRE) return {rain:W.rain, snow:W.snow * .8, wind:W.wind * .7};
return {rain:W.rain, snow:W.snow, wind:W.wind};
}
function weatherIs(n){
const L = localW(zone[idx(player.x, player.y)]);
if (n === 'storm') return state.weather.type === 'storm' && L.rain > .4;
return (L[n] || 0) > .4;
}
const gust = (t, x) => Math.pow(.5 + .5 * Math.sin(x * .12 - t * 1.7 * W.dir + Math.sin(t * .3) * 2), 3);
// =====================================================================
// LOS / FOV / Light
// =====================================================================
function los(x0, y0, x1, y1){
let dx = Math.abs(x1-x0), dy = Math.abs(y1-y0), sx = x0<x1?1:-1, sy = y0<y1?1:-1, err = dx-dy, x = x0, y = y0;
for (;;) {
if (x === x1 && y === y1) return true;
if (!(x === x0 && y === y0) && TD[map[idx(x,y)]].opaque) return false;
const e2 = 2*err;
if (e2 > -dy) { err -= dy; x += sx; }
if (e2 < dx) { err += dx; y += sy; }
}
}
function bline(x0, y0, x1, y1){
const pts = [];
let dx = Math.abs(x1-x0), dy = Math.abs(y1-y0), sx = x0<x1?1:-1, sy = y0<y1?1:-1, err = dx-dy, x = x0, y = y0;
while (!(x === x1 && y === y1)) {
const e2 = 2*err;
if (e2 > -dy) { err -= dy; x += sx; }
if (e2 < dx) { err += dx; y += sy; }
pts.push([x, y]);
}
return pts;
}
function computeContribs(lx, ly, r){
const c = [], R = Math.ceil(r);
for (let y = ly - R; y <= ly + R; y++) for (let x = lx - R; x <= lx + R; x++) {
if (!inb(x, y)) continue;
const d = Math.hypot(x - lx, (y - ly) * 1.2);
if (d > r || !los(lx, ly, x, y)) continue;
c.push(idx(x, y), Math.pow(1 - d / r, 1.4));
}
return c;
}
function addLight(x, y, r, col, int, fl){ lights.push({x, y, col, int, fl, seed:hash(idx(x,y))*50, c:computeContribs(x, y, r)}); }
function rebuildLights(){
lights = [];
const P = player, R = 34;
for (let y = Math.max(0, P.y - R); y <= Math.min(MH - 1, P.y + R); y++)
for (let x = Math.max(0, P.x - R); x <= Math.min(MW - 1, P.x + R); x++) {
const i = idx(x, y), t = map[i];
if (t === 'TORCH') addLight(x, y, 10, [1,.62,.3], 1.5, 1);
else if (t === 'HEARTH' || t === 'CAMPFIRE') addLight(x, y, 9, [1,.58,.28], 1.6, 1);
else if (t === 'RUNELIT') addLight(x, y, 7, [.55,.8,1], 1.4, 1);
else if (t === 'GRAVEDONE') addLight(x, y, 4, [1,.7,.8], .8, 1);
else if (t === 'EGGSAC') addLight(x, y, 2.5, [.8,.75,.5], .35, 1);
else if (t === 'LAVA' && hash(i) < .4) addLight(x, y, 4, [1,.38,.1], .7, 2);
else if (t === 'VENT') addLight(x, y, 3, [1,.5,.2], .6, 2);
else if (t === 'ALTAR') { const D = altarDeity(i); addLight(x, y, 6, D ? D.col : [1,.8,.5], 1.3, 1); }
if (fire[i] > 0) addLight(x, y, 4, [1,.45,.12], .9, 2);
}
for (const e of ents) {
if (e.dead || cheb(e, P) > R) continue;
if (e.burning > 0) addLight(e.x, e.y, 3, [1,.5,.15], .7, 2);
const g = MONS[e.type]?.glow; if (g && !e.npc && !e.isPlayer) addLight(e.x, e.y, e.boss ? 6 : 3.5, g, e.boss ? 1.2 : .8, 1);
if (e.phase === 'charge') addLight(e.x, e.y, 5 + (3 - e.pt) * 2, [1,.45,.12], 1 + (3 - e.pt) * .5, 2);
}
if (!P.dead) state.belief ? addLight(P.x, P.y, 7.5, [1,.85,.55], 1.05, 0) : addLight(P.x, P.y, 6, [.5,.58,.5], .85, 0);
lumS.fill(0);
for (const L of lights) { const m = Math.max(...L.col) * L.int; for (let j = 0; j < L.c.length; j += 2) lumS[L.c[j]] += L.c[j+1] * m; }
for (let y = Math.max(0, P.y - R); y <= Math.min(MH - 1, P.y + R); y++)
for (let x = Math.max(0, P.x - R); x <= Math.min(MW - 1, P.x + R); x++) { const i = idx(x, y); lumS[i] += dayLight(zone[i]); }
}
function flash(x, y, r, col, int, dur){ flashes.push({col, int, dur, t0:now(), c:computeContribs(x, y, r)}); }
// you see clearly in a circle of SIGHT tiles: everything (and everyone) in it.
// Past that, lit places in line of sight show only as dim shapes, and no monsters.
const SIGHT = 7.3;
const sightD = (x, y) => Math.hypot(x - player.x, y - player.y);
function computeFOV(){
vis.fill(0); farv.fill(0);
const P = player, R = 31;
for (let y = Math.max(0, P.y - R); y <= Math.min(MH - 1, P.y + R); y++)
for (let x = Math.max(0, P.x - R); x <= Math.min(MW - 1, P.x + R); x++) {
if (los(P.x, P.y, x, y)) {
const i = idx(x, y);
if (sightD(x, y) <= SIGHT) { vis[i] = 1; seen[i] = 1; }
else if (lumS[i] > .07) { farv[i] = 1; seen[i] = 1; }
}
}
}
// daylight under the open sky (dimmer in rain, gloomier in the mire)
function dayLight(z){
if (!ZONES[z].outdoor) return 0;
const base = z === Z.MIRE ? .3 : z === Z.PASS ? .5 : .55;
return base * (1 - .35 * W.rain - .15 * W.snow);
}
const DAYCOL = {[Z.MIRE]:[.75,.9,.72], [Z.PASS]:[.85,.9,1.05]};
const AMB = .03;
function computeLight(t, tn){
lr.fill(AMB); lg.fill(AMB); lb.fill(AMB);
// inside your circle of sight the world is lighter, fading off at the rim
{ const P = player, R = Math.ceil(SIGHT);
for (let y = Math.max(0, P.y - R); y <= Math.min(MH - 1, P.y + R); y++) for (let x = Math.max(0, P.x - R); x <= Math.min(MW - 1, P.x + R); x++) {
const i = idx(x, y); if (!vis[i]) continue;
const k = .07 + .17 * (1 - smooth(SIGHT - 2.5, SIGHT + .3, Math.hypot(x - P.vx, y - P.vy)));
lr[i] += k; lg[i] += k * .97; lb[i] += k * .9;
} }
const x0 = Math.max(0, Math.floor(CX) - 1), x1 = Math.min(MW - 1, Math.floor(CX) + WVW + 1);
const y0 = Math.max(0, Math.floor(CY) - 1), y1 = Math.min(MH - 1, Math.floor(CY) + WVH + 1);
const th = tn - state.thunderT, thunder = th < 700 ? Math.exp(-th / 90) * 1.6 + (th > 160 ? Math.exp(-(th - 160) / 120) * 1.2 : 0) : 0;
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
const i = idx(x, y), z = zone[i], d = dayLight(z);
if (!d && !thunder) continue;
const c = DAYCOL[z] || [1,1,1], k = d + (ZONES[z].outdoor ? thunder : 0);
lr[i] += c[0] * k; lg[i] += c[1] * k; lb[i] += c[2] * k;
}
for (const L of lights) {
let k = L.int;
if (L.fl === 1) k *= .78 + .3 * flick(t, L.seed);
else if (L.fl === 2) k *= .55 + .5 * flick(t * 1.6, L.seed);
const c = L.c, r = L.col[0]*k, g = L.col[1]*k, b = L.col[2]*k;
for (let j = 0; j < c.length; j += 2) { const i = c[j], f = c[j+1]; lr[i] += r*f; lg[i] += g*f; lb[i] += b*f; }
}
flashes = flashes.filter(F => {
const p = (tn - F.t0) / F.dur; if (p >= 1) return false;
const k = F.int * (1 - p) * (1 - p), c = F.c;
for (let j = 0; j < c.length; j += 2) { const i = c[j], f = c[j+1] * k; lr[i] += F.col[0]*f; lg[i] += F.col[1]*f; lb[i] += F.col[2]*f; }
return true;
});
// fireflies: tiny moving lights, no shadows
for (const f of flies) {
const k = .35 * (.5 + .5 * Math.sin(t * 3 + f.ph));
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) {
const x = Math.round(f.x) + dx, y = Math.round(f.y) + dy; if (!inb(x, y)) continue;
const d = Math.hypot(x - f.x, y - f.y); if (d > 2.5) continue;
const i = idx(x, y), q = k * (1 - d / 2.5); lr[i] += .7 * q; lg[i] += 1 * q; lb[i] += .35 * q;
}
}
}
// =====================================================================
// Animation: moves, attacks, idles
// =====================================================================
// entities can be bigger than one tile (the bosses are 2x2); e.x/e.y is the top-left corner
const covers = (e, x, y) => x >= e.x && y >= e.y && x < e.x + e.s && y < e.y + e.s;
const entAt = (x, y) => ents.find(e => !e.dead && covers(e, x, y));
const cellsOf = e => { const c = []; for (let j = 0; j < e.s; j++) for (let i = 0; i < e.s; i++) c.push([e.x + i, e.y + j]); return c; };
const ctr = e => [e.x + (e.s - 1) / 2, e.y + (e.s - 1) / 2];
// the cell of a big entity nearest to a point
const nearCell = (e, x, y) => [clamp(x, e.x, e.x + e.s - 1), clamp(y, e.y, e.y + e.s - 1)];
const losE = (m, x, y) => cellsOf(m).some(([cx, cy]) => los(cx, cy, x, y));
const easeOutBack = p => { const c1 = 1.4, c3 = c1 + 1; return 1 + c3*Math.pow(p-1,3) + c1*Math.pow(p-1,2); };
const S = Math.sin, PI = Math.PI;
const MOVES = {
normal:{dur:160, hop:.25, wob:.28}, slide:{dur:230, hop:0, wob:0, squash:1}, heavy:{dur:250, hop:.12, wob:.12, thud:1},
quick:{dur:110, hop:.12, wob:.2}, float:{dur:230, hop:0, wob:.1, sine:1}, leap:{dur:320, hop:.95, wob:.7},
};
function moveEnt(e, nx, ny, style){
const D = MONS[e.type] || {};
const m = style || (e.isPlayer || e.npc ? 'normal' : D.move || 'normal');
if (nx !== e.x) e.face = Math.sign(nx - e.x);
e.anim = {fx:e.vx, fy:e.vy, tx:nx, ty:ny, t0:now(), m, dir:e.face};
e.x = nx; e.y = ny;
}
// attack styles: f(p, dx, dy, s) -> transform; hit = fraction of dur where the blow lands
const ATK = {
whip: {dur:360, hit:.55, ghosts:3, f:(p, dx, dy, s) => {
if (p < .3) { const k = p / .3; return {ox:-dx*.12*k, oy:-dy*.12*k, rot:-.8*s*k, sx:1 - .1*k, sy:1 + .08*k}; }
if (p < .72) { const k = (p - .3) / .42, e = k*k*(3 - 2*k), l = S(PI*k);
return {ox:dx*.48*l, oy:dy*.48*l - .1*l, rot:s*(-.8 + (2*PI + 1)*e), sx:1 + .3*l, sy:1 - .15*l}; }
const k = (p - .72) / .28; return {ox:0, oy:0, rot:s*(2*PI + .2*(1 - k)*S(k*9)), sx:1, sy:1}; }},
bite: {dur:260, hit:.25, f:(p, dx, dy, s) => { const k = Math.max(0, S(p*4*PI)) * (p < .5 ? 1 : .6);
return {ox:dx*.38*k, oy:dy*.38*k, rot:s*.25*k, sx:1 + .25*k, sy:1 - .1*k}; }},
stab: {dur:300, hit:.55, f:(p, dx, dy, s) => {
if (p < .4) { const k = p / .4; return {ox:-dx*.18*k, oy:-dy*.18*k, rot:-.4*s*k, sx:1, sy:1}; }
const q = (p - .4) / .6, l = S(PI*q); return {ox:dx*(.62*l - .18*(1 - q)), oy:dy*(.62*l - .18*(1 - q)), rot:s*(-.4*(1 - q) + .6*l), sx:1 + .15*l, sy:1}; }},
engulf: {dur:380, hit:.5, f:(p, dx, dy) => { const k = S(PI*p), hz = Math.abs(dx) >= Math.abs(dy);
return {ox:dx*.45*k, oy:dy*.45*k, rot:0, sx:hz ? 1 + .9*k : 1 - .3*k, sy:hz ? 1 - .35*k : 1 + .9*k}; }},
cleave: {dur:400, hit:.55, ghosts:2, f:(p, dx, dy, s) => {
if (p < .35) { const k = p / .35; return {ox:-dx*.1*k, oy:-dy*.1*k - .12*k, rot:-1.3*s*k, sx:1 + .1*k, sy:1 + .1*k}; }
const q = (p - .35) / .65, e = 1 - Math.pow(1 - Math.min(1, q * 1.6), 3), back = q > .62 ? (q - .62) / .38 : 0;
return {ox:dx*.45*S(PI*q), oy:dy*.45*S(PI*q), rot:s*(-1.3 + 2.8*e)*(1 - back), sx:1, sy:1}; }},
tongue: {dur:340, hit:.45, f:(p) => { const k = S(PI*p); return {ox:0, oy:0, rot:0, sx:1 + .2*k, sy:1 - .15*k, tongue:k}; }},
latch: {dur:360, hit:.5, f:(p, dx, dy) => { const k = S(PI*p), hz = Math.abs(dx) >= Math.abs(dy);
return {ox:dx*.5*k, oy:dy*.5*k, rot:.4*S(p*6*PI), sx:hz ? 1 + .6*k : 1, sy:hz ? 1 : 1 + .6*k}; }},
pounce: {dur:340, hit:.55, ghosts:3, f:(p, dx, dy, s) => { const k = S(PI*p), land = p > .55 ? S(PI*(p - .55)/.45) : 0;
return {ox:dx*.65*k, oy:dy*.65*k - .55*k, rot:s*.9*k, sx:1 + .25*land, sy:1 - .3*land}; }},
clap: {dur:380, hit:.5, f:(p, dx, dy) => {
if (p < .45) { const k = p / .45; return {ox:0, oy:0, rot:0, sx:1 - .6*k, sy:1 + .2*k}; }
const q = (p - .45) / .55, b = S(PI*q); return {ox:dx*.3*b, oy:dy*.3*b, rot:0, sx:.4 + .6*q + 1*b, sy:1.2 - .2*q - .2*b}; }},
swoop: {dur:400, hit:.5, ghosts:3, f:(p, dx, dy, s) => { const k = S(PI*p), w = S(2*PI*p);
return {ox:dx*.62*k - dy*.38*w, oy:dy*.62*k + dx*.38*w, rot:s*.5*w, sx:1, sy:1 + .2*k, fade:1}; }},
spear: {dur:320, hit:.55, f:(p, dx, dy) => { const a = Math.atan2(dy, dx) + PI/2, aim = Math.min(1, p / .25) * (p > .85 ? (1 - p) / .15 : 1);
const th = p > .25 && p < .85 ? S(PI*(p - .25)/.6) : 0; return {ox:dx*.58*th, oy:dy*.58*th, rot:a*aim, sx:1, sy:1 + .3*th}; }},
slam: {dur:440, hit:.62, f:(p, dx, dy) => {
if (p < .5) { const k = p / .5; return {ox:0, oy:-.6*k, rot:0, sx:1 + .35*k, sy:1 + .35*k}; }
const q = (p - .5) / .5, l = S(PI*q); return {ox:dx*.42*l, oy:dy*.42*l - .6*Math.max(0, 1 - q*4), rot:0, sx:1 + .35*(1 - q) + .3*l, sy:1 + .35*(1 - q) - .5*l}; }},
punch: {dur:460, hit:.62, f:(p, dx, dy, s) => {
if (p < .5) { const k = p / .5; return {ox:-dx*.2*k, oy:-dy*.2*k, rot:-.3*s*k, sx:1 + .55*k, sy:1 + .55*k}; }
const q = (p - .5) / .5, l = S(PI*q); return {ox:dx*.55*l, oy:dy*.55*l, rot:-.3*s*(1 - q), sx:1 + .55*(1 - q), sy:1 + .55*(1 - q) - .3*l}; }},
dive: {dur:340, hit:.6, f:(p, dx, dy, s, t) => {
const fl = .55 + .45*Math.abs(S(t*30));
if (p < .4) { const k = p / .4; return {ox:0, oy:-.5*k, rot:0, sx:fl, sy:1}; }
const q = (p - .4) / .6, l = S(PI*q); return {ox:dx*.58*l, oy:dy*.58*l - .5*(1 - q), rot:s*.6*l, sx:fl, sy:1}; }},
};
// idle styles: f(t, e) -> {ox, oy (px), rot, sx, sy}
const IDLES = {
player: (t, e) => { const f = Math.pow(Math.max(0, S(t * .9 + e.seed)), 24);
return {ox:0, oy:0, rot:.28 * S(t * 30) * f + .05 * e.face, sx:1, sy:1 + .035 * S(t * 2.2)}; },
twitch: (t, e) => { const j = hash(Math.floor(t * 7) + e.seed) > .82; return {ox:j ? (hash(t * 99) - .5) * 3 : 0, oy:0, rot:0, sx:1, sy:1}; },
bounce: (t, e) => { const b = Math.abs(S(t * 4 + e.seed)); return {ox:0, oy:-b * 2.6, rot:0, sx:1 + .05 * (1 - b), sy:1 - .05 * (1 - b)}; },
jiggle: (t, e) => { const w = S(t * 3.3 + e.seed); return {ox:0, oy:w * 1.4, rot:0, sx:1 + .12 * w, sy:1 - .12 * w}; },
breathe:(t, e) => { const w = S(t * 1.8 + e.seed); return {ox:0, oy:0, rot:0, sx:1 + .04 * w, sy:1 + .05 * w}; },
throat: (t, e) => { const f = Math.pow(Math.max(0, S(t * 1.6 + e.seed)), 8); return {ox:0, oy:0, rot:0, sx:1 + .18 * f, sy:1 - .05 * f}; },
wiggle: (t, e) => ({ox:3 * S(t * 4 + e.seed + 1), oy:0, rot:.28 * S(t * 4 + e.seed), sx:1, sy:1}),
float: (t, e) => ({ox:S(t * 1.3 + e.seed) * 2.5, oy:S(t * 2 + e.seed) * 4 - 2, rot:.12 * S(t + e.seed), sx:1, sy:1}),
sway: (t, e) => ({ox:0, oy:0, rot:.08 * S(t * 1.1 + e.seed), sx:1, sy:1}),
pant: (t, e) => ({ox:0, oy:0, rot:0, sx:1, sy:1 + .06 * S(t * 11 + e.seed)}),
flicker:(t, e) => ({ox:(rnd() - .5) * 1.4, oy:(rnd() - .5) * 1.4, rot:.06 * S(t * 17 + e.seed), sx:1, sy:1 + .05 * S(t * 9)}),
smolder:(t, e) => { const w = S(t * 1.2 + e.seed); return {ox:0, oy:0, rot:0, sx:1 + .05 * w, sy:1 + .05 * w}; },
flap: (t, e) => ({ox:S(t * 2 + e.seed) * 2, oy:S(t * 4 + e.seed) * 3 - 3, rot:0, sx:.5 + .5 * Math.abs(S(t * 14 + e.seed)), sy:1}),
slither:(t, e) => ({ox:2 * S(t * 5 + e.seed + .6), oy:0, rot:.2 * S(t * 5 + e.seed), sx:1, sy:1}),
rock: (t, e) => ({ox:0, oy:S(t * 1.4) * 1, rot:.07 * S(t * 1.4), sx:1, sy:1}),
};
function updateEnt(e, t, tn){
let x = e.x, y = e.y;
const T = {ox:0, oy:0, rot:0, sx:1, sy:1, alpha:1, tongue:0};
const D = MONS[e.type] || {};
if (e.anim) {
const a = e.anim, M = MOVES[a.m] || MOVES.normal, p = (tn - a.t0) / M.dur;
if (p >= 1) {
e.anim = null;
if (M.thud && vis[idx(e.x, e.y)]) { shake(1.2); for (let k = 0; k < 3; k++) part(e.x + (rnd() - .5) * .8, e.y + .35, (rnd() - .5), -.3, .4, '.', [.6,.5,.4], 1); }
} else {
const k = M.sine ? .5 - .5 * Math.cos(PI * p) : easeOutBack(p), l = S(PI * p);
x = a.fx + (a.tx - a.fx) * k; y = a.fy + (a.ty - a.fy) * k - M.hop * l;
T.rot += l * M.wob * a.dir;
if (M.squash) { T.sx *= 1 + .3 * l; T.sy *= 1 - .22 * l; }
}
}
if (e.act) {
const A = ATK[e.act.style], p = (tn - e.act.t0) / A.dur;
if (p >= 1) e.act = null;
else { const f = A.f(p, e.act.dx, e.act.dy, e.act.s, t);
x += f.ox; y += f.oy; T.rot += f.rot; T.sx *= f.sx; T.sy *= f.sy; T.tongue = f.tongue || 0; if (f.fade) T.alpha = .6 + .4 * Math.abs(S(p * 20)); }
}
if (e.knock && tn >= e.knock.t0) {
const p = (tn - e.knock.t0) / 260;
if (p >= 1) e.knock = null;
else { const k = (1 - p) * (1 - p); x += e.knock.dx * .22 * k; y += e.knock.dy * .22 * k; T.sx *= 1 + .25 * k; T.sy *= 1 - .2 * k; T.rot += e.knock.dx * .25 * k; }
}
const idle = (e.isPlayer ? IDLES.player : e.npc ? IDLES.rock : IDLES[D.idle]);
if (idle && !e.frozen) { const f = idle(t, e); T.ox += f.ox / TW; T.oy += f.oy; T.rot += f.rot; T.sx *= f.sx; T.sy *= f.sy; }
if (D.flip || e.isPlayer) T.sx *= e.face < 0 ? -1 : 1;
T.sx *= e.sz; T.sy *= e.sz;
e.vx = x; e.vy = y; e.tf = T;
}
function part(x, y, vx, vy, life, ch, col, g = 0, delay = 0, big = false){ if (parts.length < 1400) parts.push({x, y, vx, vy, life, max:life, ch, col, g, d:delay, big}); }
function ember(x, y, col = [1,.55,.15]){ part(x + (rnd()-.5)*.6, y - .2, (rnd()-.5)*.4, -1 - rnd()*1.2, .5 + rnd()*.6, rnd()<.5?'.':'\'', col, -.3); }
function steam(x, y){ Snd.sizzle(); for (let k = 0; k < 6; k++) part(x + (rnd()-.5)*.8, y, (rnd()-.5)*.6, -.6 - rnd()*.8, .8 + rnd()*.6, rnd()<.5?'°':'.', [.8,.85,.9], -.2); }
function frostBits(x, y){ for (let k = 0; k < 4; k++) part(x + (rnd()-.5)*.8, y + (rnd()-.5)*.8, (rnd()-.5)*.8, (rnd()-.5)*.8, .6 + rnd()*.5, rnd()<.5?'*':'·', [.7,.95,1]); }
function sparks(x, y, n = 4){ for (let k = 0; k < n; k++) { const a = rnd()*PI*2, s = 2 + rnd()*4; part(x, y, Math.cos(a)*s, Math.sin(a)*s, .25 + rnd()*.3, rnd()<.5?'+':'·', [.85,.92,1], 4); } }
function shatter(e){
const chars = [e.ch, '.', ',', '\'', '`', ':'], [cx, cy] = ctr(e);
for (let k = 0; k < 18 * e.s * e.s; k++) { const a = rnd()*PI*2, s = 1 + rnd()*4 * e.s;
part(cx + (rnd() - .5) * (e.s - 1), cy + (rnd() - .5) * (e.s - 1), Math.cos(a)*s, Math.sin(a)*s - 1.5, .6 + rnd()*.7, chars[ri(0, chars.length-1)], e.col, 7); }
}
function shake(a){ shakeAmp = Math.max(shakeAmp, a); }
function damage(e, n, src, delay = 0, from = null, crit = false){
if (e.dead) return;
if (e.npc) {
if (src !== 'melee' && now() - (state.npcSpark || 0) > 3000) { state.npcSpark = now();
log(`${state.mem.knowsName ? 'Eli' : 'The old man'} brushes a spark off his sleeve. "Careful, now."`, [.8,.75,1]); }
return;
}
const D = MONS[e.type] || {}, [cx, cy] = ctr(e);
if (src === 'holy' && (e.isPlayer || !D.undead)) { if (!e.isPlayer) part(cx, cy - .3, 0, -1, .9, 'unharmed', [1,.9,.6], .5, delay / 1000); return; }
if (!e.isPlayer && D.hydra) { hydraHit(e, n, src, delay, crit); return; }
if (!e.isPlayer && D.immune?.[src]) { part(cx, cy - .3 - (e.s - 1) * .5, 0, -1, .9, 'immune', [.7,.7,.7], .5, delay / 1000); return; }
if (!e.isPlayer && D.weak?.[src]) n *= D.weak[src];
if (e.spent) n = Math.ceil(n * 1.5);
e.hp -= n;
const at = now() + delay;
e.hitT = at;
if (from) e.knock = {dx:Math.sign(e.x - from.x), dy:Math.sign(e.y - from.y), t0:at};
if (crit) part(cx, cy - .4, (rnd()-.5)*.4, -2, 1.1, String(n), [1,.9,.3], 1.5, delay / 1000, true);
else part(cx, cy - .3, (rnd()-.5)*.5, -1.6, .8, String(n), e.isPlayer ? [1,.3,.3] : [1,1,.8], 1.5, delay / 1000);
if (delay) setTimeout(() => Snd.hit(!!e.isPlayer), delay); else Snd.hit(!!e.isPlayer);
if (e.isPlayer) { setTimeout(() => shake(4), delay); if (state.travel && !state.travel.target) state.travel = null; }
if (e.boss && !e.awake) wake(e);
if (e.boss && D.title && !e.enraged && e.hp > 0 && e.hp < e.maxhp * .4 && e.type === 'matriarch') {
e.enraged = true; e.dmg += 2; setTimeout(() => { Snd.roar(); shake(6); }, delay);
log('Grukka bellows and froths. She is FURIOUS now, and hits harder.', [1,.45,.35]);
}
if (e.hp <= 0) kill(e, src, delay);
}
// the hydra has no use for hit points: cut its heads off. Cut one without fire and two grow back.
function hydraHit(e, n, src, delay, crit){
const [cx, cy] = ctr(e), at = now() + delay;
if (src === 'melee') {
const cut = Math.min(e.heads, crit ? 2 : 1);
e.heads -= cut; e.hitT = at;
for (let k = 0; k < 12; k++) part(cx + (rnd() - .5), cy - .8, (rnd() - .5) * 4, -1 - rnd() * 2, .7, pick(['§', ',', '\'', '~']), [.45,.85,.45], 6, delay / 1000);
if (e.burning > 0) {
log(cut > 1 ? 'Two heads fly, and the flames sear both stumps shut. Cauterized!' : 'A head flies, and the flames sear the stump shut. Cauterized!', [1,.75,.35]);
part(cx, cy - .6, 0, -1.2, 1, 'seared!', [1,.65,.25], .6, delay / 1000);
} else {
e.stumps += cut;
log(cut > 1 ? 'You lop off two heads! The stumps writhe and bulge...' : 'You lop off a head! The stump writhes and bulges...', [.6,1,.6]);
part(cx, cy - .6, 0, -1.2, 1, 'it writhes...', [.5,.9,.5], .6, delay / 1000);
}
if (delay) setTimeout(() => Snd.hit(false), delay); else Snd.hit(false);
if (e.heads <= 0) { e.hp = 0; kill(e, 'melee', delay); }
} else if (src === 'burn') {
if (rnd() < .4) part(cx, cy - .6, 0, -1, .8, 'singed', [1,.6,.3], .5, delay / 1000);
} else part(cx, cy - .6, 0, -1, .9, 'the heads just hiss', [.7,.8,.7], .5, delay / 1000);
if (!e.awake) wake(e);
}
function kill(e, src, delay = 0){
e.dead = true;
dying.push({e, at:now() + delay});
setTimeout(() => e.isPlayer ? Snd.gameover() : Snd.death(), delay);
if (e.isPlayer) { state.dead = true; log('You fall. Press R to try this floor again. (He would tell you to.)', [1,.35,.3]); return; }
state.mem.kills++;
const verb = e.type === 'hydra' ? 'collapses, headless at last' : src === 'holy' ? 'crumbles to bright dust' : src === 'shock' ? 'is fried' : src === 'burn' ? 'burns to a crisp'
: src === 'melee' && e.frozen ? 'shatters into ice shards' : 'dies';
log(`${e.boss ? capF(e.name) : 'The ' + e.name} ${verb}.`, [.9,.9,.7]);
const drop = (kind, extra) => { const [x, y] = nearCell(e, player.x, player.y); items.push({x, y, kind, ...extra}); };
if (e.carry) { drop(e.carry); log(`Something glints where it fell: ${ITEMS[e.carry].name}!`, [.85,.9,1]); }
else if (!e.boss && !e.minion && rnd() < .3) drop('gold');
if (e.boss) bossDown(e);
}
const BOSS_SPELL = {matriarch:'fire', brood:'lightning', hydra:'frost', dragon:'holy'};
function bossDown(e){
const [cx, cy] = ctr(e);
setTimeout(() => { shake(10); flash(e.x, e.y, 9, [1,.9,.6], 3, 1400); Snd.win(); }, 300);
state.bossSeen = false;
if (BOSS_SPELL[e.type]) { items.push({x:e.x, y:e.y, kind:'tome', spell:BOSS_SPELL[e.type]}); log('Something heavy thumps to the floor: a book, bound in old leather and humming.', [1,.9,.55]); }
if (e.type === 'lich') {
items.push({x:e.x, y:e.y, kind:'stone'});
for (const m of ents) if (m.minion && !m.dead) kill(m, 'shock', 200);
log('The king comes apart like a dropped vase. Where his heart was, something glows.', [1,.95,.8]);
}
if (e.type === 'dragon') items.push({x:e.x + 1, y:e.y, kind:'gold'}, {x:e.x, y:e.y + 1, kind:'gold'}, {x:e.x + 1, y:e.y + 1, kind:'potion'});
player.maxhp += 4; healPlayer(8, true);
log('You feel tougher for having lived through that. (+4 max HP)', [1,.85,.6]);
if (level.exit) {
const [x, y] = level.exit; map[idx(x, y)] = 'STAIRS';
setTimeout(() => { flash(x, y, 6, [1,1,.6], 2.5, 1600); Snd.zone(); }, 700);
log('Stone grinds on stone. A way down opens.', [1,1,.6]);
}
}
function wake(m){
if (m.awake) return;
m.awake = true; state.bossSeen = true;
m.seen = [player.x, player.y];
Snd.roar(); shake(5);
const D = MONS[m.type];
log(`${capF(m.name)}, ${D.title}, ${{matriarch:'heaves herself up and roars', brood:'unfolds from the dark, leg by leg',
hydra:'lifts three heads out of the reeds', dragon:'opens one molten eye', lich:'turns, slowly, and smiles'}[m.type] || 'wakes'}.`, [1,.6,.45]);
}
// =====================================================================
// Turn logic: to-hit rolls against armour class, critical hits
// =====================================================================
function rollHit(a, d){
const nat = ri(1, 20);
if (nat === 1) return {hit:false, nat};
const bonus = a.isPlayer ? playerHit() : a.hit;
const ac = d.isPlayer ? playerAC() : d.frozen ? Math.min(d.ac, 6) : d.ac;
const critOn = a.isPlayer ? weaponStats().crit : 20;
const hit = nat === 20 || nat + bonus >= ac;
return {hit, crit:hit && nat >= critOn, nat};
}
function attack(a, d, extraDelay = 0){
const Wp = a.isPlayer ? weaponStats() : null;
const D = a.isPlayer ? {atk:Wp.style} : MONS[a.type];
const style = ATK[D.atk] ? D.atk : 'stab', A = ATK[style];
const [ax, ay] = nearCell(a, d.x, d.y), [tx, ty] = nearCell(d, ax, ay);
const dx = Math.sign(tx - ax), dy = Math.sign(ty - ay);
const go = () => {
a.act = {style, t0:now(), dx, dy, s:dx || a.face || 1};
if (dx) a.face = dx;
if (style === 'whip') Snd.whip(); else Snd.swing();
if (style === 'tongue') Snd.tongue();
};
if (extraDelay) setTimeout(go, extraDelay); else go();
const delay = A.dur * A.hit + extraDelay;
if (a.isPlayer && MONS[d.type]?.immune?.melee) {
log(`Your ${state.weapon ? 'blade' : 'tail'} passes right through the ${d.name}, like a hand through fog.`, [.7,.75,.85]);
damage(d, 1, 'melee', delay, a); return;
}
const r = rollHit(a, d);
if (!r.hit) {
setTimeout(() => { Snd.miss(); const [cx, cy] = ctr(d); part(cx, cy - .3, (rnd() - .5) * .6, -1.2, .7, 'miss', [.6,.65,.6], 1); }, delay);
log(a.isPlayer ? pick([`You miss the ${d.name}.`, `The ${d.name} turns your blow on its hide.`, `Your swing goes wide of the ${d.name}.`])
: `The ${a.name} ${a.boss ? 'misses' : pick(['misses you', 'glances off your armour'])}.`, a.isPlayer ? [.6,.65,.6] : [.75,.8,.7]);
if (a.isPlayer && d.boss && !d.awake) wake(d);
return;
}
if (style === 'slam' || style === 'punch') setTimeout(() => { shake(5); Snd.slam();
for (let k = 0; k < 6; k++) part(d.x + (rnd() - .5), d.y + .3, (rnd() - .5) * 3, -rnd() * 2, .5, '.', [.7,.6,.5], 5); }, delay);
if (r.crit) critFX(d, delay);
if (a.isPlayer) {
let dmg = ri(Wp.lo, Wp.hi) * (d.frozen ? 2 : 1) * (r.crit ? Wp.mult : 1);
const what = state.weapon ? `your ${Wp.name}` : 'your tail';
log(r.crit ? pick([`CRITICAL! You drive ${what} home into the ${d.name}!`, `CRITICAL! A perfect strike on the ${d.name}!`])
: d.frozen ? `You strike the frozen ${d.name}. It cracks!`
: state.weapon ? pick([`You hit the ${d.name}.`, `You cut the ${d.name}.`, `${capF(what)} bites into the ${d.name}.`])
: pick([`Your tail whips the ${d.name}.`, `You lash the ${d.name}.`, `You spin and strike the ${d.name}.`]), r.crit ? [1,.88,.4] : undefined);
damage(d, dmg, 'melee', delay, a, r.crit);
} else {
let dmg = a.dmg + ri(0, a.boss ? 2 : 1);
if (r.crit) dmg *= 2;
log(`${r.crit ? 'CRITICAL! ' : ''}${a.boss ? capF(a.name) : 'The ' + a.name} ${{bite:'bites', stab:'stabs', engulf:'engulfs', cleave:'cleaves', tongue:'lashes its tongue at', latch:'latches onto',
pounce:'pounces on', clap:'claps its great hands on', swoop:'swoops through', spear:'jabs', slam:'slams', punch:'smashes', dive:'dives at',
whip:'tail-whips'}[style] || 'hits'} you.`, r.crit ? [1,.35,.3] : [1,.6,.5]);
damage(d, dmg, 'melee', delay, a, r.crit);
if (D.drain && !a.dead) { a.hp = Math.min(a.maxhp, a.hp + dmg); }
if (D.poison && !d.dead) { if (!d.poison) setTimeout(() => Snd.poison(), delay); d.poison = Math.max(d.poison, D.poison);
log('Venom burns in the wound. You are poisoned!', [.6,1,.4]); }
}
}
// crits get the works: a white slash, a starburst, a jolt, a moment where time holds its breath
function critFX(e, delay){
setTimeout(() => {
const [cx, cy] = ctr(e);
flash(e.x, e.y, 6, [1,.92,.7], 3.2, 520);
shake(e.isPlayer ? 7 : 9); hitStop = now() + 110; screenFlashT = now();
slashes.push({x:cx, y:cy, a:-.6 + rnd() * .4 + (rnd() < .5 ? PI : 0), t0:now(), dur:340, len:.9 + e.s * .55, col:e.isPlayer ? [1,.35,.3] : [1,.95,.75]});
for (let k = 0; k < 26; k++) { const a = rnd() * PI * 2, s = 3 + rnd() * 6;
part(cx, cy, Math.cos(a) * s, Math.sin(a) * s, .35 + rnd() * .4, pick(['*', '+', '·', 'x']), e.isPlayer ? [1, .4 + rnd() * .3, .3] : [1, .85 + rnd() * .15, .4 + rnd() * .4], 3); }
part(cx, cy - .9 - (e.s - 1) * .5, 0, -.9, 1.2, e.isPlayer ? 'OUCH!' : 'CRITICAL!', e.isPlayer ? [1,.4,.35] : [1,.9,.35], .3, 0, true);
Snd.crit();
}, delay);
}
const blocksFor = (m, i) => { const t = map[i], d = TD[t];
if (d.lava && MONS[m.type]?.lavawalk) return false;
if (MONS[m.type]?.dry && d.water) return true;
return d.block && t !== 'DOOR'; };
// can m stand with its top-left corner at (nx, ny)?
function fits(m, nx, ny){
for (let j = 0; j < m.s; j++) for (let i = 0; i < m.s; i++) {
const x = nx + i, y = ny + j; if (!inb(x, y)) return false;
if (blocksFor(m, idx(x, y)) || (m.s > 1 && map[idx(x, y)] === 'DOOR')) return false;
const o = entAt(x, y); if (o && o !== m) return false;
}
return true;
}
function tryStep(m, nx, ny, style){
if (!inb(nx, ny)) return false;
const i = idx(nx, ny);
if (m.s === 1 && map[i] === 'DOOR') { map[i] = 'OPEN'; if (vis[i]) Snd.door(); return true; }
if (!fits(m, nx, ny)) return false;
if (m.npc && cheb({x:nx, y:ny}, {x:m.home[0], y:m.home[1]}) > 2) return false;
moveEnt(m, nx, ny, style); return true;
}
function stepToward(m, tx, ty){
const T = {x:tx, y:ty}, cur = cheb(m, T);
let best = null, bs = 1e9;
for (const [dx, dy] of DIR8) {
const nx = m.x + dx, ny = m.y + dy;
if (!fits(m, nx, ny)) continue;
const i = idx(nx, ny);
const s = cheb({x:nx, y:ny, s:m.s}, T) + (fire[i] && !MONS[m.type]?.immune?.burn ? 4 : 0) + rnd()*.2;
if (s < bs) { bs = s; best = [nx, ny]; }
}
if (best && bs <= cur + .2) return tryStep(m, best[0], best[1]);
return false;
}
function monsterAct(m){
if (m.npc) { if (rnd() < .04 && cheb(m, player) > 1) { const [dx, dy] = pick(DIR8); tryStep(m, m.x + dx, m.y + dy); } return; }
const D = MONS[m.type];
if (D.boss && !m.awake) {
const B = level.bossRoom, inRoom = B && player.x >= B.x && player.y >= B.y && player.x < B.x + B.w && player.y < B.y + B.h;
if (inRoom || (canSee(m) && cheb(m, player) <= 7)) wake(m); else return;
}
if (m.frozen > 0) { m.frozen--; if (!m.frozen && vis[idx(m.x, m.y)]) log(`${m.boss ? capF(m.name) : 'The ' + m.name} thaws out.`); return; }
if (D.hydra) { hydraAct(m); return; }
if (m.type === 'dragon') { dragonAct(m); return; }
if (m.type === 'lich') { lichAct(m); return; }
if (m.type === 'brood' && broodAct(m)) return;
if (D.slow && state.turn % 2) return;
if (D.regen && m.hp < m.maxhp && !m.burning && state.turn - (m.burnT || -99) > 3) {
m.hp++; if (canSee(m) && rnd() < .3) part(m.x, m.y - .3, 0, -.8, .7, '+', [.5,1,.5], .5);
}
for (let n = D.fast ? 2 : 1; n > 0 && !m.dead && !player.dead && !m.frozen; n--) actOnce(m, D);
}
function actOnce(m, D){
const P = player, d = cheb(m, P);
if (d <= 9 && losE(m, P.x, P.y)) {
if (!m.seen && canSee(m)) { Snd.alert(); if (D.howl) Snd.howl(); if (m.type === 'frog') Snd.croak(); }
m.seen = [P.x, P.y];
}
if (D.erratic && rnd() < D.erratic && !(d === 1 && m.seen)) { const [dx, dy] = pick(DIR8); tryStep(m, m.x + dx, m.y + dy); return; }
if (m.seen) {
if (d === 1 && m.seen[0] === P.x && m.seen[1] === P.y) { attack(m, P); return; }
if (D.leap && d >= 3 && rnd() < .6) {
const dx = Math.sign(P.x - m.x), dy = Math.sign(P.y - m.y), ax = m.x + dx, ay = m.y + dy, bx = m.x + 2*dx, by = m.y + 2*dy;
if (inb(bx, by) && !blocksFor(m, idx(ax, ay)) && !blocksFor(m, idx(bx, by)) && !entAt(bx, by) && !entAt(ax, ay) && map[idx(bx, by)] !== 'DOOR') {
moveEnt(m, bx, by, 'leap'); if (vis[idx(bx, by)]) Snd.croak(); return; }
}
stepToward(m, m.seen[0], m.seen[1]);
if (covers(m, m.seen[0], m.seen[1])) m.seen = null;
} else if (rnd() < .3 && !m.boss) { const [dx, dy] = pick(DIR8); tryStep(m, m.x + dx, m.y + dy); }
}
// ---------------- the bosses ----------------
function hydraAct(m){
if (m.stumps > 0) {
const grow = Math.min(9 - m.heads, m.stumps * 2);
m.heads += grow; m.stumps = 0;
if (grow > 0) { log(grow > 2 ? `${grow} new heads burst, hissing, from the stumps!` : 'Two new heads burst, hissing, from the stump!', [.6,1,.5]); Snd.roar(); shake(3); }
}
const P = player, d = cheb(m, P);
if (d === 1) {
const bites = Math.min(m.heads, 4);
for (let k = 0; k < bites && !P.dead; k++) attack(m, P, k * 140);
return;
}
if (state.turn % 2 === 0) { m.seen = [P.x, P.y]; stepToward(m, P.x, P.y); }
}
// the dragon fights a few turns, then breathes: everything it can see burns. Hide behind something.
function dragonAct(m){
const P = player;
if (m.phase === 'charge') {
m.pt--;
if (m.pt <= 0) { dragonBreath(m); m.phase = 'spent'; m.pt = 3; m.spent = true; return; }
Snd.charge(); shake(2);
log(m.pt === 1 ? 'Cinder\'s throat glows white-hot. HIDE!' : 'Cinder draws in a long, roaring breath. Its chest is glowing...', [1,.6,.3]);
return;
}
if (m.phase === 'spent') {
m.pt--;
if (m.pt <= 0) { m.phase = null; m.spent = false; m.pt = ri(3, 5); log('Cinder shakes the smoke out of its head.', [1,.7,.5]); }
else if (rnd() < .5) part(m.x + 1, m.y - .3, (rnd() - .5) * .4, -.8, 1.4, '°', [.6,.6,.6], -.1);
return;
}
m.pt--;
if (m.pt <= 0) { m.phase = 'charge'; m.pt = 3; Snd.roar(); log('Cinder rears back and sucks in air. Its chest begins to glow. Get behind something!', [1,.55,.25]); return; }
m.seen = [P.x, P.y];
if (cheb(m, P) === 1) attack(m, P); else stepToward(m, P.x, P.y);
}
function dragonMouth(m){ return nearCell(m, player.x, player.y); }
function breathCells(m){
const [mx, my] = dragonMouth(m), out = [];
for (let y = my - 12; y <= my + 12; y++) for (let x = mx - 12; x <= mx + 12; x++) {
if (!inb(x, y) || covers(m, x, y) || Math.hypot(x - mx, y - my) > 12.5) continue;
if (TD[map[idx(x, y)]].opaque) continue;
if (los(mx, my, x, y)) out.push([x, y]);
}
return out;
}
function dragonBreath(m){
const cells = breathCells(m), [mx, my] = dragonMouth(m), P = player;
Snd.boom(); Snd.whoosh(); shake(12);
flash(mx, my, 12, [1,.5,.15], 3.5, 1100);
log('Cinder BREATHES. The hall fills with fire!', [1,.5,.2]);
let hitP = false;
for (const [x, y] of cells) {
const i = idx(x, y), d = Math.hypot(x - mx, y - my);
if (rnd() < .5) part(x + (rnd() - .5) * .6, y + (rnd() - .5) * .6, (x - mx) / (d || 1) * 2, (y - my) / (d || 1) * 2 - 1, .5 + rnd() * .4, pick(['*', '^', '\'']), [1, .3 + rnd() * .5, .08], -1, d * .025);
if (TD[map[i]].burn) ignite(i);
if (map[i] === 'ICE') { map[i] = under[i] || 'WATER'; steam(x, y); }
if (map[i] === 'OBSIDIAN' && rnd() < .3) { map[i] = 'LAVA'; }
const e = entAt(x, y);
if (e && e !== m && !e.npc) {
if (e.isPlayer) hitP = true;
damage(e, e.isPlayer ? 14 : 10, 'burn', d * 25);
if (!MONS[e.type]?.immune?.burn || e.isPlayer) e.burning = Math.max(e.burning, 3);
}
}
if (!hitP && !P.dead) log('The fire roars past your hiding place. You are untouched!', [.8,1,.8]);
else if (!P.dead) log('The flames find you. You are burning!', [1,.4,.3]);
log('Cinder sags, smoking and panting. NOW is your chance!', [1,.9,.5]);
}
// the lich: every spell is shown before it lands
function lichAct(m){
const P = player, B = level.bossRoom;
if (m.cast) {
m.cast.t--;
if (m.cast.t <= 0) { lichResolve(m); m.cast = null; m.cd = ri(1, 2); }
else { Snd.charge(); log(m.cast.kind === 'ray' ? 'The black light in his hand is blinding now. Break his line of sight!' : 'The sigils under your feet burn brighter. MOVE!', [.85,.65,1]); }
return;
}
const d = cheb(m, P), sees = los(m.x, m.y, P.x, P.y);
if (d === 1 && rnd() < .55) { lichBlink(m); return; }
if (m.cd > 0) {
m.cd--; m.seen = [P.x, P.y];
if (d === 1) attack(m, P); else if (d > 5) stepToward(m, P.x, P.y);
return;
}
const minions = ents.filter(e => e.minion && !e.dead).length;
const r = rnd();
if (minions < 3 && r < .25) { lichRaise(m); m.cd = 2; return; }
if (sees && r < .65) {
m.cast = {kind:'ray', t:2}; Snd.charge();
log('King Aurex lifts one finger. Black light gathers on it. (Break his line of sight!)', [.85,.65,1]);
} else {
const cells = []; for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) cells.push([P.x + dx, P.y + dy]);
m.cast = {kind:'nova', t:2, cells}; Snd.freeze();
log('King Aurex points at the floor beneath you. Frost sigils spread out around your feet!', [.7,.8,1]);
}
}
function lichResolve(m){
const P = player, c = m.cast;
if (c.kind === 'ray') {
const clear = los(m.x, m.y, P.x, P.y) && cheb(m, P) <= 16;
const end = clear ? [P.x, P.y] : (() => { let last = [m.x, m.y]; for (const [x, y] of bline(m.x, m.y, P.x, P.y)) { last = [x, y]; if (TD[map[idx(x, y)]].opaque) break; } return last; })();
bolts.push({pts:[[m.x, m.y], ...bline(m.x, m.y, end[0], end[1])], t0:now(), dur:520, col:[.7,.4,1]});
flash(end[0], end[1], 5, [.7,.4,1], 2.5, 700); sparks(end[0], end[1], 12); shake(8); Snd.zap();
if (clear) { damage(P, 13, 'magic'); log('The black ray hits you full in the chest!', [1,.4,.5]); }
else log('The black ray splashes harmlessly against stone.', [.8,1,.8]);
} else {
Snd.shatter(); shake(5);
let hit = false;
for (const [x, y] of c.cells) {
if (!inb(x, y)) continue;
frostT[idx(x, y)] = now(); frostBits(x, y); frostBits(x, y);
const e = entAt(x, y); if (e && e !== m && !e.npc) { if (e.isPlayer) hit = true; damage(e, e.isPlayer ? 11 : 6, 'frost'); }
}
flash(c.cells[4][0], c.cells[4][1], 4, [.6,.85,1], 2.2, 600);
log(hit ? 'The frost sigils erupt around you. Cold bites to the bone!' : 'The frost sigils erupt — on an empty floor.', hit ? [1,.5,.5] : [.8,1,.8]);
}
}
function lichBlink(m){
const B = level.bossRoom, P = player;
for (let tries = 0; tries < 60; tries++) {
const x = ri(B.x + 1, B.x + B.w - 2), y = ri(B.y + 1, B.y + B.h - 2);
if (cheb({x, y}, P) < 5 || !fits(m, x, y)) continue;
for (let k = 0; k < 14; k++) part(m.x, m.y, (rnd() - .5) * 3, (rnd() - .5) * 3, .6, '·', [.7,.5,1], 0);
flash(m.x, m.y, 4, [.6,.4,1], 1.8, 400);
m.x = m.vx = x; m.y = m.vy = y; m.anim = null;
flash(x, y, 4, [.6,.4,1], 1.8, 400); Snd.frost();
log('King Aurex folds into shadow and steps out somewhere else.', [.8,.65,1]);
return;
}
}
function lichRaise(m){
let n = 0;
for (const [dx, dy] of DIR8) {
if (n >= 2) break;
const x = m.x + dx * 2, y = m.y + dy * 2;
if (!inb(x, y) || TD[map[idx(x, y)]].block || entAt(x, y)) continue;
const s = mkEnt('skeleton', x, y, {minion:true, name:'risen skeleton', hp:6, maxhp:6});
ents.push(s); n++;
for (let k = 0; k < 10; k++) part(x, y + .3, (rnd() - .5) * 2, -rnd() * 2, .6, pick([';', ',', '.']), [.9,.88,.8], 3);
}
if (n) { Snd.slam(); log('King Aurex spreads his hands. The floor coughs up bones, and the bones stand up.', [.85,.75,1]); }
}
// the broodmother spits webs from a distance, then comes in to bite
function broodAct(m){
const P = player, d = cheb(m, P);
m.cd = (m.cd || 0) - 1;
if (d >= 2 && d <= 6 && m.cd <= 0 && losE(m, P.x, P.y) && rnd() < .5) {
m.cd = 4;
const [sx, sy] = nearCell(m, P.x, P.y), cells = bline(sx, sy, P.x, P.y);
projs.push({cells, msPer:28, ch:'%', col:[.9,.9,.95], trail:(x, y) => { if (rnd() < .4) part(x, y, 0, 0, .3, '·', [.8,.8,.85]); },
onDone:() => {}, t0:now(), sx, sy, x:sx, y:sy});
const i = idx(P.x, P.y);
if (!TD[map[i]].water && !TD[map[i]].block) map[i] = 'WEB';
P.webbed = 2; log('The Broodmother spits a gob of web. You are stuck fast!', [.85,.85,.9]);
return true;
}
return false;
}
function ignite(i){ const d = TD[map[i]]; if (d.burn && !fire[i]) { fire[i] = d.fuel + ri(0, 1); snowAcc[i] = 0; } }
function burnItemsAt(x, y){
items = items.filter(it => { if (ITEMS[it.kind].burn && it.x === x && it.y === y) { if (vis[idx(x,y)]) log('A scroll curls up and burns away.', [1,.6,.3]); return false; } return true; });
}
function burnOut(i){
const x = i % MW, y = (i / MW) | 0;
if (map[i] === 'CHEST') { items.push({x, y, kind:'gold'}); if (vis[i]) log('The chest burns away, spilling gold.', [1,.8,.3]); }
if (map[i] === 'EGGSAC') {
state.eggs = (state.eggs || 0) + 1; Snd.death();
for (let k = 0; k < 10; k++) part(x, y, (rnd() - .5) * 3, -rnd() * 2, .6, pick(['.', ',', '°']), [.9,.85,.6], 4);
log(state.eggs >= 3 ? 'The last egg sac pops and shrivels. That\'s all three. Eli will want to know.' : `An egg sac bursts in the flames. (${state.eggs} of 3)`, [1,.8,.5]);
}
if (map[i] === 'BRAMBLE' && vis[i]) log('The brambles crumble to ash. There was something behind them!', [1,.8,.5]);
if (map[i] === 'BARRICADE' && vis[i]) log('The coffin barricade collapses into embers. The way is open.', [1,.8,.5]);
map[i] = zone[i] === Z.MIRE ? 'MUD' : 'ASH';
}
function tickFire(){
const ign = [];
for (let i = 0; i < fire.length; i++) {
if (fire[i] <= 0) continue;
const x = i % MW, y = (i / MW) | 0, L = localW(zone[i]);
const damp = 1 - .75 * L.rain - .5 * Math.min(1, snowAcc[i] + L.snow * .5);
burnItemsAt(x, y);
for (const [dx, dy] of DIR8) {
const nx = x + dx, ny = y + dy; if (!inb(nx, ny)) continue;
const j = idx(nx, ny), d = TD[map[j]];
const windB = 1 + L.wind * (Math.sign(dx) === W.dir ? .8 : -.4);
if (d.burn && !fire[j] && rnd() < d.spread * damp * windB * (dx && dy ? .6 : 1)) ign.push(j);
snowAcc[j] *= .6;
}
fire[i]--; if (L.rain > .4 && rnd() < L.rain * .5) { fire[i]--; if (rnd() < .2 && vis[i]) steam(x, y); }
if (fire[i] <= 0) { fire[i] = 0; burnOut(i); }
}
ign.forEach(ignite);
}
function stormStrike(){
if (state.weather.type !== 'storm' || rnd() > .045) return;
const P = player;
state.thunderT = now(); setTimeout(() => Snd.thunder(), 120 + rnd() * 500);
for (let tries = 0; tries < 30; tries++) {
const x = P.x + ri(-13, 13), y = P.y + ri(-10, 10);
if (!inb(x, y) || cheb({x, y}, P) < 4) continue;
const i = idx(x, y); if (!ZONES[zone[i]].outdoor || !vis[i]) continue;
bolts.push({pts:[[x + ri(-2, 2), y - 14], [x + ri(-1, 1), y - 7], [x, y]], t0:now(), dur:380});
flash(x, y, 6, [.8,.85,1], 2.5, 600); sparks(x, y, 10); shake(6);
log('Lightning strikes nearby!', [.8,.85,1]);
const e = entAt(x, y); if (e) damage(e, 8, 'shock');
if (TD[map[i]].water) electrify([i], now());
else if (TD[map[i]].burn) ignite(i);
return;
}
}
function checkZone(){
const z = zone[idx(player.x, player.y)], m = state.mem;
if (z !== state.zone) {
state.zone = z;
const first = !m.visited[z]; m.visited[z] = 1;
log(`— ${ZONES[z].name} —`, [.95,.9,.65]);
if (first) log(ZONES[z].enter, [.75,.75,.6]);
if (first && state.turn > 0) Snd.zone();
}
if (!m.called && !npc.dead && cheb(player, npc) <= 8 && canSee(npc) && !m.met) {
m.called = true;
log('A voice by the fire: "Come and sit, you look half frozen. Mind the step."', [.85,.8,1]);
}
}
function endTurn(){
state.turn++;
for (const m of ents.slice()) if (!m.isPlayer && !m.dead) monsterAct(m);
for (const e of ents) {
if (e.dead || e.npc) continue;
const i = idx(e.x, e.y), d = TD[map[i]], fireproof = MONS[e.type]?.immune?.burn && !e.isPlayer;
if (fire[i] > 0 && !d.water && !fireproof) e.burning = Math.max(e.burning, 3);
if (fireproof) e.burning = 0;
if (e.burning > 0) {
e.burnT = state.turn;
if (d.water) { e.burning = 0; steam(e.x, e.y); if (e.isPlayer) log('The water douses your flames.', [.7,.85,1]); }
else if (localW(zone[i]).rain > .5 && rnd() < .5) { e.burning = 0; steam(e.x, e.y); if (e.isPlayer) log('The rain puts you out.', [.7,.85,1]); }
else { if (e.isPlayer) log('You are burning!', [1,.55,.2]); damage(e, 1, 'burn'); e.burning--; ignite(i); }
}
if (e.smite > 0 && !e.dead) {
e.smite--; damage(e, 2, 'holy');
if (!e.dead) for (let k = 0; k < 3; k++) part(e.x + (rnd() - .5) * .6, e.y, (rnd() - .5) * .3, -.8, .8, pick(['+', '·']), [1,.9,.55], -.2);
}
if (e.poison > 0 && !e.dead) {
e.poison--; damage(e, 1, 'poison');
if (e.isPlayer) { Snd.poison(); part(e.x, e.y - .2, 0, -.6, .8, '•', [.5,1,.3], -.2); if (!e.poison) log('The venom wears off.', [.7,.9,.7]); }
}
}
tickFire();
{ let n = 0; for (let i = 0; i < fire.length; i++) if (fire[i] > 0 && vis[i]) n++; Snd.crackle(n); }
tickWeather();
stormStrike();
if (!player.dead) player.mp = Math.min(player.maxmp, player.mp + 1);
ents = ents.filter(e => !e.dead || e.isPlayer);
rebuildLights(); computeFOV();
computeDanger();
checkZone();
if (!state.dead && !state.won) maybeEcho();
saveGame();
}
// tiles about to be hit by a telegraphed attack
function computeDanger(){
danger.fill(0);
for (const m of ents) {
if (m.dead) continue;
if (m.phase === 'charge') for (const [x, y] of breathCells(m)) danger[idx(x, y)] = 1;
if (m.cast?.kind === 'ray') { for (const [x, y] of bline(m.x, m.y, player.x, player.y)) { if (!inb(x, y) || TD[map[idx(x, y)]].opaque) break; danger[idx(x, y)] = 2; } }
if (m.cast?.kind === 'nova') for (const [x, y] of m.cast.cells) if (inb(x, y)) danger[idx(x, y)] = 3;
}
}
function pickUp(it){
const P = player, I = ITEMS[it.kind];
if (it.kind === 'gold') { const g = ri(5, 15) + 3 * state.floor; state.gold += g; Snd.coin(); log(`You pick up ${g} gold.`, [1,.85,.3]); }
else if (I.pack) { state.inv[it.kind] = (state.inv[it.kind] || 0) + 1; Snd.coin();
log(`You pack away a ${I.name}. (${it.kind === 'potion' ? '5' : '6'} to drink, I for your pack)`, it.kind === 'potion' ? [1,.5,.6] : [.6,.7,1]); }
else if (it.kind === 'scroll') { P.maxmp += 4; P.mp = P.maxmp; Snd.scroll(); log('You read a scroll of insight: max MP +4.', [.95,.9,.7]); }