-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebtris.js
1757 lines (1512 loc) · 50.9 KB
/
debtris.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
class Debtris {
// tetromino names
static Z_TETROMINO = 'z';
static S_TETROMINO = 's';
static O_TETROMINO = 'o';
static L_TETROMINO = 'l';
static J_TETROMINO = 'j';
static T_TETROMINO = 't';
static I_TETROMINO = 'i';
// initial positions
static Z_INITIAL = [ 4, 1 ];
static S_INITIAL = [ 4, 1 ];
static O_INITIAL = [ 4, 2 ];
static L_INITIAL = [ 4, 1 ];
static J_INITIAL = [ 4, 1 ];
static T_INITIAL = [ 4, 1 ];
static I_INITIAL = [ 3, 0 ];
static Z_BOX = [ 1, 0, 2, 3 ]; // x y hei wid
static S_BOX = [ 1, 0, 2, 3 ];
static O_BOX = [ 0, 0, 2, 2 ];
static L_BOX = [ 1, 0, 2, 3 ];
static J_BOX = [ 1, 0, 2, 3 ];
static T_BOX = [ 1, 0, 2, 3 ];
static I_BOX = [ 2, 0, 1, 4 ];
static Z_ROTATIONS = [
[
[ 0, 0, 0 ],
[ 1, 1, 0 ],
[ 0, 1, 1 ]
],
[
[ 0, 0, 1 ],
[ 0, 1, 1 ],
[ 0, 1, 0 ]
]
];
static S_ROTATIONS = [
[
[ 0, 0, 0 ],
[ 0, 1, 1 ],
[ 1, 1, 0 ]
],
[
[ 0, 1, 0 ],
[ 0, 1, 1 ],
[ 0, 0, 1 ]
]
];
static O_ROTATIONS = [
[
[ 1, 1 ],
[ 1, 1 ]
]
];
static L_ROTATIONS = [
[
[ 0, 0, 0 ],
[ 1, 1, 1 ],
[ 1, 0, 0 ]
],
[
[ 1, 1, 0 ],
[ 0, 1, 0 ],
[ 0, 1, 0 ]
],
[
[ 0, 0, 1 ],
[ 1, 1, 1 ],
[ 0, 0, 0 ]
],
[
[ 0, 1, 0 ],
[ 0, 1, 0 ],
[ 0, 1, 1 ]
]
];
static J_ROTATIONS = [
[
[ 0, 0, 0 ],
[ 1, 1, 1 ],
[ 0, 0, 1 ]
],
[
[ 0, 1, 0 ],
[ 0, 1, 0 ],
[ 1, 1, 0 ]
],
[
[ 1, 0, 0 ],
[ 1, 1, 1 ],
[ 0, 0, 0 ]
],
[
[ 0, 1, 1 ],
[ 0, 1, 0 ],
[ 0, 1, 0 ]
]
];
static T_ROTATIONS = [
[
[ 0, 0, 0 ],
[ 1, 1, 1 ],
[ 0, 1, 0 ]
],
[
[ 0, 1, 0 ],
[ 1, 1, 0 ],
[ 0, 1, 0 ]
],
[
[ 0, 1, 0 ],
[ 1, 1, 1 ],
[ 0, 0, 0 ]
],
[
[ 0, 1, 0 ],
[ 0, 1, 1 ],
[ 0, 1, 0 ]
]
];
static I_ROTATIONS = [
[
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 1, 1, 1, 1 ],
[ 0, 0, 0, 0 ]
],
[
[ 0, 0, 1, 0 ],
[ 0, 0, 1, 0 ],
[ 0, 0, 1, 0 ],
[ 0, 0, 1, 0 ]
]
];
// game states
static STATE_DROP = 0;
static STATE_BURN = 1;
static STATE_ARE = 2;
static STATE_GAME_OVER = 3;
static STATE_PAUSE = 4;
// events
static GAME_START = 'game-start';
static GAME_OVER = 'game-over';
static GAME_OVER_START = 'game-over-start';
static GAME_OVER_END = 'game-over-end';
static GAME_PAUSE = 'game-pause';
static GAME_RESUME = 'game-resume';
static TETROMINO_MOVE_LEFT = 'tetromino-move-left';
static TETROMINO_MOVE_RIGHT = 'tetromino-move-right';
static TETROMINO_MOVE_DOWN = 'tetromino-move-down';
static TETROMINO_HARD_DROP = 'tetromino-hard-drop';
static TETROMINO_ROTATE_CLOCKWISE = 'tetromino-rotate-clockwise';
static TETROMINO_ROTATE_COUNTERCLOCKWISE = 'tetromino-rotate-counterclockwise';
static TETROMINO_LOCK = 'tetromino-lock';
static NEXT_TETROMINO = 'next-tetromino';
static LEVEL_CHANGE = 'level-change';
static SCORE_CHANGE = 'score-change';
static LINE_CLEAR_START = 'line-clear-start';
static LINE_CLEAR_END = 'line-clear-end';
static LINE_CLEAR = 'line-clear';
// doard size in terms of squares
// this is typically 10x20, but we are adding 2 invisible rows
// at the top to have enough room to spawn all tetrominoes
static BOARD_WIDTH = 10;
static BOARD_HEIGHT = 22;
// constructor needs a canvas
constructor(canvas, {
boardWidth = Debtris.BOARD_WIDTH,
boardHeight = Debtris.BOARD_HEIGHT,
boardX = 30,
boardY = -35,
squareSide = 28,
scoreX = 330,
scoreY = 100,
levelX = 330,
levelY = 130,
linesX = 330,
linesY = 160,
cashX = 330,
cashY = 190,
timeX = 330,
timeY = 220,
nextX = 330,
nextY = 260,
nextOffsetX = 330,
nextOffsetY = 280,
pauseX = 145,
pauseY = 220,
zColor = [ '#fe103c', '#f890a7' ],
sColor = [ '#66fd00', '#c4fe93' ],
oColor = [ '#ffde00', '#fff88a' ],
lColor = [ '#ff7308', '#ffca9b' ],
jColor = [ '#1801ff', '#5a95ff' ],
tColor = [ '#f890a7', '#fcc2cf' ],
iColor = [ '#00e6fe', '#86fefe' ],
gameOverColor = [ '#000', '#ddd' ],
ghostColor = [ '#000', '#fff' ],
canvasFont = '17px ubuntu',
canvasFontColor = '#fff',
backgroundColor = '#222',
tetrisBackgroundColor = '#fff',
borderColor = '#fff',
gridColor = '#ddd',
tapClickMaxDuration = 500,
tapClickMaxDistance = 10,
rotateSound = undefined,
moveSound = undefined,
setSound = undefined,
gameOverSound = undefined,
lineSound = undefined,
tetrisSound = undefined,
levelChangeSound = undefined,
pauseSound = undefined,
gameTheme = undefined
} = {}) {
// game canvas
this.canvas = canvas;
this.context = this.canvas.getContext('2d');
this.context.lineJoin = 'round';
// board dimensions
this.boardWidth = boardWidth;
this.boardHeight = boardHeight;
// init board
this.board = [];
for (let i = 0; i < this.boardHeight; ++i) {
const row = [];
for (let j = 0; j < this.boardWidth; ++j) row.push(7);
this.board.push(row);
}
// render parameters
this.boardX = boardX; // board's left
this.boardY = boardY; // board's top
this.squareSide = squareSide; // width of individual squares
// board's bounding box
this.boardBorder = [
-0.5 + this.boardX,
-0.5 + this.boardY + 2 * this.squareSide,
0.5 + this.boardX + this.boardWidth * this.squareSide,
0.5 + this.boardY + this.boardHeight * this.squareSide
];
// HUD stuff coordinates
this.scoreX = scoreX; // score label coordinates
this.scoreY = scoreY;
this.levelX = levelX; // level label coordinates
this.levelY = levelY;
this.linesX = linesX; // lines label coordinates
this.linesY = linesY;
this.cashX = cashX; // cash label coordinates
this.cashY = cashY;
this.timeX = timeX; // time label coordinates
this.timeY = timeY;
this.nextX = nextX; // next label coordinates
this.nextY = nextY;
this.nextOffsetX = nextOffsetX; // next tetromino coords
this.nextOffsetY = nextOffsetY;
this.pauseX = pauseX; // pause label coords
this.pauseY = pauseY;
// canvas font
this.canvasFont = canvasFont;
this.canvasFontColor = canvasFontColor;
// tetromino colors
this.zColor = [ ...zColor ];
this.sColor = [ ...sColor ];
this.oColor = [ ...oColor ];
this.lColor = [ ...lColor ];
this.jColor = [ ...jColor ];
this.tColor = [ ...tColor ];
this.iColor = [ ...iColor ];
// game over tile colors
this.gameOverColor = [ ...gameOverColor ];
this.ghostColor = [ ...ghostColor ];
this.backgroundColor = backgroundColor;
this.tetrisBackgroundColor = tetrisBackgroundColor;
this.borderColor = borderColor;
this.gridColor = gridColor;
// max time between pointerdown and pointerup for the game to count it as click
this.tapClickMaxDuration = tapClickMaxDuration; // grandpa's tap/click duration!
// maximum distance between pointer-down and pointer-up coordinates
// for the game to count it as a click/tap
this.tapClickMaxDistance = tapClickMaxDistance;
// sounds
this.rotateSound = rotateSound; // rotation
this.moveSound = moveSound; // move
this.setSound = setSound; // tetromino lock
this.gameOverSound = gameOverSound; // game over
this.lineSound = lineSound; // line burn
this.tetrisSound = tetrisSound; // tetris
this.levelChangeSound = levelChangeSound; // level increase
this.pauseSound = pauseSound; // game paused
this.gameTheme = gameTheme; // theme song
// tetrominoes
this.tetrominoes = [
{
id: 0,
name: Debtris.Z_TETROMINO,
rot: Debtris.Z_ROTATIONS,
iniPos: Debtris.Z_INITIAL,
col: this.zColor,
box: Debtris.Z_BOX
},
{
id: 1,
name: Debtris.S_TETROMINO,
rot: Debtris.S_ROTATIONS,
iniPos: Debtris.S_INITIAL,
col: this.sColor,
box: Debtris.S_BOX
},
{
id: 2,
name: Debtris.O_TETROMINO,
rot: Debtris.O_ROTATIONS,
iniPos: Debtris.O_INITIAL,
col: this.oColor,
box: Debtris.O_BOX
},
{
id: 3,
name: Debtris.L_TETROMINO,
rot: Debtris.L_ROTATIONS,
iniPos: Debtris.L_INITIAL,
col: this.lColor,
box: Debtris.L_BOX
},
{
id: 4,
name: Debtris.J_TETROMINO,
rot: Debtris.J_ROTATIONS,
iniPos: Debtris.J_INITIAL,
col: this.jColor,
box: Debtris.J_BOX
},
{
id: 5,
name: Debtris.T_TETROMINO,
rot: Debtris.T_ROTATIONS,
iniPos: Debtris.T_INITIAL,
col: this.tColor,
box: Debtris.T_BOX
},
{
id: 6,
name: Debtris.I_TETROMINO,
rot: Debtris.I_ROTATIONS,
iniPos: Debtris.I_INITIAL,
col: this.iColor,
box: Debtris.I_BOX
}
];
// movement/controls
this.moveLeft = false;
this.moveRight = false;
this.moveDown = false;
this.rotateClockwise = false;
this.rotateCounterclockwise = false;
this.hardDrop = true;
this.doUndoPause = false; // pause state changed
// pointer coords
this.xIni = undefined;
this.yIni = undefined;
this.tIni = undefined;
// pointer game controls
this.pointerMoveDownEnabled = false; // flag to allow/disallow pointer to move tetromino down
// game flags
this.playing = false; // ongoing game
this.gameLoop = false; // ongoing game loop (loop ends after game-over animation)
this.tetromino = this.tetrominoes[0]; // current tetromino
this.tetrominoPosition = [ 0, 0 ]; // current tetromino's position
this.tetrominoRotation = 0; // current tetromino's rotation
this.next = this.tetrominoes[0]; // next tetromino
// this.isFlashing = false;
// this.flashFrames = 8;
// game parameters
this.startLevel = 0;
this.level = 0;
this.lines = 0;
this.score = 0;
this.pressDownScore = 0;
this.cash = 150;
this.currentTimer = 15;
// event listeners
this.handlers = new Map();
this.handlers.set(Debtris.GAME_START, []);
this.handlers.set(Debtris.GAME_OVER, []);
this.handlers.set(Debtris.GAME_OVER_START, []);
this.handlers.set(Debtris.GAME_OVER_END, []);
this.handlers.set(Debtris.GAME_PAUSE, []);
this.handlers.set(Debtris.GAME_RESUME, []);
this.handlers.set(Debtris.TETROMINO_MOVE_LEFT, []);
this.handlers.set(Debtris.TETROMINO_MOVE_RIGHT, []);
this.handlers.set(Debtris.TETROMINO_MOVE_DOWN, []);
this.handlers.set(Debtris.TETROMINO_HARD_DROP, []);
this.handlers.set(Debtris.TETROMINO_ROTATE_CLOCKWISE, []);
this.handlers.set(Debtris.TETROMINO_ROTATE_COUNTERCLOCKWISE, []);
this.handlers.set(Debtris.TETROMINO_LOCK, []);
this.handlers.set(Debtris.NEXT_TETROMINO, []);
this.handlers.set(Debtris.LEVEL_CHANGE, []);
this.handlers.set(Debtris.SCORE_CHANGE, []);
this.handlers.set(Debtris.LINE_CLEAR_START, []);
this.handlers.set(Debtris.LINE_CLEAR_END, []);
this.handlers.set(Debtris.LINE_CLEAR, []);
// animation frames counters
this.frameCounter = 0;
this.areFrames = -1;
this.framesTilDrop = -1;
// counters for line-clear and game-over animations
this.columnsCleared = -1;
this.gameOverLine = -1;
// game state
this.previousGameState = Debtris.STATE_GAME_OVER;
this.gameState = Debtris.STATE_GAME_OVER;
// an empty row used to exploit syntactic sugar
this.emptyRow = [];
for (let i = 0; i < this.boardWidth; ++i) this.emptyRow.push(-1);
// paint something for the user to see
this._render();
}
// set the starting level
// does nothing if playing
setStartLevel(level) {
if (this.gameState === Debtris.STATE_GAME_OVER) {
this.startLevel = Math.max(0, Math.min(19, level)); // between 0 and 19
}
}
// set the border and fill colors for game-over squares
setGameOverColor(color) {
this.gameOverColor = [ ...color ];
}
// set ghost tetromino colors
setGhostColor(color) {
this.ghostColor = [ ...color ];
}
// set the border and fill colors for a tetromino
setTetrominoColor(tetromino, color) {
switch (tetromino) {
case Debtris.Z_TETROMINO: this.zColor = [ ...color ]; break;
case Debtris.S_TETROMINO: this.sColor = [ ...color ]; break;
case Debtris.O_TETROMINO: this.oColor = [ ...color ]; break;
case Debtris.L_TETROMINO: this.lColor = [ ...color ]; break;
case Debtris.J_TETROMINO: this.jColor = [ ...color ]; break;
case Debtris.T_TETROMINO: this.tColor = [ ...color ]; break;
case Debtris.I_TETROMINO: this.iColor = [ ...color ]; break;
}
}
_startCountdown() {
// Clear any existing interval to prevent multiple timers
if (this.timerInterval) clearInterval(this.timerInterval);
// Set up the interval
this.timerInterval = setInterval(() => {
if (this.currentTimer > 0) {
this.currentTimer--;
} else {
// Reset timer and add cash
this.currentTimer = 15;
this.cash += 25;
}
}, 1000); // Runs every 1 second
}
// frames before the tetromino drops 1 tile
// depends on the level
_getFramesPerGridcell(level) {
if (level === 0) return 96; //48;
else if (level === 1) return 86; //43;
else if (level === 2) return 76; //38;
else if (level === 3) return 66; //33;
else if (level === 4) return 56; //28;
else if (level === 5) return 46; //23;
else if (level === 6) return 36; //18;
else if (level === 7) return 26; //13;
else if (level === 8) return 16; //8;
else if (level === 9) return 12; //6;
else if (level <= 12) return 10; //5;
else if (level <= 15) return 8; //4;
else if (level <= 18) return 6; //3;
else if (level <= 28) return 4; //2;
return 2; //1;
}
togglePlayPause() {
if (this.playing) {
this.doUndoPause = true;
} else {
this.play();
}
}
quit() {
if (this.playing && this.gameState != Debtris.STATE_GAME_OVER) {
this._triggerGameOver();
}
}
// start new game
async play() {
if (this.playing) return;
this.playing = true;
this._startCountdown();
// disable UI
// attach event listeners
this._disableUI();
this._addEventListeners();
// reset params
this._resetParameters();
// play theme song
if (this.gameTheme) {
this.gameTheme.currentTime = 0;
this.gameTheme.loop = true;
this.gameTheme.play();
}
// fire game start event
this._dispatch(Debtris.GAME_START, {
type: Debtris.GAME_START,
level: this.level,
score: this.score,
lines: this.lines,
cash: this.cash
});
// fire new tetromino placed event
this._dispatch(Debtris.NEXT_TETROMINO, {
type: Debtris.NEXT_TETROMINO,
tetromino: this.tetromino.name,
nextTetromino: this.next.name
});
// game loop
this.gameLoop = true;
do {
this._process();
this._render();
await this._sleep();
} while(this.gameLoop);
// remove event listeners
// enable UI
this._removeEventListeners();
this._enableUI();
// toggle playing flag
this.playing = false;
// fire game finish event
this._dispatch(Debtris.GAME_OVER, {
type: Debtris.GAME_OVER,
level: this.level,
score: this.score,
lines: this.lines,
cash: this.cash
});
}
// get game params ready for a new game
_resetParameters() {
// pointer stuff
this.pointerMoveDownEnabled = false;
// movement/control flags
this.moveLeft = false;
this.moveRight = false;
this.moveDown = false;
this.rotateClockwise = false;
this.rotateCounterclockwise = false;
this.hardDrop = false;
this.doUndoPause = false;
// pointer coords
this.xIni = undefined;
this.yIni = undefined;
this.tIni = undefined;
// select random tetrominoes
this.tetromino = this.tetrominoes[(Math.random() * this.tetrominoes.length) | 0];
this.next = this.tetrominoes[this._nextTetrominoId()];
// initial tetromino's position and rotation
this.tetrominoPosition = this.tetromino.iniPos.slice(0);
this.tetrominoRotation = 0;
// starting level, lines and score
this.level = this.startLevel;
this.lines = 0;
this.score = 0;
this.cash = 150;
this.currentTimer = 15;
this.pressDownScore = 0;
// clear board
for (let i = 0; i < this.boardHeight; ++i)
for (let j = 0; j < this.boardWidth; ++j)
this.board[i][j] = -1;
// frame counters
this.frameCounter = 0;
this.areFrames = -1;
this.framesTilDrop = -1;
this.columnsCleared = -1;
this.gameOverLine = -1;
// frames until the tetromino automatically moves down
this.framesTilDrop = 36 + this._getFramesPerGridcell(this.level); // 18 + this._getFramesPerGridcell(this.level);
// initial state
this.previousGameState = Debtris.STATE_DROP;
this.gameState = Debtris.STATE_DROP;
}
// add and remove event listeners
_addEventListeners() {
this.canvas.addEventListener('contextmenu', this._handleContextMenu, { capture: true, passive: false });
document.addEventListener('pointerdown', this._handlePointerDown, { capture: true, passive: false });
document.addEventListener('pointermove', this._handlePointerMove, { capture: true, passive: false });
document.addEventListener('pointerup', this._handlePointerUp, { capture: true, passive: false });
document.addEventListener('pointercancel', this._handlePointerCancel, { capture: true, passive: false });
document.addEventListener('wheel', this._handleWheel, { capture: true, passive: false });
document.addEventListener('keydown', this._handleKeyDown, { capture: true, passive: false });
}
_removeEventListeners() {
this.canvas.removeEventListener('contextmenu', this._handleContextMenu, true);
document.removeEventListener('pointerdown', this._handlePointerDown, true);
document.removeEventListener('pointermove', this._handlePointerMove, true);
document.removeEventListener('pointerup', this._handlePointerUp, true);
document.removeEventListener('pointercancel', this._handlePointerCancel, true);
document.removeEventListener('wheel', this._handleWheel, true);
document.removeEventListener('keydown', this._handleKeyDown, true);
}
// disable/enable UI
_disableUI() {
this.canvas.style.touchAction = 'none';
}
_enableUI() {
this.canvas.style.touchAction = 'auto';
}
// context menu handler: don't open during game
_handleContextMenu = event => {
event.preventDefault();
}
//
// default keyboard inputs:
//
// action key key-code
// ---------------------------------------------
// rotate clockwise up arrow 38
// down down arrow 40
// left left arrow 37
// right right arrow 39
// rotate clockwise 'x' 88
// rotate countercw 'z' 90
// hard drop space bar 32
// pause esc 27
// pause 'p' 80
//
// key event listener
_handleKeyDown = event => {
switch (event.keyCode || event.which) {
case 37:
// left
event.preventDefault();
this.moveRight = !(this.moveLeft = true);
break;
case 39:
// right
event.preventDefault();
this.moveLeft = !(this.moveRight = true);
break;
case 88:
// rotate clockwise
event.preventDefault();
this.rotateCounterclockwise = !(this.rotateClockwise = true);
break;
case 90:
// rotate counterclockwise
event.preventDefault();
this.rotateClockwise = !(this.rotateCounterclockwise = true);
break;
case 40:
// down
event.preventDefault();
this.moveDown = true;
break;
case 32:
// hard drop
event.preventDefault();
this.hardDrop = true;
break;
case 27:
case 80:
// pause
event.preventDefault();
if (this.gameState != Debtris.STATE_GAME_OVER) {
this.doUndoPause = true;
}
break;
}
}
//
// pointer device inputs:
//
// action pointer moves
// ------------------------------------------------------------------
// left move the pointer to the left of the tetromino
// right move the pointer to the right of the tetromino
// down use the pointer drag the tetromino down
// rotate clockwise click / touch
// rotate countercw click / touch
// pointer move handler
_handlePointerMove = event => {
event.preventDefault();
// no movement tracking during pause
if (this.gameState === Debtris.STATE_PAUSE) return;
// find out if pointer is left or right or below the tetromino
// then move tetromino accordingly
const { x, y } = this._getEventCoords(event);
// get pointer's row & column
const row = ((y - this.boardY) / this.squareSide) | 0;
const column = ((x - this.boardX) / this.squareSide) | 0;
// get tetromino's bounds, calculate center column and row center
const { top, bottom, left, right } = this._getTetrominoBounds();
const middleRow = ((top + bottom) / 2) | 0;
const middleColumn = ((left + right) / 2) | 0;
// enable pointer's ability to move down
// if the pointer is on the tetromino or above
if (row <= bottom) {
this.pointerMoveDownEnabled = true;
}
// move left
if (column < middleColumn) {
this.moveRight = !(this.moveLeft = true);
}
// move right
if (column > middleColumn) {
this.moveLeft = !(this.moveRight = true);
}
// move down
if (this.pointerMoveDownEnabled && row > middleRow) {
this.moveDown = true;
}
}
// pointerdown handler
_handlePointerDown = event => {
//event.preventDefault();
// do nothing during pause
if (this.gameState === Debtris.STATE_PAUSE) return;
const { x, y } = this._getEventCoords(event);
this.xIni = x; // store pointer coords
this.yIni = y;
this.tIni = performance.now(); // time since time origin
}
// pointer up handler
_handlePointerUp = event => {
event.preventDefault();
// do nothing during pause
if (this.gameState === Debtris.STATE_PAUSE) return;
const { x, y } = this._getEventCoords(event);
const a = this.xIni - x; // calculate distance
const b = this.yIni - y; // between tap-down and tap-up coordinates
const dist = Math.sqrt(a * a + b * b);
// detect tap/click:
if (dist <= this.tapClickMaxDistance && // similar coords
performance.now() - this.tIni <= this.tapClickMaxDuration) { // gesture was short
if (event.button === 0) {
// left mouse button, touch contact, pen contact
// rotate tetromino clockwise
this.rotateCounterclockwise = !(this.rotateClockwise = true);
} else {
// right button, mouse wheel...
// rotate tetromino counterclockwise
this.rotateClockwise = !(this.rotateCounterclockwise = true);
}
}
}
// pointer cancel
_handlePointerCancel = event => {
event.preventDefault();
// reset pointer flags
this.pointerMoveDownEnabled = false;
}
// wheel rotates the tetromino
_handleWheel = event => {
event.preventDefault();
// do nothing during pause
if (this.gameState === Debtris.STATE_PAUSE) return;
if (event.deltaY > 0) {
// rotate tetromino clockwise
this.rotateCounterclockwise = !(this.rotateClockwise = true);
} else if (event.deltaY < 0) {
// rotate tetromino counterclockwise
this.rotateClockwise = !(this.rotateCounterclockwise = true);
}
}
// pointer coordinates
_getEventCoords(event) {
const rect = this.canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
// get current tetromino's left and right bounds
_getTetrominoBounds() {
const p = this.tetromino.rot[this.tetrominoRotation];
let top = this.boardHeight;
let bottom = 0;
let left = this.boardWidth;
let right = 0;
for (let i = 0; i < p.length; ++i) {
for (let j = 0; j < p[i].length; ++j) {
if (p[i][j] != 0) {
const x = this.tetrominoPosition[0] + j;
const y = this.tetrominoPosition[1] + i;
left = Math.min(left, x);
right = Math.max(right, x);
top = Math.min(top, y);
bottom = Math.max(bottom, y);
}
}
}
return {
top: top,
bottom: bottom,
left: left,
right: right
};
}
_process() {
// game possibly paused/unpaused
this._pauseCheck();
// process current state
switch (this.gameState) {
case Debtris.STATE_DROP:
this._processDrop();
break;
case Debtris.STATE_BURN:
this._processBurn();
break;
case Debtris.STATE_ARE:
this._processARE();
break;
case Debtris.STATE_GAME_OVER:
this._processGameOver();
break;
case Debtris.STATE_PAUSE:
// do nothing if paused
break;
}
// clear input flags
this._resetInputs();
// global frame counter
++this.frameCounter;
}
_processDrop() {
// decrease drop counter
--this.framesTilDrop;
// do move if buffered
if (this.moveLeft && this._canMoveTetromino(-1, 0)) {
const oldPosition = [ ...this.tetrominoPosition ];
--this.tetrominoPosition[0];
// play move sound
if (this.moveSound) {
this.moveSound.currentTime = 0;
this.moveSound.play();
}
// fire move left event
this._dispatch(Debtris.TETROMINO_MOVE_LEFT, {
type: Debtris.TETROMINO_MOVE_LEFT,
tetromino: this.tetromino.name,
rotation: this.tetrominoRotation,
oldPosition: oldPosition,
newPosition: [ ...this.tetrominoPosition ]
});
}
if (this.moveRight && this._canMoveTetromino(1, 0)) {
const oldPosition = [ ...this.tetrominoPosition ];
++this.tetrominoPosition[0];
// play move sound
if (this.moveSound) {
this.moveSound.currentTime = 0;