-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetris.js
655 lines (569 loc) · 14.1 KB
/
tetris.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
// initialized the canvas
const canvas = document.querySelector('.my-canvas');
// canvas dimension
canvas.width = 260;
canvas.height = 400;
//canvas context
const ctx = canvas.getContext('2d');
//used for checking if this is a fresh start
let isGameStart = true;
//used for storing the current, next tetromino and its position
let tetromino = {
currentTetro: null,
currentTetroLetter: null,
nextTetroLetter: null,
pos: { x: 0, y: 0 },
};
//used for storing player details
let player = {
score: 0,
highScore: 0,
level: 1,
};
//used for showing next tetromino
const next = document.querySelector('.tetro-img');
// used for accessing pause button
const pauseBtn = document.querySelector('.pause');
// used for accessing sound button
const soundBtn = document.querySelector('.sound');
//used for main header text inside the game canvas
const gameHeader = document.querySelector('.game-condition h4');
//used for sub header text inside the game canvas
const gameSubHeader = document.querySelector('.game-condition p');
//used for accessing audio
const theme = new Audio('./resources/sounds/theme.mp3');
const tetroDropAudio = new Audio('./resources/sounds/rotate.mp3');
const gameOverAudio = new Audio('./resources/sounds/gameover.mp3');
const lineRemoveAudio = new Audio('./resources/sounds/line-removal.mp3');
const pauseAudio = new Audio('./resources/sounds/pause.mp3');
//sued for holding all the audios
const audios = [
theme,
tetroDropAudio,
gameOverAudio,
lineRemoveAudio,
pauseAudio,
];
//colors array
const colors = [
null,
'#23A148',
'#DB98AE',
'#EE7828',
'#870116',
'#008FCD',
'#9B469C',
'#ECE000',
];
//game board of size 20x13 for holding the tetrominos position
const gameBoard = new Array(20).fill(0).map(() => new Array(13).fill(0));
// /**
// * Initialize the game
// */
// const init = () => {
// //scaling the canvas elements
// ctx.scale(20, 20);
// tetromino.nextTetroLetter = randomTetrominoLetter();
// gameBoardReset();
// timer();
// soundPlay();
// //running the game
// run();
// };
/*************DRAWING THE BOARD AND TETROMINOS*************/
/**
* drawing the game board and tetrominos
*/
const draw = () => {
ctx.beginPath();
ctx.fillStyle = '#E0ECFF';
//trail effect
if (keyPressed) ctx.globalAlpha = 0.1;
ctx.fillRect(0, 0, canvas.width, canvas.height);
//resetting alpha value
ctx.globalAlpha = 1;
drawBoard();
drawTetromino();
};
/**
* drawing the game board
*/
const drawBoard = () => {
gameBoard.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
ctx.beginPath();
ctx.fillStyle = colors[value];
ctx.fillRect(x, y, 1, 1);
}
});
});
};
/**
* drawing the tetromino
*/
const drawTetromino = () => {
tetromino.currentTetro.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
ctx.beginPath();
ctx.fillStyle = colors[value];
ctx.fillRect(x + tetromino.pos.x, y + tetromino.pos.y, 1, 1);
}
});
});
};
/*************Game Board Interactions*************/
/**
*Checking if the there is collision between tetrominos or game board boundaries
* @returns {Boolean} true if collision happened and false if not
*/
const collision = () => {
const [current, pos] = [tetromino.currentTetro, tetromino.pos];
for (let y = 0; y < current.length; y++) {
for (let x = 0; x < current[y].length; x++) {
//checking if the tetromino matrix non zero value is colliding with the game board matrix non zero value
if (
current[y][x] !== 0 &&
(gameBoard[y + pos.y] && gameBoard[y + pos.y][x + pos.x]) !== 0
)
return true;
}
}
return false;
};
/**
* Adding tetromino to gameBoard matrix
*/
const addTetrominoToBoard = () => {
//looping through the tetromino array
tetromino.currentTetro.forEach((row, y) => {
row.forEach((value, x) => {
//adding all non zero value to gameBoard array
if (value !== 0)
gameBoard[y + tetromino.pos.y][x + tetromino.pos.x] = value;
});
});
};
//for increasing level
let levelScore = 0;
/**
* Removing the completed lines from the game board array
*/
const gameBoardSweep = () => {
//for checking how many lines are completed
let linesCleared = 0;
//checking if there is any completed lines
outer: for (let y = gameBoard.length - 1; y > 0; y--) {
for (let x = 0; x < gameBoard[y].length; x++) {
if (gameBoard[y][x] === 0) continue outer;
}
//removing that line from the game board matrix
const row = gameBoard.splice(y, 1)[0].fill(0);
//moving that line to the top of the matrix
gameBoard.unshift(row);
y++;
linesCleared++;
levelScore += 10;
lineRemoveAudio.play();
}
//adding score 10 points for each line
player.score += linesCleared * 10;
//updating level after each 50 points scored
if (levelScore >= 50) {
levelScore = 0;
player.level += 1;
//reducing the time to drop by 200 millisecond after each level increase
if (player.level <= 5) timeForDrop -= 200;
else {
//reducing it with 20 millisecond after level 5
timeForDrop -= 20;
}
updateLevel();
}
};
/**
* Resetting the game board after every tetromino drop is complete
*/
const gameBoardReset = () => {
//setting up the current and next tetromino
tetromino.currentTetroLetter = tetromino.nextTetroLetter;
tetromino.nextTetroLetter = randomTetrominoLetter();
tetromino.currentTetro = getTetromino(tetromino.currentTetroLetter);
//setting the next tetromino image
next.src = './resources/images/' + tetromino.nextTetroLetter + '.svg';
//adjusting the starting position of the tetromino
tetromino.pos.y = 0;
tetromino.pos.x =
((gameBoard[0].length / 2) | 0) -
((tetromino.currentTetro[0].length / 2) | 0);
const letter = tetromino.currentTetroLetter;
//adjusting the position of the 'O' and 'I' tetrominos
if (letter === 'O' || letter === 'I') tetromino.pos.x++;
//if collision happened just after a tetromino was added
//call game over
if (collision()) {
isGameOver = true;
//updating high score
updateHighScore();
gameOver();
}
};
/*************Tetromino Structure & Functions*************/
/**
* Provide the shape of tetromino according to the given type
*
* @param {String} type Letter of the shape
* @returns {Number[][]} 2D array Representing the shape of tetromino
*/
const getTetromino = (type) => {
if (type === 'T') {
return [
[0, 0, 0],
[1, 1, 1],
[0, 1, 0],
];
} else if (type === 'O') {
return [
[2, 2],
[2, 2],
];
} else if (type === 'L') {
return [
[0, 3, 0],
[0, 3, 0],
[0, 3, 3],
];
} else if (type === 'J') {
return [
[0, 4, 0],
[0, 4, 0],
[4, 4, 0],
];
} else if (type === 'S') {
return [
[0, 5, 5],
[5, 5, 0],
[0, 0, 0],
];
} else if (type === 'Z') {
return [
[6, 6, 0],
[0, 6, 6],
[0, 0, 0],
];
} else if (type === 'I') {
return [
[0, 7, 0, 0],
[0, 7, 0, 0],
[0, 7, 0, 0],
[0, 7, 0, 0],
];
}
};
/**
*
* @returns {String} Representing the letter of the tetromino
*/
const randomTetrominoLetter = () => {
const tetrominos = ['T', 'O', 'L', 'J', 'S', 'Z', 'I'];
const index = Math.floor(Math.random() * tetrominos.length);
return tetrominos[index];
};
/**
* Moving the tetromino vertically
*/
const tetrominoMoveVertical = () => {
tetroDropAudio.play();
//increasing the y value
tetromino.pos.y++;
if (collision()) {
tetromino.pos.y--;
addTetrominoToBoard();
gameBoardReset();
gameBoardSweep();
updateScore();
}
//resetting the drop count
dropCounter = 0;
};
/**
* Moving the tetromino horizontally
* @param {Number} direction (+) Move right or (-) Move left
*/
const tetrominoMoveHorizontal = (direction) => {
tetroDropAudio.play();
//changing the x value according to direction
tetromino.pos.x += direction;
//stop horizontal movement when collision happens
//with game board boundary or other tetromino
if (collision()) tetromino.pos.x -= direction;
};
/**
* Rotate the tetromino matrix
* @param {Number[][]} tetromino The tetromino matrix
* @param {Number} direction (+) Rotate Clockwise (-) Rotate Anti-clockwise
*/
const rotate = (tetromino, direction) => {
//transposing the matrix
for (let y = 0; y < tetromino.length; y++) {
for (let x = 0; x < y; x++) {
[tetromino[x][y], tetromino[y][x]] = [tetromino[y][x], tetromino[x][y]];
}
}
//reversing each row in the matrix clockwise
if (direction > 0) tetromino.forEach((row) => row.reverse());
//reversing the matrix anti clockwise
else tetromino.reverse();
};
/**
* Calling the rotate on current tetromino and check collision while rotating
* * @param {Number} direction (+) Rotate Clockwise (-) Rotate Anti-clockwise
*/
const tetrominoRotate = (direction) => {
tetroDropAudio.play();
rotate(tetromino.currentTetro, direction);
//when rotation causes collision
const posX = tetromino.pos.x;
let offset = 1;
while (collision()) {
tetromino.pos.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if (offset > tetromino.currentTetro[0].length) {
rotate(tetromino.currentTetro, -direction);
tetromino.pos.x = posX;
return;
}
}
};
/*************Keyboard Interactions*************/
//for trail effect
let keyPressed = false;
document.addEventListener('keyup', (e) => {
if (isPause || isGameOver) return;
if (e.key === 's') keyPressed = false;
});
//handling key events
document.addEventListener('keydown', (e) => {
if (isPause || isGameOver) return;
//when 'a' is pressed
if (e.key === 'a') tetrominoMoveHorizontal(-1);
//when 'd' is pressed
else if (e.key === 'd') tetrominoMoveHorizontal(+1);
//when 's' is pressed
else if (e.key === 's') {
keyPressed = true;
tetrominoMoveVertical();
}
//when 'w' is pressed
else if (e.key === 'w') tetrominoRotate(+1);
});
/*************Statistics Functions*************/
let sec = 0;
let min = 0;
let hr = 0;
/**
* To show game run time
*/
const timer = () => {
//when game is paused or game over
if (isPause || isGameOver) return;
sec = parseInt(sec);
min = parseInt(min);
hr = parseInt(hr);
sec = sec + 1;
if (sec == 60) {
min = min + 1;
sec = 0;
}
if (min == 60) {
hr = hr + 1;
min = 0;
sec = 0;
}
if (sec < 10 || sec == 0) {
sec = '0' + sec;
}
if (min < 10 || min == 0) {
min = '0' + min;
}
if (hr < 10 || hr == 0) {
hr = '0' + hr;
}
document.querySelector('.time').textContent =
'Time: ' + hr + ':' + min + ':' + sec;
setTimeout('timer()', 1000);
};
/**
* Resetting the timer
*/
const resetTime = () => {
sec = 0;
min = 0;
hr = 0;
document.querySelector('.time').textContent = 'Time: 00:00:00';
};
/**
* Updating score value in html dom element
*/
const updateScore = () => {
document.querySelector('.score').textContent = 'Score: ' + player.score;
};
/**
* Updating highscore value in html dom element
*/
const updateHighScore = () => {
//checking if the score is greater than highscore or not
if (player.score > player.highScore) {
player.highScore = player.score;
document.querySelector('.topScore').textContent =
'Top Score: ' + player.highScore;
}
};
/**
* Updating level value in html dom element
*/
const updateLevel = () => {
document.querySelector('.level').textContent = 'Level: ' + player.level;
};
/*************Button Interaction*************/
let isPause = false;
/**
* Pausing the game
*/
pauseBtn.addEventListener('click', () => {
pauseAudio.play();
if (isPause) {
isPause = false;
theme.play();
run();
timer();
removeHeaders();
} else {
setHeaders('Paused', '');
theme.pause();
isPause = true;
}
});
let isSound = true;
soundBtn.addEventListener('click', () => {
if (isSound) {
isSound = false;
soundOff();
} else {
isSound = true;
soundOn();
}
});
/*************Game Headers*************/
/**
* Setting the header of the game
* @param {String} header Main header
* @param {String} subHeader Sub Header
*/
const setHeaders = (header, subHeader) => {
gameHeader.textContent = header;
gameSubHeader.textContent = subHeader;
//setting the blur effect
canvas.style.filter = 'blur(2px)';
};
/**
* Removing the headers from the canvas
*/
const removeHeaders = () => {
gameHeader.textContent = '';
gameSubHeader.textContent = '';
canvas.style.filter = 'blur(0)';
};
/*************Audio Functions*************/
/**
* for playing theme sound
*/
const soundPlay = () => {
theme.play();
theme.volume = 0.3;
theme.loop = true;
};
/**
* mute all the audios
*/
const soundOff = () => {
audios.forEach((e) => {
e.muted = true;
});
};
/**
* unmute all the audios
*/
const soundOn = () => {
audios.forEach((e) => {
e.muted = false;
});
};
/*************Game Over*************/
let isGameOver = false;
const gameOver = () => {
theme.pause();
gameOverAudio.play();
setHeaders('Game Over', 'Press Enter to restart');
pauseBtn.disabled = true;
};
/*************Game Run*************/
//used to check when to drop the tetromino
let dropCounter = 0;
//used for how much time it take for tetromino to drop
//1 sec = 1000 ms
let timeForDrop = 1000;
//used to store the previous time
let prevTime = 0;
/**
* creating animation by moving the tetromino inside the board
* @param {number} time The current time in millisecond
*/
const run = (time = 0) => {
//when game is paused
if (isPause || isGameOver) return;
//finding the difference between current and previous time
const deltaTime = time - prevTime;
//adding it to the drop counter
dropCounter += deltaTime;
//performing the drop if dropCounter is greater than time for drop
if (dropCounter > timeForDrop) {
tetrominoMoveVertical();
}
//storing the current time
prevTime = time;
draw();
requestAnimationFrame(run);
};
///////////////////////////////////////////
/**
* Starting the game
*/
window.addEventListener('load', () => {
setHeaders('Start Game', 'Press Enter to start');
ctx.scale(20, 20);
tetromino.nextTetroLetter = randomTetrominoLetter();
gameBoardReset();
pauseBtn.disabled = true;
//when 'Enter' is pressed
document.addEventListener('keydown', (e) => {
if (e.code === 'Enter' && (isGameOver || isGameStart)) {
//removing all tetrominos from the game board
gameBoard.forEach((row) => row.fill(0));
//resetting and updating all data all data
player.score = 0;
player.level = 1;
isGameOver = false;
isGameStart = false;
pauseBtn.disabled = false;
soundPlay();
updateScore();
updateLevel();
resetTime();
removeHeaders();
run();
timer();
}
});
});