-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex12.html
More file actions
1562 lines (1399 loc) · 56.7 KB
/
index12.html
File metadata and controls
1562 lines (1399 loc) · 56.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
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<title>Tower Defense — Всё в одном</title>
<style>
html, body { margin: 0; padding: 0; }
body { font-family: sans-serif; background: #28323a; color: #ebebeb;}
canvas { display: block; background: #1d2227; margin: 20px auto 0; border:3px solid #444; }
.ui-panel {
max-width: 800px;
margin: 20px auto;
padding: 8px;
text-align: left;
background: #222a30;
border: 1px solid #333; border-radius:8px;
position:relative;
}
.ui-panel button {
margin: 3px 5px;
font-size: 16px;
background: #48607c;
color: #fff;
border:none; border-radius:5px; cursor:pointer;
padding: 6px 20px;
transition: background 0.15s;
}
.ui-panel button.selected {
background: #b36218;
}
.ui-panel .money { color: #f9d648; font-weight:bold; }
.ui-panel .health { color: #d9675f; font-weight:bold; }
.ui-panel .wave { color:#76e0a6; }
.wave-counter {
position: absolute;
right: 20px;
top: 10px;
font-weight: bold;
font-size: 1.25em;
background: #355d2650;
border-radius: 8px;
padding: 4px 12px;
color: #96f586;
z-index:2;
box-shadow: 0 0 12px #202 ;
pointer-events: none;
}
@keyframes green-blink {
0%, 100% { outline: 3px dashed #0f0; box-shadow: 0 0 15px 4px #99ff9960; }
50% { outline: 3px dashed #00ffae; box-shadow: 0 0 15px 6px #00ffae94; }
}
.ui-panel button.selected {
animation: green-blink 0.34s infinite;
outline: 3px dashed #15ff00 !important;
border: 2px solid #fff !important;
box-shadow: 0 0 15px 4px #0f0a;
}
.gameover, .victory {
background: #0f161bcc;
padding: 40px 80px;
position:absolute; top:50px; left:50%; transform:translateX(-50%);
color: #fff; border-radius: 18px; border: 4px solid #dda000;
font-size:2em; letter-spacing:0.08em; z-index:3; text-align: center;
}
.dev-panel {
font-size:13px;
max-width:760px;
margin:5px auto;
padding:4px 8px;
color:#9cf;
background:#173045;
}
.building-cell-allowed {
box-shadow: 0 0 14px #58a181 !important;
animation: pulse-green 0.82s infinite;
}
.building-cell-denied {
box-shadow: 0 0 14px #b84c4c !important;
animation: pulse-red 0.82s infinite;
}
#tower-info {
transition: opacity 0.17s cubic-bezier(.43,.39,.5,1.15);
}
.td-btn {
margin: 3px 5px;
font-size: 15px;
font-family: inherit;
border: 1.5px solid #222;
border-radius: 5px;
cursor: pointer;
padding: 6px 20px;
transition: background 0.15s;
min-width: 110px;
display: inline-block;
}
.td-btn.disabled {
filter: brightness(0.55) grayscale(0.5);
cursor: not-allowed;
background: #333 !important;
color: #888 !important;
border-color: #444 !important;
font-weight:400;
}
@keyframes pulse-green {
0%,100% { outline: 3px solid #36ef97cc; }
50% { outline: 3px solid #3bd1d4aa; }
}
@keyframes pulse-red {
0%,100% { outline: 3px solid #d1573dcc; }
50% { outline: 3px solid #ec2323bb; }
}
</style>
</head>
<body>
<div id="tower-info" style="
display:none;
position:absolute;
top:80px; left:50px;
min-width:180px;
background:#181a22;
color:#fff;
padding:12px 14px;
border-radius:8px;
box-shadow:0 0 12px #28285a;
z-index:10;
font-family:monospace;
font-size:15px;"
></div>
<canvas id="game"></canvas>
<div class="ui-panel" id="ui-panel"></div>
<div class="dev-panel" id="dev-panel" style="display:none"></div>
<div id="wave-timer" class="wave-counter" style="display:none"></div>
<script>
// ===== 1. Константы и параметры =====
const GRID_SIZE = 15;
const CELL_SIZE = 40;
const CANVAS_WIDTH = GRID_SIZE * CELL_SIZE;
const CANVAS_HEIGHT = GRID_SIZE * CELL_SIZE;
const enemyData = [
// Индекс 0 — стандартный "пехотинец", слабый, дешёвый.
{ name: "Grunt", hp: 120, speed: 120, color:'#c43448', reward:6, damage:1 },
// Индекс 1 — быстрый враг (очень быстро бежит, но тоже 1 урона, много hp — для демонстрации скорости)
{ name: "Fast", hp: 80, speed: 250, color:'#fca312', reward:7, damage:1 },
// Индекс 2 — "танк" (медленный, но живучий и наносит 2 урона по базе)
{ name: "Tank", hp: 850, speed: 100, color:'#2fd999', reward:15, damage:2 },
// Индекс 3 — Босс (огромный запас здоровья, средняя скорость, мощный урон, жирная награда)
{ name: "Boss", hp: 8000, speed: 200, color:'#af3aff', reward:65, damage:4},
// Индекс 4 — Bel
{ name: "Bel", hp: 4000, speed: 800, color:'#0a0da3', reward:120, damage:4},
// Индекс 5 — Vel
{ name: "Vel", hp: 2000, speed: 1200, color:'#81e4a5', reward:180, damage:4},
];
// hp - единицы здоровья
// speed - клетки в секунду
// color - как рисовать этого врага
// reward - сколько монет тебе дадут за убийство
// damage - сколько жизней заберет, если добежит до базы
const towerData = [
// Индекс 0 — обычная пушка (дешёвая, средний урон и радиус)
{ name: "Gun", cost:18, range:4.0, damage:11, cooldown:0.40, color:'#e4e4e4', bulletSpeed:640 },
// Индекс 1 — пулемёт (дороже, чуть меньше радиус, меньше урона, но огромная скорострельность)
{ name: "MGun", cost:28, range:2.0, damage:3, cooldown:0.15, color:'#bfff56', bulletSpeed:960 },
// Индекс 2 — снайперка (дорогая, ОГРОМНЫЙ урон и радиус, но медленно стреляет)
{ name: "Snip", cost:43, range:5.0, damage:40, cooldown:1.2, color:'#e080e0', bulletSpeed:1280 },
// Индекс 3 — GOGO
{ name: "GOGO", cost:200, range:3.0, damage:120, cooldown:0.6, color:'#c39f09', bulletSpeed:960 },
// Индекс 4 — MANI
{ name: "MANI", cost:400, range:2.0, damage:350, cooldown:0.3, color:'#9b3f1c', bulletSpeed:2560 },
// Индекс 5 — LA1
{ name: "LA1", cost:60, range:4.0, damage:8, cooldown:0.03, color:'#29ff77', bulletSpeed:4096 },
// Индекс 6 — LA2
{ name: "LA2", cost:800, range:5.0, damage:40, cooldown:0.01, color:'#0ba898', bulletSpeed:12288 },
];
// cost - сколько стоит построить башню (в монетах)
// range - дальность поражения (в клетках сетки, CELL_SIZE = 1.0)
// damage - урон одной пулей
// cooldown - время между выстрелами в секундах (меньше = быстрее)
// color - для рисования на поле
// bulletSpeed - скорость пули (в клетках/сек)
const waveData = [
{ enemies: [ {e:0, n:7, d:0.62} ] },
{ enemies: [ {e:0, n:9, d:0.59}, {e:1, n:4, d:0.66} ] },
{ enemies: [ {e:0, n:11, d:0.56}, {e:1, n:5, d:0.64} ] },
{ enemies: [ {e:0, n:13, d:0.53}, {e:1, n:6, d:0.62} ] },
// Волна 5
{ enemies: [ {e:0, n:15, d:0.4}, {e:1, n:10, d:0.45}, {e:2, n:1, d:2.0} ] },
{ enemies: [ {e:0, n:16, d:0.39}, {e:1, n:11, d:0.44}, {e:2, n:2, d:1.9} ] },
{ enemies: [ {e:0, n:17, d:0.38}, {e:1, n:12, d:0.43}, {e:2, n:3, d:1.8} ] },
{ enemies: [ {e:0, n:18, d:0.37}, {e:1, n:13, d:0.42}, {e:2, n:4, d:1.7} ] },
{ enemies: [ {e:0, n:19, d:0.36}, {e:1, n:14, d:0.41}, {e:2, n:5, d:1.6} ] },
// Волна 10
{ enemies: [ {e:1, n:18, d:0.35}, {e:2, n:10, d:1.3}, {e:3, n:1, d:3.0} ] },
{ enemies: [ {e:1, n:19, d:0.35}, {e:2, n:10, d:1.28} ] },
{ enemies: [ {e:1, n:20, d:0.34}, {e:2, n:11, d:1.26} ] },
{ enemies: [ {e:1, n:21, d:0.34}, {e:2, n:11, d:1.24} ] },
{ enemies: [ {e:1, n:22, d:0.33}, {e:2, n:12, d:1.22} ] },
// Волна 15
{ enemies: [ {e:1, n:23, d:0.33}, {e:2, n:12, d:1.2}, {e:3, n:1, d:3.0} ] },
{ enemies: [ {e:1, n:24, d:0.32}, {e:2, n:13, d:1.18} ] },
{ enemies: [ {e:1, n:25, d:0.32}, {e:2, n:13, d:1.16} ] },
{ enemies: [ {e:1, n:26, d:0.31}, {e:2, n:14, d:1.14} ] },
{ enemies: [ {e:1, n:27, d:0.31}, {e:2, n:14, d:1.12} ] },
// Волна 20
{ enemies: [ {e:1, n:22, d:0.26}, {e:2, n:20, d:0.7}, {e:4, n:4, d:1.2}, {e:3, n:2, d:3.0} ] },
{ enemies: [ {e:1, n:22, d:0.26}, {e:2, n:20, d:0.69}, {e:4, n:4, d:1.2} ] },
{ enemies: [ {e:1, n:23, d:0.26}, {e:2, n:21, d:0.67}, {e:4, n:4, d:1.2} ] },
{ enemies: [ {e:1, n:23, d:0.25}, {e:2, n:21, d:0.66}, {e:4, n:4, d:1.2} ] },
{ enemies: [ {e:1, n:24, d:0.25}, {e:2, n:22, d:0.64}, {e:4, n:4, d:1.2} ] },
// Волна 25
{ enemies: [ {e:1, n:24, d:0.25}, {e:2, n:22, d:0.62}, {e:4, n:5, d:1.2}, {e:3, n:2, d:3.0} ] },
{ enemies: [ {e:1, n:25, d:0.25}, {e:2, n:23, d:0.61}, {e:4, n:5, d:1.2} ] },
{ enemies: [ {e:1, n:25, d:0.25}, {e:2, n:23, d:0.59}, {e:4, n:5, d:1.2} ] },
{ enemies: [ {e:1, n:26, d:0.24}, {e:2, n:24, d:0.58}, {e:4, n:5, d:1.2} ] },
{ enemies: [ {e:1, n:26, d:0.24}, {e:2, n:24, d:0.56}, {e:4, n:5, d:1.2} ] },
// Волна 30
{ enemies: [ {e:1, n:25, d:0.2}, {e:2, n:25, d:0.6}, {e:4, n:7, d:0.8}, {e:5, n:6, d:1.5} ] },
{ enemies: [ {e:1, n:25, d:0.2}, {e:2, n:25, d:0.6}, {e:4, n:7, d:0.8}, {e:5, n:6, d:1.5} ] },
{ enemies: [ {e:1, n:25, d:0.2}, {e:2, n:26, d:0.6}, {e:4, n:8, d:0.8}, {e:5, n:6, d:1.5} ] },
{ enemies: [ {e:1, n:26, d:0.2}, {e:2, n:26, d:0.6}, {e:4, n:8, d:0.8}, {e:5, n:6, d:1.5} ] },
{ enemies: [ {e:1, n:26, d:0.2}, {e:2, n:27, d:0.6}, {e:4, n:8, d:0.8}, {e:5, n:6, d:1.5} ] },
// Волна 35
{ enemies: [ {e:1, n:26, d:0.2}, {e:2, n:27, d:0.6}, {e:4, n:8, d:0.8}, {e:5, n:7, d:1.5} ] },
{ enemies: [ {e:1, n:27, d:0.2}, {e:2, n:28, d:0.6}, {e:4, n:9, d:0.8}, {e:5, n:7, d:1.5} ] },
{ enemies: [ {e:1, n:27, d:0.2}, {e:2, n:28, d:0.6}, {e:4, n:9, d:0.8}, {e:5, n:7, d:1.5} ] },
{ enemies: [ {e:1, n:27, d:0.2}, {e:2, n:29, d:0.6}, {e:4, n:9, d:0.8}, {e:5, n:7, d:1.5} ] },
{ enemies: [ {e:1, n:28, d:0.2}, {e:2, n:29, d:0.6}, {e:4, n:9, d:0.8}, {e:5, n:7, d:1.5} ] },
// Волна 40
{ enemies: [ {e:3, n:2, d:3.5}, {e:4, n:14, d:1.0}, {e:5, n:13, d:0.9} ] },
{ enemies: [ {e:3, n:3, d:3.2}, {e:4, n:14, d:1.0}, {e:5, n:13, d:0.9} ] },
{ enemies: [ {e:3, n:4, d:2.9}, {e:4, n:14, d:1.0}, {e:5, n:13, d:0.9} ] },
{ enemies: [ {e:3, n:5, d:2.6}, {e:4, n:14, d:1.0}, {e:5, n:13, d:0.9} ] },
{ enemies: [ {e:3, n:6, d:2.3}, {e:4, n:15, d:1.0}, {e:5, n:14, d:0.9} ] },
// Волна 45
{ enemies: [ {e:3, n:7, d:2.0}, {e:4, n:15, d:1.0}, {e:5, n:14, d:0.9} ] }
];
/*
В каждой {enemies: [...]}
e — индекс enemyData
n — сколько штук подряд выпустить
d — задержка (delay, сек) между этим типом врагов
*/
// ===== 2. Главные переменные =====
let canvas, ctx;
let grid = [];
let towers = [], enemies = [], bullets = [];
let path = [];
let money = 100;
let health = 10;
let wave = 1;
let selectedTowerType = null;
let isPlacingTower = false;
let devMode = false;
let devLog = [];
let placingTowerCell = null;
let gameOver = false;
let victory = false;
let defeatCause = "";
let buildZoneHints = [];
let mouseGridX = null, mouseGridY = null;
// Spawn control
let enemySpawnTimer = 0;
let lastUpdateTime = Date.now();
let curSpawnList = [], curSpawnIdx = 0, spawnLeft = 0, nextEnemySpawnAt = 0;
// Wave timer/pause между волнами
let waveTimeoutActive = false;
let nextWaveDelay = 3;
let wavePauseLeft = 0;
// ===== 3. Инициализация =====
function init() {
// 1. Сбросим ВСЕ переменные!
towers = []; enemies = []; bullets = [];
money = 100; health = 10; wave = 1;
selectedTowerType = null;
isPlacingTower = false; placingTowerCell = null;
mouseGridX = mouseGridY = null;
buildZoneHints = [];
gameOver = false; victory = false; defeatCause = "";
curSpawnIdx = 0; nextEnemySpawnAt = 0; curSpawnList = []; spawnLeft = 0;
waveTimeoutActive = false; wavePauseLeft = 0;
if (typeof devLog === "undefined") devLog = [];
canvas = document.getElementById('game');
if (!canvas) {
alert('Canvas не найден!');
return;
}
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
ctx = canvas.getContext('2d');
createEmptyGrid();
if (!Array.isArray(grid) || grid.length !== GRID_SIZE) {
alert('Ошибка при создании сетки!');
return;
}
generateEnemyPath();
if (!Array.isArray(path) || path.length < 2) {
alert('Путь для врагов не найден! Проверьте сетку!');
showGameOverScreen();
return;
}
updateUI();
try {
document.getElementById('dev-panel').style.display = devMode ? "" : "none";
document.getElementById('wave-timer').style.display = 'none';
} catch(e) {}
if (!canvas._tdEvents) {
canvas.addEventListener('mousedown', handleMouseClick);
canvas.addEventListener('mousemove', handleMouseMove);
canvas.addEventListener('mouseleave', ()=>{mouseGridX=null;mouseGridY=null;buildZoneHints=[];});
document.addEventListener('keydown', handleKeyDown);
canvas._tdEvents = true;
}
createUIButtons();
// НЕ вызываем startNextWave() сразу!
// Ставим паузу 3 секунды перед первой волной
waveTimeoutActive = true;
wavePauseLeft = nextWaveDelay; // Обычно это 3 секунды
updateWaveTimerUI(Math.ceil(nextWaveDelay));
document.getElementById('wave-timer').style.display = "";
requestAnimationFrame(gameLoop);
if (devMode) {
setTimeout(()=>{
console.log('[TD] State after init:', {
towers, enemies, bullets,
grid: grid ? 'OK' : 'fail', path: path ? path.length : 0,
wave, money, health
});
}, 100);
}
}
// ===== 4. Сетка и маршрут =====
function createEmptyGrid() {
grid = [];
for (let y = 0; y < GRID_SIZE; ++y) {
let row = [];
for (let x = 0; x < GRID_SIZE; ++x)
row.push({ tower: null, base: x === GRID_SIZE - 1 && y === GRID_SIZE - 1, blocked: false });
grid.push(row);
}
}
// ==== Поиск пути A* между любыми точками =====
// ==== Поиск пути A* между двумя точками с логами =====
function findPath(start, goal) {
function toKey([x, y]) { return `${x},${y}`; }
function heuristic(a, b) { return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); }
let openSet = [start];
let gScore = {};
let fScore = {};
let cameFrom = {};
gScore[toKey(start)] = 0;
fScore[toKey(start)] = heuristic(start, goal);
let closedSet = {};
while (openSet.length) {
// Найти узел с минимальным fScore в openSet
let bestIdx = 0;
for (let i = 1; i < openSet.length; ++i)
if ((fScore[toKey(openSet[i])]||Infinity) < (fScore[toKey(openSet[bestIdx])]||Infinity)) bestIdx = i;
let current = openSet[bestIdx];
openSet.splice(bestIdx, 1);
let ckey = toKey(current);
if (current[0] === goal[0] && current[1] === goal[1]) {
let totalPath = [current];
while (cameFrom[toKey(totalPath[0])])
totalPath.unshift(cameFrom[toKey(totalPath[0])]);
if (devMode) debugLogEvent("path_found", { from: start, to: goal, length: totalPath.length });
return totalPath;
}
closedSet[ckey] = true;
let [x, y] = current;
let neighbors = [[1, 0], [-1, 0], [0, 1], [0, -1]]
.map(([dx, dy]) => [x + dx, y + dy])
.filter(([nx, ny]) =>
nx >= 0 && nx < GRID_SIZE &&
ny >= 0 && ny < GRID_SIZE &&
!grid[ny][nx].blocked
);
for (let neighbor of neighbors) {
let nkey = toKey(neighbor);
if (closedSet[nkey]) continue;
let tentative_gScore = gScore[ckey] + 1;
if (!(nkey in gScore) || tentative_gScore < gScore[nkey]) {
cameFrom[nkey] = current;
gScore[nkey] = tentative_gScore;
fScore[nkey] = gScore[nkey] + heuristic(neighbor, goal);
if (!openSet.some(([ox, oy]) => ox === neighbor[0] && oy === neighbor[1])) {
openSet.push(neighbor);
}
}
}
}
if (devMode) debugLogEvent("path_fail", { from: start, to: goal });
return [];
}
// ==== A* для врагов, общий путь от входа до базы =====
function generateEnemyPath() {
const start = [0, 0], goal = [GRID_SIZE - 1, GRID_SIZE - 1];
const totalPath = findPath(start, goal);
if (Array.isArray(totalPath) && totalPath.length > 1) {
path = totalPath;
if (devMode) debugLogEvent("enemy_path_updated", { length: path.length, path });
} else {
path = [];
if (devMode) debugLogEvent("enemy_path_error", { path: totalPath, message: "Empty or invalid path" });
}
}
// ==== Пересчёт маршрутов всех врагов после постройки башни ====
function recalcPathsForAllEnemies() {
for (let e of enemies) {
let current = e.path && e.path[e.pathIdx] ? e.path[e.pathIdx] : [0, 0];
let newPath = findPath(current, [GRID_SIZE - 1, GRID_SIZE - 1]);
if (newPath && newPath.length > 1) {
e.path = newPath;
e.pathIdx = 0;
if (devMode) debugLogEvent("enemy_path_recalc", { from: current, to: [GRID_SIZE - 1, GRID_SIZE - 1], length: newPath.length });
} else {
if (devMode) debugLogEvent("enemy_path_recalc_fail", { from: current, to: [GRID_SIZE - 1, GRID_SIZE - 1] });
e.path = [];
e.pathIdx = 0;
}
}
}
// ===== 5. Игровой цикл =====
function gameLoop() {
if (gameOver) return;
update();
draw();
requestAnimationFrame(gameLoop);
}
// ===== 6. Обновление =====
function update() {
let dt = getDeltaTime();
updateTimers(dt);
if (!waveTimeoutActive) {
updateEnemies(dt);
updateTowers(dt);
updateBullets(dt);
handleCollisions();
checkWaveEnd();
}
checkGameOver();
checkVictoryCondition();
}
function updateTimers(dt) {
if (!waveTimeoutActive)
enemySpawnTimer += dt;
if (waveTimeoutActive && wavePauseLeft > 0) {
wavePauseLeft -= dt;
updateWaveTimerUI(Math.max(0, Math.ceil(wavePauseLeft)));
if (wavePauseLeft <= 0) {
waveTimeoutActive = false;
document.getElementById('wave-timer').style.display = "none";
wave++;
startNextWave();
updateUI();
}
}
}
function getDeltaTime() {
const now = Date.now();
const dt = (now - lastUpdateTime) / 1000;
lastUpdateTime = now;
return dt;
}
// ===== 7. Волны и спавн врагов =====
function startNextWave() {
if (!Array.isArray(path) || path.length < 2) {
alert('Невозможно начать волну: путь для врагов не найден!');
gameOver = true;
showGameOverScreen();
return;
}
if (wave > waveData.length) {
// Все волны пройдены, проверяем условие победы
checkVictoryCondition();
return;
}
curSpawnList = JSON.parse(JSON.stringify(waveData[wave - 1].enemies));
curSpawnIdx = 0;
nextEnemySpawnAt = 0;
spawnLeft = curSpawnList.reduce((sum, o) => sum + o.n, 0);
enemySpawnTimer = 0;
}
// === Масштабирующие функции для каждого параметра ===
// 1. МАССИВНАЯ функция: общий множитель хп (+30% каждую 5-ю волну)
function scalingHP(wave) {
let bonus = Math.floor((wave - 1) / 5) * 0.30; // +30% каждые 5 волн
return 1 + bonus;
}
// 2. Масштабирование скорости (пример - +1% каждые 3 волны и +5% каждые 10 волн)
function scalingSpeed(wave) {
let bonus_3 = Math.floor((wave - 1) / 3) * 0.01; // +1% каждые 3 волны
let bonus_10 = Math.floor((wave - 1) / 10) * 0.05; // +5% каждые 10 волн
return 1 + bonus_3 + bonus_10;
}
// 3. Масштабирование награды (например +10% каждые 5 волн)
function scalingReward(wave) {
let bonus = Math.floor((wave - 1) / 5) * 0.10; // +10% каждой 5-й волне
return 1 + bonus;
}
// 4. Масштабирование урона (например, +1 по каждой 10-й волне)
function scalingDamage(wave) {
let bonus = Math.floor((wave - 1) / 10); // +1 к урону каждые 10 волн
return 1 + bonus;
}
// 5. Общий (глобальный) множитель — если нужно глобальное усиление по всем событиям
function scalingAll(wave) {
let bonus = Math.floor((wave - 1) / 15) * 0.10; // +10% по всем статам каждые 15 волн
return 1 + bonus;
}
// === Фрагмент спавна врага с применением всех масштабирований ===
function spawnEnemy() {
if (curSpawnIdx >= curSpawnList.length) return;
if (!Array.isArray(path) || path.length < 2) return; // без пути спавнить врага нельзя!
let entry = curSpawnList[curSpawnIdx];
let eidx = entry.e;
let econf = enemyData[eidx];
// === Применяем масштабирование к каждому показателю отдельно ===
// -- Здесь можно куда угодно вставить формулы масштабирования!
let hpMult = scalingHP(wave) * scalingAll(wave); // множитель для HP
let speedMult = scalingSpeed(wave) * scalingAll(wave); // множитель для скорости
let rewardMult = scalingReward(wave) * scalingAll(wave); // множитель для награды
let damageMult = scalingDamage(wave) * scalingAll(wave); // множитель для урона (обычно округляют)
// -- Собираем итоговую конфигурацию врага для этой волны --
let scaledConf = {
...econf,
hp: Math.round(econf.hp * hpMult),
speed: Math.round(econf.speed * speedMult),
reward: Math.round(econf.reward * rewardMult),
damage: Math.floor(econf.damage * damageMult) // <-- здесь округление вниз!
};
// -- Передаем масштабированные параметры врагу --
enemies.push(new Enemy([...path], scaledConf, eidx));
entry.n--; spawnLeft--;
if (entry.n <= 0) {
curSpawnIdx++;
nextEnemySpawnAt = enemySpawnTimer + (curSpawnList[curSpawnIdx] ? curSpawnList[curSpawnIdx].d : 99);
} else {
nextEnemySpawnAt = enemySpawnTimer + entry.d;
}
}
function checkWaveEnd() {
if (spawnLeft <= 0 && enemies.length == 0 && wave < waveData.length && !gameOver && !waveTimeoutActive) {
waveTimeoutActive = true;
wavePauseLeft = nextWaveDelay;
updateWaveTimerUI(nextWaveDelay);
document.getElementById('wave-timer').style.display = "";
}
}
function updateWaveTimerUI(secLeft) {
let el = document.getElementById('wave-timer');
if (el) el.textContent = "Следующая волна: " + secLeft + " сек.";
}
function updateEnemies(dt) {
if (curSpawnIdx < curSpawnList.length && !gameOver) {
if (enemySpawnTimer >= nextEnemySpawnAt) spawnEnemy();
}
for (let i = enemies.length - 1; i >= 0; --i) {
let e = enemies[i];
// ====== Если враг без пути или в тупике — пересчитаем ======
if (!Array.isArray(e.path) || e.path.length < 2 || e.pathIdx >= e.path.length - 1) {
let cx = Math.floor(e.x / CELL_SIZE);
let cy = Math.floor(e.y / CELL_SIZE);
let newPath = findPath([cx, cy], [GRID_SIZE - 1, GRID_SIZE - 1]);
if (Array.isArray(newPath) && newPath.length > 1) {
e.path = newPath;
e.pathIdx = 0;
e.progress = 0;
if (devMode) debugLogEvent("enemy_repath_success", { from: [cx, cy], newLen: newPath.length });
} else {
if (devMode) debugLogEvent("enemy_stuck", { at: [cx, cy], reason: "no path" });
continue;
}
}
// ====== Движение между клетками ======
let speedCellsPerSecond = e.conf.speed / 100;
e.progress += dt * speedCellsPerSecond;
while (e.progress >= 1 && e.pathIdx < e.path.length - 1) {
e.progress -= 1;
e.pathIdx++;
}
let [cx, cy] = e.path[e.pathIdx];
let [nx, ny] = e.path[Math.min(e.pathIdx + 1, e.path.length - 1)];
// Интерполяция между текущей и следующей клеткой
let tx = cx + (nx - cx) * e.progress;
let ty = cy + (ny - cy) * e.progress;
e.x = tx * CELL_SIZE + CELL_SIZE / 2;
e.y = ty * CELL_SIZE + CELL_SIZE / 2;
// ====== Если достиг базы ======
if (e.pathIdx >= e.path.length - 1) {
health -= e.conf.damage;
debugLogEvent('enemy_base', { eidx: e.type, damage: e.conf.damage, wave, health });
enemies.splice(i, 1);
updateUI();
}
}
}
function updateTowers(dt) {
for (let t of towers) {
t.cooldown -= dt;
if (t.cooldown <= 0) {
let conf = towerData[t.type];
let inRange = enemies.filter(
e => distance(t.cx, t.cy, e.x, e.y) <= conf.range * CELL_SIZE
);
if (inRange.length) {
let target = inRange.sort(
(a, b) => b.pathIdx - a.pathIdx || a.hp - b.hp
)[0];
bullets.push(new Bullet(t.cx, t.cy, target, t));
t.cooldown = conf.cooldown; // проще и чуть быстрее!
}
}
}
}
function updateBullets(dt) {
for (let i = bullets.length - 1; i >= 0; --i) {
let b = bullets[i];
// Если цель уже умерла — удаляем пулю
if (!b.target || b.target.hp <= 0) {
if (devMode) debugLogEvent("bullet_removed_dead_target", { id: i });
bullets.splice(i, 1);
continue;
}
// === Работа в КЛЕТКАХ ===
let dx = (b.target.x - b.x) / CELL_SIZE;
let dy = (b.target.y - b.y) / CELL_SIZE;
let dist = Math.hypot(dx, dy);
let step = dt * (b.speed / 100); // как у врагов — в клетках/сек
if (dist < step + 0.2) { // запас ~0.2 клетки
b.hit = true;
b.target.hp -= b.damage;
debugLogEvent('hit', {
tower: b.towerType,
eidx: b.target.type,
dmg: b.damage,
left: b.target.hp
});
if (b.target.hp <= 0) {
money += b.target.conf.reward;
debugLogEvent('enemy_die', {
eid: b.target.type,
wv: wave,
money
});
let idx = enemies.indexOf(b.target);
if (idx > -1) enemies.splice(idx, 1);
updateUI();
}
bullets.splice(i, 1);
continue;
}
// ===== Движение пули (в пикселях) =====
b.x += (dx / dist) * step * CELL_SIZE;
b.y += (dy / dist) * step * CELL_SIZE;
if (devMode) debugLogEvent("bullet_move", {
id: i,
speed: b.speed,
step: (step * CELL_SIZE).toFixed(2),
dist: (dist * CELL_SIZE).toFixed(2),
to: [b.target.x.toFixed(1), b.target.y.toFixed(1)]
});
}
}
function handleCollisions() {}
// ===== 8. Мышь и башни =====
function handleMouseClick(e) {
if (gameOver || victory) return;
let pos = getCellFromMouse(e);
if (!pos) return;
let [x, y] = pos;
// --- Показывать инфо-бокс при клике по башне вне режима строительства ---
if (!isPlacingTower && grid[y][x].tower) {
showTowerInfo(grid[y][x].tower.type, x, y);
return;
}
if (e.button === 2) {
selectedTowerType = null;
isPlacingTower = false;
placingTowerCell = null;
updateUI();
buildZoneHints = [];
return false;
}
if (selectedTowerType === null) return;
if (isCellEmpty(x, y) && canPlaceTower(x, y)) {
placeTower(x, y, selectedTowerType);
// selectedTowerType = null;
// isPlacingTower = false;
placingTowerCell = null;
buildZoneHints = [];
updateUI();
}
}
function handleMouseMove(e) {
if (!isPlacingTower) {
mouseGridX = mouseGridY = null;
buildZoneHints = [];
return;
}
let pos = getCellFromMouse(e);
if (pos) {
mouseGridX = pos[0];
mouseGridY = pos[1];
buildZoneHints = [];
let viewRange = 2;
for (let y = Math.max(0, mouseGridY - viewRange); y <= Math.min(GRID_SIZE - 1, mouseGridY + viewRange); y++) {
for (let x = Math.max(0, mouseGridX - viewRange); x <= Math.min(GRID_SIZE - 1, mouseGridX + viewRange); x++) {
if ((x === 0 && y === 0) || (x === GRID_SIZE - 1 && y === GRID_SIZE - 1)) continue;
let allowed = isCellEmpty(x, y) && canPlaceTower(x, y);
buildZoneHints.push({ x, y, allowed });
}
}
}
}
// ===== 9. Проверки пути и установки с профессиональным логированием =====
// Проверка: занята ли клетка (логгируем каждый этап!)
function isCellEmpty(x, y) {
if (grid[y][x].blocked) {
if (devMode) debugLogEvent('cell_blocked', { x, y });
return false;
}
if (grid[y][x].tower) {
if (devMode) debugLogEvent('cell_tower_exists', { x, y });
return false;
}
for (let t of towers)
if (t.gridX === x && t.gridY === y) {
if (devMode) debugLogEvent('cell_tower_in_array', { x, y });
return false;
}
if (devMode) debugLogEvent('cell_empty', { x, y });
return true;
}
// Можно ли построить башню на этой клетке? (Залогировано каждое решение)
function canPlaceTower(x, y) {
if ((x === 0 && y === 0) || (x === GRID_SIZE - 1 && y === GRID_SIZE - 1)) {
if (devMode) debugLogEvent("deny_entrance_exit", { x, y });
return false;
}
if (!isCellEmpty(x, y)) {
if (devMode) debugLogEvent("not_empty", { x, y });
return false;
}
grid[y][x].blocked = true;
let found = hasEnemyPath();
if (devMode) debugLogEvent("bfs_check", {
x, y,
ok: found,
message: found ? "Путь есть, строить можно" : "Путь перекрывается, строить нельзя",
towersCount: towers.length
});
grid[y][x].blocked = false;
return found;
}
// Проверка BFS — не перекроет ли башня путь врагам наглухо (логгируем исход)
function hasEnemyPath() {
let visited = Array.from({ length: GRID_SIZE }, () => Array(GRID_SIZE).fill(false));
let queue = [[0, 0]];
visited[0][0] = true;
let dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (queue.length) {
let [cx, cy] = queue.shift();
if (cx === GRID_SIZE - 1 && cy === GRID_SIZE - 1) {
if (devMode) debugLogEvent("bfs_pass", { cx, cy, result: "finish reached" });
return true;
}
for (let [dx, dy] of dirs) {
let nx = cx + dx, ny = cy + dy;
if (nx < 0 || ny < 0 || nx >= GRID_SIZE || ny >= GRID_SIZE) continue;
if (visited[ny][nx] || grid[ny][nx].blocked) continue;
visited[ny][nx] = true;
queue.push([nx, ny]);
}
}
if (devMode) debugLogEvent("bfs_fail", { result: "no path for enemy" });
return false;
}
// Построить башню и пересчитать маршрут врага (логируем всё)
function placeTower(x, y, type) {
let conf = towerData[type];
if (money < conf.cost) {
if (devMode) debugLogEvent('not_enough_money', { x, y, type, money });
return;
}
towers.push(new Tower(x, y, type));
grid[y][x].tower = towers[towers.length - 1];
grid[y][x].blocked = true; // <<-- теперь башня блокирует путь!
money -= conf.cost;
if (devMode) debugLogEvent('tower_built', {
x, y, type,
cost: conf.cost,
money_left: money,
total_towers: towers.length
});
generateEnemyPath();
recalcPathsForAllEnemies(); // <-- ДОБАВЬ ЭТУ СТРОКУ!
if (devMode) {
debugLogEvent('path_updated_after_tower', {
new_path: path.map(pair => ({x: pair[0], y: pair[1]}))
});
}
updateUI();
}
// ===== 10. Классы/фабрики =====
function Tower(x, y, type) {
return {
gridX: x, gridY: y, type,
cx: x * CELL_SIZE + CELL_SIZE / 2,
cy: y * CELL_SIZE + CELL_SIZE / 2,
cooldown: 0
};
}
function Enemy(pth, conf, type) {
let x = (Array.isArray(pth) && pth.length) ? pth[0][0]*CELL_SIZE+CELL_SIZE/2 : 0;
let y = (Array.isArray(pth) && pth.length) ? pth[0][1]*CELL_SIZE+CELL_SIZE/2 : 0;
return {
path: pth,
pathIdx: 0,
conf,
type,
hp: conf.hp,
x,
y,
initPos: 1,
progress: 0 // ✅
};
}
// --- создание пули ---
function Bullet(x, y, target, tower) {
let conf = towerData[tower.type];
return {
x, y, target,
damage: conf.damage,
speed: conf.bulletSpeed,
color: conf.color,
towerType: tower.type,
hit: false
};
}
// ===== 11. Отрисовка =====
function draw() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
drawGrid();
drawBuildHints();
drawTowerRanges();
drawTowers();
drawEnemies();
drawBullets();
if (devMode) debugDrawPath(path);
if (victory) showVictoryScreen();
if (gameOver) showGameOverScreen();
}
function drawGrid() {
ctx.save();
for (let y = 0; y < GRID_SIZE; ++y)
for (let x = 0; x < GRID_SIZE; ++x) {
ctx.strokeStyle = (x == 0 && y == 0) ? "#e3ed7a" : (x == GRID_SIZE - 1 && y == GRID_SIZE - 1 ? "#ffae00" : "#3a3a3a");
ctx.lineWidth = 2;
ctx.strokeRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
if (grid[y][x].blocked) {
ctx.fillStyle = "#593045";
ctx.globalAlpha = 0.2;
ctx.fillRect(x * CELL_SIZE + 3, y * CELL_SIZE + 3, CELL_SIZE - 6, CELL_SIZE - 6);
ctx.globalAlpha = 1.0;
}
}
ctx.restore();
if (devMode) {
ctx.save();
ctx.strokeStyle = "#31aec8"; ctx.lineWidth = 5; ctx.globalAlpha = 0.21;
ctx.beginPath();
for (let i = 0; i < path.length; ++i) {
let [x, y] = path[i];
if (i == 0) ctx.moveTo(x * CELL_SIZE + CELL_SIZE / 2, y * CELL_SIZE + CELL_SIZE / 2);
else ctx.lineTo(x * CELL_SIZE + CELL_SIZE / 2, y * CELL_SIZE + CELL_SIZE / 2);
}
ctx.stroke();
ctx.globalAlpha = 1;
ctx.restore();
}
}
function drawBuildHints() {
if (buildZoneHints && buildZoneHints.length) {
for (let hint of buildZoneHints) {