Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
2554 lines (2424 loc) · 99.7 KB
/
Copy pathgame.js
File metadata and controls
2554 lines (2424 loc) · 99.7 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
(() => {
const { BGM_PATH, ENEMY_BEHAVIORS, TAU } = globalThis.CellConstants;
const { angleDelta, clamp, dist2, isOutsideRect, rand } = globalThis.CellUtils;
const { createRuntimeConfig } = globalThis.CellPlatform;
const { SpatialHash } = globalThis.CellSpatial;
const { acquire, release } = globalThis.CellObjectPool;
const { countEffects, resetParticle } = globalThis.CellParticleSystem;
const { applyEnemyBehavior } = globalThis.CellEnemyBehaviors;
const { activeMutationCount, readMemoryUsage } = globalThis.CellDebug;
const { applyMutationLabel } = globalThis.CellMutationRegistry;
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const hpBar = document.getElementById("hpBar");
const xpBar = document.getElementById("xpBar");
const levelText = document.getElementById("levelText");
const timeText = document.getElementById("timeText");
const statPanel = document.getElementById("statPanel");
const startPanel = document.getElementById("startPanel");
const startButton = document.getElementById("startButton");
const difficultyButtons = Array.from(document.querySelectorAll("[data-difficulty]"));
const pausePanel = document.getElementById("pausePanel");
const resumeButton = document.getElementById("resumeButton");
const mutationPanel = document.getElementById("mutationPanel");
const choiceGrid = document.getElementById("choiceGrid");
const mutationTitle = document.getElementById("mutationTitle");
const gameOverPanel = document.getElementById("gameOverPanel");
const restartButton = document.getElementById("restartButton");
const overStats = document.getElementById("overStats");
const overTitle = document.getElementById("overTitle");
const painFlash = document.getElementById("painFlash");
const evolutionBanner = document.getElementById("evolutionBanner");
const evolutionText = document.getElementById("evolutionText");
const runtimeConfig = createRuntimeConfig();
const quality = runtimeConfig.quality;
const MAX_ENEMIES = quality.maxEnemies;
const MAX_PARTICLES = quality.maxParticles;
const MAX_PROJECTILES = quality.maxProjectiles;
const enemyGrid = new SpatialHash(quality.spatialCellSize);
let width = 0;
let height = 0;
let dpr = 1;
let last = 0;
let state = "start";
let shake = 0;
let pulse = 0;
let runTime = 0;
let spawnTimer = 0;
let bossTimer = 38;
let mobilePointer = null;
let choices = [];
let audio = null;
let bgm = null;
let hitStop = 0;
let playerHurt = 0;
let screenPulse = 0;
let lastContactHit = 0;
let bannerTimer = 0;
let finalPhase = false;
let finalBossSpawned = false;
let enemyFortifyPulse = 0;
let lastStatsSignature = "";
let mutationLockTimer = 0;
let swarmAngle = 0;
let activeDifficulty = "easy";
const keys = new Set();
const enemies = [];
const particles = [];
const projectiles = [];
const perf = {
fps: 60,
drawCalls: 0,
spatialCandidates: 0,
};
const scratchEnemies = [];
const cullRect = { left: 0, right: 0, top: 0, bottom: 0 };
const viewRect = { left: 0, right: 0, top: 0, bottom: 0 };
const enemyProjectileHit = { kind: "phage", x: 0, y: 0 };
const pools = { enemies: [], particles: [], projectiles: [] };
const perfGuard = {
effectScale: 1,
trailLimit: 9,
hpBarStride: 1,
shadowScale: 1,
gridSkip: false,
particleDrawStride: 1,
bodyStep: 1,
enemySoftCap: MAX_ENEMIES,
textCooldown: 0,
};
const balance = {
window: 5,
damageTotal: 0,
healTotal: 0,
bucketStep: 0.5,
bucketCursor: -1,
damageBuckets: new Array(10).fill(0),
healBuckets: new Array(10).fill(0),
playerDps: 0,
playerHps: 0,
avgEnemyHp: 0,
avgEnemyDamage: 0,
avgTtk: 0,
wave: 1,
};
const difficultyDefs = {
easy: { hp: 1.32, damage: 1.08, speed: 1.03, spawn: 1.08, cap: 1.04, name: "EASY" },
normal: { hp: 1.62, damage: 1.22, speed: 1.08, spawn: 1.22, cap: 1.1, name: "NORMAL" },
hard: { hp: 2.05, damage: 1.42, speed: 1.15, spawn: 1.42, cap: 1.2, name: "HARD" },
};
const mutationIcons = {
tentacles: "🦑",
acid: "🧪",
electric: "⚡",
spores: "🫧",
eyes: "👁️",
shell: "🛡️",
splitting: "🧫",
absorption: "🩸",
slime: "💧",
dash: "💨",
acceleration: "🦵",
evolutionUpgrade: "✴️",
};
const session = {
tutorialMarks: [5, 10, 15],
tutorialIndex: 0,
finalPhaseAt: 900,
nextWaveAt: 180,
waveIndex: 0,
};
const camera = {
x: 0,
y: 0,
scale: 1,
targetScale: 1,
worldWidth: 0,
worldHeight: 0,
};
const player = {
x: 0,
y: 0,
vx: 0,
vy: 0,
radius: 22,
hp: 100,
maxHp: 100,
xp: 0,
nextXp: 16,
level: 1,
kills: 0,
speed: 260,
acceleration: 10,
accelStack: 0,
armor: 0,
regen: 0,
absorption: 0,
attackSpeed: 1,
bite: 1,
tentacles: 0,
acid: 0,
electric: 0,
spores: 0,
eyes: 0,
shell: 0,
splitting: 0,
dash: 0,
slime: 0,
evolutionLevel: 0,
evolution: "",
evolutionName: "",
evolutions: {},
mutationPulse: 0,
cooldowns: {
bite: 0,
lash: 0,
acid: 0,
spark: 0,
spore: 0,
split: 0,
shell: 0,
dash: 0,
toxin: 0,
},
trail: [],
};
const cooldownKeys = Object.keys(player.cooldowns);
const MAX_STACK = 5;
const EVOLUTION_STACK = 4;
const PLAYER_DEATH_HP = 0.5;
const PLAYER_DAMAGE_SCALE = 0.76;
const evolutionDefs = [
{ id: "electricTentacles", name: "전기 촉수 군체", needs: ["tentacles", "electric"], hint: "촉수 + 감전" },
{ id: "toxicHive", name: "독성 군락체", needs: ["acid", "spores"], hint: "산성 + 포자" },
{ id: "immortalMass", name: "불멸 생체질량", needs: ["regen", "shell"], hint: "재생 + 외골격" },
{ id: "swarmOrganism", name: "분열 포식군", needs: ["splitting", "absorption"], hint: "분열 + 흡수" },
];
const mutations = [
{ id: "tentacles", name: "촉수 증식", type: "공격 장기", tag: "촉수 +1, 근접 자동공격", desc: "살덩이에서 붙잡는 촉수가 자라 근처 먹이를 후려친다.", path: "감전 기관과 결합하면 전기 촉수 군체", apply: () => player.tentacles = Math.min(MAX_STACK, player.tentacles + 1) },
{ id: "acid", name: "산성 주머니", type: "공격 장기", tag: "산성 산탄 +1", desc: "부식성 체액을 부채꼴로 뿜어 적을 녹인다.", path: "포자낭과 결합하면 독성 군락체", apply: () => player.acid = Math.min(MAX_STACK, player.acid + 1) },
{ id: "electric", name: "감전 기관", type: "공격 장기", tag: "전기 연쇄 +1, 범위 피해", desc: "노출된 신경 다발이 주변 생체를 태우는 전류를 방출한다.", path: "촉수와 결합하면 전기 촉수 군체", apply: () => player.electric = Math.min(MAX_STACK, player.electric + 1) },
{ id: "spores", name: "산성 포자낭", type: "공격 장기", tag: "포자 +1, 사방 발사", desc: "맥동하는 혹에서 기생 포자가 흘러나와 사방으로 번진다.", path: "산성 주머니와 결합하면 독성 군락체", apply: () => player.spores = Math.min(MAX_STACK, player.spores + 1) },
{ id: "eyes", name: "다중 안구", type: "감각 장기", tag: "공격 속도 +14%", desc: "눈이 더 열린다. 먹이를 더 빨리 찾고 더 자주 공격한다.", path: "모든 공격 변이를 선명하게 보조", apply: () => { player.eyes = Math.min(MAX_STACK, player.eyes + 1); player.attackSpeed += 0.14; } },
{ id: "regen", name: "재생 육질", type: "방어 장기", tag: "초당 회복 +1, 최대 체력 +8", desc: "찢긴 살이 스스로 기어 붙어 상처를 메운다.", path: "외골격과 결합하면 불멸 생체질량", apply: () => { player.regen = Math.min(MAX_STACK, player.regen + 1); player.maxHp += 8; player.hp += 8; } },
{ id: "shell", name: "외골격 형성", type: "방어 장기", tag: "피해 감소 +7%, 최대 체력 +12", desc: "뼈 같은 판이 살갗을 뚫고 올라와 충격을 분산한다.", path: "재생 육질과 결합하면 불멸 생체질량", apply: () => { player.shell = Math.min(MAX_STACK, player.shell + 1); player.armor += 0.07; player.maxHp += 12; player.hp += 12; } },
{ id: "splitting", name: "분열 세포", type: "방어 장기", tag: "분열 공격 +1", desc: "작은 살점들이 떨어져 나와 추격자를 물어뜯는다.", path: "흡수구와 결합하면 분열 포식군", apply: () => player.splitting = Math.min(MAX_STACK, player.splitting + 1) },
{ id: "absorption", name: "흡수구 개방", type: "방어 장기", tag: "흡수 회복 +2.5, XP +8%", desc: "새로운 입이 열려 죽은 조직의 열과 질량을 빨아들인다.", path: "분열 세포와 결합하면 분열 포식군", apply: () => player.absorption = Math.min(MAX_STACK, player.absorption + 1) },
{ id: "dash", name: "경련성 돌진", type: "이동 변이", tag: "자동 돌진 +1, 쿨다운 감소", desc: "근육이 비정상적으로 수축해 젖은 잔상을 남기며 튄다.", path: "이동 생존력 강화", apply: () => player.dash = Math.min(MAX_STACK, player.dash + 1) },
{ id: "slime", name: "점액 흔적", type: "이동 변이", tag: "장판 둔화 + 피해", desc: "뒤틀린 점액이 바닥에 남아 추격자를 늦추고 녹인다.", path: "후반 압박을 늦추는 오염 지대", apply: () => player.slime = Math.min(MAX_STACK, player.slime + 1) },
{ id: "acceleration", name: "경련 근섬유", type: "이동 변이", tag: "이동 속도 +22, 가속 +1.8", desc: "움직임이 인간적인 방향성을 잃고 더 갑작스러워진다.", path: "기동성 강화", apply: () => { player.accelStack = Math.min(MAX_STACK, player.accelStack + 1); player.acceleration += 1.8; player.speed += 22; } },
];
const evolutionLabels = {
electricTentacles: { name: "전기 촉수 군체", hint: "촉수 + 감전" },
toxicHive: { name: "산성 포자 군체", hint: "산성 + 포자" },
immortalMass: { name: "불멸 생체질량", hint: "재생 + 껍질" },
swarmOrganism: { name: "분열 사식군", hint: "분열 + 흡수" },
};
const evolutionUpgradeLabels = {
electricTentacles: ["전류 분기", "번개가 더 많은 적에게 갈라집니다."],
toxicHive: ["독성 배양", "독 장판이 더 넓고 오래 남습니다."],
immortalMass: ["불멸 파동", "생체 파동 피해와 밀어내기가 강화됩니다."],
swarmOrganism: ["분열 회전", "회전 투사체 발사량과 피해가 증가합니다."],
};
const mutationLabels = {
tentacles: {
name: "촉수 증식",
type: "공격 변이",
tag: "촉수 +1, 근접 자동공격",
desc: "등 뒤에서 붉은 촉수가 자라 근처 먹이를 휘감습니다.",
path: "감전 기관과 결합하면 전기 촉수 군체",
},
acid: {
name: "산성 주머니",
type: "공격 변이",
tag: "산성 산탄 +1",
desc: "부식성 체액을 부채꼴 산탄으로 뿜어 적을 녹입니다.",
path: "포자낭과 결합하면 산성 포자 군체",
},
electric: {
name: "감전 기관",
type: "공격 변이",
tag: "전기 연쇄 +1, 범위 피해",
desc: "노출된 신경 다발이 주변 생체를 태우는 전류를 방출합니다.",
path: "촉수와 결합하면 전기 촉수 군체",
},
spores: {
name: "산성 포자낭",
type: "공격 변이",
tag: "포자 +1, 산탄 발사",
desc: "맥동하는 낭에서 기생 포자가 흘러나와 사방으로 번집니다.",
path: "산성 주머니와 결합하면 산성 포자 군체",
},
eyes: {
name: "다중 안구",
type: "감각 변이",
tag: "공격 속도 +14%",
desc: "여러 눈이 먹이를 더 빨리 찾아내고 더 자주 공격합니다.",
path: "모든 공격 변이를 선명하게 보조",
},
regen: {
name: "재생 점막",
type: "방어 변이",
tag: "초당 회복 +1, 최대 체력 +8",
desc: "찢긴 살이 스스로 기어 붙어 상처를 메웁니다.",
path: "껍질 형성과 결합하면 불멸 생체질량",
},
shell: {
name: "껍질 형성",
type: "방어 변이",
tag: "피해 감소 +7%, 최대 체력 +12",
desc: "뼈 같은 막이 두껍게 닫히며 충격을 분산합니다.",
path: "재생 점막과 결합하면 불멸 생체질량",
},
splitting: {
name: "분열 세포",
type: "방어 변이",
tag: "분열 공격 +1",
desc: "작은 세포들이 떨어져 나가 추격자를 물어뜯습니다.",
path: "흡수구 개방과 결합하면 분열 사식군",
},
absorption: {
name: "흡수구 개방",
type: "방어 변이",
tag: "흡수 회복 +2.5, XP +8%",
desc: "새로운 입이 열려 죽은 조직의 피와 질량을 빨아들입니다.",
path: "분열 세포와 결합하면 분열 사식군",
},
dash: {
name: "경련성 돌진",
type: "이동 변이",
tag: "자동 돌진 +1, 쿨다운 감소",
desc: "근육이 비정상적으로 수축해 위기 순간 몸을 튕겨냅니다.",
path: "이동 생존력 강화",
},
slime: {
name: "점액 흔적",
type: "이동 변이",
tag: "늪판 둔화 + 피해",
desc: "끈적한 점액이 바닥에 남아 추격자를 늦추고 녹입니다.",
path: "전장 장악과 추격 저지",
},
acceleration: {
name: "경련 근섬유",
type: "이동 변이",
tag: "이동 속도 +22, 가속 +1.8",
desc: "움직임이 순간적인 방향성을 얻고 갑작스럽게 돌진합니다.",
path: "기동력 강화",
},
};
evolutionDefs.forEach((evo) => Object.assign(evo, evolutionLabels[evo.id]));
mutations.forEach((mutation) => applyMutationLabel(mutation, mutationLabels));
const enemyTypes = {
cell: { hp: 10, speed: 64, radius: 12, damage: 7, xp: 2, color: "#d12d55", behavior: ENEMY_BEHAVIORS.CHASER },
parasite: { hp: 7, speed: 128, radius: 8, damage: 5, xp: 2, color: "#8fffd3", behavior: ENEMY_BEHAVIORS.DASHER },
toxic: { hp: 16, speed: 50, radius: 14, damage: 11, xp: 4, color: "#b6ff4b", behavior: ENEMY_BEHAVIORS.CHASER },
splitter: { hp: 22, speed: 48, radius: 16, damage: 9, xp: 5, color: "#ff7b3f", behavior: ENEMY_BEHAVIORS.CHASER },
giant: { hp: 112, speed: 34, radius: 34, damage: 18, xp: 20, color: "#ff245c", behavior: ENEMY_BEHAVIORS.CHASER },
tutorial: { hp: 18, speed: 36, radius: 15, damage: 0, xp: 7, color: "#d4fff0", behavior: ENEMY_BEHAVIORS.CHASER },
phage: { hp: 6200, speed: 28, radius: 86, damage: 42, xp: 420, color: "#d8f0ff", behavior: ENEMY_BEHAVIORS.RANGED },
};
function playerScaleFactor() {
return clamp(player.radius / 22, 1, 2.45);
}
function enemyProgressScale() {
return 1 + runTime / 390 + Math.max(0, runTime - 240) / 620 + Math.max(0, runTime - 720) / 1200;
}
function difficultyScale(key) {
return (difficultyDefs[activeDifficulty] || difficultyDefs.easy)[key] || 1;
}
function enemyCapDifficultyScale() {
return difficultyScale("hp");
}
function enemyCapDamageScale() {
return difficultyScale("damage");
}
function enemyCapSpeedScale() {
return difficultyScale("speed");
}
function fortifyExistingEnemies(strength = 1) {
if (finalPhase || !enemies.length) return;
const count = Math.min(enemies.length, Math.max(3, Math.floor(4 + strength * 4)));
for (let i = 0; i < count; i++) {
const enemy = enemies[(Math.floor(Math.random() * enemies.length) + i * 7) % enemies.length];
if (!enemy || enemy.kind === "tutorial" || enemy.kind === "phage") continue;
const hpGain = enemy.maxHp * (0.035 + strength * 0.012);
enemy.maxHp += hpGain;
enemy.hp += hpGain;
enemy.damage *= 1.015 + strength * 0.004;
enemy.speed *= 1.006 + strength * 0.002;
enemy.fortified = Math.min(3, (enemy.fortified || 0) + 1);
enemy.pulse = Math.max(enemy.pulse || 0, 1.2);
if (enemy.components && enemy.components.render) enemy.components.render.flash = 0.35;
}
enemyFortifyPulse = 1.4;
}
function xpMultiplier() {
return 1 + player.absorption * 0.08 + Math.min(1.2, Math.floor(runTime / 180) * 0.12);
}
function updatePerformanceGuard(dt) {
perfGuard.textCooldown = Math.max(0, perfGuard.textCooldown - dt);
const timePressure = clamp((runTime - 480) / 360, 0, 1);
const fpsPressure = clamp((60 - perf.fps) / 14, 0, 1);
const objectPressure = Math.max(particles.length / MAX_PARTICLES, projectiles.length / MAX_PROJECTILES);
const pressure = clamp(Math.max(timePressure * 0.7, fpsPressure, objectPressure - 0.55), 0, 1);
perfGuard.effectScale = clamp(1 - pressure * 0.84, runtimeConfig.mobile ? 0.12 : 0.2, 1);
perfGuard.trailLimit = pressure > 0.82 ? 0 : Math.max(1, Math.round(8 - pressure * 7));
perfGuard.hpBarStride = pressure > 0.78 ? 999 : pressure > 0.55 ? 5 : pressure > 0.3 ? 3 : enemies.length > 100 ? 2 : 1;
perfGuard.shadowScale = pressure > 0.55 ? 0 : clamp(1 - pressure * 1.6, 0.12, 1);
perfGuard.gridSkip = pressure > 0.35;
perfGuard.particleDrawStride = pressure > 0.78 ? 4 : pressure > 0.55 ? 3 : pressure > 0.3 ? 2 : 1;
perfGuard.bodyStep = pressure > 0.65 ? 3 : pressure > 0.35 ? 2 : 1;
perfGuard.enemySoftCap = Math.floor(MAX_ENEMIES * difficultyScale("cap") * clamp(1 - pressure * 0.28, 0.72, 1));
}
function enemySizeScale(kind) {
if (kind === "tutorial") return clamp(playerScaleFactor() * 0.92, 1, 1.8);
if (kind === "phage") return clamp(playerScaleFactor() * 1.12, 1, 2.2);
return clamp(0.78 + playerScaleFactor() * 0.38 + runTime / 1600, 1, 2.15);
}
function updateCamera(dt = 1) {
camera.targetScale = clamp(1 / (1 + Math.max(0, player.radius - 22) / 92), 0.56, 1);
camera.scale += (camera.targetScale - camera.scale) * clamp(dt * 2.8, 0, 1);
camera.worldWidth = width / camera.scale;
camera.worldHeight = height / camera.scale;
camera.x += (player.x - camera.x) * clamp(dt * 2.6, 0, 1);
camera.y += (player.y - camera.y) * clamp(dt * 2.6, 0, 1);
}
function bioRange() {
const evolved = hasEvolution("electricTentacles");
return 130 + Math.max(player.tentacles, player.electric) * 32 + (evolved ? 70 : 0);
}
function tentacleRange() {
return bioRange();
}
function electricRange() {
return bioRange();
}
function screenToWorld(x, y) {
return {
x: camera.x + (x - width / 2) / camera.scale,
y: camera.y + (y - height / 2) / camera.scale,
};
}
function resize() {
dpr = Math.min(2, window.devicePixelRatio || 1);
width = window.innerWidth;
height = window.innerHeight;
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
player.x = player.x || width / 2;
player.y = player.y || height / 2;
camera.x = camera.x || player.x;
camera.y = camera.y || player.y;
updateCamera(1);
}
function reset() {
Object.assign(player, {
x: width / 2,
y: height / 2,
vx: 0,
vy: 0,
radius: 22,
hp: 100,
maxHp: 100,
xp: 0,
nextXp: 16,
level: 1,
kills: 0,
speed: 260,
acceleration: 10,
accelStack: 0,
armor: 0,
regen: 0,
absorption: 0,
attackSpeed: 1,
bite: 1,
tentacles: 0,
acid: 0,
electric: 0,
spores: 0,
eyes: 0,
shell: 0,
splitting: 0,
dash: 0,
slime: 0,
evolutionLevel: 0,
evolution: "",
evolutionName: "",
evolutions: {},
mutationPulse: 0,
cooldowns: { bite: 0, lash: 0, acid: 0, spark: 0, spore: 0, split: 0, shell: 0, dash: 0, toxin: 0 },
trail: [],
});
enemies.length = 0;
particles.length = 0;
projectiles.length = 0;
runTime = 0;
spawnTimer = 0;
bossTimer = 68;
finalPhase = false;
finalBossSpawned = false;
enemyFortifyPulse = 0;
mutationLockTimer = 0;
swarmAngle = 0;
lastStatsSignature = "";
balance.damageTotal = 0;
balance.healTotal = 0;
balance.bucketCursor = -1;
balance.damageBuckets.fill(0);
balance.healBuckets.fill(0);
balance.playerDps = 0;
balance.playerHps = 0;
balance.avgEnemyHp = 0;
balance.avgEnemyDamage = 0;
balance.avgTtk = 0;
balance.wave = 1;
session.tutorialIndex = 0;
session.nextWaveAt = 180;
session.waveIndex = 0;
camera.x = player.x;
camera.y = player.y;
camera.scale = 1;
camera.targetScale = 1;
shake = 0;
hitStop = 0;
playerHurt = 0;
screenPulse = 0;
lastContactHit = 0;
bannerTimer = 0;
evolutionBanner.classList.add("hidden");
pausePanel.classList.add("hidden");
}
function setDifficulty(id) {
activeDifficulty = difficultyDefs[id] ? id : "easy";
difficultyButtons.forEach((button) => {
button.classList.toggle("active", button.dataset.difficulty === activeDifficulty);
});
lastStatsSignature = "";
updateHud();
}
function startRun() {
initAudio();
reset();
state = "play";
startPanel.classList.add("hidden");
gameOverPanel.classList.add("hidden");
pausePanel.classList.add("hidden");
mutationPanel.classList.add("hidden");
for (let i = 0; i < Math.round(7 * difficultyScale("spawn")); i++) spawnEnemy("cell");
}
function getEnemy() {
return acquire(pools.enemies);
}
function freeEnemy(enemy) {
enemy.alive = false;
release(pools.enemies, enemy);
}
function getParticle() {
if (particles.length >= MAX_PARTICLES) {
return null;
}
return acquire(pools.particles);
}
function getProjectile() {
if (projectiles.length >= MAX_PROJECTILES) {
return null;
}
return acquire(pools.projectiles);
}
function recycleParticleAt(index) {
const p = particles.splice(index, 1)[0];
if (!p) return;
release(pools.particles, p, resetParticle);
}
function recycleProjectileAt(index) {
const p = projectiles.splice(index, 1)[0];
if (!p) return;
if (p.hitTargets) p.hitTargets.clear();
release(pools.projectiles, p);
}
function spawnEnemy(kind, options = {}) {
const type = enemyTypes[kind];
if (!type) return;
if (enemies.length >= perfGuard.enemySoftCap) {
fortifyExistingEnemies(kind === "giant" ? 0.8 : kind === "phage" ? 1.4 : 0.25);
return false;
}
const angle = Object.prototype.hasOwnProperty.call(options, "angle") ? options.angle : rand(0, TAU);
const distance = Object.prototype.hasOwnProperty.call(options, "distance") ? options.distance : Math.max(camera.worldWidth || width, camera.worldHeight || height) * 0.58 + rand(30, 120);
const progressScale = enemyProgressScale();
const sizeScale = enemySizeScale(kind);
const hpScale = (kind === "tutorial" ? 1 : kind === "phage" ? 1 + runTime / 300 : progressScale) * enemyCapDifficultyScale();
const damageScale = (kind === "tutorial" ? 0 : kind === "phage" ? 1 + runTime / 720 : 1 + runTime / 680) * enemyCapDamageScale();
const enemy = getEnemy();
enemy.alive = true;
enemy.kind = kind;
enemy.x = Object.prototype.hasOwnProperty.call(options, "x") ? options.x : player.x + Math.cos(angle) * distance;
enemy.y = Object.prototype.hasOwnProperty.call(options, "y") ? options.y : player.y + Math.sin(angle) * distance;
if (kind === "phage") {
enemy.x = player.x + Math.cos(angle) * Math.min(distance, Math.max(width, height) * 0.34);
enemy.y = player.y + Math.sin(angle) * Math.min(distance, Math.max(width, height) * 0.34);
}
enemy.vx = 0;
enemy.vy = 0;
enemy.components = {
stats: { baseHp: type.hp, baseDamage: type.damage, baseSpeed: type.speed, progressScale, sizeScale },
render: { flash: 0, hpBar: true },
collision: { attackImmune: kind === "tutorial", contactBreak: kind === "tutorial" },
movement: { lockTimer: 0, targetX: player.x, targetY: player.y, fixedDirX: 0, fixedDirY: 0 },
boss: kind === "phage" ? { attackTimer: 2.4, waveTimer: 7.2 } : null,
};
if ((type.behavior || ENEMY_BEHAVIORS.CHASER) === ENEMY_BEHAVIORS.DASHER) {
const dx = player.x - enemy.x;
const dy = player.y - enemy.y;
const d = Math.hypot(dx, dy) || 1;
enemy.components.movement.fixedDirX = dx / d;
enemy.components.movement.fixedDirY = dy / d;
enemy.components.movement.targetX = enemy.x + enemy.components.movement.fixedDirX * 1200;
enemy.components.movement.targetY = enemy.y + enemy.components.movement.fixedDirY * 1200;
}
enemy.hp = type.hp * hpScale * (kind === "phage" ? 1 : 1.18);
enemy.maxHp = enemy.hp;
enemy.speed = type.speed * (1.08 + runTime / 620) * enemyCapSpeedScale();
enemy.baseRadius = type.radius;
enemy.baseDamage = type.damage;
enemy.behavior = type.behavior || ENEMY_BEHAVIORS.CHASER;
enemy.radius = type.radius * sizeScale;
enemy.damage = type.damage * damageScale;
enemy.xp = type.xp;
enemy.color = type.color;
enemy.hit = 0;
enemy.pulse = 0;
enemy.splitDone = false;
enemy.shellContactCooldown = 0;
enemy.fortified = 0;
enemies.push(enemy);
return true;
}
function spawnParticle(x, y, color, count, force = 1, life = 0.8) {
const scaledCount = Math.max(1, Math.floor(count * quality.particleScale * perfGuard.effectScale));
for (let i = 0; i < scaledCount; i++) {
const p = getParticle();
if (!p) return;
const a = rand(0, TAU);
const s = rand(30, 260) * force;
p.x = x;
p.y = y;
p.vx = Math.cos(a) * s;
p.vy = Math.sin(a) * s;
p.life = rand(life * 0.45, life);
p.maxLife = p.life;
p.radius = rand(1.5, 5.5) * force;
p.color = color;
p.kind = "splash";
p.text = "";
p.hitTargets = null;
particles.push(p);
}
}
function spawnText(x, y, text, color = "#ffe5ea") {
if (perfGuard.textCooldown > 0 || particles.length >= MAX_PARTICLES * 0.92) return;
perfGuard.textCooldown = perf.fps < 52 ? 0.16 : 0.07;
const p = getParticle();
if (!p) return;
p.x = x;
p.y = y;
p.vx = rand(-18, 18);
p.vy = rand(-96, -58);
p.life = 0.72;
p.maxLife = 0.72;
p.radius = 0;
p.color = color;
p.text = text;
p.kind = "text";
p.hitTargets = null;
particles.push(p);
}
function spawnElectricArc(x1, y1, x2, y2, color = "#8fffd3") {
if (perfGuard.effectScale < 0.55 && Math.random() < 0.45) return;
const p = getParticle();
if (!p) return;
p.x = x1;
p.y = y1;
p.x2 = x2;
p.y2 = y2;
p.vx = 0;
p.vy = 0;
p.life = 0.16;
p.maxLife = 0.16;
p.radius = rand(4, 8);
p.color = color;
p.kind = "electricArc";
p.hitTargets = null;
particles.push(p);
}
function spawnToxicZone(x, y, power = 1) {
const p = getParticle();
if (!p) return;
p.x = x;
p.y = y;
p.vx = 0;
p.vy = 0;
p.life = 2.35;
p.maxLife = 2.35;
p.radius = 18;
p.maxRadius = 118 + power * 14;
p.damage = (18 + power * 5) * PLAYER_DAMAGE_SCALE;
p.color = "#caff55";
p.kind = "toxicZone";
p.hitTargets = null;
particles.push(p);
}
function spawnMassWave(power = 1) {
const p = getParticle();
if (!p) return;
p.x = player.x;
p.y = player.y;
p.vx = 0;
p.vy = 0;
p.life = 0.92;
p.maxLife = 0.92;
p.radius = player.radius * 1.4;
p.maxRadius = Math.max(camera.worldWidth || width, camera.worldHeight || height) * 0.48;
p.damage = 20 + power * 5.5;
p.color = "#ffd3dc";
p.kind = "massWave";
if (!p.hitTargets) p.hitTargets = new Set();
else p.hitTargets.clear();
particles.push(p);
}
function pushTrailPoint(trail, x, y, life, radius, maxLength) {
let point = trail.length >= maxLength ? trail.pop() : null;
if (!point) point = {};
point.x = x;
point.y = y;
point.life = life;
if (radius !== undefined) point.r = radius;
trail.unshift(point);
}
function initAudio() {
if (audio) {
audio.context.resume();
startBgm();
return;
}
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (!AudioContext) return;
const context = new AudioContext();
const master = context.createGain();
master.gain.value = 0.18;
master.connect(context.destination);
audio = { context, master };
startBgm();
}
function startBgm() {
if (!bgm) {
bgm = new Audio(BGM_PATH);
bgm.loop = true;
bgm.volume = 0.42;
}
bgm.play().catch(() => {
console.info(`[CELL] 배경음 파일을 찾지 못했거나 재생이 차단되었습니다: ${BGM_PATH}`);
});
}
function playSound(kind) {
if (!audio) return;
const { context, master } = audio;
const now = context.currentTime;
const osc = context.createOscillator();
const gain = context.createGain();
const filter = context.createBiquadFilter();
const noise = context.createBufferSource();
const buffer = context.createBuffer(1, Math.floor(context.sampleRate * 0.12), context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = (Math.random() * 2 - 1) * (1 - i / data.length);
noise.buffer = buffer;
const settings = {
hit: [150, 46, 0.11, 0.17, 780],
hurt: [92, 28, 0.22, 0.24, 420],
attack: [210, 64, 0.1, 0.13, 980],
death: [120, 22, 0.18, 0.26, 520],
mutate: [82, 24, 0.18, 0.62, 520],
evolve: [54, 18, 0.28, 1.15, 360],
level: [260, 72, 0.2, 0.48, 860],
card: [420, 120, 0.12, 0.2, 1200],
}[kind] || [150, 46, 0.1, 0.16, 700];
osc.type = kind === "evolve" || kind === "mutate" ? "sawtooth" : "triangle";
osc.frequency.setValueAtTime(settings[0], now);
osc.frequency.exponentialRampToValueAtTime(settings[1], now + settings[3]);
filter.type = "lowpass";
filter.frequency.value = settings[4];
gain.gain.setValueAtTime(settings[2], now);
gain.gain.exponentialRampToValueAtTime(0.001, now + settings[3]);
osc.connect(filter);
noise.connect(filter);
filter.connect(gain);
gain.connect(master);
osc.start(now);
noise.start(now);
osc.stop(now + settings[3] + 0.02);
noise.stop(now + Math.min(settings[3], 0.18));
}
function fireProjectile(kind, x, y, target, power) {
if (!target) return;
const a = Math.atan2(target.y - y, target.x - x);
fireProjectileAngle(kind, x, y, a, power);
}
function fireProjectileAngle(kind, x, y, angle, power) {
const p = getProjectile();
if (!p) return false;
const enemyShot = kind === "phageNeedle" || kind === "phageWave";
p.kind = kind;
p.owner = enemyShot ? "enemy" : "player";
p.x = x;
p.y = y;
const speed = kind === "swarmShard" ? 680 : kind === "spore" ? 170 : kind === "shard" ? 410 : kind === "bite" ? 520 : kind === "phageNeedle" ? 360 : kind === "phageWave" ? 245 : 330;
p.vx = Math.cos(angle) * speed;
p.vy = Math.sin(angle) * speed;
p.radius = kind === "swarmShard" ? 5 + power * 0.35 : kind === "spore" ? 8 + power * 1.4 : kind === "shard" ? 5 + power * 0.45 : kind === "bite" ? 7 + power * 0.45 : kind === "phageNeedle" ? 9 : kind === "phageWave" ? 13 : 6 + power;
p.damage = kind === "swarmShard" ? 9 + power * 3.2 : kind === "acid" ? 15 + power * 8 : kind === "shard" ? 12 + power * 4 : kind === "bite" ? 10 + power * 0.9 : kind === "phageNeedle" ? 18 + runTime / 60 : kind === "phageWave" ? 12 + runTime / 80 : 8 + power * 4;
p.life = kind === "swarmShard" ? 2.2 : kind === "spore" ? 3.4 : kind === "shard" ? 0.9 : kind === "bite" ? 0.52 : kind === "phageNeedle" ? 3.2 : kind === "phageWave" ? 4.2 : 1.35;
p.maxLife = p.life;
p.color = kind === "swarmShard" ? "#ff89a1" : kind === "acid" ? "#caff55" : kind === "shard" ? "#ffd3dc" : kind === "bite" ? "#ff89a1" : enemyShot ? "#d8f0ff" : "#8fffd3";
if (!p.trail) p.trail = [];
else p.trail.length = 0;
if (kind === "swarmShard") {
if (!p.hitTargets) p.hitTargets = new Set();
else p.hitTargets.clear();
} else if (p.hitTargets) {
p.hitTargets.clear();
}
projectiles.push(p);
return true;
}
function fireShotgun(kind, x, y, angle, count, spread, power) {
let fired = 0;
for (let i = 0; i < count; i++) {
const offset = count === 1 ? 0 : (i / (count - 1) - 0.5) * spread;
if (fireProjectileAngle(kind, x, y, angle + offset, power)) fired++;
}
return fired;
}
function nearestEnemy(range = 9999) {
let best = null;
let bestD = range * range;
perf.spatialCandidates = 0;
enemyGrid.forEachInCircle(player.x, player.y, range, (enemy) => {
perf.spatialCandidates++;
const d = dist2(player, enemy);
if (d < bestD) {
best = enemy;
bestD = d;
}
});
return best;
}
function sortedEnemiesInRange(range, limit = enemies.length) {
const range2 = range * range;
scratchEnemies.length = 0;
enemyGrid.forEachInCircle(player.x, player.y, range, (enemy) => {
const d = dist2(player, enemy);
if (d <= range2) {
enemy._queryD = d;
scratchEnemies.push(enemy);
}
});
scratchEnemies.sort((a, b) => a._queryD - b._queryD);
if (scratchEnemies.length > limit) scratchEnemies.length = limit;
return scratchEnemies;
}
function syncBalanceBucket() {
const cursor = Math.floor(runTime / balance.bucketStep);
if (balance.bucketCursor === cursor) return;
if (balance.bucketCursor < 0 || cursor - balance.bucketCursor >= balance.damageBuckets.length) {
balance.damageBuckets.fill(0);
balance.healBuckets.fill(0);
} else {
for (let step = balance.bucketCursor + 1; step <= cursor; step++) {
const index = step % balance.damageBuckets.length;
balance.damageBuckets[index] = 0;
balance.healBuckets[index] = 0;
}
}
balance.bucketCursor = cursor;
}
function sumBalanceWindow(buckets) {
let total = 0;
for (let i = 0; i < buckets.length; i++) total += buckets[i];
return total;
}
function recordDamage(amount) {
if (amount <= 0) return;
syncBalanceBucket();
balance.damageBuckets[balance.bucketCursor % balance.damageBuckets.length] += amount;
}
function healPlayer(amount) {
if (amount <= 0 || player.hp >= player.maxHp) return 0;
const before = player.hp;
player.hp = Math.min(player.maxHp, player.hp + amount);
const healed = player.hp - before;
syncBalanceBucket();
balance.healBuckets[balance.bucketCursor % balance.healBuckets.length] += healed;
return healed;
}
function healPlayerFromKill(amount) {
updateBalanceMetrics();
const hpsCap = 8 + player.absorption * 4.2 + (hasEvolution("swarmOrganism") ? 8 : 0);
const remainingBudget = Math.max(0, hpsCap * balance.window - balance.healTotal);
return healPlayer(Math.min(amount, remainingBudget));
}
function estimatePlayerDps() {
const haste = player.attackSpeed;
let dps = (10 + player.level * 0.9) / (0.42 / haste);
if (player.tentacles) {
const evolved = hasEvolution("electricTentacles");
const hits = Math.min(player.tentacles + (evolved ? 2 : 0), evolved ? 7 : 5);
dps += hits * (17 + player.tentacles * 5 + (evolved ? 10 : 0)) / ((evolved ? 0.72 : 0.86) / haste);
if (evolved) dps += hits * (6 + player.electric * 2.5 + player.evolutionLevel * 2) * 1.2 / (0.72 / haste);
}
if (player.acid) dps += (15 + player.acid * 8) / ((hasEvolution("toxicHive") ? 0.82 : 1.05) / haste) * (hasEvolution("toxicHive") ? 3 : 1);
if (player.spores && !hasEvolution("toxicHive")) dps += (player.spores + 1) * (8 + player.spores * 4) / (1.65 / haste);
if (player.electric && !hasEvolution("electricTentacles")) dps += (1 + player.electric) * (14 + player.electric * 7) / (1.25 / haste);
if (player.splitting) {
if (hasEvolution("swarmOrganism")) dps += (3 + player.splitting + player.evolutionLevel) * (9 + (player.splitting + player.absorption) * 3.2) * 0.38 / (0.28 / haste);
else dps += (12 + player.splitting * 6) / (0.68 / haste);
}
if (hasEvolution("immortalMass")) dps += (20 + (player.shell + player.regen) * 5.5) * 3.2 / (2.2 / haste);
if (hasEvolution("toxicHive")) dps += (2 + Math.min(4, player.acid + player.spores) * 0.7) * (18 + (player.acid + player.spores) * 5) * 0.55;
return dps * PLAYER_DAMAGE_SCALE;
}
function estimateAverageEnemyStats() {
const scale = enemyProgressScale() * enemyCapDifficultyScale();
const damageScale = (1 + runTime / 680) * enemyCapDamageScale();
const weights = [
["cell", 0.46],
["parasite", runTime > 0 ? 0.28 : 0],
["toxic", runTime > 115 ? 0.16 : 0],
["splitter", runTime > 185 ? 0.08 : 0],
["giant", runTime > 330 ? 0.02 : 0],
];
let weightTotal = 0;
let hp = 0;
let damage = 0;
for (const [kind, weight] of weights) {
if (weight <= 0) continue;
const type = enemyTypes[kind];
weightTotal += weight;
hp += type.hp * 1.18 * scale * weight;
damage += type.damage * damageScale * weight;
}
if (!weightTotal) return { hp: enemyTypes.cell.hp * scale, damage: enemyTypes.cell.damage * damageScale };
return { hp: hp / weightTotal, damage: damage / weightTotal };
}
function updateBalanceMetrics() {
balance.wave = Math.floor(runTime / 60) + 1;
syncBalanceBucket();
balance.damageTotal = sumBalanceWindow(balance.damageBuckets);
balance.healTotal = sumBalanceWindow(balance.healBuckets);
const measuredDps = balance.damageTotal / balance.window;
const estimatedDps = estimatePlayerDps();
balance.playerDps = measuredDps > 1 ? measuredDps : estimatedDps;
balance.playerHps = balance.healTotal / balance.window;
const enemyStats = estimateAverageEnemyStats();
balance.avgEnemyHp = enemyStats.hp;
balance.avgEnemyDamage = enemyStats.damage;
balance.avgTtk = balance.playerDps > 0 ? balance.avgEnemyHp / balance.playerDps : Infinity;
}
function damageEnemy(enemy, damage, color = "#ff416d", knock = 0, source = "attack") {
if (enemy.components && enemy.components.collision && enemy.components.collision.attackImmune && source !== "contact") {
enemy.hit = 0.12;
enemy.components.render.flash = 0.12;
spawnText(enemy.x, enemy.y - enemy.radius, "IMMUNE", "#d4fff0");
return false;
}
const finalDamage = source === "contact" ? damage : damage * PLAYER_DAMAGE_SCALE;
const beforeHp = enemy.hp;
enemy.hp -= finalDamage;
if (source !== "contact") recordDamage(Math.max(0, Math.min(beforeHp, finalDamage)));
enemy.hit = 0.22;