-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1069 lines (934 loc) · 74.5 KB
/
Copy pathindex.html
File metadata and controls
1069 lines (934 loc) · 74.5 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="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Baletris</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* --- Global Box Sizing --- */
*, *::before, *::after { box-sizing: border-box; }
/* Basic styling */
html, body { height: 100%; overflow: hidden; }
body {
font-family: 'Inter', sans-serif; display: flex; justify-content: center; align-items: center;
background-color: #1a1a2e; color: #e0e0e0; margin: 0; padding: 0;
flex-direction: column;
}
.game-area-wrapper {
display: flex; flex-direction: column; align-items: center; gap: 0.5rem;
width: 100%; max-width: 600px; padding: 0.5rem; flex-grow: 1;
justify-content: center;
}
/* Modifier and Timer Display Styling */
.status-display { display: flex; gap: 1rem; background-color: rgba(0, 0, 0, 0.3); padding: 0.25rem 0.75rem; border-radius: 0.375rem; margin-bottom: 0.5rem; min-height: 1.5rem; align-items: center; }
#temporary-modifier-display { font-size: 1rem; font-weight: 500; color: #facc15; }
#modifier-timer-display { font-size: 0.9rem; font-weight: 400; color: #9ca3af; }
.game-container {
display: flex; gap: 1rem; align-items: flex-start; padding: 0.5rem;
background-color: #162447; border-radius: 0.75rem; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.4);
width: 100%; justify-content: space-around; flex-wrap: wrap;
}
#hold-item-container {
cursor: pointer;
}
/* --- Board Area Wrapper --- */
#board-area {
position: relative; /* Positioning context for overlay */
/* line-height: 0; */ /* Removed */
/* Width/height set by JS */
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
min-width: 200px;
min-height: 400px;
overflow: hidden;
}
button {
touch-action: manipulation;
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
-webkit-tap-highlight-color: transparent;
}
#game-board {
--board-border-width: 3px; border: var(--board-border-width) solid #4b5563; display: grid;
border-radius: 0.5rem; box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.5);
overflow: hidden; transition: background-color 0.5s ease;
/* Width/height now implicitly 100% of #board-area (minus borders) */
/* Grid templates set by JS */
background-color: #0f172a; /* Default color set here */
flex-shrink: 0;
position: relative; /* Needed for the ::after pseudo-element positioning */
}
/* Restricted Zone Overlay */
#restricted-zone-overlay {
position: absolute; /* Top, Left, Width, Height set by JS */
background: repeating-linear-gradient( 45deg, rgb(95 95 0 / 41%), rgb(95 95 0 / 41%) 3px, rgba(0, 0, 0, 0.25) 3px, rgba(0, 0, 0, 0.25) 6px );
z-index: 100; pointer-events: none; transition: height 0.3s ease, width 0s, left 0s; /* No transition for width or left */
display: none; /* Initially hidden, shown by JS */
}
.cell { border: 1px solid #374151; border-radius: 0.125rem; position: relative; z-index: 1; }
/* Tetromino Colors */
.T { background-color: #a855f7; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); } .O { background-color: #facc15; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); } .L { background-color: #f97316; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); } .J { background-color: #3b82f6; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); } .I { background-color: #22d3ee; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); } .S { background-color: #22c55e; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); } .Z { background-color: #ef4444; box-shadow: inset 0 0 5px rgba(255,255,255,0.3); }
.ghost { background-color: rgba(255, 255, 255, 0.1); border: 1px dashed rgba(255, 255, 255, 0.3); } .garbage { background-color: #6b7280; box-shadow: inset 0 0 5px rgba(0,0,0,0.3); }
/* Info Panel Styling */
.info-panel { display: flex; flex-direction: column; gap: 0.5rem; min-width: 120px; height: 606px; padding: 0.5rem; background-color: #1e3a8a; border-radius: 0.5rem; }
.info-item { background-color: #172554; padding: 0.5rem; border-radius: 0.375rem; text-align: center; }
.info-label { font-size: 0.75rem; color: #9ca3af; margin-bottom: 0.1rem; display: block; }
.info-value { font-size: 1.1rem; font-weight: 600; color: #e5e7eb; }
/* Message Box Styling */
#message-box { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.8); color: white; padding: 2rem; border-radius: 0.75rem; text-align: center; z-index: 200; display: none; border: 2px solid #4b5563; }
#message-box button { margin-top: 1rem; padding: 0.5rem 1rem; background-color: #3b82f6; color: white; border: none; border-radius: 0.375rem; cursor: pointer; transition: background-color 0.2s; }
#message-box button:hover { background-color: #2563eb; }
/* Shop Modal Styling */
#shop-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.7); display: none; justify-content: center; align-items: center; z-index: 150; padding: 1rem; }
.shop-content { background-color: #162447; padding: 2rem; border-radius: 0.75rem; border: 2px solid #4b5563; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); color: #e0e0e0; min-width: 300px; max-width: 500px; text-align: center; }
.shop-title { font-size: 1.5rem; font-weight: 600; margin-bottom: 1.5rem; color: #fff; }
.shop-items { display: flex; gap: 1.5rem; justify-content: center; margin-bottom: 1.5rem; flex-wrap: wrap; }
.shop-item-card { background-color: #1e3a8a; padding: 1rem; border-radius: 0.5rem; border: 1px solid #3b82f6; display: flex; flex-direction: column; align-items: center; gap: 0.5rem; min-width: 150px; flex-basis: 150px; position: relative; }
.shop-item-active { border-color: #ef4444; box-shadow: 0 0 10px rgba(239, 68, 68, 0.7); }
.shop-item-active-label { position: absolute; top: -10px; left: 50%; transform: translateX(-50%); background-color: #ef4444; color: white; font-size: 0.75rem; font-weight: bold; padding: 0.1rem 0.5rem; border-radius: 0.25rem; white-space: nowrap; }
.shop-item-name { font-weight: 600; font-size: 1.1rem; margin-top: 5px; }
.shop-item-desc { font-size: 0.875rem; color: #9ca3af; min-height: 3.5em; margin-bottom: 0.5rem; }
.shop-item-cost { font-weight: bold; color: #facc15; }
.shop-buy-button { padding: 0.5rem 1rem; background-color: #10b981; color: white; border: none; border-radius: 0.375rem; cursor: pointer; transition: background-color 0.2s; width: 100%; margin-top: auto; }
.shop-buy-button:hover:not(:disabled) { background-color: #059669; }
.shop-buy-button:disabled { background-color: #4b5563; cursor: not-allowed; opacity: 0.7; }
.shop-close-button { margin-top: 1rem; padding: 0.5rem 1rem; background-color: #ef4444; color: white; border: none; border-radius: 0.375rem; cursor: pointer; transition: background-color 0.2s; }
.shop-close-button:hover { background-color: #dc2626; }
/* Visual Effects */
@keyframes shake { 0%, 100% { transform: translateX(0); } 10%, 30%, 50%, 70%, 90% { transform: translateX(-3px); } 20%, 40%, 60%, 80% { transform: translateX(3px); } } .screen-shake { animation: shake 0.2s cubic-bezier(.36,.07,.19,.97) both; }
/* Flash Effect Pseudo-Element */
#game-board::after {
content: '';
position: absolute;
/* Cover the entire element including borders */
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: white; /* Base color for flash */
opacity: 0; /* Start transparent */
pointer-events: none; /* Don't interfere with clicks */
z-index: 5; /* Above cells, below overlay? */
/* border-radius removed, will use parent's radius */
}
@keyframes flash-1 { 0% { opacity: 0; } 50% { opacity: 0.3; } 100% { opacity: 0; } } @keyframes flash-2 { 0% { opacity: 0; } 50% { opacity: 0.45; } 100% { opacity: 0; } } @keyframes flash-3 { 0% { opacity: 0; } 50% { opacity: 0.6; } 100% { opacity: 0; } } @keyframes flash-tetris { 0% { opacity: 0; background-color: #fff; } 25% { opacity: 0.8; background-color: #ff0; } 50% { opacity: 0.8; background-color: #0ff; } 75% { opacity: 0.8; background-color: #f0f; } 100% { opacity: 0; background-color: #fff; } }
.flash-1::after { animation: flash-1 0.15s ease-out; } .flash-2::after { animation: flash-2 0.2s ease-out; } .flash-3::after { animation: flash-3 0.25s ease-out; } .flash-tetris::after { animation: flash-tetris 0.4s ease-out; }
/* --- Mobile Controls Styling --- */
#controls-container { display: flex; justify-content: center; align-items: center; flex-wrap: wrap; gap: 0.5rem; padding: 0.75rem 0.5rem; width: 100%; max-width: 600px; background-color: none; border-top: 1px solid #374151; }
.control-button { background-color: #374151; color: #e5e7eb; border: 1px solid #4b5563; border-radius: 0.5rem; padding: 0.75rem; display: flex; justify-content: center; align-items: center; cursor: pointer; transition: background-color 0.15s ease; flex-grow: 1; min-width: 44px; min-height: 44px; }
.control-button:active { background-color: #4b5563; }
.control-button img { width: 24px; height: 24px; filter: invert(99%) sepia(1%) saturate(312%) hue-rotate(199deg) brightness(118%) contrast(89%); }
</style>
</head>
<body>
<div class="game-area-wrapper">
<div class="game-container" id="game-container">
<div style="width: 100%; display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: space-around;">
<div class="status-display">
<div id="temporary-modifier-display">Modifier: None</div>
<div id="modifier-timer-display">(Next in: 15s)</div>
</div>
</div>
<div id="board-area" style="position: relative;">
<div id="game-board"></div>
<div id="restricted-zone-overlay"></div>
</div>
<div class="info-panel", id='info-panel'>
<div class="info-item"> <span class="info-label">Score</span> <span id="score" class="info-value">0</span> </div>
<div class="info-item"> <span class="info-label">Combo</span> <span id="combo-multiplier" class="info-value">1.00x</span> </div>
<div class="info-item"> <span class="info-label">Speed (ms)</span> <span id="speed-display" class="info-value">0</span> </div>
<div class="info-item"> <span class="info-label">Next</span> <div id="next-piece-preview" class="mx-auto" style="width: 80px; height: 80px; display: grid; grid-template-columns: repeat(4, 20px); grid-template-rows: repeat(4, 20px);"></div> </div>
<div class="info-item" id="hold-item-container"> <span class="info-label">Hold</span> <div id="hold-piece-preview" class="mx-auto" style="width: 80px; height: 80px; display: grid; grid-template-columns: repeat(4, 20px); grid-template-rows: repeat(4, 20px);"></div> </div>
<button id="restart-button" class="control-button"><b>R</b></button>
<button id="btn-pause" class="control-button" title="Pause (P)" style="display: none;"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/pause.svg" alt="Pause" style="display: none;"/> </button>
<button id="btn-shop" class="control-button" title="Shop (B)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/shopping-cart.svg" alt="Shop"/> </button>
</div>
<div id="controls-container">
<button id="btn-rotate-l" class="control-button" title="Rotate CCW (Z)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/rotate-ccw.svg" alt="Rotate Left"/> </button>
<button id="btn-left" class="control-button" title="Move Left (A/Left)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/arrow-left.svg" alt="Left"/> </button>
<button id="btn-move-down" class="control-button" title="Move down (Down)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/arrow-down.svg" alt="Down"/> </button>
<button id="btn-drop" class="control-button" title="Hard Drop (Space)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/arrow-up.svg" alt="Drop"/> </button>
<button id="btn-right" class="control-button" title="Move Right (D/Right)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/arrow-right.svg" alt="Right"/> </button>
<button id="btn-rotate-r" class="control-button" title="Rotate CW (X/Up/W)"> <img src="https://cdn.jsdelivr.net/npm/lucide-static@latest/icons/rotate-cw.svg" alt="Rotate Right"/> </button>
</div>
</div>
</div>
<div id="message-box"> <p id="message-text"></p> <button id="message-button">OK</button> </div>
<div id="shop-modal">
<div class="shop-content">
<h2 class="shop-title">Item Shop</h2>
<p class="mb-4 text-sm text-gray-400">Press Esc or Close to resume game.</p>
<div class="shop-items" id="shop-items-container"></div>
<button id="shop-close-button" class="shop-close-button">Close</button>
</div>
</div>
<script>
// --- Game Configuration ---
const config = { /* ... */
BOARD_WIDTH: 10, BOARD_HEIGHT: 20, STARTING_SPEED: 1000, SPEED_INCREMENT_PER_LEVEL: 0.9, LINES_PER_LEVEL: 10, SCORE_MULTIPLIER: 1.0, POINTS_PER_LINE: [0, 100, 300, 500, 800], ALLOW_HOLD: true, SHOW_GHOST_PIECE: true, ALLOW_GARBAGE: true, DAS_DELAY: 160, ARR_INTERVAL: 50, SOFT_DROP_DAS_DELAY: 100, SOFT_DROP_ARR_INTERVAL: 30, LOCK_DELAY: 500, SHAKE_DURATION: 200, FLASH_DURATION_1: 150, FLASH_DURATION_2: 200, FLASH_DURATION_3: 250, FLASH_DURATION_TETRIS: 400, CELL_SIZE: 30, PREVIEW_CELL_SIZE: 20, MIN_GAME_SPEED: 50,
RISING_SPEED_FACTOR: 1.01, SHOP_ITEM_COST: 500,
SHOP_COST_INCREASE_FACTOR: 1.3,
TEMPORARY_MODIFIER_INTERVAL: 15000,
UI_TIMER_UPDATE_INTERVAL: 250,
NONE_MODIFIER_CHANCE: 0.2,
GLASS_CANNON_ROW_PENALTY: 4,
};
// --- Constants ---
const BOARD_BORDER_WIDTH = 3;
const DEFAULT_BOARD_COLOR = '#0f172a';
const NO_MODIFIER = { id: 'none', name: 'None', backgroundColor: DEFAULT_BOARD_COLOR };
const DEFAULT_PIECE_WEIGHTS = { T: 1, O: 1, L: 1, J: 1, I: 1, S: 1, Z: 1 };
// --- DOM Elements ---
const gameContainerElement = document.getElementById('game-container');
const boardAreaElement = document.getElementById('board-area'); // Get wrapper element
const gameBoardElement = document.getElementById('game-board'); // Keep for grid setup & cell append
const scoreElement = document.getElementById('score'); const linesElement = document.getElementById('lines');
const speedDisplayElement = document.getElementById('speed-display');
const nextPiecePreviewElement = document.getElementById('next-piece-preview'); const holdPiecePreviewElement = document.getElementById('hold-piece-preview');
const messageBox = document.getElementById('message-box'); const messageText = document.getElementById('message-text'); const messageButton = document.getElementById('message-button'); const restartButton = document.getElementById('restart-button');
const shopModalElement = document.getElementById('shop-modal'); const shopItemsContainerElement = document.getElementById('shop-items-container'); const shopCloseButton = document.getElementById('shop-close-button');
const temporaryModifierDisplay = document.getElementById('temporary-modifier-display');
const modifierTimerDisplay = document.getElementById('modifier-timer-display');
const restrictedZoneOverlay = document.getElementById('restricted-zone-overlay');
// Control Buttons
const btnPause = document.getElementById('btn-pause'); const btnRotateL = document.getElementById('btn-rotate-l'); const btnLeft = document.getElementById('btn-left'); const btnDrop = document.getElementById('btn-drop'); const btnRight = document.getElementById('btn-right'); const btnRotateR = document.getElementById('btn-rotate-r'); const btnShop = document.getElementById('btn-shop'); const btnDown = document.getElementById('btn-move-down');
// --- Game State ---
let board, currentPiece, nextPiece, heldPiece, canHold, score, linesCleared, level;
let baseGameSpeed; let effectiveGameSpeed;
let gameLoopInterval, isGameOver, isPaused;
let moveLeftHeld, moveRightHeld, moveDownHeld; let dasTimeoutLeft, dasTimeoutRight, dasTimeoutDown; let arrIntervalLeft, arrIntervalRight, arrIntervalDown;
let isShaking = false; let isFlashing = false; let lockDelayTimeout = null; let isPieceGrounded = false;
let isShopOpen = false;
let temporaryModifier = NO_MODIFIER; let temporaryModifierInterval = null;
let lastTemporaryModifierId = NO_MODIFIER.id;
let isFirstModifierCycle = true;
let nextModifierTimestamp = null; let uiTimerInterval = null; let pauseStartTime = null;
let shopItemsForCurrentModifier = []; // Holds the 2 items for the current cycle
let purchasedThisModifierCycle = false; // Tracks purchase within the current cycle
let comboCount = 0; // Track consecutive line clears
// --- Modifier State (Permanent & Temporary Flags/Values) ---
let modifiers = {};
function resetModifiers() {
comboCount = 0;
modifiers = {
// Permanent Modifiers (Stackable where applicable)
speedMultiplier: 1.0, // Multiplicative stacking
lineScoreMultiplierBonus: 0.0, // Additive stacking
tetrisSpecialistMultiplier: 1.0, // Multiplicative stacking for Tetris score
otherLineSpecialistMultiplier: 1.0, // Multiplicative stacking for non-Tetris score
shopCostMultiplier: 1.0, // Multiplicative stacking
isGamblerActive: false, // Boolean (effect is probabilistic per clear)
purchasedItemCount: 0, // Counter for cost increase
lockDelayMultiplier: 1.0, // Multiplicative stacking
pieceWeights: { ...DEFAULT_PIECE_WEIGHTS }, // Overwritten by 'Cursed?'
restrictedTopRows: 0, // Additive stacking
glassCannonScoreMultiplier: 1.0, // Multiplicative stacking
shopCostIncreaseMultiplier: 1.0, // Multiplicative stacking ('No Restrictions')
economyGarbageBonus: 0, // Additive stacking for extra garbage lines
// Temporary Modifiers (Generally replace previous temp effect)
tempSpeedMultiplier: 1.0,
tempLineScoreMultiplierBonus: 0.0,
tempTetrisSpecialistMultiplier: 1.0, // Added for temp Tetris Specialist
tempOtherLineSpecialistMultiplier: 1.0, // Added for temp Tetris Specialist
tempIsGamblerActive: false,
tempLockDelayMultiplier: 1.0,
tempPieceWeights: null,
tempRestrictedTopRows: 0,
tempGlassCannonScoreMultiplier: 1.0,
tempShopCostIncreaseMultiplier: 1.0,
};
updateRestrictedZoneUI();
}
// --- Item Pool Definition ---
const ITEM_POOL = [
// Stackable: Adrenaline (Score Bonus additive, Speed Multiplicative) - REBALANCED
{ id: 'adrenaline', name: 'Adrenaline', cost: config.SHOP_ITEM_COST, description: 'Score 1.25x. Speed 1.25x.', backgroundColor: '#2f1a2e',
applyEffect: () => { modifiers.lineScoreMultiplierBonus += 0.25; modifiers.speedMultiplier *= 0.75; },
applyTemporaryEffect: () => { modifiers.tempLineScoreMultiplierBonus = 0.25; modifiers.tempSpeedMultiplier = 0.75; return true; },
removeTemporaryEffect: () => { modifiers.tempLineScoreMultiplierBonus = 0.0; modifiers.tempSpeedMultiplier = 1.0; } },
// Stackable: Slowdown (Score and Speed multiplicative)
{ id: 'slowdown', name: 'Slowdown', cost: config.SHOP_ITEM_COST, description: 'Score 0.5x. Speed 0.5x.', backgroundColor: '#1a2e2e',
applyEffect: () => { modifiers.lineScoreMultiplierBonus *= 0.5; modifiers.speedMultiplier /= 0.5; },
applyTemporaryEffect: () => { modifiers.tempLineScoreMultiplierBonus *= 0.5; modifiers.tempSpeedMultiplier /= 0.5; return true; },
removeTemporaryEffect: () => { modifiers.tempLineScoreMultiplierBonus /= 0.5; modifiers.tempSpeedMultiplier *= 0.5; } },
// Stackable: Tetris Specialist (Multiplicative for Tetris/Other scores) - REBALANCED
{ id: 'tetris_specialist', name: 'Tetris Specialist', cost: config.SHOP_ITEM_COST, description: 'Tetris score +75%. Others -50%.', backgroundColor: '#1a2e2e',
applyEffect: () => { modifiers.tetrisSpecialistMultiplier *= 1.75; modifiers.otherLineSpecialistMultiplier *= 0.5; },
applyTemporaryEffect: () => { modifiers.tempTetrisSpecialistMultiplier = 1.75; modifiers.tempOtherLineSpecialistMultiplier = 0.5; return true; },
removeTemporaryEffect: () => { modifiers.tempTetrisSpecialistMultiplier = 1.0; modifiers.tempOtherLineSpecialistMultiplier = 1.0; } },
// Stackable: Economy (Multiplicative Cost, Additive Garbage)
{ id: 'economy', name: 'Economy', cost: config.SHOP_ITEM_COST, description: 'Shop costs -30%. +1 garbage line per cycle.', backgroundColor: '#1a2a1a',
applyEffect: () => { modifiers.shopCostMultiplier *= 0.7; modifiers.economyGarbageBonus += 1; },
applyTemporaryEffect: () => { return true; }, // No direct temporary effect, cost calculated at purchase, garbage is permanent
removeTemporaryEffect: () => {} },
// Not Stackable (Boolean Flag): Gambler
{ id: 'gambler', name: 'Gambler', cost: config.SHOP_ITEM_COST, description: '50% chance: double score, 50% chance: zero score.', backgroundColor: '#2a2a1a',
applyEffect: () => { modifiers.isGamblerActive = true; },
applyTemporaryEffect: () => { modifiers.tempIsGamblerActive = true; return true; },
removeTemporaryEffect: () => { modifiers.tempIsGamblerActive = false; } },
// Stackable: Rotation Master (Lock Delay Multiplicative, Speed Multiplicative)
{ id: 'rotation_master', name: 'Rotation Master', cost: config.SHOP_ITEM_COST, description: 'Lock delay x1.5. Speed +10%.', backgroundColor: '#1a1a2f',
applyEffect: () => { modifiers.lockDelayMultiplier *= 1.5; modifiers.speedMultiplier *= 0.9; },
applyTemporaryEffect: () => { modifiers.tempLockDelayMultiplier = 1.5; modifiers.tempSpeedMultiplier = 0.9; return true; },
removeTemporaryEffect: () => { modifiers.tempLockDelayMultiplier = 1.0; modifiers.tempSpeedMultiplier = 1.0; } },
// Not Stackable (Overwrites Weights): Cursed?
{ id: 'cursed', name: 'Cursed?', cost: config.SHOP_ITEM_COST, description: 'More I pieces! But also more S and Z pieces.', backgroundColor: '#2a1f1f',
applyEffect: () => { modifiers.pieceWeights = { T: 0.5, O: 0.5, L: 0.5, J: 0.5, I: 2, S: 2, Z: 2 }; },
applyTemporaryEffect: () => { modifiers.tempPieceWeights = { T: 0.5, O: 0.5, L: 0.5, J: 0.5, I: 2, S: 2, Z: 2 }; return true; },
removeTemporaryEffect: () => { modifiers.tempPieceWeights = null; } },
// Stackable: Glass Cannon (Rows Additive, Score Multiplicative) - DESCRIPTION CHANGED
{ id: 'glass_cannon', name: 'Glass Cannon', cost: config.SHOP_ITEM_COST, description: 'Score +100%. Top 4 rows blocked per purchase.', backgroundColor: '#2f1f1f',
applyEffect: () => { modifiers.restrictedTopRows += config.GLASS_CANNON_ROW_PENALTY; modifiers.glassCannonScoreMultiplier *= 2; updateRestrictedZoneUI(); },
applyTemporaryEffect: () => { modifiers.tempRestrictedTopRows = config.GLASS_CANNON_ROW_PENALTY; modifiers.tempGlassCannonScoreMultiplier = 2.0; updateRestrictedZoneUI(); return true; },
removeTemporaryEffect: () => { modifiers.tempRestrictedTopRows = 0; modifiers.tempGlassCannonScoreMultiplier = 1.0; updateRestrictedZoneUI(); } },
// Stackable: No Restrictions (Rows Additive (negative), Speed Multiplicative, Cost Multiplicative)
{ id: 'no_restrictions', name: 'No Restrictions', cost: config.SHOP_ITEM_COST, description: 'Reduce restriction by 1 row. Speed +30%, Shop Costs +40%.', backgroundColor: '#22222a',
applyEffect: () => { modifiers.restrictedTopRows = Math.max(0, modifiers.restrictedTopRows - 1); modifiers.speedMultiplier *= (1 / 1.3); modifiers.shopCostIncreaseMultiplier *= 1.4; updateRestrictedZoneUI(); },
applyTemporaryEffect: () => { if (getTotalRestrictedRows() <= 0) return false; modifiers.tempRestrictedTopRows = -1; modifiers.tempSpeedMultiplier *= (1 / 1.3); modifiers.tempShopCostIncreaseMultiplier = 1.4; updateRestrictedZoneUI(); return true; },
removeTemporaryEffect: () => { modifiers.tempRestrictedTopRows = 0; modifiers.tempSpeedMultiplier /= (1 / 1.3); modifiers.tempShopCostIncreaseMultiplier = 1.0; updateRestrictedZoneUI(); } },
// Stackable: Kinetic Conversion (Converts combo to base score/speed, resets combo)
{ id: 'kinetic_conversion', name: 'Kinetic Conversion', cost: config.SHOP_ITEM_COST, description: 'Adds combo to multiplier, increases speed.', backgroundColor: '#2a1a2f',
applyEffect: () => {
if (comboCount > 0) {
const comboBonus = comboCount * 0.05;
const speedFactor = Math.pow(0.95, comboCount);
modifiers.lineScoreMultiplierBonus += comboBonus;
modifiers.speedMultiplier *= speedFactor;
console.log(`Kinetic Conversion: Added ${comboBonus.toFixed(2)} to score bonus, speed multiplier now ${modifiers.speedMultiplier.toFixed(3)}`);
comboCount = 0; // Reset combo
}
},
applyTemporaryEffect: () => {
if (comboCount > 0) {
const comboBonus = comboCount * 0.05;
const speedFactor = Math.pow(0.95, comboCount);
modifiers.tempLineScoreMultiplierBonus = comboBonus; // Set temporary bonus
modifiers.tempSpeedMultiplier = speedFactor; // Set temporary speed factor
console.log(`Temp Kinetic Conversion: Added ${comboBonus.toFixed(2)} temp score bonus, speed mult ${speedFactor.toFixed(3)}`);
comboCount = 0; // Reset combo
return true; // Effect applied
}
return false; // Cannot apply if combo is 0
},
removeTemporaryEffect: () => {
// Reset the temporary effects applied by this item
modifiers.tempLineScoreMultiplierBonus = 0.0;
modifiers.tempSpeedMultiplier = 1.0;
// DO NOT restore combo count here
}
},
];
// --- Tetromino Definitions ---
const TETROMINOS = { 'T': { shape: [[0, 1, 0], [1, 1, 1]], color: 'T' }, 'O': { shape: [[1, 1], [1, 1]], color: 'O' }, 'L': { shape: [[1, 0, 0], [1, 1, 1]], color: 'L' }, 'J': { shape: [[0, 0, 1], [1, 1, 1]], color: 'J' }, 'I': { shape: [[1, 1, 1, 1]], color: 'I' }, 'S': { shape: [[0, 1, 1], [1, 1, 0]], color: 'S' }, 'Z': { shape: [[1, 1, 0], [0, 1, 1]], color: 'Z' } };
const PIECE_KEYS = Object.keys(TETROMINOS);
// --- Game Functions ---
function createEmptyBoard() { return Array.from({ length: config.BOARD_HEIGHT }, () => Array(config.BOARD_WIDTH).fill(null)); }
function getRandomPieceType() { const weights = modifiers.tempPieceWeights || modifiers.pieceWeights; const total = PIECE_KEYS.reduce((s, k) => s + (weights[k] || 0), 0); if (total <= 0) return PIECE_KEYS[Math.floor(Math.random() * PIECE_KEYS.length)]; let r = Math.random() * total; for (const k of PIECE_KEYS) { const w = weights[k] || 0; if (r < w) return k; r -= w; } return PIECE_KEYS[PIECE_KEYS.length - 1]; }
function createPiece(type) { const d = TETROMINOS[type]; return { type: type, shape: d.shape.map(r => r.slice()), color: d.color, x: Math.floor(config.BOARD_WIDTH / 2) - Math.ceil(d.shape[0].length / 2), y: 0 }; }
function getTotalRestrictedRows() { return Math.max(0, modifiers.restrictedTopRows + modifiers.tempRestrictedTopRows); }
function updateRestrictedZoneUI() {
const totalRows = getTotalRestrictedRows();
const height = totalRows * config.CELL_SIZE;
const overlayWidth = config.BOARD_WIDTH * config.CELL_SIZE; // Overlay width matches the grid width
if (restrictedZoneOverlay && boardAreaElement && gameBoardElement) {
// Calculate the total width of the game board element including borders
const gameBoardTotalWidth = gameBoardElement.offsetWidth; // Use offsetWidth which includes borders
// Calculate the width of the container
const boardAreaWidth = boardAreaElement.offsetWidth;
// Calculate the space on the left side due to centering
const leftOffset = (boardAreaWidth - gameBoardTotalWidth) / 2;
// Position the overlay: start after the left margin AND after the board's left border
const overlayLeftPosition = leftOffset + BOARD_BORDER_WIDTH;
// console.log(`DEBUG: Updating restricted zone UI. Total Rows: ${totalRows}, Height: ${height}px, Width: ${overlayWidth}px, Left: ${overlayLeftPosition}px`);
restrictedZoneOverlay.style.height = `${height}px`;
restrictedZoneOverlay.style.width = `${overlayWidth}px`; // Set the width dynamically
restrictedZoneOverlay.style.top = `${BOARD_BORDER_WIDTH}px`; // Position below top border
restrictedZoneOverlay.style.left = `${overlayLeftPosition}px`; // Set calculated left position
restrictedZoneOverlay.style.display = totalRows > 0 ? 'block' : 'none';
} else {
console.error("Required elements for restricted zone UI update not found!");
}
}
// Removed isPiecePotentiallyBlocked function
function isValidMove(x, y, shape) {
// Removed restriction check from here
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
if (shape[r][c]) {
const bX = x + c;
const bY = y + r;
if (bX < 0 || bX >= config.BOARD_WIDTH || bY >= config.BOARD_HEIGHT) { return false; }
if (bY >= 0 && board[bY][bX] !== null) { return false; }
}
}
}
return true;
}
function clearLockDelay() { clearTimeout(lockDelayTimeout); lockDelayTimeout = null; isPieceGrounded = false; }
function tryLockPiece() { if (!currentPiece || isGameOver || isPaused) { clearLockDelay(); return; } if (!isValidMove(currentPiece.x, currentPiece.y + 1, currentPiece.shape)) { lockPiece(); } else { clearLockDelay(); } }
function startOrResetLockDelay() { clearLockDelay(); isPieceGrounded = true; const currentLockDelay = config.LOCK_DELAY * modifiers.lockDelayMultiplier * modifiers.tempLockDelayMultiplier; lockDelayTimeout = setTimeout(tryLockPiece, currentLockDelay); }
function rotatePiece(direction) { if (!currentPiece || currentPiece.type === 'O' || isPaused || isGameOver) return; const oS = currentPiece.shape; const rws = oS.length; const cls = oS[0].length; let nS; if (direction === 1) { nS = Array.from({ length: cls }, () => Array(rws).fill(0)); for (let r=0;r<rws;r++) for (let c=0;c<cls;c++) nS[c][rws-1-r] = oS[r][c]; } else if (direction === -1) { nS = Array.from({ length: cls }, () => Array(rws).fill(0)); for (let r=0;r<rws;r++) for (let c=0;c<cls;c++) nS[cls-1-c][r] = oS[r][c]; } else return; const kcks = [ { x: 0, y: 0 }, { x: direction * -1, y: 0 }, { x: direction * -1, y: -1 }, { x: 0, y: 2 }, { x: direction * -1, y: 2 } ]; let fVK = false; let fKX = 0, fKY = 0; for (const k of kcks) { if (isValidMove(currentPiece.x + k.x, currentPiece.y + k.y, nS)) { fKX = k.x; fKY = k.y; fVK = true; break; } } if (fVK) { currentPiece.shape = nS; currentPiece.x += fKX; currentPiece.y += fKY; if (isPieceGrounded) { if (isValidMove(currentPiece.x, currentPiece.y + 1, currentPiece.shape)) { clearLockDelay(); } else { startOrResetLockDelay(); } } drawBoard(); } }
function movePiece(dx, dy) { if (!currentPiece || isPaused || isGameOver) return false; const nX = currentPiece.x + dx; const nY = currentPiece.y + dy; if (isValidMove(nX, nY, currentPiece.shape)) { const wasGrounded = isPieceGrounded; currentPiece.x = nX; currentPiece.y = nY; if (dy > 0) { clearLockDelay(); } else if (dx !== 0 && wasGrounded) { if (isValidMove(currentPiece.x, currentPiece.y + 1, currentPiece.shape)) { clearLockDelay(); } else { startOrResetLockDelay(); } } return true; } else if (dx === 0 && dy === 1 && !isPieceGrounded) { startOrResetLockDelay(); return false; } return false; }
function getGhostPieceY() { if (!currentPiece || !config.SHOW_GHOST_PIECE) return -1; let gY = currentPiece.y; while (isValidMove(currentPiece.x, gY + 1, currentPiece.shape)) gY++; return gY; }
function triggerShake() { if (!isShaking) { isShaking = true; gameContainerElement.classList.add('screen-shake'); setTimeout(() => { gameContainerElement.classList.remove('screen-shake'); isShaking = false; }, config.SHAKE_DURATION); } }
function triggerFlash(linesCount) { if (isFlashing || linesCount <= 0) return; let fC = '', dur = 0; switch (linesCount) { case 1: fC = 'flash-1'; dur = config.FLASH_DURATION_1; break; case 2: fC = 'flash-2'; dur = config.FLASH_DURATION_2; break; case 3: fC = 'flash-3'; dur = config.FLASH_DURATION_3; break; default: fC = 'flash-tetris'; dur = config.FLASH_DURATION_TETRIS; break; } isFlashing = true; gameBoardElement.classList.add(fC); setTimeout(() => { gameBoardElement.classList.remove(fC); isFlashing = false; }, dur); }
function hardDrop() { if (!currentPiece || isPaused || isGameOver) return; clearLockDelay(); const sY = currentPiece.y; while (movePiece(0, 1)) { } const eY = currentPiece.y; if (eY > sY) { triggerShake(); } lockPiece(); drawBoard(); }
function lockPiece() {
if (!currentPiece) return;
// Reset combo if no lines were cleared
const linesBefore = linesCleared;
// Removed initial restriction check
clearLockDelay();
// Place piece on board
for (let r = 0; r < currentPiece.shape.length; r++) for (let c = 0; c < currentPiece.shape[r].length; c++) if (currentPiece.shape[r][c]) { const bX = currentPiece.x + c, bY = currentPiece.y + r; if (bY < 0) { /* Standard top-out */ gameOver(); return; } if(bY < config.BOARD_HEIGHT && bX < config.BOARD_WIDTH) { board[bY][bX] = currentPiece.color; } }
clearHorizontalMovement(true); clearHorizontalMovement(false); clearVerticalMovement();
if (!isGameOver) {
baseGameSpeed = Math.max(config.MIN_GAME_SPEED, Math.floor(baseGameSpeed / config.RISING_SPEED_FACTOR));
updateGameSpeed();
// console.log(`Piece locked. New base speed interval: ${baseGameSpeed}, Effective: ${effectiveGameSpeed}`);
const lC = clearLines(); // Clear lines first
// Reset combo if piece locked without clearing lines
if (lC === 0) { // Use actual lines cleared count from this lock
comboCount = 0;
updateInfoPanel(); // Force UI update when combo resets
}
// --- New Glass Cannon Game Over Check (Post-Lock, Post-Clear) ---
const restrictedRows = getTotalRestrictedRows();
if (restrictedRows > 0) {
for (let y = 0; y < restrictedRows; y++) { // Check rows from 0 up to (but not including) restrictedRows
for (let x = 0; x < config.BOARD_WIDTH; x++) {
if (board[y][x] !== null) { // Check if any locked block exists in the restricted zone
console.log(`Game Over: Locked block found at (${x}, ${y}) within restricted zone (< ${restrictedRows})`);
gameOver();
return; // Exit lockPiece
}
}
}
}
// --- End New Check ---
if (!isGameOver) { // Check again in case the stack check caused game over
spawnNewPiece();
}
canHold = true;
drawBoard();
} else {
drawBoard();
}
}
function clearLines() {
let linesToClear = [];
for (let y = config.BOARD_HEIGHT - 1; y >= 0; y--) { if (board[y].every(c => c !== null) && !board[y].every(c => c === 'garbage')) linesToClear.push(y); }
const linesCount = linesToClear.length;
if (linesCount > 0) {
triggerFlash(linesCount);
linesToClear.sort((a, b) => a - b);
for (let i = linesCount - 1; i >= 0; i--) board.splice(linesToClear[i], 1);
for (let i = 0; i < linesCount; i++) board.unshift(Array(config.BOARD_WIDTH).fill(null));
let basePoints = config.POINTS_PER_LINE[linesCount] || 0;
let currentScoreMultiplier = config.SCORE_MULTIPLIER * (1 + modifiers.lineScoreMultiplierBonus + modifiers.tempLineScoreMultiplierBonus);
// Apply Tetris Specialist multipliers (permanent and temporary stack multiplicatively)
if (linesCount === 4) {
currentScoreMultiplier *= modifiers.tetrisSpecialistMultiplier * modifiers.tempTetrisSpecialistMultiplier;
} else {
currentScoreMultiplier *= modifiers.otherLineSpecialistMultiplier * modifiers.tempOtherLineSpecialistMultiplier;
}
let gamblerMultiplier = 1.0;
if (modifiers.isGamblerActive || modifiers.tempIsGamblerActive) {
if (Math.random() < 0.5) {
gamblerMultiplier = 2.0; console.log("Gambler: Double Score!");
} else {
gamblerMultiplier = 0.0; console.log("Gambler: Zero Score!");
}
}
// Apply Glass Cannon multiplier (permanent and temporary stack multiplicatively)
let glassCannonMult = modifiers.glassCannonScoreMultiplier * modifiers.tempGlassCannonScoreMultiplier;
// Calculate combo multiplier (5% per line in combo)
const comboMultiplier = 1 + (comboCount * 0.05);
let finalScore = basePoints * currentScoreMultiplier * level * gamblerMultiplier * glassCannonMult * comboMultiplier;
score += Math.floor(finalScore);
comboCount += linesCount; // Increase combo AFTER calculating score for this clear
linesCleared += linesCount;
const newLevel = Math.floor(linesCleared / config.LINES_PER_LEVEL) + 1;
let levelUpOccurred = false;
if (newLevel > level) { level = newLevel; baseGameSpeed = config.STARTING_SPEED * Math.pow(config.SPEED_INCREMENT_PER_LEVEL, level - 1); levelUpOccurred = true; }
updateGameSpeed(); updateInfoPanel();
}
return linesCount;
}
function addGarbageLines(count, holePos = -1) { if (!config.ALLOW_GARBAGE || count <= 0 || isPaused || isGameOver) return; console.log(`Adding ${count} garbage line(s)`); for (let i = 0; i < count; i++) { board.shift(); const nL = Array(config.BOARD_WIDTH).fill('garbage'); const hC = holePos === -1 ? Math.floor(Math.random() * config.BOARD_WIDTH) : holePos % config.BOARD_WIDTH; nL[hC] = null; board.push(nL); } if (currentPiece && !isValidMove(currentPiece.x, currentPiece.y, currentPiece.shape)) { if (isValidMove(currentPiece.x, currentPiece.y - 1, currentPiece.shape)) currentPiece.y--; else if (isValidMove(currentPiece.x, currentPiece.y - 2, currentPiece.shape)) currentPiece.y -= 2; else console.warn("Piece conflict after adding garbage lines."); } drawBoard(); }
function spawnNewPiece() {
if (isGameOver) return;
clearLockDelay();
currentPiece = createPiece(nextPiece.type);
nextPiece = createPiece(getRandomPieceType());
// console.log("Spawn Cycle: Was Next:", currentPiece.type, "| Just Spawned:", currentPiece.type, "| New Next:", nextPiece.type);
updateNextPiecePreview();
// Standard spawn check
if (!isValidMove(currentPiece.x, currentPiece.y, currentPiece.shape)) {
console.log(`Game Over: Piece spawn invalid at x=${currentPiece.x}, y=${currentPiece.y}. (Not restriction related)`);
currentPiece = null;
gameOver();
}
}
function holdPiece() { if (!config.ALLOW_HOLD || !canHold || !currentPiece || isPaused || isGameOver) return; clearLockDelay(); const prevH = heldPiece; heldPiece = createPiece(currentPiece.type); updateHoldPiecePreview(); clearHorizontalMovement(true); clearHorizontalMovement(false); clearVerticalMovement(); if (prevH) { currentPiece = createPiece(prevH.type); currentPiece.x = Math.floor(config.BOARD_WIDTH / 2) - Math.ceil(currentPiece.shape[0].length / 2); currentPiece.y = 0; if (!isValidMove(currentPiece.x, currentPiece.y, currentPiece.shape)) gameOver(); } else { spawnNewPiece(); } canHold = false; drawBoard(); }
function drawBoard() {
if (!gameBoardElement) return;
requestAnimationFrame(() => {
config.CELL_SIZE = (document.getElementById('game-container').offsetWidth - BOARD_BORDER_WIDTH * 2 - document.getElementById('info-panel').offsetWidth) / config.BOARD_WIDTH * 0.8;
// --- Board Size Calculation (Set on Wrapper) ---
const totalWidth = ((config.BOARD_WIDTH * config.CELL_SIZE) + (BOARD_BORDER_WIDTH * 2));
const totalHeight = (config.BOARD_HEIGHT * config.CELL_SIZE) + (BOARD_BORDER_WIDTH * 2);
if (boardAreaElement) { // Check if wrapper exists
boardAreaElement.style.width = `${totalWidth}px`;
boardAreaElement.style.height = `${totalHeight}px`;
} else { console.error("Board Area element not found!"); }
// Set grid template on the actual board
gameBoardElement.style.gridTemplateColumns = `repeat(${config.BOARD_WIDTH}, ${config.CELL_SIZE}px)`;
gameBoardElement.style.gridTemplateRows = `repeat(${config.BOARD_HEIGHT}, ${config.CELL_SIZE}px)`;
// Update restricted zone UI after board size is set
updateRestrictedZoneUI();
// --- End Board Size ---
if(isGameOver && !currentPiece) { gameBoardElement.innerHTML = ''; for (let y=0;y<config.BOARD_HEIGHT; y++) for(let x=0;x<config.BOARD_WIDTH;x++) {const c=document.createElement('div');c.classList.add('cell');c.style.width=`${config.CELL_SIZE}px`;c.style.height=`${config.CELL_SIZE}px`;c.style.backgroundColor='#333';gameBoardElement.appendChild(c);} return; }
gameBoardElement.innerHTML = ''; // Clear only grid cells container
const gY = getGhostPieceY(); const cells = [];
for (let y=0;y<config.BOARD_HEIGHT;y++) for(let x=0;x<config.BOARD_WIDTH;x++) {const c=document.createElement('div');c.classList.add('cell');c.style.width=`${config.CELL_SIZE}px`;c.style.height=`${config.CELL_SIZE}px`;if(board[y][x])c.classList.add(board[y][x]);cells.push(c);gameBoardElement.appendChild(c);}
if (currentPiece && config.SHOW_GHOST_PIECE && gY !== -1) { currentPiece.shape.forEach((row, r) => row.forEach((val, c) => { if (val) { const bX = currentPiece.x + c, bY = gY + r; if (isValidMove(bX, bY, [[1]])) { const idx = bY * config.BOARD_WIDTH + bX; if (cells[idx] && !board[bY][bX]) cells[idx].classList.add('ghost'); } } })); }
if (currentPiece) { currentPiece.shape.forEach((row, r) => row.forEach((val, c) => { if (val) { const bX = currentPiece.x + c, bY = currentPiece.y + r; if (bY >= 0 && bY < config.BOARD_HEIGHT && bX >= 0 && bX < config.BOARD_WIDTH) { const idx = bY * config.BOARD_WIDTH + bX; if (cells[idx]) { cells[idx].className = 'cell'; cells[idx].classList.add(currentPiece.color); cells[idx].style.width = `${config.CELL_SIZE}px`; cells[idx].style.height = `${config.CELL_SIZE}px`; } } } })); }
});
}
function drawPreview(element, piece) { element.innerHTML = ''; element.style.gridTemplateColumns = `repeat(4, ${config.PREVIEW_CELL_SIZE}px)`; element.style.gridTemplateRows = `repeat(4, ${config.PREVIEW_CELL_SIZE}px)`; if (piece) { const { shape: s, color: clr } = piece; const h = s.length, w = s[0].length; const oX = Math.floor((4 - w) / 2), oY = Math.floor((4 - h) / 2); for (let r=0;r<4;r++) for(let c=0;c<4;c++) {const cell=document.createElement('div');cell.style.width=`${config.PREVIEW_CELL_SIZE}px`;cell.style.height=`${config.PREVIEW_CELL_SIZE}px`;cell.style.borderRadius='2px';const sR=r-oY,sC=c-oX;if(sR>=0&&sR<h&&sC>=0&&sC<w&&s[sR][sC])cell.classList.add(clr);else cell.style.backgroundColor='transparent';element.appendChild(cell);} } else { for(let i=0;i<16;i++){const c=document.createElement('div');c.style.width=`${config.PREVIEW_CELL_SIZE}px`;c.style.height=`${config.PREVIEW_CELL_SIZE}px`;c.style.backgroundColor='transparent';element.appendChild(c);} } }
function updateNextPiecePreview() { drawPreview(nextPiecePreviewElement, nextPiece); } function updateHoldPiecePreview() { drawPreview(holdPiecePreviewElement, heldPiece); }
function updateInfoPanel() {
scoreElement.textContent = score;
// Calculate the current combo multiplier value
const comboMultiplierValue = 1 + (comboCount * 0.05);
// Calculate total multiplier including all bonuses
const totalMultiplier = comboMultiplierValue *
(1 + modifiers.lineScoreMultiplierBonus + modifiers.tempLineScoreMultiplierBonus) *
modifiers.glassCannonScoreMultiplier * modifiers.tempGlassCannonScoreMultiplier;
// Display the total multiplier including all active bonuses
document.getElementById('combo-multiplier').textContent = totalMultiplier.toFixed(2) + 'x';
speedDisplayElement.textContent = effectiveGameSpeed;
}
function updateGameSpeed() {
// Permanent and temporary speed multipliers stack multiplicatively
let combinedSpeedMultiplier = modifiers.speedMultiplier * modifiers.tempSpeedMultiplier;
effectiveGameSpeed = Math.max(config.MIN_GAME_SPEED, Math.floor(baseGameSpeed * combinedSpeedMultiplier));
clearInterval(gameLoopInterval);
if (!isGameOver && !isPaused) {
gameLoopInterval = setInterval(gameLoop, effectiveGameSpeed);
}
// console.log(`Updating speed. Base: ${baseGameSpeed}, PermMod: ${modifiers.speedMultiplier}, TempMod: ${modifiers.tempSpeedMultiplier}, Effective: ${effectiveGameSpeed}`);
if(speedDisplayElement) { speedDisplayElement.textContent = effectiveGameSpeed; }
}
function showMessage(text, btnText, cb) { messageText.textContent = text; messageButton.textContent = btnText; messageButton.onclick = () => { messageBox.style.display = 'none'; if (cb) cb(); }; messageBox.style.display = 'block'; }
function pauseGame(showMsg = true) { if (isPaused || isGameOver) return; isPaused = true; pauseStartTime = Date.now(); clearInterval(gameLoopInterval); clearInterval(temporaryModifierInterval); clearInterval(uiTimerInterval); clearHorizontalMovement(true); clearHorizontalMovement(false); clearVerticalMovement(); clearLockDelay(); if (showMsg) { showMessage('Paused', 'Resume', resumeGame); } console.log("Game Paused"); }
function resumeGame() { if (!isPaused || isGameOver) return; isPaused = false; if (pauseStartTime && nextModifierTimestamp) { const pauseDuration = Date.now() - pauseStartTime; nextModifierTimestamp += pauseDuration; } pauseStartTime = null; messageBox.style.display = 'none'; updateGameSpeed(); if (temporaryModifierInterval !== null) { const remainingTime = nextModifierTimestamp ? Math.max(0, nextModifierTimestamp - Date.now()) : config.TEMPORARY_MODIFIER_INTERVAL; clearInterval(temporaryModifierInterval); temporaryModifierInterval = setTimeout(() => { cycleTemporaryModifier(); clearInterval(temporaryModifierInterval); temporaryModifierInterval = setInterval(cycleTemporaryModifier, config.TEMPORARY_MODIFIER_INTERVAL); }, remainingTime); } if (uiTimerInterval !== null) { clearInterval(uiTimerInterval); uiTimerInterval = setInterval(updateUITimer, config.UI_TIMER_UPDATE_INTERVAL); } console.log("Game Resumed"); }
function togglePause() { if (isShopOpen) return; if (isPaused) { resumeGame(); } else { pauseGame(true); } }
function gameOver() { if (isGameOver) return; isGameOver = true; clearInterval(gameLoopInterval); clearInterval(temporaryModifierInterval); clearInterval(uiTimerInterval); clearHorizontalMovement(true); clearHorizontalMovement(false); clearVerticalMovement(); clearLockDelay(); showMessage(`Game Over!\nScore: ${score}`, 'Restart', startGame); console.log("Game Over!"); drawBoard(); }
function gameLoop() { if (isGameOver || isPaused || !currentPiece) return; if (!arrIntervalDown && !lockDelayTimeout) { if (!movePiece(0, 1)) { } else { drawBoard(); } } }
// --- Temporary Modifier Logic ---
function cycleTemporaryModifier() {
if (isPaused || isGameOver) return;
// Reset purchase flag for the new cycle
purchasedThisModifierCycle = false;
// Remove previous temporary effect
if (temporaryModifier && temporaryModifier.removeTemporaryEffect) {
console.log(`Removing temp modifier: ${temporaryModifier.name}`);
temporaryModifier.removeTemporaryEffect();
}
// Reset all temporary modifier values explicitly before applying the new one
modifiers.tempSpeedMultiplier = 1.0;
modifiers.tempLineScoreMultiplierBonus = 0.0;
modifiers.tempTetrisSpecialistMultiplier = 1.0;
modifiers.tempOtherLineSpecialistMultiplier = 1.0;
modifiers.tempIsGamblerActive = false;
modifiers.tempLockDelayMultiplier = 1.0;
modifiers.tempPieceWeights = null;
modifiers.tempRestrictedTopRows = 0;
modifiers.tempGlassCannonScoreMultiplier = 1.0;
modifiers.tempShopCostIncreaseMultiplier = 1.0;
if (isFirstModifierCycle) {
temporaryModifier = NO_MODIFIER;
lastTemporaryModifierId = NO_MODIFIER.id;
isFirstModifierCycle = false;
console.log("Applying initial temp modifier: None");
} else {
if (Math.random() < config.NONE_MODIFIER_CHANCE) {
temporaryModifier = NO_MODIFIER;
console.log("Applying temp modifier: None");
} else {
// Filter potential items, excluding the last one and conditional ones
const possibleItems = ITEM_POOL.filter(item => {
if (item.id === lastTemporaryModifierId) return false;
if (item.id === 'no_restrictions' && getTotalRestrictedRows() <= 0) return false;
if (item.id === 'kinetic_conversion' && comboCount <= 0) return false; // Cannot apply if combo is 0
return true;
});
let selectedItem;
if (possibleItems.length > 0) {
const randomIndex = Math.floor(Math.random() * possibleItems.length);
selectedItem = possibleItems[randomIndex];
} else {
// Fallback if filtering removed all options (e.g., only last modifier was possible)
const fallbackOptions = ITEM_POOL.filter(item => item.id !== lastTemporaryModifierId);
selectedItem = fallbackOptions.length > 0 ? fallbackOptions[Math.floor(Math.random() * fallbackOptions.length)] : NO_MODIFIER;
// Re-check conditions for the fallback item
if (selectedItem.id === 'no_restrictions' && getTotalRestrictedRows() <= 0) selectedItem = NO_MODIFIER;
if (selectedItem.id === 'kinetic_conversion' && comboCount <= 0) selectedItem = NO_MODIFIER;
}
// Apply the new temporary effect
if (selectedItem.applyTemporaryEffect) {
if (selectedItem.applyTemporaryEffect()) { // Check if effect could be applied
temporaryModifier = selectedItem;
console.log(`Applying temp modifier: ${temporaryModifier.name}`);
} else {
temporaryModifier = NO_MODIFIER; // Failed to apply
console.log(`Failed to apply temp modifier ${selectedItem.name}, defaulting to None.`);
}
} else {
temporaryModifier = NO_MODIFIER; // Default to None if no temp effect function
console.log(`Selected item ${selectedItem.name} has no temp effect, defaulting to None.`);
}
}
lastTemporaryModifierId = temporaryModifier.id;
}
// Generate the shop items for this new cycle
generateShopItemsForCycle(temporaryModifier.id);
temporaryModifierDisplay.textContent = `Modifier: ${temporaryModifier.name}`;
gameBoardElement.style.backgroundColor = temporaryModifier.backgroundColor || DEFAULT_BOARD_COLOR;
updateRestrictedZoneUI(); // Update UI based on combined permanent + new temporary state
updateInfoPanel(); // Update combo display if Kinetic Conversion reset it
// Add garbage lines: base 1 + bonus from Economy items
if (!isFirstModifierCycle && config.ALLOW_GARBAGE) {
const garbageToAdd = 1 + modifiers.economyGarbageBonus;
if (garbageToAdd > 0) {
addGarbageLines(garbageToAdd);
}
}
nextModifierTimestamp = Date.now() + config.TEMPORARY_MODIFIER_INTERVAL;
updateGameSpeed(); // Update speed based on combined permanent + new temporary state
updateUITimer();
}
// --- UI Timer Update ---
function updateUITimer() {
if (isPaused || isGameOver || !nextModifierTimestamp) {
modifierTimerDisplay.textContent = ""; return;
}
const now = Date.now();
const timeLeft = Math.max(0, Math.ceil((nextModifierTimestamp - now) / 1000));
modifierTimerDisplay.textContent = `(Next in: ${timeLeft}s)`;
}
// --- Shop Logic ---
// New function to generate shop items for the current modifier cycle
function generateShopItemsForCycle(activeTempModifierId) {
shopItemsForCurrentModifier = []; // Clear previous items
let activeTempItem = null;
if (activeTempModifierId !== NO_MODIFIER.id) {
activeTempItem = ITEM_POOL.find(item => item.id === activeTempModifierId);
if (activeTempItem) {
shopItemsForCurrentModifier.push(activeTempItem); // Add active item first
}
}
// Filter available items: exclude active temp item and items with unmet conditions
const availableItems = ITEM_POOL.filter(item => {
if (item.id === activeTempModifierId) return false; // Exclude active temp item
if (item.id === 'no_restrictions' && getTotalRestrictedRows() <= 0) return false; // Exclude No Restrictions if no rows are restricted
if (item.id === 'kinetic_conversion' && comboCount <= 0) return false; // Exclude Kinetic Conversion if combo is 0
return true;
});
// Add random items until we have 2 (or run out of available items)
while (shopItemsForCurrentModifier.length < 2 && availableItems.length > 0) {
const randomIndex = Math.floor(Math.random() * availableItems.length);
const newItem = availableItems.splice(randomIndex, 1)[0];
// Ensure no duplicates (shouldn't happen with current logic, but good practice)
if (!shopItemsForCurrentModifier.some(existing => existing.id === newItem.id)) {
shopItemsForCurrentModifier.push(newItem);
}
}
// If still less than 2 and the pool has more items (e.g., active item was the only one filtered initially)
if (shopItemsForCurrentModifier.length < 2 && ITEM_POOL.length > shopItemsForCurrentModifier.length) {
const fallbackItems = ITEM_POOL.filter(item =>
!shopItemsForCurrentModifier.some(existing => existing.id === item.id) &&
!(item.id === 'no_restrictions' && getTotalRestrictedRows() <= 0) &&
!(item.id === 'kinetic_conversion' && comboCount <= 0) // Also check condition here
);
if (fallbackItems.length > 0) {
shopItemsForCurrentModifier.push(fallbackItems[Math.floor(Math.random() * fallbackItems.length)]);
}
}
console.log("Generated shop items for cycle:", shopItemsForCurrentModifier.map(i => i.name));
}
function openShop() {
if (isGameOver || isShopOpen || isPaused) return;
console.log("Opening Shop...");
pauseGame(false); // Pause without showing the 'Paused' message
isShopOpen = true;
// Items are already generated by generateShopItemsForCycle
populateShopUI(); // Populate UI with the current cycle's items
shopModalElement.style.display = 'flex';
}
function closeShop() {
if (!isShopOpen) return;
console.log("Closing Shop...");
isShopOpen = false;
shopModalElement.style.display = 'none';
resumeGame();
}
function populateShopUI() {
shopItemsContainerElement.innerHTML = '';
if (shopItemsForCurrentModifier.length === 0) {
shopItemsContainerElement.innerHTML = '<p>No items available!</p>';
return;
}
shopItemsForCurrentModifier.forEach((item, index) => {
const itemCard = document.createElement('div');
itemCard.className = 'shop-item-card';
// Calculate base cost considering purchase count increase
const currentBaseCost = config.SHOP_ITEM_COST * Math.pow(config.SHOP_COST_INCREASE_FACTOR, modifiers.purchasedItemCount);
// Apply permanent cost multipliers (Economy, No Restrictions)
// Temporary cost multipliers are NOT applied here, as they are temporary effects, not shop price changes
const displayCost = Math.floor(currentBaseCost * modifiers.shopCostMultiplier * modifiers.shopCostIncreaseMultiplier);
// Check if this item is the currently active temporary modifier (and is the first item displayed)
const isActiveTemporary = temporaryModifier && item.id !== NO_MODIFIER.id && item.id === temporaryModifier.id && index === 0;
if (isActiveTemporary) {
itemCard.classList.add('shop-item-active');
const activeLabel = document.createElement('div');
activeLabel.className = 'shop-item-active-label';
activeLabel.textContent = 'Active Effect';
itemCard.appendChild(activeLabel);
}
const nameEl = document.createElement('div'); nameEl.className = 'shop-item-name'; nameEl.textContent = item.name;
const descEl = document.createElement('div'); descEl.className = 'shop-item-desc'; descEl.textContent = item.description;
const costEl = document.createElement('div'); costEl.className = 'shop-item-cost'; costEl.textContent = `Cost: ${displayCost}`;
const buyButton = document.createElement('button'); buyButton.className = 'shop-buy-button'; buyButton.textContent = 'Buy'; buyButton.dataset.itemId = item.id; buyButton.dataset.itemIndex = index; // Keep index for potential future use
// Disable button if cannot afford OR if an item was already bought THIS MODIFIER CYCLE
// Also disable Kinetic Conversion if comboCount is 0
let isDisabled = score < displayCost || purchasedThisModifierCycle;
if (item.id === 'kinetic_conversion' && comboCount <= 0) {
isDisabled = true;
descEl.textContent += " (Requires Combo > 0)"; // Add note to description
}
buyButton.disabled = isDisabled;
buyButton.onclick = () => buyItem(item.id, displayCost);
itemCard.appendChild(nameEl); itemCard.appendChild(descEl); itemCard.appendChild(costEl); itemCard.appendChild(buyButton);
shopItemsContainerElement.appendChild(itemCard);
});
}
function buyItem(itemId, purchaseCost) {
// Check if already purchased this modifier cycle
if (purchasedThisModifierCycle) {
console.log("Already purchased an item this modifier cycle.");
showMessage("You can only buy one item per modifier cycle.", "OK");
return;
}
const itemIndex = shopItemsForCurrentModifier.findIndex(item => item.id === itemId);
if (itemIndex === -1) return; // Should not happen
const item = shopItemsForCurrentModifier[itemIndex];
// Specific check for Kinetic Conversion
if (item.id === 'kinetic_conversion' && comboCount <= 0) {
console.log("Cannot buy Kinetic Conversion with 0 combo.");
showMessage("Cannot buy Kinetic Conversion with 0 combo.", "OK");
return;
}
if (score >= purchaseCost) {
console.log(`Buying item: ${item.name} for ${purchaseCost}`);
score -= purchaseCost;
item.applyEffect(); // Apply permanent (stacking) effect
modifiers.purchasedItemCount++;
purchasedThisModifierCycle = true; // Set flag for this cycle
// Update dependent game state immediately after purchase
updateGameSpeed(); // Speed might change
updateInfoPanel(); // Update score display AND combo display (if reset)
updateRestrictedZoneUI(); // Restrictions might change
populateShopUI(); // Re-populate to disable buttons and update costs for next potential purchase (if cycle limit removed)
} else {
console.log(`Cannot afford item: ${item.name} (Cost: ${purchaseCost})`);
showMessage(`Cannot afford ${item.name}.\nNeed ${purchaseCost}, have ${score}.`, "OK");
}
}
// --- Input Handling ---
function clearHorizontalMovement(isLeft) { if (isLeft) { clearTimeout(dasTimeoutLeft); clearInterval(arrIntervalLeft); dasTimeoutLeft = null; arrIntervalLeft = null; moveLeftHeld = false; } else { clearTimeout(dasTimeoutRight); clearInterval(arrIntervalRight); dasTimeoutRight = null; arrIntervalRight = null; moveRightHeld = false; } } function clearVerticalMovement() { clearTimeout(dasTimeoutDown); clearInterval(arrIntervalDown); dasTimeoutDown = null; arrIntervalDown = null; moveDownHeld = false; } function startHorizontalArr(isLeft) { const dir = isLeft ? -1 : 1; const intId = setInterval(() => { if (movePiece(dir, 0)) drawBoard(); }, config.ARR_INTERVAL); if (isLeft) arrIntervalLeft = intId; else arrIntervalRight = intId; } function startVerticalArr() { arrIntervalDown = setInterval(() => { if (!movePiece(0, 1)) { clearVerticalMovement(); } else { drawBoard(); } }, config.SOFT_DROP_ARR_INTERVAL); }
function handleKeyDown(event) {
if (event.key === 'Escape' && isShopOpen) { closeShop(); return; }
if (event.key === 'b' || event.key === 'B') { if (isShopOpen) { closeShop(); } else { openShop(); } return; }
if (isShopOpen) return;
if (event.key === 'p' || event.key === 'P') { togglePause(); return; }
if (isGameOver || isPaused || !currentPiece) return;
const key = event.key;
const pieceType = currentPiece.type;
if (key === 'ArrowLeft' || key === 'a') { if (!moveLeftHeld) { moveLeftHeld = true; clearHorizontalMovement(false); if (movePiece(-1, 0)) drawBoard(); dasTimeoutLeft = setTimeout(() => { if (moveLeftHeld) startHorizontalArr(true); }, config.DAS_DELAY); } event.preventDefault(); }
else if (key === 'ArrowRight' || key === 'd') { if (!moveRightHeld) { moveRightHeld = true; clearHorizontalMovement(true); if (movePiece(1, 0)) drawBoard(); dasTimeoutRight = setTimeout(() => { if (moveRightHeld) startHorizontalArr(false); }, config.DAS_DELAY); } event.preventDefault(); }
else if (key === 'ArrowDown' || key === 's') { if (!moveDownHeld) { moveDownHeld = true; if (movePiece(0, 1)) { drawBoard(); dasTimeoutDown = setTimeout(() => { if (moveDownHeld) startVerticalArr(); }, config.SOFT_DROP_DAS_DELAY); } } event.preventDefault(); }
else if (key === 'ArrowUp' || key === 'w' || key === 'x') { rotatePiece(1); } // CW
else if (key === 'z') { rotatePiece(-1); } // CCW
else if (key === ' ') { hardDrop(); }
else if (key === 'Shift' || key === 'c') { holdPiece(); }
// else if (key === 'l') { /* Debug Level up removed */ }
}
function handleKeyUp(event) { if (isShopOpen || isGameOver || isPaused) return; const key = event.key; if (key === 'ArrowLeft' || key === 'a') clearHorizontalMovement(true); else if (key === 'ArrowRight' || key === 'd') clearHorizontalMovement(false); else if (key === 'ArrowDown' || key === 's') clearVerticalMovement(); }
function startGame() {
console.log("Starting Game...");
board = createEmptyBoard(); score = 0; linesCleared = 0; level = 1; comboCount = 0;
updateInfoPanel(); // Use the full calculation instead of hardcoded value
baseGameSpeed = config.STARTING_SPEED;
isGameOver = false; isPaused = false; isShopOpen = false;
canHold = true; heldPiece = null;
resetModifiers(); // Reset permanent item effects & temporary flags
temporaryModifier = NO_MODIFIER; // Start with None
lastTemporaryModifierId = NO_MODIFIER.id; // Reset last modifier tracking
isFirstModifierCycle = true; // Ensure first cycle is handled correctly
purchasedThisModifierCycle = false; // Reset purchase flag
shopItemsForCurrentModifier = []; // Clear shop items
clearInterval(temporaryModifierInterval);
clearInterval(uiTimerInterval);
temporaryModifierDisplay.textContent = 'Modifier: None';
modifierTimerDisplay.textContent = '';
gameBoardElement.style.backgroundColor = DEFAULT_BOARD_COLOR;
updateRestrictedZoneUI(); // Reset overlay
// Generate initial shop items for the first "None" cycle
generateShopItemsForCycle(NO_MODIFIER.id);
clearHorizontalMovement(true); clearHorizontalMovement(false); clearVerticalMovement(); clearLockDelay();
shopModalElement.style.display = 'none'; messageBox.style.display = 'none';
nextPiece = createPiece(getRandomPieceType()); // Generate initial next piece
spawnNewPiece(); // Spawn first piece, generate second next piece
clearInterval(gameLoopInterval);
updateGameSpeed();
updateInfoPanel();
updateHoldPiecePreview(); drawBoard();
nextModifierTimestamp = Date.now() + config.TEMPORARY_MODIFIER_INTERVAL;
// Start interval normally, first cycle logic handled inside cycleTemporaryModifier
temporaryModifierInterval = setInterval(cycleTemporaryModifier, config.TEMPORARY_MODIFIER_INTERVAL);
uiTimerInterval = setInterval(updateUITimer, config.UI_TIMER_UPDATE_INTERVAL);
updateUITimer();
}
function addButtonListeners() {
// Блокируем контекстное меню для всех кнопок
const allButtons = [
btnPause, btnRotateL, btnLeft, btnDrop,
btnDown, btnRight, btnRotateR, btnShop,
holdPiecePreviewElement
].filter(Boolean);
allButtons.forEach(button => {
button.addEventListener('contextmenu', (e) => e.preventDefault());
});
// Простая обработка touchstart/touchend вместо click
btnPause.addEventListener('touchstart', (e) => {
e.preventDefault();
togglePause();
});
btnPause.addEventListener('click', togglePause);
// Кнопки движения с поддержкой удержания
let moveLeftInterval, moveRightInterval, moveDownInterval;
// Влево
btnLeft.addEventListener('touchstart', (e) => {
e.preventDefault();
movePiece(-1, 0);
drawBoard();
clearInterval(moveLeftInterval);
moveLeftInterval = setInterval(() => {
movePiece(-1, 0);
drawBoard();
}, 100); // Интервал повторения
});
btnLeft.addEventListener('touchend', () => {
clearInterval(moveLeftInterval);
});
// C обычным кликом для десктопа
btnLeft.addEventListener('click', () => {
movePiece(-1, 0);
drawBoard();
});
// Вправо
btnRight.addEventListener('touchstart', (e) => {
e.preventDefault();
movePiece(1, 0);
drawBoard();
clearInterval(moveRightInterval);
moveRightInterval = setInterval(() => {
movePiece(1, 0);
drawBoard();
}, 100);
});
btnRight.addEventListener('touchend', () => {
clearInterval(moveRightInterval);
});
btnRight.addEventListener('click', () => {
movePiece(1, 0);
drawBoard();
});
// Вниз
btnDown.addEventListener('touchstart', (e) => {
e.preventDefault();
movePiece(0, 1);
drawBoard();
clearInterval(moveDownInterval);
moveDownInterval = setInterval(() => {
movePiece(0, 1);
drawBoard();
}, 100);
});