-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
499 lines (457 loc) · 14 KB
/
script.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
// Start the game automatically after the page has loaded
// and enable touch event handling
window.onload = function() {
startButton.click()
Touch(gameBoard);
}
function gridSize() {
let pixels = gameBoard.clientHeight / 20;
// XXX the game board height should be divisible by 20, but it's not
// We cannot use contrasting colours for the block border, and it doesn't look as good.
// console.assert(pixels % 1 === 0, "Grid size is not an integer")
return pixels;
}
const gameBoard = document.getElementById("game-board");
const startButton = document.getElementById("start-button");
const pauseButton = document.getElementById("pause-button");
const currentScoreDisplay = document.getElementById("current-score-display");
const highScoreDisplay = document.getElementById("high-score-display");
const autopilotButton = document.getElementById("automate-button");
const autopilot = new Autopilot(autopilotButton);
let tickInterval = 1000;
(function maybeDebug() {
// Show the debug button if the URL contains the #debug hash
// The debug button toggles debugging features
const debugButton = document.getElementById("debug-button");
if (window.location.hash === '#debug') {
debugButton.classList.add('visible');
} else {
debugButton.classList.remove('visible');
}
debugButton.addEventListener('click', function() {
document.querySelector('html').classList.toggle('debug');
});
})();
(function maybeEnableAutopilot() {
// if the URL looks like https://example.com/?...&autopilot=true&...
if (window.location.search.includes('autopilot=true')) {
// Start the autopilot automatically after the page has loaded
window.onload = function() {
startButton.click()
autopilotButton.click()
}
}
})();
const pieceTypes = ["I", "O", "T", "S", "Z", "J", "L"];
const pieces = {
I: {
shape: [
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]
]
},
O: {
shape: [
[1, 1],
[1, 1]
]
},
T: {
shape: [
[0, 1, 0],
[1, 1, 1],
[0, 0, 0]
]
},
S: {
shape: [
[0, 1, 1],
[1, 1, 0],
[0, 0, 0]
]
},
Z: {
shape: [
[1, 1, 0],
[0, 1, 1],
[0, 0, 0]
]
},
J: {
shape: [
[0, 1, 0],
[0, 1, 0],
[1, 1, 0]
]
},
L: {
shape: [
[0, 1, 0],
[0, 1, 0],
[0, 1, 1]
]
}
};
let currentPiece;
let gameBoardArray = [];
let score = 0;
let gameInterval;
// Initialize game board array with empty rows
for (let i = 0; i < 20; i++) {
gameBoardArray.push(new Array(10).fill(0));
}
// Create a new random piece
function createPiece() {
if (isGameOver()) return;
let type = pieceTypes[Math.floor(Math.random() * pieceTypes.length)];
currentPiece = {
type: type,
x: 4,
y: 0,
shape: pieces[type].shape,
rotation: 0
};
// Check if the new piece collides with any other piece and move it upwards if it does
while (!checkCollision(currentPiece.shape)) {
currentPiece.y--;
}
}
// Draw the current piece on the game board
function drawPiece() {
// Remove current element from the game board
const blocks = gameBoard.getElementsByClassName("current-piece");
for (let i = blocks.length - 1; i >= 0; i--) {
gameBoard.removeChild(blocks[i]);
}
// Add block elements for each block in the piece
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
let block = document.createElement("div");
block.classList.add("block", currentPiece.type, "current-piece");
block.style.top = `calc(var(--grid-size) * ${currentPiece.y + y})`;
block.style.left = `calc(var(--grid-size) * ${currentPiece.x + x})`;
gameBoard.appendChild(block);
}
});
});
}
// Check if the current piece can move down by one row
function canMoveDown() {
let canMove = true;
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
let newY = currentPiece.y + y + 1;
if (newY > 19 || gameBoardArray[newY] && gameBoardArray[newY][currentPiece.x + x] !== 0) {
canMove = false;
}
}
});
});
return canMove;
}
// Move the current piece down by one row
function movePieceDown() {
if (canMoveDown()) {
currentPiece.y++;
} else {
addPieceToBoard();
createPiece();
}
drawPiece();
}
// Rotate the current piece clockwise
function rotatePiece() {
let newShape = transpose(currentPiece.shape);
newShape = flip(newShape);
if (checkCollision(newShape)) {
currentPiece.shape = newShape;
currentPiece.rotation = (currentPiece.rotation + 1) % 4;
}
drawPiece();
}
// Transpose a matrix (turn rows into columns and columns into rows)
function transpose(matrix) {
let newMatrix = [];
for (let x = 0; x < matrix[0].length; x++) {
newMatrix.push([]);
for (let y = 0; y < matrix.length; y++) {
newMatrix[x].push(matrix[y][x]);
}
}
return newMatrix;
}
// Flip a matrix horizontally
function flip(matrix) {
return matrix.map(row => row.reverse());
}
// Check if the current piece collides with any other pieces or the edges of the game board
function checkCollision(shape, xOffset = 0) {
let collision = false;
shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
x += xOffset
if (
currentPiece.x + x < 0 ||
currentPiece.x + x > 9 ||
//currentPiece.y + y < 0 ||
currentPiece.y + y > 19 ||
gameBoardArray[currentPiece.y + y] && gameBoardArray[currentPiece.y + y][currentPiece.x + x] !== 0
) {
collision = true;
}
}
});
});
return !collision;
}
// Add the current piece to the game board array
function addPieceToBoard() {
currentPiece.shape.forEach((row, y) => {
if (currentPiece.y + y < 0) return;
row.forEach((value, x) => {
if (value !== 0) {
gameBoardArray[currentPiece.y + y][currentPiece.x + x] = currentPiece.type;
}
});
});
}
// Check if the game is over
function isGameOver() {
let gameOver = gameBoardArray[0].some(value => value !== 0)
return gameOver;
}
// Update the game state and redraw the game board
function gameLoop() {
if (isPaused()) return;
movePieceDown();
checkRows();
drawBoard();
if (isGameOver()) {
clearInterval(gameInterval);
document.body.classList.add("game-over");
}
}
// Check for completed rows and remove them
function checkRows() {
for (let y = gameBoardArray.length - 1; y >= 0; y--) {
if (gameBoardArray[y].every(value => value !== 0)) {
gameBoardArray.splice(y, 1);
gameBoardArray.unshift(new Array(10).fill(0));
score++;
maybeSaveHighScore();
currentScoreDisplay.innerHTML = score;
// Remove any existing block elements from the DOM
while (gameBoard.firstChild) gameBoard.removeChild(gameBoard.firstChild);
}
}
}
// Clear board and reset score
function resetGame() {
clearInterval(gameInterval);
unPause()
// Remove any existing block elements from the DOM
while (gameBoard.firstChild) {
gameBoard.removeChild(gameBoard.firstChild);
}
gameBoardArray = [];
for (let i = 0; i < 20; i++) {
gameBoardArray.push(new Array(10).fill(0));
}
score = 0;
currentScoreDisplay.innerHTML = score;
updateHighScoreDisplay();
gameOver = false;
document.body.classList.remove("game-over");
}
function getHighScore() {
return +localStorage.getItem("highScore") || 0;
}
function updateHighScoreDisplay() {
highScoreDisplay.innerHTML = getHighScore();
}
function maybeSaveHighScore() {
if (score > localStorage.getItem("highScore")) {
localStorage.setItem("highScore", score);
// updateHighScoreDisplay();
}
}
// This function is not connected to any UI -- call it manually in the console to reset the high score
function resetHighScore(value = 0) {
localStorage.setItem("highScore", value);
updateHighScoreDisplay();
}
// Draw the game board
function drawBoard() {
// Add block elements for each element in the game board array
gameBoardArray.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0 && !fallenBlockExistsAtPosition(x, y)) {
// console.log("Adding to the board:", `calc(var(--grid-size) * ${y})`, `calc(var(--grid-size) * ${x}`);
let block = document.createElement("div");
block.classList.add("fallen", "block", value, `x${x}`, `y${y}`);
block.style.top = `calc(var(--grid-size) * ${y})`;
block.style.left = `calc(var(--grid-size) * ${x})`;
gameBoard.appendChild(block);
}
});
});
}
// Check if a fallen block exists at a given position
function fallenBlockExistsAtPosition(x, y) {
return gameBoard.querySelector(`.x${x}.y${y}`);
}
// Handle keyboard input
document.addEventListener("keydown", event => {
switch (event.keyCode) {
case 32: // Space
Control.drop();
break;
case 37: // Left arrow
Control.left();
break;
case 39: // Right arrow
Control.right();
break;
case 40: // Down arrow
Control.down()
break;
case 38: // Up arrow
Control.rotate();
break;
}
drawPiece();
});
function Piece(piece) {
this.piece = piece
this.columnOccupancy = () => {
let result = []
for (let i = 0; i < this.piece.shape[0].length; i++) {
result[i] = 0
for (let j = 0; j < this.piece.shape.length; j++) {
result[i] |= this.piece.shape[j][i]
}
}
return result
}
this.leftEdgeX = () => {
let leftOffset = this.columnOccupancy(this.piece).indexOf(1)
let leftEdge = this.piece.x + leftOffset
return leftEdge
}
this.rightEdgeX = () => {
let rightOffset = this.columnOccupancy(this.piece).reverse().indexOf(1)
let rightEdge = this.piece.x + (this.piece.shape.length - 1) - rightOffset
return rightEdge
}
this.rowOccupancy = () => {
let result = []
for (let i = 0; i < this.piece.shape.length; i++) {
result[i] = 0
for (let j = 0; j < this.piece.shape[0].length; j++) {
result[i] |= this.piece.shape[i][j]
}
}
return result
}
this.topEdgeY = () => {
let topOffset = this.rowOccupancy(this.piece).indexOf(1)
let topEdge = this.piece.y + topOffset
return topEdge
}
this.bottomEdgeY = () => {
let bottomOffset = this.rowOccupancy(this.piece).reverse().indexOf(1)
let bottomEdge = this.piece.y + (this.piece.shape.length - 1) - bottomOffset
return bottomEdge
}
}
// Start the game
startButton.addEventListener("click", (event) => {
event.preventDefault()
event.target.blur() // lest the <Space> keypress that we use to drop the current piece depresses the button *facepalm*
Control.newGame();
});
class Control {
static drop() {
while (canMoveDown()) {
movePieceDown();
}
}
static left() {
if (new Piece(currentPiece).leftEdgeX() > 0 && checkCollision(currentPiece.shape, -1)) {
currentPiece.x--;
}
}
static right() {
if (new Piece(currentPiece).rightEdgeX() < 9 && checkCollision(currentPiece.shape, 1)) {
currentPiece.x++;
}
}
static down() {
if (canMoveDown()) {
movePieceDown();
}
}
static rotate() {
rotatePiece();
}
static getScore() {
return score;
}
static getBoard() {
const board = JSON.parse(JSON.stringify(gameBoardArray));
board.forEach(row => row.forEach((value, index) => row[index] = value ? 1 : 0)); // normalise in place
return board;
}
static getPiece() {
return JSON.parse(JSON.stringify(currentPiece));
}
static getHighScore() { return getHighScore(); }
static getScore() { return score; }
static getState() {
const result = {
"board": Control.getBoard(),
"piece": Control.getPiece(),
"score": score,
"highScore": getHighScore(),
"isGameOver": isGameOver(),
}
return result;
}
static newGame() {
resetGame();
createPiece();
drawPiece();
gameInterval = setInterval(gameLoop, tickInterval);
}
static isGameOver() { return isGameOver(); }
static getTick() { return tickInterval; }
static setTick(newTick) {
tickInterval = newTick;
clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, tickInterval);
}
static getPieceTypes() { return pieceTypes; }
}
function isPaused() {
let isPaused = document.body.classList.contains("paused")
return isPaused
}
function unPause() {
document.body.classList.remove("paused")
}
// Pause/resume the game
pauseButton.addEventListener("click", () => {
event.preventDefault()
event.target.blur() // XXX for some reason this doesn't work
startButton.focus(); startButton.blur() // lest the <Space> keypress that we use to drop the current piece depresses the button *facepalm*
if (isPaused()) {
unPause()
} else {
document.body.classList.add("paused")
}
});