forked from leognon/tritris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
507 lines (457 loc) · 18.6 KB
/
game.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
class Game {
constructor(piecesJSON, level) {
this.w = 8;
this.h = 16;
this.grid = new Grid(this.w, this.h);
this.alive = true;
if (level < 0) level = 0;
if (level > 29) level = 29;
this.startLevel = level;
this.level = level;
this.lines = 0;
this.score = 0;
this.scoreWeights = { 1: 100, 2: 400, 3: 1200 };
this.colors = [
color(255, 0, 0),
color(0, 255, 0),
color(255, 255, 0),
color(255, 0, 255),
color(0, 255, 255),
color(250, 100, 25),
color(255),
];
this.piecesJSON = piecesJSON.pieces;
const frameRate = 60.0988; //frames per second
const msPerFrame = 1000 / frameRate;
this.entryDelays = [
10 * msPerFrame,
12 * msPerFrame,
14 * msPerFrame, //Numbers from https://tetris.wiki/Tetris_(NES,_Nintendo)
16 * msPerFrame,
18 * msPerFrame,
];
this.currentPieceIndex = -1;
this.currentPiece = null; //The current piece starts as null
this.nextPieceIndex = 1 + floor(random(this.piecesJSON.length - 1));
this.nextPiece = new Piece(this.piecesJSON[this.nextPieceIndex]); //The next piece starts as a random piece that isn't a single triangles
this.nextSingles = 0;
this.spawnPiece(); //This will correctly set the currentPiece and correctly pick a new next piece
this.levelSpeeds = {
0: 48,
1: 43, //From https://tetris.wiki/Tetris_(NES,_Nintendo)
2: 38,
3: 33,
4: 28,
5: 23,
6: 18,
7: 13,
8: 8,
9: 6,
10: 5, //Level 10-12
13: 4, //13 - 15
16: 3, //16 - 18
19: 2, //19 - 28
29: 1, //29+
};
for (let lvl of Object.keys(this.levelSpeeds)) {
this.levelSpeeds[lvl] *= msPerFrame; //Make sure the are in the correct units
}
this.pieceSpeed = 0;
this.setSpeed(); //This will correctly set pieceSpeed depending on which level it's starting on
this.softDropSpeed = msPerFrame * 2;
this.lastMoveDown = Date.now() + 750;
this.das = 0;
this.dasMax = msPerFrame * 16; //It takes 16 frames on an NES to fully charge DAS
this.dasCharged = msPerFrame * 10; //When charged, DAS reset to 10 frames
this.lastFrame = Date.now(); //Used to calculate deltaTime and for DAS
this.entryDelay = msPerFrame * 14; //There is a 10 frame entry delay (the time btwn the last piece locking in, and the next spawning)
this.spawnNextPiece = 0;
this.animationTime = 0;
this.animatingLines = [];
this.maxAnimationTime = 20 * msPerFrame;
this.lastColCleared = 0;
this.maxFlashTime = 20 * msPerFrame;
this.flashTime = 0;
this.flashAmount = 4;
this.redraw = true;
this.downPressedAt = 0; //Used to calculate how many cells a piece traveled when down was pressed
this.downWasPressed = false;
this.leftWasPressed = false;
this.rightWasPressed = false;
this.zWasPressed = false;
this.zCharged = false;
this.xWasPressed = false;
this.xCharged = false;
this.playClearSound = false;
this.playFallSound = false;
this.playMoveSound = false;
this.playTritrisSound = false;
}
update() {
if (!this.alive) return;
const now = Date.now();
const deltaTime = now - this.lastFrame;
//Play a line clear animation
if (now <= this.animationTime) {
const percentDone =
(this.animationTime - now) / this.maxAnimationTime;
const clearingCol = Math.floor(percentDone * 10);
for (const row of this.animatingLines) {
//Clear as many cols as necessary
for (let col = this.lastColCleared; col >= clearingCol; col--) {
//Clear from middle to left (triangle by traingle)
const colPos = Math.floor(col / 2);
if (col % 2 == 1) this.grid.removeRightTri(row, colPos);
else this.grid.removeLeftTri(row, colPos);
//Clear from middle to right
const otherColPos = this.w - 1 - colPos;
if (col % 2 == 0)
this.grid.removeRightTri(row, otherColPos);
else this.grid.removeLeftTri(row, otherColPos);
}
}
this.lastColCleared = clearingCol; //To ensure lag doesn't cause any to get skipped
this.redraw = true;
} else if (this.animatingLines.length > 0) {
//After a line clear animation has just been completed
//Readjust the entry delay to accomodate for the animation time
this.spawnNextPiece += this.maxAnimationTime;
this.score +=
this.scoreWeights[this.animatingLines.length] *
(this.level + 1);
this.lines += this.animatingLines.length;
//Increase the level after a certain amt of lines, then every 10 lines
let incLevel = false;
if (this.level == this.startLevel) {
//This formula is from https://tetris.wiki/Tetris_(NES,_Nintendo)
if (
this.lines >= (this.startLevel + 1) * 10 ||
this.lines >= max(100, this.startLevel * 10 - 50)
) {
incLevel = true;
}
} else {
//If the tens digit increases (Ex from 128 to 131)
const prevLineAmt = Math.floor(
(this.lines - this.animatingLines.length) / 10
);
const newLineAmt = Math.floor(this.lines / 10);
if (newLineAmt > prevLineAmt) incLevel = true;
}
if (incLevel) {
this.level++;
this.setSpeed();
}
for (const row of this.animatingLines) {
this.grid.removeLine(row);
}
this.animatingLines = [];
this.redraw = true;
}
//Spawn the next piece after entry delay
if (
this.currentPiece == null &&
now > this.spawnNextPiece &&
now > this.animationTime
) {
this.spawnPiece();
this.lastMoveDown = now;
this.redraw = true;
if (!this.isValid(this.currentPiece)) {
this.alive = false; //If the new piece is already blocked, game over
}
}
if (this.currentPiece !== null) {
//If either left is pressed or right is pressed and down isn't
const oneKeyPressed =
keyIsDown(LEFT_ARROW) != keyIsDown(RIGHT_ARROW) &&
!keyIsDown(DOWN_ARROW);
let move = false;
if (oneKeyPressed) {
this.das += deltaTime;
if (
(keyIsDown(LEFT_ARROW) && !this.leftWasPressed) ||
(keyIsDown(RIGHT_ARROW) && !this.rightWasPressed)
) {
//If it was tapped, move and reset das
move = true;
this.das = 0;
} else if (this.das >= this.dasMax) {
move = true; //Key is being held, keep moving
this.das = this.dasCharged;
}
}
let horzDirection = 0;
if (move) {
if (keyIsDown(LEFT_ARROW)) horzDirection = -1;
if (keyIsDown(RIGHT_ARROW)) horzDirection = 1;
}
const zPressed = keyIsDown(90) && (!this.zWasPressed || this.zCharged);
const xPressed = keyIsDown(88) && (!this.xWasPressed || this.xCharged);
const rotation = (zPressed ? -1 : 0) + (xPressed ? 1 : 0);
let pieceSpeed = this.pieceSpeed;
if (keyIsDown(DOWN_ARROW)) {
//Pressing down moves twice as fast, or as fast as the min
pieceSpeed = min(pieceSpeed, this.softDropSpeed);
}
if (keyIsDown(DOWN_ARROW) && !this.downWasPressed) {
this.downPressedAt = this.currentPiece.pos.y; //Save when the piece was first pressed down
}
const moveDown = Date.now() >= this.lastMoveDown + pieceSpeed;
if (horzDirection != 0 || rotation != 0 || moveDown) {
this.redraw = true; //A piece has moved, so the game must be redrawn
const placePiece = this.movePiece(
horzDirection,
rotation,
moveDown
);
if (placePiece) {
if (keyIsDown(DOWN_ARROW)) {
//If it was pushed down, give 1 point per grid cell
this.score +=
this.currentPiece.pos.y - this.downPressedAt;
this.downPressedAt = 0;
}
//Place the piece
this.placePiece();
this.zCharged = false; //After a piece is placed, don't rotate the next piece
this.xCharged = false;
} else {
//If the piece was able to just move down, reset the timer
if (moveDown) this.lastMoveDown = Date.now();
}
}
}
this.downWasPressed = keyIsDown(DOWN_ARROW);
this.leftWasPressed = keyIsDown(LEFT_ARROW);
this.rightWasPressed = keyIsDown(RIGHT_ARROW);
this.zWasPressed = keyIsDown(90); //If Z was pressed
this.xWasPressed = keyIsDown(88); //If X was pressed
if (!keyIsDown(90)) this.zCharged = false; //If the player is pressing anymore, they no longer want to rotate, so don't charge
if (!keyIsDown(88)) this.xCharged = false;
this.lastFrame = Date.now();
}
placePiece() {
this.grid.addPiece(this.currentPiece);
const row = this.currentPiece.getBottomRow();
//Only clear lines if the next piece is not a triangle, or the next piece is a triangle, but it is a new triplet
if (this.nextPieceIndex != 0 || this.nextSingles == 2) {
this.clearLines(); //Clear any complete lines
}
const entryDelay = this.calcEntryDelay(row);
this.spawnNextPiece = Date.now() + entryDelay;
this.currentPiece = null; //There is an entry delay for the next piece
}
spawnPiece() {
this.currentPieceIndex = this.nextPieceIndex;
this.currentPiece = this.nextPiece; //Assign the new current piece
if (this.nextSingles > 0) {
this.nextPieceIndex = 0; //This will make it spawn 3 single triangles in a row
this.nextSingles--;
} else {
this.nextPieceIndex = floor(random(this.piecesJSON.length));
if (this.nextPieceIndex == this.currentPieceIndex) {
//Reroll to make it less likely to get the same piece twice in a row
this.nextPieceIndex = floor(random(this.piecesJSON.length));
}
if (this.nextPieceIndex == 0) {
//If it randomly chose to spawn 1 triangle, spawn 2 more
this.nextSingles = 2;
}
}
this.nextPiece = new Piece(this.piecesJSON[this.nextPieceIndex]);
this.playFallSound = true;
}
clearLines() {
let linesCleared = this.grid.clearLines();
if (linesCleared.length > 0) {
//Set the time for when to stop animating
this.animationTime = Date.now() + this.maxAnimationTime;
this.lastColCleared = 0; //Used to ensure all triangles are removed. Starts at 0 to only remove 1 on the first frame
this.animatingLines = linesCleared; //Which lines are being animated (and cleared)
if (linesCleared.length == 3) {
//Tritris!
this.flashTime = Date.now() + this.maxFlashTime;
this.playTritrisSound = true;
} else {
this.playClearSound = true;
}
}
}
setSpeed() {
let lvl = this.level;
if (this.level > 29) lvl = 29;
if (this.level < 0) lvl = 0;
while (true) {
if (this.levelSpeeds.hasOwnProperty(lvl)) {
this.pieceSpeed = this.levelSpeeds[lvl];
break;
} //Finds the correct range for the level speed
lvl--;
if (lvl < 0) {
//Uh oh, something went wrong
console.error('Level Speed could not be found!');
break;
}
}
}
movePiece(horzDirection, rotation, moveDown) {
//Apply all transformations
const vertDirection = moveDown ? 1 : 0;
this.currentPiece.move(horzDirection, vertDirection);
if (rotation == -1) this.currentPiece.rotateLeft();
if (rotation == 1) this.currentPiece.rotateRight();
//Try with all transformations
let valid = this.isValid(this.currentPiece);
if (valid) {
//The piece (possibly) moved horizontally, rotated and moved down
if (horzDirection != 0) {
this.playMoveSound = true;
}
if (rotation != 0) {
this.playMoveSound = true;
this.zCharged = false;
this.xCharged = false;
}
return false; //Don't place the piece
}
//If blocked, undo horz move and maybe wall-charge
this.currentPiece.move(-horzDirection, 0);
valid = this.isValid(this.currentPiece);
if (valid) {
//If the piece was block when moving horz, then wall charge
this.das = this.dasMax;
if (rotation != 0) {
this.playMoveSound = true;
this.zCharged = false; //If it was able to move, don't keep rotating
this.xCharged = false;
}
return false;
}
//If not valid, undo rotation
if (rotation == 1) this.currentPiece.rotateLeft();
if (rotation == -1) this.currentPiece.rotateRight();
valid = this.isValid(this.currentPiece);
if (valid) {
//The piece was blocked by rotating
if (rotation == 1) this.xCharged = true;
if (rotation == -1) this.zCharged = true;
if (horzDirection != 0) this.das = this.dasMax; //Also charge das if blocked by a rotation/wall
return false; //Don't place the piece
}
//If it reaches here, the piece was blocked by moving down and should be placed
if (moveDown) this.currentPiece.move(0, -1); //Move the piece back up
//The extra if statement is incase the pieces are at the top and spawn in other pieces
return true; //Place the piece
}
calcEntryDelay(y) {
if (y >= 18) return this.entryDelays[0];
if (y >= 14) return this.entryDelays[1];
if (y >= 10) return this.entryDelays[2];
if (y >= 6) return this.entryDelays[3];
return this.entryDelays[4];
}
isValid(piece) {
if (piece.outOfBounds(this.w, this.h)) return false;
return this.grid.isValid(piece);
}
playSounds(clearSound, fallSound, moveSound, tritrisSound) {
if (this.playClearSound) {
if (!clearSound.isPlaying()) clearSound.play();
this.playClearSound = false;
}
if (this.playFallSound) {
if (!fallSound.isPlaying()) fallSound.play();
this.playFallSound = false;
}
if (this.playMoveSound) {
if (!moveSound.isPlaying()) moveSound.play();
this.playMoveSound = false;
}
if (this.playTritrisSound) {
if (!tritrisSound.isPlaying()) tritrisSound.play();
this.playTritrisSound = false;
}
}
show(x, y, w, h, paused) {
//Play flashing animation
const flashing = this.flashTime >= Date.now();
if (!this.redraw && !flashing) return; //If not flashing, only draw when necessary
if (flashing) {
const timePassed = this.flashTime - Date.now();
const interval = Math.floor(this.flashAmount * timePassed / this.maxFlashTime);
if (interval % 2 == 0) {
background(150);
} else {
background(100);
}
this.redraw = true; //If flashing, redraw each frame
} else {
background(100);
}
noStroke();
fill(0);
rect(x, y, w, h);
const cellW = w / this.w;
const cellH = h / this.h;
if (this.currentPiece && !paused) {
this.currentPiece.show(x, y, cellW, cellH, this.colors);
}
this.grid.show(x, y, w, h, this.colors, paused);
const txtSize = 20;
textSize(txtSize);
textAlign(LEFT, TOP);
const padding = 10;
const scorePos = createVector(x + w + cellW, y + cellH);
const scoreTxt = `Score ${this.score}`;
const linesTxt = `Lines ${this.lines}`;
const levelTxt = `Level ${this.level}`;
const textW = max(
textWidth(scoreTxt),
textWidth(linesTxt),
textWidth(levelTxt),
4 * cellW
);
const scoreDim = createVector(
textW + padding + 10,
txtSize * 4.5 + padding * 2
);
noFill();
stroke(0);
strokeWeight(3);
//The box outline
rect(scorePos.x, scorePos.y, scoreDim.x, scoreDim.y);
noStroke();
fill(0);
text(scoreTxt, scorePos.x + padding, scorePos.y + padding);
text(
linesTxt,
scorePos.x + padding,
scorePos.y + padding + 1.75 * txtSize
);
text(
levelTxt,
scorePos.x + padding,
scorePos.y + padding + 3.5 * txtSize
);
const nextPiecePos = createVector(
scorePos.x,
scorePos.y + scoreDim.y + cellH
);
const nextPieceDim = createVector(cellW * 3, cellW * 3);
noFill();
stroke(0);
strokeWeight(3);
rect(nextPiecePos.x, nextPiecePos.y, nextPieceDim.x, nextPieceDim.y);
if (!paused) {
this.nextPiece.showAt(
nextPiecePos.x,
nextPiecePos.y,
nextPieceDim.x,
nextPieceDim.y,
this.colors
);
}
if (!flashing) this.redraw = false;
}
}