-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
2231 lines (2173 loc) · 58.5 KB
/
index.js
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
// src/prototype.ts
Array.prototype.random = function() {
const { length } = this;
if (!length) {
return null;
}
return this[Math.floor(Math.random() * length)];
};
String.prototype.capitalize = function() {
const { length } = this;
if (!length) {
return this.valueOf();
}
return this.substring(0, 1).toUpperCase() + this.substring(1);
};
String.prototype.article = function() {
let a = this.match(/^[aeiou]/i) ? "an" : "a";
return `${a} ${this}`;
};
Array.prototype.distance = function(other) {
let dx = Math.abs(this[0] - other[0]);
let dy = Math.abs(this[1] - other[1]);
return Math.max(dx, dy);
};
Array.prototype.norm = function() {
return Math.sqrt(this[0] * this[0] + this[1] * this[1]);
};
Array.prototype.normalize = function() {
let norm = this.norm();
return this.map(($) => $ / norm);
};
// src/metrics.ts
var tileCount;
var tileSize;
var charWidth;
var { style } = document.documentElement;
var RCtor;
var resizeTimeout;
function onResized() {
measure();
window.dispatchEvent(new CustomEvent("metrics-change"));
}
function onResize() {
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(onResized, 100);
}
function measure() {
let realTileCount = [tileCount[0], tileCount[1] + 5];
tileSize = RCtor.computeTileSize(realTileCount, [window.innerWidth, window.innerHeight], [0.7, 1]);
style.setProperty("--tile-width", `${tileSize[0]}px`);
style.setProperty("--tile-height", `${tileSize[1]}px`);
charWidth = measureCharWidth();
style.setProperty("--char-width", `${charWidth}px`);
}
async function init(tc, R) {
tileCount = tc;
RCtor = R;
style.setProperty("--map-width", String(tileCount[0]));
style.setProperty("--map-height", String(tileCount[1]));
document.fonts.forEach((f) => f.load());
await document.fonts.ready;
measure();
window.addEventListener("resize", onResize);
}
function measureCharWidth() {
let span = document.createElement("span");
span.style.fontSize = "var(--tile-height)";
span.textContent = "P";
document.body.append(span);
let rect = span.getBoundingClientRect();
span.remove();
return rect.width;
}
// src/sfx.ts
var DB = {
"zombie-spawn": 8,
"rake": 3,
"crowbar": 3,
"swoosh": 3,
"barrier": 3,
"wire": 3,
"fence": 2,
"bazooka": 1,
"mine": 1,
"game-over": 1,
"ping": 1,
"ow": 1
};
var audio = {};
function init2() {
Object.entries(DB).forEach(([key, count]) => {
let list = [];
for (let i = 1; i <= count; i++) {
let a = new Audio(`sfx/${key}-${i}.mp3`);
a.load();
list.push(a);
}
audio[key] = list;
});
}
function play(what) {
let a = audio[what];
a && a.random().play();
}
// src/entity.ts
var Entity = class {
constructor(map) {
this.map = map;
}
_position;
_hp = 1;
get name() {
return "";
}
get position() {
return this._position;
}
set position(position) {
this._position = position;
this.map.changed(this);
}
damage(source) {
this._hp -= 1;
if (this._hp == 0) {
this.die(source);
}
}
};
// src/keyboard.ts
async function readKey() {
let ac = new AbortController();
let { signal } = ac;
return new Promise((resolve) => {
function onKeyDown(e) {
ac.abort();
resolve(e);
}
window.addEventListener("keydown", onKeyDown, { signal });
});
}
// src/log.ts
var node = document.querySelector("#log");
var shown = [];
var pending = [];
function add(str) {
let span = document.createElement("span");
span.innerHTML = str + " ";
let length = str.length + 1;
pending.push({ node: span, length });
showPending();
}
async function flush() {
while (pending.length > 0) {
await waitForMore();
while (shown.length > 0) {
shown.shift().node.remove();
}
showPending();
}
}
function clear() {
node.replaceChildren();
shown = [];
pending = [];
}
function showPending() {
let limit = tileCount[0] * 2 - 15;
let shownLength = shown.reduce((acc, h) => acc + h.length, 0);
while (pending.length > 0) {
let first = pending[0];
if (shownLength + first.length > limit) {
break;
}
node.append(first.node);
shownLength += first.length;
shown.push(pending.shift());
}
}
async function waitForMore() {
let more = document.createElement("span");
let kbd = document.createElement("kbd");
kbd.textContent = "space";
more.append("...", kbd);
node.append(more);
while (true) {
let key = await readKey();
if (key.code == "Space") {
break;
}
}
more.remove();
}
// src/items/item.ts
var Item = class extends Entity {
static Name = "";
static description = "";
get blocksMovement() {
return false;
}
get isDestructible() {
return true;
}
get blocksBazooka() {
return this.blocksMovement;
}
get name() {
return this.constructor.Name;
}
die(source) {
this.map.removeItem(this);
}
activate(being) {
}
// stepped on something
use(position, direction) {
const { map } = this;
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
let being = map.getBeing(tx, ty);
let item = map.getItem(tx, ty);
if (being) {
add(`Cannot use ${this.name}: ${being.name.article()} is standing there!`);
return false;
}
if (item) {
if (item.blocksMovement) {
add(`Cannot use ${this.name}: ${item.name.article()} is standing there!`);
return false;
} else if (item instanceof Corpse) {
map.removeItem(item);
return true;
} else {
add(`Cannot use ${this.name}: ${item.name.article()} is lying there!`);
return false;
}
}
return true;
}
};
// src/items/corpse.ts
var Corpse = class extends Item {
visual = { ch: "%", fg: "" };
_name;
constructor(map, being) {
super(map);
this.visual.fg = being.visual.fg || "";
this._position = being.position;
this._name = `${being.name} corpse`;
}
get name() {
return this._name;
}
};
// src/beings/being.ts
var Being = class extends Entity {
die(source) {
const { map, position } = this;
map.removeBeing(this);
let valid = map.isPositionValid(position[0], position[1]);
let existing = map.getItem(position[0], position[1]);
if (valid && !existing) {
let corpse = new Corpse(map, this);
map.addItem(corpse);
}
}
};
// src/colors.ts
var WOOD = ["#c90", "#850", "#300"];
var WATER = "#006";
var WAVE = ["#05f", "#28f", "#6cf"];
var TREE = [WOOD[0], WOOD[1], "#181"];
var FENCE = ["#c0c", "#a0a", "#909"];
var METAL = "gray";
var WINDOW = "dodgerblue";
var ZOMBIE = ["DarkOliveGreen", "LightSlateGray", "Olive", "OliveDrab", "SaddleBrown", "GoldenRod", "DarkSeaGreen"];
var DOT = "#222";
var ROAD = "saddlebrown";
var SHOCK = FENCE[0];
// src/items/trap.ts
var Trap = class extends Item {
static Name = "bear trap";
static description = "Kills several zombies dumb enough to step on it.";
visual = { ch: "0", fg: METAL };
_hp = 3;
use(position, direction) {
let ok = super.use(position, direction);
if (!ok) {
return false;
}
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
this._position = [tx, ty];
this.map.addItem(this);
add("You set up a bear trap.");
return true;
}
activate(being) {
play("rake");
this.damage(being);
being.damage(this);
}
};
// src/items/barrier.ts
var COLORS = ["", ...WOOD.slice().reverse()];
var Barrier = class extends Item {
static Name = "wooden barrier";
static description = "Can hold them for some time.";
_hp = COLORS.length - 1;
visual = { ch: "#", fg: COLORS[COLORS.length - 1] };
get blocksMovement() {
return true;
}
damage(source) {
play("barrier");
super.damage(source);
if (this._hp > 0) {
this.visual.fg = COLORS[this._hp];
this.map.changed(this);
}
}
use(position, direction) {
let ok = super.use(position, direction);
if (!ok) {
return false;
}
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
this._position = [tx, ty];
this.map.addItem(this);
add("You build a barrier.");
return true;
}
};
// src/items/rake.ts
var Rake = class extends Item {
static Name = "rake";
static description = "Kills one zombie dumb enough to step on it.";
visual = { ch: "T", fg: WOOD[1] };
use(position, direction) {
let ok = super.use(position, direction);
if (!ok) {
return false;
}
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
this._position = [tx, ty];
this.map.addItem(this);
add("You set up a rake.");
return true;
}
activate(being) {
play("rake");
this.map.removeItem(this);
being.damage(this);
}
};
// src/dirs.ts
var dirs_default = [
[0, -1],
[1, -1],
[1, 0],
[1, 1],
[0, 1],
[-1, 1],
[-1, 0],
[-1, -1]
];
var CHARS = ["|", "/", "-", "\\", "|", "/", "-", "\\"];
// src/beings/zombie.ts
var CHARS2 = ["z", "Z"];
var Zombie = class extends Being {
constructor(map, zombies) {
super(map);
this.zombies = zombies;
if (Math.random() < 1e-3) {
this._name = "zombie lutefisk";
} else {
this._name = this.visual.ch == "z" ? "zombie" : "large zombie";
}
}
visual = { ch: CHARS2.random(), fg: ZOMBIE.random() };
_name;
get name() {
return this._name;
}
async play(player) {
const { position } = this;
let results = dirs_default.map((dir) => {
let x = position[0] + dir[0];
let y = position[1] + dir[1];
return this.getMovementResult(x, y, player);
});
let best = pickBestMovementResult(results);
if (!best) {
return;
}
switch (best.type) {
case "player":
player.damage(this);
break;
case "item":
best.item.damage(this);
break;
case "move":
this.position = best.position;
if (best.item) {
await best.item.activate(this);
}
break;
}
}
die(source) {
super.die(source);
this.zombies.remove(this);
}
getMovementResult(x, y, player) {
const { map, position } = this;
if (!map.isPositionValid(x, y)) {
return { type: "invalid" };
}
let being = map.getBeing(x, y);
if (being) {
let type = being == player ? "player" : "invalid";
return { type };
}
let currentDistance = player.position.distance(position);
let dist = player.position.distance([x, y]);
if (dist > currentDistance) {
return { type: "invalid" };
}
let item = map.getItem(x, y);
if (item) {
if (item.blocksMovement) {
if (item.isDestructible) {
return { type: "item", dist, item };
} else {
return { type: "invalid" };
}
} else {
return { type: "move", dist, position: [x, y], item };
}
} else {
return { type: "move", dist, position: [x, y] };
}
}
};
function pickBestMovementResult(results) {
let valid = results.filter((r) => r.type != "invalid");
if (!valid.length) {
return null;
}
let player = valid.find((r) => r.type == "player");
if (player) {
return player;
}
let moves = valid.filter((r) => r.type == "move");
if (moves.length > 0) {
return pickBestDistanceResult(moves);
}
let items = valid.filter((r) => r.type == "item");
return pickBestDistanceResult(items);
}
function pickBestDistanceResult(results) {
let distances = results.map((r) => r.dist);
let best = Math.min(...distances);
return results.filter((r) => r.dist == best).random();
}
// src/explosion.ts
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function gatherPositions(map, center, r) {
let positions = [];
for (let i = center[0] - r; i <= center[0] + r; i++) {
for (let j = center[1] - r; j <= center[1] + r; j++) {
let verticalEdge = Math.abs(i - center[0]) == r;
let horizontalEdge = Math.abs(j - center[1]) == r;
if (verticalEdge && horizontalEdge) {
continue;
}
if (!map.isPositionValid(i, j)) {
continue;
}
positions.push([i, j]);
}
}
return positions;
}
function extractZombies(positions, map) {
let zombies = [];
positions.forEach((pos) => {
let being = map.getBeing(pos[0], pos[1]);
if (being instanceof Zombie) {
zombies.push(being);
}
});
return zombies;
}
function drawExplosions(map, positions, fraction) {
let amount = Math.round(3 * 255 * (1 - fraction));
let r = Math.max(0, Math.min(amount - 0 * 255, 255));
let g = Math.max(0, Math.min(amount - 1 * 255, 255));
let b = Math.max(0, Math.min(amount - 2 * 255, 255));
let fg = `rgb(${r} ${g} ${b})`;
let visual = { ch: "*", fg };
positions.forEach((pos) => map.setFX(pos[0], pos[1], visual));
}
async function explode(map, center, radius, source) {
let positions = gatherPositions(map, center, radius);
let zombies = extractZombies(positions, map);
const DIST = 10;
zombies.forEach((z) => {
let expCenter = z.position.distance(center) == 0 ? source.position : center;
let dx = z.position[0] - expCenter[0];
let dy = z.position[1] - expCenter[1];
if (dx == 0 && dy == 0) {
return;
}
let vec = [dx, dy].normalize();
let pos = [z.position[0] + vec[0] * DIST, z.position[1] + vec[1] * DIST];
z.position = [Math.round(pos[0]), Math.round(pos[1])];
});
positions.forEach((pos) => {
let item = map.getItem(pos[0], pos[1]);
if (item instanceof Corpse) {
map.removeItem(item);
}
});
let duration = 400;
let step = 30;
for (let i = 0; i < duration; i += step) {
drawExplosions(map, positions, i / duration);
await sleep(step);
}
positions.forEach((pos) => map.setFX(pos[0], pos[1], null));
zombies.forEach((z) => z.damage(source));
}
// src/items/mine.ts
var Mine = class extends Item {
static Name = "mine";
static description = "Explodes when stepped on by a zombie.";
visual = { ch: "+", fg: METAL };
use(position, direction) {
let ok = super.use(position, direction);
if (!ok) {
return false;
}
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
this._position = [tx, ty];
this.map.addItem(this);
add("You set up a mine.");
return true;
}
async activate(being) {
const { map, position } = this;
map.removeItem(this);
play("mine");
await explode(map, position, 3, this);
}
};
// src/items/bazooka.ts
var Bazooka = class extends Item {
visual = { ch: "*", fg: "yellow" };
static Name = "bazooka";
static description = "Flies in a straight line, explodes on impact.";
async use(position, direction) {
const { map, visual } = this;
this._position = position;
play("swoosh");
add("You launch a rocket...");
let { target, distance } = getTarget(map, position, direction);
let hitPlayed = false;
let [x, y] = position;
for (let i = 0; i < distance; i++) {
x += direction[0];
y += direction[1];
if (target && !hitPlayed && distance - i < 10) {
play("bazooka");
hitPlayed = true;
}
map.setFX(x, y, visual);
await sleep2(50);
map.setFX(x, y, null);
}
if (target) {
add(`${target.name.article()} is hit!`);
await explode(map, [x, y], 2, this);
} else {
add("it flies away.");
}
return true;
}
};
function getTarget(map, position, direction) {
let [x, y] = position;
let distance = 0;
while (true) {
x += direction[0];
y += direction[1];
if (!map.isPositionValid(x, y)) {
return { target: null, distance };
}
distance++;
let being = map.getBeing(x, y);
if (being) {
return { target: being, distance };
}
let item = map.getItem(x, y);
if (item && item.blocksBazooka) {
return { target: item, distance };
}
}
}
function sleep2(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// src/items/wire.ts
var CONNECTION_DISTANCE = 3;
var Wire = class extends Item {
static Name = "barbed wire fence";
static description = "Auto-connects to nearby wires (up to 3 blocks away). Has little health.";
visual = { ch: "*", fg: METAL };
sound = "wire";
activate(being) {
play(this.sound);
this.damage(being);
being.damage(this);
}
use(position, direction) {
let ok = super.use(position, direction);
if (!ok) {
return false;
}
const { map } = this;
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
this._position = [tx, ty];
map.addItem(this);
let Ctor = this.constructor;
dirs_default.forEach((dir, i) => {
tryConnection([tx, ty], i, map, Ctor);
});
add(`You build ${this.name.article()} segment.`);
return true;
}
};
function tryConnection(position, directionIndex, map, Ctor) {
let amount = 0;
let direction = dirs_default[directionIndex];
let ch = CHARS[directionIndex];
for (let i = 1; i <= CONNECTION_DISTANCE; i++) {
let x = position[0] + i * direction[0];
let y = position[1] + i * direction[1];
let being = map.getBeing(x, y);
let item = map.getItem(x, y);
if (being && !(being instanceof Player)) {
break;
}
if (item) {
if (item instanceof Corpse) {
continue;
}
if (item instanceof Ctor) {
amount = i - 1;
}
break;
}
}
for (let i = 1; i <= amount; i++) {
let x = position[0] + i * direction[0];
let y = position[1] + i * direction[1];
let corpse = map.getItem(x, y);
corpse && map.removeItem(corpse);
let item = new Ctor(map);
item.visual.ch = ch;
item.position = [x, y];
map.addItem(item);
}
}
// src/items/fence.ts
var COLORS2 = ["", ...FENCE.slice().reverse()];
var Fence = class extends Wire {
static Name = "electric fence";
static description = "Auto-connects to nearby fences (up to 3 blocks away). Has more health.";
_hp = COLORS2.length - 1;
visual = { ch: "*", fg: COLORS2[this._hp] };
sound = "fence";
damage(source) {
super.damage(source);
if (this._hp > 0) {
this.visual.fg = COLORS2[this._hp];
this.map.changed(this);
}
}
};
// src/items/shock.ts
var Shock = class extends Item {
visual = {};
static Name = "electric shock";
static description = "Electrocutes a nearby zombie, jumps to neighboring zombies.";
async use(position, direction) {
const { map } = this;
let tx = position[0] + direction[0];
let ty = position[1] + direction[1];
let being = map.getBeing(tx, ty);
if (!(being instanceof Zombie)) {
add(`Cannot use ${this.name}: there is no zombie in that direction!`);
return false;
}
await useAtBeing(map, being, this);
return true;
}
};
async function useAtBeing(map, being, source) {
play("fence");
add("You electrocute a zombie...");
let processed = [];
let queue = [being];
while (queue.length > 0) {
let being2 = queue.shift();
const { visual, position } = being2;
visual.fg = SHOCK;
map.changed(being2);
await sleep3(50);
being2.damage(source);
processed.push(being2);
dirs_default.forEach((dir) => {
let being3 = map.getBeing(position[0] + dir[0], position[1] + dir[1]);
if (!being3) {
return;
}
if (!(being3 instanceof Zombie)) {
return;
}
if (queue.includes(being3) || processed.includes(being3)) {
return;
}
queue.push(being3);
});
}
}
function sleep3(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// src/items/db.ts
var ITEMS = [{
id: "barrier",
short: "barrier",
key: "1",
price: 1,
amount: 5,
ctor: Barrier
}, {
id: "rake",
key: "2",
price: 1,
amount: 3,
ctor: Rake
}, {
id: "trap",
short: "trap",
key: "3",
price: 2,
amount: 3,
ctor: Trap
}, {
id: "mine",
key: "4",
price: 3,
amount: 3,
ctor: Mine
}, {
id: "shock",
short: "shock",
key: "5",
price: 4,
amount: 2,
ctor: Shock
}, {
id: "bazooka",
key: "6",
price: 5,
amount: 1,
ctor: Bazooka
}, {
id: "wire",
short: "wire",
key: "7",
price: 2,
amount: 2,
ctor: Wire
}, {
id: "fence",
short: "fence",
key: "8",
price: 3,
amount: 2,
ctor: Fence
}];
// src/dialogs/dialog.ts
var Dialog = class {
dialog = document.createElement("dialog");
resolve;
keys = [];
constructor(title) {
let h2 = document.createElement("h2");
h2.textContent = title;
this.append(h2);
}
append(...nodes) {
this.dialog.append(...nodes);
}
async show() {
const { dialog } = this;
document.body.append(dialog);
dialog.showModal();
document.activeElement && document.activeElement.blur();
while (true) {
let event = await readKey();
if (event.key == "Escape") {
event.preventDefault();
}
let id = this.matchKeyEvent(event);
if (id !== null) {
dialog.close();
dialog.remove();
return id;
}
}
}
addKey(key) {
this.keys.push(key);
}
matchKeyEvent(event) {
let key = this.keys.find((key2) => {
if ("key" in key2 && key2.key != event.key) {
return false;
}
if ("code" in key2 && key2.code != event.code) {
return false;
}
return true;
});
return key ? key.id : null;
}
};
// src/dialogs/start.ts
async function start() {
let dialog = new Dialog("Start the zombie invasion?");
dialog.addKey({ id: "", key: "Escape" });
dialog.addKey({ id: "ok", code: "Space" });
let info = document.createElement("p");
info.innerHTML = HTML;
dialog.append(info);
let result = await dialog.show();
return result == "ok";
}
var HTML = `
If you want to start the zombie invasion, press <kbd>space</kbd>.
Zombies will slowly start spawning and wandering around. (Item shop is still available in non-sandbox game modes).
<br/><br/>
Press <kbd>esc</kbd> to return back to preparations.
`;
// src/beings/player.ts
var MAX_HP = 3;
var Player = class extends Being {
constructor(level) {
super(level.map);
this.level = level;
this._money = level.initialMoney;
}
visual = { ch: "@", fg: "red" };
_hp = MAX_HP;
_money;
items = new window.Map();
get hp() {
return this._hp;
}
async play() {
while (true) {
let key = await readKey();
let acted = await this.processKey(key);
if (acted) {
break;
}
}
}
getItem(id) {
return this.items.get(id) || 0;
}
setItem(id, amount) {
this.items.set(id, amount);
this.level.updateStatus();
}
get money() {
return this._money;
}
set money(money) {
this._money = money;
this.level.updateStatus();
}
async processKey(key) {
const { level } = this;
clear();
if (isIdle(key)) {
return true;
}
if (key.code in MOVEMENT) {
let diff = MOVEMENT[key.code];
return this.moveBy(...diff);
}
if (key.code.startsWith("Digit")) {
let num = key.code.match(/\d/);
return num ? this.tryItem(num[0]) : false;
}
if (key.code == "KeyI" && level.isAllowed("shop")) {
await level.shop();
return false;
}
if (key.code == "KeyS" && level.isAllowed("start")) {
let result = await start();
if (result) {
level.start();
return true;
} else {
return false;
}
}
if (key.key == "?") {
await level.help();
return false;
}
return false;
}
moveBy(dx, dy) {
const { position, map } = this;
let x = position[0] + dx;
let y = position[1] + dy;
if (!map.isPositionValid(x, y)) {
return false;
}
let being = map.getBeing(x, y);
if (being) {
play("crowbar");
add(`You hit the ${being.name}.`);
being.damage(this);
return true;
}
let item = map.getItem(x, y);
if (item) {
if (item.blocksMovement) {
add(`${item.name.article().capitalize()} blocks the way.`);
return false;
} else {
add(`${item.name.article().capitalize()} is here.`);
}
}
this.position = [x, y];
return true;
}
async tryItem(num) {
let it = ITEMS.find((it2) => it2.key == num);
if (!it) {
return false;
}
let name = it.ctor.Name;
let amount = this.getItem(it.id);
if (!amount) {
add(`You don't have any ${name}s.`);
return false;
}
let direction = await waitForDirection(`Use ${name.article()}`);
if (!direction) {