-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetrilight.source.js
executable file
·2049 lines (2045 loc) · 115 KB
/
tetrilight.source.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
/*************************************************************
**************** TetriLight - ꓱꓛꓠꓵꓳꓭ ꓕꓠꓱꓛꓠꓲꓥ ****************
**************** https://x.com/VincentBounce ****************
**************** 2011 to 2024 - v0.4 ****************
**************************************************************
Source https://github.com/VincentBounce/TetriLight
Play 🕹 https://vincentbounce.github.io/TetriLight/
**************** Minor known bugs ****************
Small bug, if riseGreyBlocks and 1 or more row appears, need to wait next drop to clear this row.
If top line only is cleared AND top line has blocks under, then the anim and sound of droping occurs again.
$$$ test browser when start!
$$$ display fps
$$$ ListAutoIndex called 1x, useless?
$$$ pentomode blinking to solve
$$$ pause doesn't pause coming grid movements
*/
"use strict"; // use JavaScript in strict mode to make code better and prevent errors
// GLOBAL VARIABLES, each one handle one class instance only
let MAIN_MENU, GAME, AUDIO, SPRITES; // SPRITES: TetrisSpritesCreation
// GLOBAL CONSTANTS
const RULES = { // tetris rules
gameSpeedRatio : 1, // default 1 normal speed, decrease speed < 1 < increase global game speed #DEBUG
initialVolume : 0.1, // default 0.6, 0 to 1, if #DEBUG
transferRowsCountMin : 2, // default 2, min height of rows to drop bad grey lines to others players, decrease for #DEBUG
pentominoesRowsCountMin : 3, // default 3, min height of rows to start pentominoes mode, decrease for #DEBUG
horizontalCellsCount : 10, // default 10, min 5 for #DEBUG
verticalCellsCount : 21, // default 21 = (20 visible + 1 hidden) #DEBUG
topLevel : 25, // default 25, max level (no more steps of drop acceleration)
risingRowsHolesCountMaxRatio: 0.3, // default 0.3, < = 0.5, max holes into each rising row, example: 0.5 = 50% means 5 holes for 10 columns
fps : 60/1000 }; // default 60/1000 = 60frames per 1000ms, average requestAnimationFrame() browser frame rate
const DURATIONS = { // tetris durations, periods in ms
pentominoesModeDuration : 10000, // 5000 ms, 15s for 3 lines cleared, 20s for 4 lines cleared
movingGridsDuration : 350, // 0350 ms
clearingRowsDuration : 350, // 0350 ms or 500, increase for #DEBUG, incompressible by any key excepted pause
rising1RowDuration : 150, // 0150 ms or 250, increase for #DEBUG
rotatingDuration : 400, // 0400 ms
gridQuakeDuration : 150, // 0150 ms or 200, increase for #DEBUG, incompressible by any key excepted pause
centralMessagesDuration : 1200, // 1200 ms, central messages displaying duration, replaced, not queued
displayingScoreDuration : 1500, // 1500 ms
hardDropDuration : 200, // 0200 ms, increase for #DEBUG
lostMessageDuration : 3500, // 3500 ms, period to display score
softDropPeriod : 50, // 0050 ms, if this is max DropDuration
initialDropPeriod : 1100 }; // 0700 ms, >= _softDropPeriod, decrease during game, increase for #DEBUG, incompressible duration by any key excepted pause
const FONTS = { scoreFont: 'Trebuchet MS, sans-serif', messageFont: 'Impact, sans-serif' }; // web safe fonts = offline fonts ; Arial, Helvetica, Trebuchet MS
//const FONTS = { scoreFont: 'Ubuntu', messageFont: 'Rock Salt' }; // online fonts
const SOUNDS = {
landFX : {ext: 'wav'},
rotateFX : {ext: 'wav'},
moveFX : {ext: 'wav', vol: 0.2},
clearFX : {ext: 'wav'},
quadrupleFX : {ext: 'wav'},
selectFX : {ext: 'wav'},
musicMusic : {ext: 'mp3', vol: 0.5} };
// values > 0 to avoid (value === 0 == false)
const GAME_STATES = { paused : 1, running: 2, runningBeforeKeyPressed: 3};
const GRID_STATES = { ready : 1, playing: 2, lost : 3}; // connected but not started
const BLOCK_TYPES = { ghost : 1, inShape: 2, orphan : 3};
const SEARCH_MODE = { down : 1, up : 2};
const DROP_TYPES = { soft : 1, hard : 2}; // 1 and 2 are useful for score: hard drop is double points
// INIT called by HTML browser
function init() {
for (let p in DURATIONS) DURATIONS[p] /= RULES.gameSpeedRatio; // change durations with coeff, float instead integer no pb, to slowdown game
AUDIO = new Audio(SOUNDS);
AUDIO.changeVolume(false);
MAIN_MENU = new MainMenu(); // #DEBUG
// if (GAME) GAME.destroyGame();
GAME = new TetrisGame();
GAME.addGrid();
GAME.addGrid();
GAME.addGrid();
}
// MainMenu Class, menu manager, make new one to open a TetrisGame
function MainMenu() { // queue or stack
window.addEventListener('keydown', this.keyCapture_, false); // for all keys, producing value or not
window.addEventListener('keyup', this.keyCapture_, false); // for all keys, producing value or not
// window.oncontextmenu = function(event){ this.cancelEvent_(event); }; // right click
// below creation for MAIN dom node
SPRITES = new TetrisSpritesCreation(); // need dom node created to get sizes for scaling
this._domNode = new DomNode({ // menus on top of the screen #DEBUG white
body: true,
topScreenSprite: { type: 'canvas',
width: _ => SPRITES.pxGameWidth, height: _ => SPRITES.pxTopMenuZoneHeight, sprite:SPRITES._spriteBackground }, // to create an HTML top free space above the tetris game
message1Div: {
width: _ => SPRITES.pxTopMenuZoneHeight, height: _ => SPRITES.pxTopMenuZoneHeight, vertical_align:'middle' },
playingAreaSprite: { type:'canvas',
width: _ => SPRITES.pxGameWidth, height: _ => SPRITES.pxGameHeight,
y: _ => SPRITES.pxTopMenuZoneHeight, sprite: SPRITES._spriteBackground }
}, 'gameAreaDiv'); // one arg only for setDomNode
SPRITES.zoom1Step(0); // we set all px sizes
this._domNode._childs.playingAreaSprite.nodeDrawSprite(); // paint black background
// this._domNode._childs.message1Div.createText('FONTS.messageFont', 'bold', 'black', '');
// this._domNode._childs.message1Div.setTex('$$$');
this._domNode._htmlElement.addEventListener('click',
function(eventClick) {
if ((eventClick.offsetX < SPRITES.pxButtonSize) && (eventClick.offsetY < SPRITES.pxButtonSize))
GAME.addGrid(); // top left square click capture to add another grid
}, false);
window.onresize = function() { GAME.organizeGrids({resize:true}) };
}
MainMenu.prototype = {
_domNode: null,
cancelEvent_(event) { //seems useless
keyboardEvent.stopPropagation(); //method prevents propagation of the same event from being called
event.preventDefault();
},
keyCapture_(keyboardEvent) {
//MAIN_MENU.cancelEvent_(keyboardEvent);
switch (keyboardEvent.code) { //key press: both keydown and keyup
case 'KeyP':
if (keyboardEvent.type=='keydown' && !keyboardEvent.repeat) //avoid P keydown repeated
GAME.pauseOrResume(); // to enter pause
break; // always exit after this instruction
default:
if (GAME._gameState !== GAME_STATES.paused) // if game is not paused
GAME._gridsListArray.forEach( myGrid => myGrid.chooseControlAction(keyboardEvent) );
}
},
};
// Audio Class, sounds management
function Audio(sounds) { // constructor
this._sounds = {};
for (let p in sounds)
this.addSound(p, sounds[p].ext, sounds[p].vol);
}
Audio.prototype = {
_mainVolume: RULES.initialVolume,
_muted: false,
_sounds: null, // object containing all sounds
addSound(name, ext, volume) { // when new is called, add all sounds in this._sounds let, 2nd arg volume is optional
this._sounds[name] = {};
this._sounds[name].sound = window.document.createElement('audio');
window.document.body.appendChild(this._sounds[name].sound);
if (name.indexOf('Music') !== -1) // check if contains Music in name, if so then play with loop
this._sounds[name].sound.loop = 'loop';
this._sounds[name].sound.setAttribute('src', 'audio/' + name + '.' + ext); // (ext ? ext : 'wav')
this._sounds[name].volumeFactor = (volume ? volume : 1);
this._sounds[name].paused = false;
},
audioPlay(name) {
this._sounds[name].paused = false;
if (GAME._gameState !== GAME_STATES.runningBeforeKeyPressed) // Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD
this._sounds[name].sound.play();
},
audioStop(name) {
this._sounds[name].paused = false;
this._sounds[name].sound.pause(); // old: this._sounds[name].sound.currentTime = 0;
},
pauseOrResume(name) {
this._sounds[name].paused = !this._sounds[name].paused;
if (this._sounds[name].paused)
this._sounds[name].sound.pause();
else
this.audioPlay(name);
},
changeVolume(up) { // -1 or +1, return false if not changed
let volume = this._mainVolume + up*0.1;
if ((volume < 0) || (volume > 1))
return false; // can't change out of [0-1] range
else {
this._mainVolume = volume;
this.refreshVolume(this._mainVolume);
return true;
}
},
muteOrUnmute() {
this.muted = !this.muted;
if (this.muted)
this.refreshVolume(0);
else
this.refreshVolume(this._mainVolume);
},
refreshVolume(volume) {
for (let sound in this._sounds)
this._sounds[sound].sound.volume = volume * this._sounds[sound].volumeFactor;
},
/*getDuration(name) {
return this._sounds[name].sound.duration;
}*/
};
// TetrisSpritesCreation Class, earlier: TetrisGraphics, GameGraphics
function TetrisSpritesCreation() {
for (let color in this._colors) this._colors[color].name = color; // adding a name field to SPRITES._colors
// creation of SPRITES below
this._spriteBackground = new SpriteObj({ // define backgroung color here: black > grey
_nocache: true,
drawSprite: (c, x, y, a, w, h) => { // context c, x, y, args a, canvas width w, canvas height h
c.fillStyle=SpriteObj.linearGradient(c,0,0,0,h,0.5,'#000',1,'#AAA');
c.fillRect(x,y,w,h) }
});
this._spriteGridFront = new SpriteObj({ // we draw 3 trapeze that we merge
_nocache: true,
widthSprite: _ => SPRITES.pxFullGridWidth,
heightSprite: _ => SPRITES.pxFullGridHeight,
drawSprite(c, x, y, a) { // context, x, y, args
let col = SPRITES._colors[a.col];
c.moveTo(x,y);c.lineTo(x+SPRITES.pxGridBorder,y); // left border
c.lineTo(x+SPRITES.pxGridBorder,y+SPRITES.pxGridHeight);
c.lineTo(x,y+SPRITES.pxFullGridHeight);
c.fillStyle=SpriteObj.linearGradient(c,0,0,SPRITES.pxGridBorder,0,1,SpriteObj.rgbaTxt(col.dark),0,SpriteObj.rgbaTxt(col.light));
c.fill();
c.beginPath();c.moveTo(x+SPRITES.pxFullGridWidth,y); // right border
c.lineTo(x+SPRITES.pxGridBorder+SPRITES.pxGridWidth,y);
c.lineTo(x+SPRITES.pxGridBorder+SPRITES.pxGridWidth,y+SPRITES.pxGridHeight);
c.lineTo(x+SPRITES.pxFullGridWidth,y+SPRITES.pxFullGridHeight);
c.fillStyle=SpriteObj.linearGradient(c,SPRITES.pxGridWidth+SPRITES.pxGridBorder,0,SPRITES.pxGridBorder,0,0,SpriteObj.rgbaTxt(col.dark),1,SpriteObj.rgbaTxt(col.light));
c.fill();
c.beginPath();c.moveTo(0,SPRITES.pxFullGridHeight); // bottom border
c.lineTo(SPRITES.pxGridBorder,SPRITES.pxGridHeight);
c.lineTo(SPRITES.pxGridBorder+SPRITES.pxGridWidth,SPRITES.pxGridHeight);
c.lineTo(SPRITES.pxFullGridWidth,SPRITES.pxFullGridHeight);
c.fillStyle=SpriteObj.linearGradient(c,0,SPRITES.pxGridHeight,0,SPRITES.pxGridBorder,0,SpriteObj.rgbaTxt(col.dark),1,SpriteObj.rgbaTxt(col.light));
c.fill();
c.fillStyle=SpriteObj.linearGradient(c,0,0,0,SPRITES.pxCellSize*2,0, SpriteObj.rgbaTxt([0,0,0],1),1, SpriteObj.rgbaTxt([0,0,0],0)); // top grid shadow
c.fillRect(0,0,SPRITES.pxFullGridWidth,SPRITES.pxFullGridHeight); // #DEBUG
}
});
this._spriteGridBackground = new SpriteObj({ // we draw grid, grid shadow, back
_nocache: true,
widthSprite: _ => SPRITES.pxFullGridWidth,
heightSprite: _ => SPRITES.pxFullGridHeight,
xSprite: _ => SPRITES.pxGridBorder,
ySprite: _ => SPRITES.pxGridBorder,
drawSprite(c, x, y, a) { // context, x, y, args
let col = SPRITES._colors[a.col];
c.fillStyle='#111';c.fillRect(x,y,SPRITES.pxGridWidth,SPRITES.pxGridHeight);
let colo = ['#000','#222'];
for (let p=colo.length-1;p>=0;p--) {
c.beginPath();
let margin = -(p*SPRITES.pxGridLineWidth)+SPRITES.pxGridLineWidth/2;
for (let i=1;i < RULES.verticalCellsCount;i++) {
c.moveTo(x, y+SPRITES.pxCellSize*i+margin);
c.lineTo(x+SPRITES.pxGridWidth, y+(SPRITES.pxCellSize)*i+margin);
c.lineWidth=SPRITES.pxGridLineWidth;c.strokeStyle=colo[p];c.stroke();
}
for (let i=1;i < RULES.horizontalCellsCount;i++) {
c.moveTo(x+SPRITES.pxCellSize*i+margin, y);
c.lineTo(x+SPRITES.pxCellSize*i+margin, y+SPRITES.pxGridHeight);
c.lineWidth=SPRITES.pxGridLineWidth;c.strokeStyle=colo[p];c.stroke();
}
}
c.rect(x,y,SPRITES.pxGridWidth,SPRITES.pxGridHeight);
c.fillStyle=SpriteObj.radialGradient(c,x+SPRITES.pxGridWidth/2,y+SPRITES.pxGridHeight,0,0,0,3*SPRITES.pxGridHeight/4,
0, SpriteObj.rgbaTxt(col.medium, 0.3), 1, SpriteObj.rgbaTxt(col.medium, 0)); c.fill();
c.fillStyle=SpriteObj.linearGradient(c,x,y,SPRITES.pxGridWidth,0,
0, SpriteObj.rgbaTxt([0,0,0],0.5), 0.1, SpriteObj.rgbaTxt([0,0,0],0),
0.9, SpriteObj.rgbaTxt([0,0,0],0), 1, SpriteObj.rgbaTxt([0,0,0],0.5)); c.fill(); }
});
this._spriteBlock = new SpriteObj({ // we draw block
_nocache: false,
widthSprite: _ => SPRITES.pxBlockSize,
heightSprite: _ => SPRITES.pxBlockSize,
xSprite: i => SPRITES.pxGridLineWidth + ( i-1 ) * SPRITES.pxCellSize,
ySprite: j => SPRITES.pxGridLineWidth + ( RULES.verticalCellsCount-j ) * SPRITES.pxCellSize,
drawSprite(c, x, y, a) { // context, x, y, args
let half = Math.round(SPRITES.pxBlockSize/2);
let margin = Math.round(SPRITES.pxBlockSize/7);
let col = SPRITES._colors[a.col];
c.fillStyle=SpriteObj.rgbaTxt(col.medium);
c.fillRect(x,y,SPRITES.pxBlockSize,SPRITES.pxBlockSize);
c.beginPath();c.moveTo(x,y);c.lineTo(x+half,y+half);c.lineTo(x+SPRITES.pxBlockSize,y);
c.fillStyle=SpriteObj.rgbaTxt(col.light);c.fill();
c.beginPath();c.moveTo(x,y+SPRITES.pxBlockSize);c.lineTo(x+half,y+half);
c.lineTo(x+SPRITES.pxBlockSize,y+SPRITES.pxBlockSize);c.fillStyle=SpriteObj.rgbaTxt(col.dark);c.fill();c.beginPath();
c.fillStyle=SpriteObj.linearGradient(c,x,y,SPRITES.pxBlockSize-2*margin,SPRITES.pxBlockSize-2*margin,0,SpriteObj.rgbaTxt(col.dark),1,SpriteObj.rgbaTxt(col.light));
c.fillRect(x+margin,y+margin,SPRITES.pxBlockSize-2*margin,SPRITES.pxBlockSize-2*margin) }
});
this._spritePreviewBlock = new SpriteObj({
_nocache: false,
widthSprite: _ => SPRITES.pxPreviewBlockSize,
heightSprite: _ => SPRITES.pxPreviewBlockSize,
xSprite: x => (SPRITES._shapesSpan + x) * (SPRITES.pxPreviewBlockSize + SPRITES.pxPreviewLineWidth),
ySprite: y => (SPRITES._shapesSpan - y) * (SPRITES.pxPreviewBlockSize + SPRITES.pxPreviewLineWidth),
drawSprite(c, x, y, a) { // context, x, y, args (gradient if true, uniform if false)
let col = SPRITES._colors[a.col]; // c.clearRect(x,y,SPRITES.pxPreviewBlockSize,SPRITES.pxPreviewBlockSize); // useful if we don't erase previous value
c.fillStyle = (a.__onOff
? SpriteObj.linearGradient(c,x,y,SPRITES.pxPreviewBlockSize,SPRITES.pxPreviewBlockSize, 0, SpriteObj.rgbaTxt(col.dark), 1, SpriteObj.rgbaTxt(col.light))
: SpriteObj.rgbaTxt(col.medium, SPRITES._previewOpacity)
);
c.fillRect(x,y,SPRITES.pxPreviewBlockSize,SPRITES.pxPreviewBlockSize) }
});
}
TetrisSpritesCreation.prototype = {
_zoomRatio : 1, // default 1, float current zoom ratio
_scaleFactor : 33, // default 33, int scale unit < SPRITES.pxBlockSize && > = 1
pxTopMenuZoneHeight : 0, // default 0 or 20, Y top part screen of the game, to display information #DEBUG
pxGameWidth : null,
pxGameHeight : null,
pxHalfGameHeight : null,
pxBlockSize : 34,
pxCellSize : null,
pxGridBorder : null,
pxGridLineWidth : null,
pxGridWidth : null,
pxFullGridWidth : null,
pxGridMargin : null,
pxGridHeight : null,
pxFullGridHeight : null,
pxCeilHeight : null,
pxFullGridAndCeil : null,
pxPreviewFullSize : null, // 2*36===72
pxPreviewBlockSize : null,
pxPreviewLineWidth : null,
pxButtonSize : 50, // default 50
pxXPreviewPosition : null,
pxYPreviewPosition : null,
pxXScorePosition : null,
pxYScorePosition : null,
pxXMessagePosition : null,
pxYMessagePosition : null,
_shapesSpan : 2, // span(means envergure)===(5-1)/2
_spriteBackground : null,
_spriteBlock : null,
_spriteGridFront : null,
_spriteGridBackground : null,
_spritePreviewBlock : null,
_spritePreviewBlockFrame: null,
_ghostShapeOpacity : 0.15, // default 0.15
_previewOpacity : 0.2, // default 0.2, opacity for preview grid
_lostShapeOpacity : 0.5, // default 0.5, to show a ghost of shape wich makes losing
_colors : { // name filed is added by constructor
pink : {light: [248, 190, 232], medium: [224, 107, 169], dark: [189, 66, 111]},
purple : {light: [210, 172, 241], medium: [136, 100, 208], dark: [ 90, 64, 177]},
red : {light: [245, 140, 140], medium: [219, 78, 78], dark: [187, 48, 48]},
green : {light: [199, 233, 88], medium: [115, 176, 13], dark: [ 75, 127, 0]},
yellow : {light: [255, 250, 134], medium: [218, 190, 13], dark: [184, 147, 0]},
orange : {light: [250, 197, 115], medium: [240, 143, 0], dark: [212, 87, 0]},
blue : {light: [ 0, 215, 246], medium: [ 13, 134, 222], dark: [ 0, 87, 190]},
grey_white: {light: [255, 255, 255], medium: [188, 197, 204], dark: [ 97, 109, 121]},
grey_blue : {light: [192, 216, 231], medium: [127, 150, 188], dark: [ 73, 85, 118]},
grey : {light: [207, 207, 207], medium: [134, 134, 134], dark: [ 88, 88, 88]}
},
condition_() {
//return ( ( // #DEBUG: to compact grids together
// (SPRITES.pxGameWidth > SPRITES.pxFullGridWidth * GAME._playersCount + SPRITES.pxGridMargin * (GAME._playersCount+1) ) && (SPRITES.pxGameHeight > SPRITES.pxFullGridHeight + 5*SPRITES.pxGridMargin)
return ( ( (this.pxGameWidth >= this.pxFullGridWidth * GAME._playersCount )
&& (this.pxGameHeight >= this.pxFullGridAndCeil ) )
|| (!(this._scaleFactor-1)) );
},
zoomToFit() { // used for scaling if needed
if (this.condition_()) {
while (this.condition_())
this.zoom1Step(1);
this.zoom1Step(-1);
} else
while (!this.condition_())
this.zoom1Step(-1);
},
zoom1Step(step) { // computing for zoom with pixels into web browser
this._scaleFactor += step;
this.pxBlockSize += step;
let oldGridWidth = this.pxFullGridWidth;
this.pxGameWidth = window.innerWidth;
this.pxGameHeight = window.innerHeight - this.pxTopMenuZoneHeight;
this.pxHalfGameHeight = Math.round(this.pxGameHeight/2);
this.pxGridLineWidth = Math.max(Math.round(this.pxBlockSize/14), 1);
this.pxGridWidth = RULES.horizontalCellsCount*this.pxBlockSize + (RULES.horizontalCellsCount+1)*this.pxGridLineWidth;
this.pxGridHeight = RULES.verticalCellsCount*this.pxBlockSize + (RULES.verticalCellsCount+1)*this.pxGridLineWidth;
this.pxCellSize = this.pxBlockSize + this.pxGridLineWidth;
this.pxGridBorder = Math.ceil(this.pxCellSize/3); // bordure de grille en dégradé
this.pxFullGridWidth = this.pxGridWidth + 2*this.pxGridBorder; // largeur grille + bordure
this.pxFullGridHeight = this.pxGridHeight + this.pxGridBorder; // hauteur grille + bordure
this.pxGridMargin = Math.round(this.pxFullGridWidth/8);
this.pxPreviewBlockSize = Math.round(this.pxBlockSize/2.6);
this.pxPreviewLineWidth = this.pxGridLineWidth; // valeur arbitraire, aurait pu etre différente
this.pxPreviewFullSize = (this.pxPreviewBlockSize + this.pxPreviewLineWidth) * (2*this._shapesSpan+1) ;
this.pxCeilHeight = this.pxPreviewFullSize + this.pxPreviewBlockSize + this.pxPreviewLineWidth; // hauteur de la zone posée sur la grille old: + this.pxCellSize
this.pxFullGridAndCeil = this.pxFullGridHeight + this.pxCeilHeight;
this.pxXPreviewPosition = Math.round(this.pxFullGridWidth/2-this.pxPreviewFullSize/2);
this.pxYPreviewPosition = 0;
this.pxXScorePosition = this.pxXPreviewPosition + this.pxPreviewFullSize; // Math.round(3*this.pxFullGridWidth/4);
this.pxYScorePosition = 0;
this.pxXMessagePosition = Math.round(this.pxFullGridWidth/2);
this.pxYMessagePosition = Math.round(this.pxFullGridHeight/2);
this._zoomRatio = !oldGridWidth ? 1 : this.pxFullGridWidth / oldGridWidth;
},
};
// TetrisGame Class
function TetrisGame() {
this._matrixHeight = RULES.verticalCellsCount * 2; // GAME blocks rise (massively sometimes) by unqueuing animated sequences: if lost, need to finish these sequences before noticing losing with new falling shape unable to place
this._iPositionStart = Math.ceil(RULES.horizontalCellsCount/2); // shape start position
this._jPositionStart = RULES.verticalCellsCount - 1;
this._gridsListArray = []; // players grids array
this._pentominoesBriefMode = new PentominoesBriefMode();
this._gameShapesWithRotations = new Array(this._storedPolyominoes.length); // table of all shapes with rotations
this._storedPolyominoes.forEach( (storedPolyo, s) => { // creating all shapes variations: browsing shapes
let shapeBlocksCount = storedPolyo.blocks.length;
let quarters = storedPolyo.quarters;
this._gameShapesWithRotations[s] = new Array(quarters);
for (let pivot=0; pivot < quarters; pivot++) { // creating all shapes rotations: browsing rotations
this._gameShapesWithRotations[s][pivot] = new Array(shapeBlocksCount);
if (pivot === 0)
for (let b=0; b < shapeBlocksCount; b++) // browsing 4 blocks
this._gameShapesWithRotations[s][pivot][b] = [
storedPolyo.blocks[b][0],
storedPolyo.blocks[b][1] ];
else // (pivot !== 0)
for (let b=0; b < shapeBlocksCount; b++) // browsing 4 blocks
this._gameShapesWithRotations[s][pivot][b] = [
-this._gameShapesWithRotations[s][pivot-1][b][1], // minus 1 here (default) for unclockwise
+this._gameShapesWithRotations[s][pivot-1][b][0] ] // minus 1 here for clockwise
}
} );
this._freeColorsArray = Object.values(SPRITES._colors).filter( color => color !== SPRITES._colors['grey'] ); // to copy available colors, excepted grey
this._anims.moveGridsAnim = new Animation({ // make tetris grid coming and leaving
animateFunc(animOutput){
this._gridsListArray.forEach( myGrid => myGrid._domNode.moveTemporaryRelatively(myGrid._vector[0]*animOutput, myGrid._vector[1]*animOutput) )
},
endAnimFunc(){
this._gridsListArray.forEach( myGrid => {
myGrid._domNode.moveRelatively( myGrid._vector[0], myGrid._vector[1]);
myGrid._vector = [0, 0];
} );
this._gameEventsQueue.dequeue();
},
timingAnimFunc: x => -(x-2*Math.sqrt(x)), // arrow replace a return // canceled: -(x-2*Math.sqrt(x));
animDuration: DURATIONS.movingGridsDuration,
animOwner: this // otherwise, it's animation context by default
});
this._gameEventsQueue = new EventsQueue(); // animating applied on this._anims.moveGridsAnim
// AUDIO.audioPlay('musicMusic'); impossible to play music here because audioPlay call GAME which is not yet created in this constructor
}
TetrisGame.prototype = {
_gridsListArray : null,
_matrixHeight : null,
_matrixBottom : -1, // 1 rising row by 1 and queued, to avoid unchained blocks levitating
_iPositionStart : null,
_jPositionStart : null,
_playersCount : 0,
_gameState : GAME_STATES.runningBeforeKeyPressed, // others states: GAME_STATES.paused, GAME_STATES.running
_shapeIdTick : 0,
_nextBlockIndex : 0,
_pentominoesBriefMode : null,
_gameShapesWithRotations: null,
_gameEventsQueue : null,
_anims : {}, // only 1 instance of game
_freeColorsArray : null, // available colors for players
_gameKeysSets : [ // up down left right, https://keycode.info/
{symbols: ['I','J','K','L'], keys : ['KeyI', 'KeyJ', 'KeyK', 'KeyL'], free : true},
{symbols: ['\u2227','<','\u2228','>'], keys: ['ArrowUp', 'ArrowLeft', 'ArrowDown', 'ArrowRight'], free: true},
{symbols: ['E','S','D','F'], keys : ['KeyE', 'KeyS', 'KeyD', 'KeyF'], free : true}
//{symbols: ['W','A','S','D'], keys : ['KeyW', 'KeyA', 'KeyS', 'KeyD'], free : true} // WASD on QWERTY/QWERTZ for left player | Recognized as ZQSD on AZERTY
],
_storedPolyominoes : [ // 5x5 shapes only, coordinates, angles count
// 4 trominoes or domino or monomino
{blocks: [[ 0, 0]], quarters: 1, color: 'grey_blue'}, // - default quarters 1
{blocks: [[ 0, 1],[0, 0]], quarters: 2, color: 'grey_white'}, // -- default quarters 2
{blocks: [[ 0, 1],[0, 0],[0,-1]], quarters: 2, color: 'grey_blue'}, // --- default quarters 2
{blocks: [[ 0, 1],[0, 0],[1, 0]], quarters: 4, color: 'grey_white'}, // |_
// 7 tetrominoes
{blocks: [[ 0, 1],[0, 0],[0,-1],[0,-2]], quarters: 2, color: 'green' }, // I default quarters 2
{blocks: [[-1, 0],[0, 0],[1, 0],[1,-1]], quarters: 4, color: 'blue' }, // J
{blocks: [[-1, 0],[0, 0],[1, 0],[1, 1]], quarters: 4, color: 'orange'}, // L
{blocks: [[ 0, 0],[0, 1],[1, 0],[1, 1]], quarters: 1, color: 'pink' }, // O default quarters 1
{blocks: [[-1,-1],[0,-1],[0, 0],[1, 0]], quarters: 2, color: 'purple'}, // S default quarters 2
{blocks: [[-1, 0],[0, 0],[0,-1],[1,-1]], quarters: 2, color: 'red' }, // Z default quarters 2
{blocks: [[-1, 0],[0, 0],[0, 1],[1, 0]], quarters: 4, color: 'yellow'}, // T
// 14 pentominoes
{blocks: [[ 0, 0],[0, 1],[1, 0],[1, 1],[ 0,-1]], quarters: 4, color: 'pink' }, // O¨
{blocks: [[ 0, 0],[0, 1],[1, 0],[1, 1],[-1, 0]], quarters: 4, color: 'pink' }, // O_
{blocks: [[-1,-1],[0,-1],[0, 0],[1, 0],[ 2, 0]], quarters: 4, color: 'purple'}, // S¨
{blocks: [[-1, 1],[0, 1],[0, 0],[1, 0],[ 2, 0]], quarters: 4, color: 'red' }, // ¨Z
{blocks: [[ 0, 2],[0, 1],[0, 0],[0,-1],[ 0,-2]], quarters: 2, color: 'green' }, // -----
{blocks: [[-1, 0],[0, 1],[0, 0],[0,-1],[ 0,-2]], quarters: 4, color: 'green' }, // T¨
{blocks: [[ 1, 0],[0, 1],[0, 0],[0,-1],[ 0,-2]], quarters: 4, color: 'green' }, // ¨T
{blocks: [[-1, 0],[0, 0],[0, 1],[1, 0],[ 0,-1]], quarters: 4, color: 'yellow'}, // -|- default quarters 1
{blocks: [[-1, 1],[-1,0],[-1,-1],[0,-1],[1,-1]], quarters: 4, color: 'orange'}, // L_
{blocks: [[-1, 0],[0, 0],[0, 1],[1, 0],[-1,-1]], quarters: 4, color: 'orange'}, // -L
{blocks: [[-1, 0],[0, 0],[0, 1],[1, 0],[ 1,-1]], quarters: 4, color: 'blue' }, // J-
{blocks: [[-1, 1],[-1,0],[ 0, 0],[1, 0],[1,-1]], quarters: 2, color: 'purple'}, // J¨
{blocks: [[-1,-1],[-1,0],[ 0, 0],[1, 0],[1, 1]], quarters: 2, color: 'red' }, // ¨L
{blocks: [[-1, 1],[-1,0],[ 0, 0],[1, 0],[1, 1]], quarters: 4, color: 'blue' } // L¨
],
_playedPolyominoesType: {
trominoes : {index: 0, count : 4}, // range of 3 blocks shapes
tetrominoes: {index: 4, count : 7}, // range of 4 blocks shapes
pentominoes: {index: 11, count: 14} // range of 5 blocks shapes
},
destroyGame() {
this._gridsListArray.forEach( myGrid => myGrid.destroyDomNode() );
this._nextBlockIndex = 0;
_domNode.destroyDomNode();
// this._pentominoesBriefMode.destroyPentoMode();// old, remove all timers
},
pauseOrResume() { // pause or resume
this._gameState = (this._gameState !== GAME_STATES.paused) ? GAME_STATES.paused : GAME_STATES.running;
AUDIO.pauseOrResume('musicMusic'); // pause or resume playing music only, because FX sounds end quickly
AUDIO.audioPlay('selectFX'); // always play sound FX for pause or resume
this._pentominoesBriefMode.pauseOrResume(); // if pentominoes mode, pause it
this._gridsListArray.forEach( myGrid => myGrid.pauseOrResume() ); // all players
},
addGrid() { // return true if added
this._gameEventsQueue.execNowOrEnqueue(this, this.addGridBody_);
},
addGridBody_() { // return grid if added, null otherwise, grids qty limit is color qty
if (this._freeColorsArray.length > 0) {
this._playersCount ++;
let p; for (p in this._gameKeysSets)
if ( this._gameKeysSets[p].free)
break;
this._gameKeysSets[p].free = false;
let randomIndex = Math.floor(Math.random()*this._freeColorsArray.length);
let randomColor = this._freeColorsArray[randomIndex];
this._freeColorsArray.splice(randomIndex, 1); // we remove from possible choice
let grid = new TetrisGrid( this._gameKeysSets[p], randomColor );
this.organizeGrids({newGrid:grid});
return grid;
} else
this._gameEventsQueue.dequeue();
return null;
},
removeGrid(grid) { // require to be sure that grid exists and is removable
this._gridsListArray.splice(this._gridsListArray.indexOf(grid), 1); // removing grid from array
grid._playerKeysSet.free = true; // release if keys used
this._freeColorsArray.push(grid._gridColor);
this._playersCount--;
grid.destroyGrid(); // stops timers etc..
this.organizeGrids({oldGrid:true});
},
organizeGrids(instruction) { // horizontal organization only, zoomToFit makes the correct zoom
SPRITES.zoomToFit();
MAIN_MENU._domNode._childs.playingAreaSprite.redrawNode(); // redraw background
let realIntervalX = (SPRITES.pxGameWidth-(SPRITES.pxFullGridWidth*this._playersCount)) / (this._playersCount+1);
if (instruction.newGrid || instruction.oldGrid) {
if (instruction.newGrid)
if (this._playersCount%2) { // from left or right
this._gridsListArray.unshift(instruction.newGrid); // added to left
instruction.newGrid._domNode.moveCenterTo(-SPRITES.pxFullGridWidth, null);
} else {
this._gridsListArray.push(instruction.newGrid); // added to right
instruction.newGrid._domNode.moveCenterTo(SPRITES.pxGameWidth+SPRITES.pxFullGridWidth, null);
}
let count = 0;
for (let p in this._gridsListArray) {
let myGrid=this._gridsListArray[p];
count++;
myGrid._domNode.redrawNode(); // we change all sizes
myGrid._domNode.moveCenterTo(null, SPRITES.pxTopMenuZoneHeight + SPRITES.pxHalfGameHeight);
myGrid._vector = [
count*realIntervalX + (count-1)*SPRITES.pxFullGridWidth - myGrid._domNode.getX(),
0 ];
}
// old: this._gameEventsQueue.execNowOrEnqueue(this._anims.moveGridsAnim, this._anims.moveGridsAnim.startAnim); // #DEBUG above, $alert(instruction);
this._anims.moveGridsAnim.startAnim();
if (instruction.newGrid)
instruction.newGrid.startGrid(); // enqueue?
} else {
let count = 0;
for (let p in this._gridsListArray) {
let myGrid=this._gridsListArray[p];
count++;
myGrid._domNode.redrawNode(); // we change all sizes
myGrid._domNode.moveCenterTo(null, SPRITES.pxTopMenuZoneHeight + SPRITES.pxHalfGameHeight);
myGrid._domNode.moveNodeTo(count*realIntervalX + (count-1)*SPRITES.pxFullGridWidth, null);
}
}
},
averageBlocksByPlayingGrid() {
let playingGridsCount = 0;
let allGridsBlocksCount = 0;
for (let p in this._gridsListArray) {
let myGrid=this._gridsListArray[p];
if (myGrid._gridState === GRID_STATES.playing) {
playingGridsCount++;
allGridsBlocksCount += myGrid._lockedBlocks._blocksCount;
}
}
return allGridsBlocksCount/playingGridsCount;
},
transferRows(from, count) { // from grid
let toGridArray = [];
this._gridsListArray.forEach( myGrid => {
if ( (myGrid !== from) && (myGrid._gridState === GRID_STATES.playing) ) toGridArray.push(myGrid);
} );
if (toGridArray.length > 0)
while ((count--) > 0) { // decrement AFTER evaluation, equivalent to 'while (count--)'
let destGrid = toGridArray[ (Math.floor(Math.random()*toGridArray.length)+count) % toGridArray.length ];
destGrid._gridEventsQueue.execNowOrEnqueue(
destGrid._lockedBlocks,
destGrid._lockedBlocks.put1NewRisingRow ); // we exec or enqueue
};
},
}
// PentominoesBriefMode Class, to manage pentominoes mode, a special mode with 5 blocks shapes, which happens after a trigger
class PentominoesBriefMode {
constructor() {
this._pentoModeTimer = new Timer({
funcAtTimeOut: _ => this.finishPentoMode(),
timerPeriod: 0,
timerOwner: this
});
this._gridWichTriggeredPentoMode;
}
/*destroyPentoMode() { with(this) { // to replace by anim timer
_pentoModeTimer.finishTimer();
}*/
pauseOrResume() {
this._pentoModeTimer.pauseOrResume();
}
isRunning() {
return (this._pentoModeTimer.isRunning());
}
finishPentoMode() {
this._pentoModeTimer.finishTimer();
GAME._gridsListArray.forEach( myGrid => {
if (myGrid._gridState === GRID_STATES.playing) {
myGrid._playedPolyominoesType = 'tetrominoes'
myGrid._nextShapePreview.unMark(myGrid._nextShape); // to mark immediately next shape on preview
myGrid._nextShape = new TetrisShape(myGrid); // previous falling shape is garbage collected
myGrid._nextShapePreview.mark(myGrid._nextShape);
myGrid._gridMessagesQueue.execNowOrEnqueue( // display message in each grid
myGrid._anims.messageAnim,
myGrid._anims.messageAnim.startAnim,
[{text: 'Normal<BR>mode', fieldCharCount: 5}]);
}
});
}
runPentoMode(gridWichTriggeredPentoMode, clearedLinesCount) {
this._gridWichTriggeredPentoMode = gridWichTriggeredPentoMode;
if (this.isRunning()) this.finishPentoMode();
GAME._gridsListArray.forEach( myGrid => { // here, argument is used
if (myGrid._gridState === GRID_STATES.playing) {
myGrid._playedPolyominoesType = (myGrid !== this._gridWichTriggeredPentoMode) ? 'pentominoes' : 'trominoes';
myGrid._nextShapePreview.unMark(myGrid._nextShape); // to mark immediately next shape on preview
myGrid._nextShape = new TetrisShape(myGrid); // previous falling shape is garbage collected
myGrid._nextShapePreview.mark(myGrid._nextShape);
myGrid._gridMessagesQueue.execNowOrEnqueue( // display message in other grids
myGrid._anims.messageAnim,
myGrid._anims.messageAnim.startAnim,
[{text: (myGrid === gridWichTriggeredPentoMode ? 'Trominoes' : 'Pentominoes') + '<BR>mode', fieldCharCount: 6}]);
}
}, this ); // this way to pass this._gridWichTriggeredPentoMode
this._pentoModeTimer.setTimerPeriod(DURATIONS.pentominoesModeDuration*clearedLinesCount) // *3 for 3 lines cleared, *4 for 4 lines cleared
.restartTimer();
gridWichTriggeredPentoMode._anims.pentominoesModeAnim.setDuration(DURATIONS.pentominoesModeDuration*clearedLinesCount);
gridWichTriggeredPentoMode._anims.pentominoesModeAnim.startAnim();
}
}
// TetrisGrid Class
function TetrisGrid(playerKeysSet, gridColor){
this._gridColor = gridColor;
this._playerKeysSet = playerKeysSet;
this._lockedBlocks = new LockedBlocks(this);
this._gridEventsQueue = new EventsQueue();
this._animsStack = [];
this._lockedShapes = [];
this._rowsToClearSet = new Set();
this._matrix = new Array(RULES.horizontalCellsCount + 2); // 12 columns, left and right boxes as margins columns, program fail if removed
for (let i=0;i < this._matrix.length;i++) {
this._matrix[i] = [];
for (let j=GAME._matrixBottom;j <= GAME._matrixHeight;j++) // height -1 to +(2x20)
this._matrix[i][j] = null;
}
this._dropTimer = new Timer({ // here this._fallingShape is not defined yet
//funcAtTimeOut() { console.log(this);this.fallingShapeTriesMove(0,-1); },
funcAtTimeOut: grid => grid.fallingShapeTriesMove(0,-1),
timerPeriod: this._normalDropPeriod,
timerOwner: this
});
this._keyPressTimer = new Timer({
funcAtTimeOut: grid => grid._keyDownPressedAtLeast200ms = true,
timerPeriod: 30,
timerOwner: this
});
//this._domNode = MAIN_MENU._domNode.
this._domNode = new DomNode({ // creating tetris DOM zone and sub elements
width: _ => SPRITES.pxFullGridWidth, height: _ => SPRITES.pxFullGridAndCeil,
frameZoneDiv: {
x: _ => SPRITES.pxGridBorder, y: _ => SPRITES.pxCeilHeight,
width: _ => SPRITES.pxGridWidth, height: _ => SPRITES.pxGridHeight,
overflow: 'hidden',
gridZoneDiv: { // tetris background, if not canvas, it's div
gridSprite: { type: 'canvas', sprite:SPRITES._spriteGridBackground },
ghostBlocksDiv: {},
realBlocksDiv: {} } },
frontZoneSprite: { type: 'canvas',
y: _ => SPRITES.pxCeilHeight, sprite: SPRITES._spriteGridFront, height: _ => SPRITES.pxFullGridHeight },
controlZoneDiv: {
width: _ => SPRITES.pxXPreviewPosition, height: _ => SPRITES.pxPreviewFullSize,
y: _ => SPRITES.pxYPreviewPosition, vertical_align: 'middle' },
nextShapePreviewSprite: { type: 'canvas',
x: _ => SPRITES.pxXPreviewPosition, y: _ => SPRITES.pxYPreviewPosition,
width: _ => SPRITES.pxPreviewFullSize, height: _ => SPRITES.pxPreviewFullSize,
sprite: SPRITES._spritePreviewBlock },
scoreZoneDiv: {
x: _ => SPRITES.pxXScorePosition, y: _ => SPRITES.pxYScorePosition,
width: _ => SPRITES.pxXPreviewPosition, height: _ => SPRITES.pxPreviewFullSize, vertical_align: 'middle' },
messageZoneDiv: {
y: _ => SPRITES.pxCeilHeight, width: _ => SPRITES.pxFullGridWidth, height: _ => SPRITES.pxFullGridHeight, vertical_align: 'middle' }
}, `fullGridDiv${MAIN_MENU._domNode.getNewUId_()}`, MAIN_MENU._domNode);
this._domNode._childs.frontZoneSprite.nodeDrawSprite({col:this._gridColor.name});
this._realBlocksNode = this._domNode._childs.frameZoneDiv._childs.gridZoneDiv._childs.realBlocksDiv; // shortcut
this._ghostBlocksNode = this._domNode._childs.frameZoneDiv._childs.gridZoneDiv._childs.ghostBlocksDiv; // shortcut
this._domNode._childs.frameZoneDiv._childs.gridZoneDiv._childs.gridSprite.nodeDrawSprite({col:this._gridColor.name});
this._domNode._childs.controlZoneDiv.createText(FONTS.scoreFont, 'bold', SpriteObj.rgbaTxt(this._gridColor.light), '0 0 0.4em '+SpriteObj.rgbaTxt(this._gridColor.light)); // _textCharCountWidthMin : 1 or 7
this._domNode._childs.controlZoneDiv.setTextIntoSizedField({
text: this._playerKeysSet.symbols[0]+'</BR>'+this._playerKeysSet.symbols[1]+' '+this._playerKeysSet.symbols[2]+' '+this._playerKeysSet.symbols[3],
fieldCharCount: 8 }); // up down left right
this._domNode._childs.scoreZoneDiv.createText(FONTS.scoreFont, 'normal', SpriteObj.rgbaTxt(this._gridColor.light), '0 0 0.4em '+SpriteObj.rgbaTxt(this._gridColor.light), 3);
this._domNode._childs.messageZoneDiv.createText(FONTS.messageFont, 'normal', SpriteObj.rgbaTxt(this._gridColor.light), '0.05em 0.05em 0em '+SpriteObj.rgbaTxt(this._gridColor.dark));
this._nextShapePreview = new NextShapePreview(this);
this._anims = {}; // need to initialize before creating new score which contains anim
this._score = new TetrisScore(this); // contains animation,
this._anims.quakeAnim = new Animation({
animateFunc(animOutput) { // to use context of this Animation
this._domNode._childs.frameZoneDiv._childs.gridZoneDiv.moveTemporaryRelatively(0, SPRITES.pxCellSize*2/4*animOutput); // default 2/4 or 3/4, proportionaly to deep 20 this._domNode use context of this TetrisGrid
},
endAnimFunc() {
this._domNode._childs.frameZoneDiv._childs.gridZoneDiv.moveTemporaryRestore();
this.gridAnimsStackPop(); // to have exclusive quake anim
},
timingAnimFunc: x => Math.sin(x*Math.PI), // arrow replace a return // or return Math.sin(x*Math.PI*2)*(1-x);
animDuration: DURATIONS.gridQuakeDuration,
animOwner: this // otherwise, it's animation context by default
});
this._anims.pentominoesModeAnim = new Animation({
animateFunc(animOutput) { // to use context of this Animation
this._domNode._childs.frontZoneSprite.setDomNode({opacity: Math.abs(animOutput)});
},
endAnimFunc() {
this._domNode._childs.frontZoneSprite.setDomNode({opacity: 1}); // 1 = totalement opaque, visble
},
timingAnimFunc: x => -Math.cos( (3**(x*3)) * Math.PI) / 2 + 0.5, // arrow replace a return // f(x)=-cos(3^(x*3)*pi)/2+0.5
animDuration: 0, // need to set duration for this animation before running
animOwner: this // otherwise, it's animation context by default
});
this._anims.clearRowsAnim = new Animation({ // loading animation to use later
animateFunc(animOutput) { // called n times recursively, this: current object AND Animation
this._rowsToClearSet.forEach( myRow => { // for each row to clear
for (let i=1;i <= RULES.horizontalCellsCount;i++) // for each column
this._matrix[i][myRow]._domNode.setScale(animOutput) }); // with blocks' _domNodes, programs goes here for each block of each row to clear
},
endAnimFunc() { // NOT GRAPHIC PROCESS
this._rowsToClearSet.forEach( myRow => this.clearFullRowAfterClearingAnim(myRow) ); // now erasing animated cleared rows data
this._lockedBlocks.chainSearchOrphan(SEARCH_MODE.down);
this.gridAnimsStackPop();
},
timingAnimFunc: x => 1 - x**2, // arrow replace a return
animDuration: DURATIONS.movingGridsDuration,
animOwner: this // otherwise, it's animation context by default
});
this._anims.shapeHardDropAnim = new Animation({ // animation for 1 shape, falling or after clearing
animateFunc(animOutput) { // to animate blocks, we move the DomNode elementjkk
this._lockedShapes.forEach( myShape => myShape._domNode.moveNodeTo(0, - myShape._jVector * animOutput * SPRITES.pxCellSize) )
},
endAnimFunc() { // fetch rows to remove, remove from moving div, draw, destroy node
this._lockedShapes.forEach( myShape => myShape.putShapeInRealBlocksNode().drawShape()._domNode.destroyDomNode() )
this._lockedShapes = [];
this.gridAnimsStackPush(this._anims.quakeAnim, this._anims.quakeAnim.startAnim); // startAnim() function stacked
this.gridAnimsStackPush(AUDIO, AUDIO.audioPlay, 'landFX'); // we stack AUDIO.audioPlay('landFX');
this.gridAnimsStackPop();
// old: this._anims.quakeAnim.startAnim();
// old: this.gridAnimsStackPop();
},
timingAnimFunc: x => x**3, // arrow replace a return
animDuration: DURATIONS.hardDropDuration,
animOwner: this // otherwise, it's animation context by default
});
this._anims.rising1RowAnim = new Animation({
animateFunc(animOutput) { // to animate block, we move the DomNode element
this._lockedShapes.forEach( myShape => myShape._domNode.moveNodeTo(0, - myShape._jVector * animOutput * SPRITES.pxCellSize) )
},
endAnimFunc() { // fetch rows to remove, remove from moving div, draw, destroy node
this._lockedShapes.forEach( myShape => myShape.putShapeInRealBlocksNode().drawShape()._domNode.destroyDomNode() )
this._lockedShapes = []; // this._ghostBlocksNode.show(); // show ghost shape after rising, not necessary to hide
this.gridAnimsStackPop(); // unstack all countandclearrows and this._gridEventsQueue.dequeue() in stack
},
timingAnimFunc: x => x, // arrow replace a return // linear rising of rows, not (2*Math.sqrt(x)-x);
animDuration: DURATIONS.rising1RowDuration,
animOwner: this // otherwise, it's animation context by default
});
this._anims.shapeRotateAnim = new Animation({ // loading animation to use later
startAnimFunc() { // to animate block, we temporary apply a transform rotation
this._fallingShape._domNode.setTransformOrigin(SPRITES._spriteBlock.xSprite(this._fallingShape._iPosition+0.5)+"px "+SPRITES._spriteBlock.ySprite(this._fallingShape._jPosition-0.5)+"px");
},
animateFunc(animOutput) {
if ( (this._fallingShape._pivotsCount === 2) && (this._fallingShape._pivot === 0) )
this._fallingShape._domNode.setRotate(-90 + animOutput);
else
this._fallingShape._domNode.setRotate(90 - animOutput);
},
endAnimFunc() {
this._fallingShape._domNode.delTransform(); // at end, we remove transform effect
},
timingAnimFunc: x => -90*(x-2*Math.sqrt(x)), // arrow replace a return
animDuration: DURATIONS.rotatingDuration,
animOwner: this // otherwise, it's animation context by default
});
this._anims.messageAnim = new Animation({
startAnimFunc(textInfos) {
this._domNode._childs.messageZoneDiv.setTextIntoSizedField.call(this._domNode._childs.messageZoneDiv, textInfos);
},
animateFunc(animOutput) {
this._domNode._childs.messageZoneDiv.moveTemporaryRelatively(0, animOutput*3*SPRITES.pxCellSize);// SPRITES.pxYMessagePosition);
this._domNode._childs.messageZoneDiv.setDomNode({opacity: 1-Math.abs(animOutput)}); // animOutput from -1 to +1
},
endAnimFunc() {
this._domNode._childs.messageZoneDiv.moveTemporaryRestore();
this._domNode._childs.messageZoneDiv.setDomNode({opacity: 0});
this._gridMessagesQueue.dequeue();
},
timingAnimFunc: x => (2*(x-0.5))**3, // arrow replace a return // bad effect: return (x<0.3)?Math.sin(x*Math.PI*8)*(0.3-x):0
animDuration: DURATIONS.centralMessagesDuration,
animOwner: this // otherwise, it's animation context by default
});
this._gridMessagesQueue = new EventsQueue(); // used only when lost
};
TetrisGrid.prototype = {
_gridState : GRID_STATES.ready,
_gridColor : null,
_domNode : null,
_realBlocksNode : null,
_ghostBlocksNode : null,
_fallingShape : null, // falling shape or locked shapes prepared to fall after sweeping
_lockedShapes : null,
_nextShape : null, // next shape about to be place
_nextShapePreview : null, // preview on top of grid
_score : null,
_dropTimer : null,
_normalDropPeriod : DURATIONS.initialDropPeriod, // going to DURATIONS.softDropPeriod
_isSoftDropping : false, // false means normal dropping, true means soft dropping
_keyPressedUpForNextShape : true, // keyup
_keyPressTimer : null,
_keyDownPressedAtLeast200ms: false,
_playedPolyominoesType : 'tetrominoes',// starts tetris with 4 blocks shape
_playerKeysSet : null,
_lockedBlocks : null, // placed blocks in grid, including falling shape?
_matrix : null,
_anims : null,
_animsStack : null, // to stack anims sequences of (hardDrop > quake)0-1 > (clearRows > hardDrop > quake)0-*: riseGreyBlocks actions are stuck
_gridEventsQueue : null, // queue for rising rows, etc..
_gridMessagesQueue : null, // used only when lost $$$
_rowsToClearSet : null, // set to prepare rows to clear to anim when animating clearing rows
_vector : null,
destroyGrid() {
if (GAME._gameState !== GAME_STATES.paused)
this.pauseOrResume(); // to stop all timers, all anims
this._lockedBlocks.destroyLockedBlocks();
this._domNode.destroyDomNode();
},
isGridAvailableToPlay() { // if grid is busy, doesn't care about message displaying
return ( (this._gridState === GRID_STATES.playing) // if grid is losing/finishing, return busy
&& !this._anims.clearRowsAnim.isAnimating()
&& !this._anims.shapeHardDropAnim.isAnimating()
&& !this._anims.rising1RowAnim.isAnimating()
&& !this._anims.quakeAnim.isAnimating() ); // to have exclusive quake anim
},
gridAnimsStackPush(o, func, param) { // o object which contains func method, this by default
this._animsStack.push([o, func, param]);
},
gridAnimsStackPop() {
while (this.isGridAvailableToPlay() && (this._animsStack.length > 0)) { // unstack only when not busy, 2nd condition equivalent to while (this._animsStack.length)
let last = this._animsStack.pop();
last[1].call(last[0], last[2]);
}
if (this._animsStack.length === 0) // dequeue at end of anims stack, equivalent to (!this._animsStack.length), #DEBUG before
this._gridEventsQueue.dequeue();
},
startGrid() { //start playing for this grid
this._gridState = GRID_STATES.playing
this._nextShape = new TetrisShape(this);
this.newFallingShape();
// putRowsAtStart, 0 when no shape
let myRowsCount = Math.round( GAME.averageBlocksByPlayingGrid() // average blocks per grid
/ (RULES.horizontalCellsCount * (1-RULES.risingRowsHolesCountMaxRatio)) ); // divided by 10, or 10*(100%-30%) = 7
while (myRowsCount-- > 0) // we put same quanity of rows
this._gridEventsQueue.execNowOrEnqueue(this._lockedBlocks, this._lockedBlocks.put1NewRisingRow);
// end putRowsAtStart
if (GAME._gameState === GAME_STATES.paused)
this.pauseOrResume();
this._gridMessagesQueue.execNowOrEnqueue( // display Go!
this._anims.messageAnim,
this._anims.messageAnim.startAnim,
[{text: 'Go!', fieldCharCount: 2.5}]);
},
newFallingShape() {
this._fallingShape = this._nextShape;
this._fallingShape.putShapeInGame();
if (this._fallingShape.canMoveToPlaced(0, 0)) { // normal mode, can move at starting position, so it's not lost
this._nextShapePreview.unMark(this._fallingShape); // change current shape preview by a new shape
this._nextShape = new TetrisShape(this); // change current shape preview by a new shape
this._nextShapePreview.mark(this._nextShape); // change current shape preview by a new shape
this._fallingShape.moveAndPlaceShape(0, 0) // only place with call without previous removeShapeFromPlace()
.drawShape()
.findNewPositionAndDrawGhost();
this._dropTimer.setTimerPeriod(this._normalDropPeriod).restartTimer();
} else { // it's lost
this._fallingShape.drawShape()
.clearGhostBlocks()
._domNode.setDomNode({opacity: SPRITES._lostShapeOpacity});
this.lose();
}
},
rotationAsked() { // do rotation if possible, else nothing
this.turnsTimerToNormalDrop_()
if (this._fallingShape.canShapeRotate())
this._fallingShape.unplaceAndRotateAndPlaceAndDrawShape();
},
horizontalMoveAsked(iRight) {
this.turnsTimerToNormalDrop_()
this.fallingShapeTriesMove(iRight, 0);
},
turnsTimerToNormalDrop_() {
if (this._isSoftDropping) { // if soft dropping, stops soft drop fall to continue normal timer
this._isSoftDropping = false;
this._dropTimer.setTimerPeriod(this._normalDropPeriod).restartTimer(); // shape can move after fall or stopped
}
},
beginSoftDropping() { // full falling, called by keydown, call falling()
switch (true) {
case ( !this._isSoftDropping && this._keyPressedUpForNextShape ): // case normal drop and reloaded by DOWN key pressed up
this._keyPressedUpForNextShape = false; // keydown
if (this._fallingShape.canMoveFromPlacedToPlaced(0, -1))
this.continueSoftDropping(); // we run fall
else // if shape is on floor and wants fall
this.unplaceAndMoveAndPlaceHardDroppingShapeThenCountAndClearRows();
break;
case (this._isSoftDropping): // case soft drop, then hard drop requested
this._keyPressedUpForNextShape = false;
this._isSoftDropping = false;
this._dropTimer.setTimerPeriod(this._normalDropPeriod).finishTimer();
this.unplaceAndMoveAndPlaceHardDroppingShapeThenCountAndClearRows();
break;
default: // case DOWN key keep pressed down since last shape, wait for DOWN key pressed up
}
},
continueSoftDropping() { // full falling iterative, called by timer
this._fallingShape.unplaceAndMoveAndPlaceAndDrawShape(0, -1);
this._isSoftDropping = true;
this._dropTimer.setTimerPeriod(DURATIONS.softDropPeriod).restartTimer();
},
fallingShapeTriesMove(iRight, jUp) { // return true if moved (not used), called by left/right/timer
if (this._fallingShape.canMoveFromPlacedToPlaced(iRight, jUp)) {
if (iRight === 0) //no left nor right
this._dropTimer.restartTimer(); // shape go down, new period
this._fallingShape.unplaceAndMoveAndPlaceAndDrawShape(iRight, jUp);
} else { // shape can't move...
if (jUp < 0) // ...player or drop timer tries move down
if (this._isSoftDropping) //if shapes hit floor, but still can move left or right
this.turnsTimerToNormalDrop_()
else
this.unplaceAndMoveAndPlaceHardDroppingShapeThenCountAndClearRows();
}
},
unplaceAndMoveAndPlaceHardDroppingShapeThenCountAndClearRows() { // can be called recursively, when falling shape or locked shapes in game hit floor
this.gridAnimsStackPush(this, this.newFallingShape); // this.newFallingShape()
this._lockedShapes = []; // release for garbage collector
this._lockedShapes[this._fallingShape._shapeIndex] = this._fallingShape;
this._anims.shapeRotateAnim.endAnim(); // because made by drop period
this.unplaceAndMoveAndPlaceHardDroppingShape(this._lockedShapes);
if (this._fallingShape._jVector === 0) { // if played single falling shape
this._fallingShape.putShapeInRealBlocksNode()
._domNode.destroyDomNode();
// AUDIO.audioPlay('landFX');
this._gridEventsQueue.execNowOrEnqueue(this, this.countAndClearRows); // exec this.countAndClearRows immediately
} else { // if locked shapes to drop, have to make animation before next counting
this.gridAnimsStackPush(this, this.countAndClearRows); // firstly stack this.countAndClearRows() for later
this._gridEventsQueue.execNowOrEnqueue(this._anims.shapeHardDropAnim, this._anims.shapeHardDropAnim.startAnim); // secondly exec hard drop startAnim() immediately
// sound played before after hardDrop and before Quake
}
},
unplaceAndMoveAndPlaceHardDroppingShape(myShapes) { // move locked shapes to drop (after clearing rows) into matrix
myShapes.forEach( myShape => myShape.unplaceShape() ) // move to a tested place
myShapes.forEach( myShape => myShape.moveAndPlaceShape(0, myShape._jVector, DROP_TYPES.hard) ) // move to placed on grid
},
countAndClearRows() { // locks block and computes rows to transfer and _scores
if (this._fallingShape !== null) // for recursive calls with fallingshape === null
this._fallingShape.clearGhostBlocks();
let rowsToClearCount = this._rowsToClearSet.size;
if (rowsToClearCount > 0) { // if there's rows to clear
this._score.combosCompute();
this._score.computeScoreForSweptRowsAndDisplay(rowsToClearCount);
if (rowsToClearCount >= RULES.transferRowsCountMin) // if 2 rows cleared, tranfer rule
GAME.transferRows(this, rowsToClearCount);
if (rowsToClearCount >= RULES.pentominoesRowsCountMin) { // if 3 rows cleared, pentominoes rule: player have 3 blocks per shape, and others players have 5 blocks per shape
GAME._pentominoesBriefMode.runPentoMode(this, rowsToClearCount);// duration of pentominoes is proportional to rowsToClearCount, 3 or 4, it auto stops by timer
AUDIO.audioPlay('quadrupleFX');
} else
AUDIO.audioPlay('clearFX');
this._dropTimer.finishTimer() // need to finish timer before voiding _fallingShape, otherwise 'canMoveFromPlacedToPlaced of null' error
this._fallingShape = null; // to avoid combo reset scores
this._anims.clearRowsAnim.startAnim();
} else {
this._score.animAndDisplaysScore(); // to refresh score
if (this._fallingShape !== null)
this._score.combosReset();
this.gridAnimsStackPop();
}
},
lose() { // lives during this._score duration
this._gridState = GRID_STATES.lost; // avoid any other players interact with this grid
this._dropTimer.finishTimer(); // otherwise, new shape is tried
this._score.animAndDisplaysScore(); // update score if necessary
this._anims.messageAnim.setDuration(DURATIONS.lostMessageDuration); // slow down message animation
this._gridMessagesQueue.execNowOrEnqueue( // empty queues necessary?
this._anims.messageAnim,
this._anims.messageAnim.startAnim,