-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetris-core.js
414 lines (363 loc) · 12.7 KB
/
tetris-core.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
import { rgba } from './colors.js';
import { createCanvas, createMatrix } from './util.js';
import { drawRect, drawFilledMatrix, drawMonospaceText } from './draw.js';
import { TetrisBlockManager } from './tetris-block-manager.js';
class ARENA_STATE {
/** @readonly Jogo rodando */
static RUNNING = 0;
/** @readonly Jogo pausado */
static PAUSED = 1;
/** @readonly Tela de fim de jogo */
static ENDSCREEN = 2;
}
class FallingBlock {
/**
* Monta um objeto que representa um dado tetromino em queda.
* @param {number} x posição no eixo horizontal
* @param {number} y posição no eixo vertical
* @param {{ code: number, matrix: number[][]}} blockMatrix
*/
constructor(x, y, blockMatrix) {
/**
* @type {number}
*/
this.x = x;
/**
* @type {number}
*/
this.y = y;
/**
* @readonly
* @type {number}
*/
this.code = blockMatrix.code;
/**
* @type {Readonly<number[][]>}
*/
this.matrix = blockMatrix.matrix;
}
}
/**
* Função que produz uma nova matriz a partir da mescla da matriz antiga
* e do bloco que está caindo.
* @param {number[][]} arena
* @param {FallingBlock} fallingBlock
* @returns {number[][]}
*/
function mergeArenaAndBlock(arena, fallingBlock, width, height) {
const mergedArena = createMatrix(width, height);
// Copiando arena antiga
for (let row = mergedArena.length; row--;) {
for (let col = mergedArena[row].length; col--;) {
mergedArena[row][col] = arena[row][col];
}
}
// Copiando falling block
const blockMatrix = fallingBlock.matrix;
for (let row = blockMatrix.length; row--;) {
for (let col = blockMatrix[row].length; col--;) {
if (blockMatrix[row][col] !== 0) {
const arenaRow = row + fallingBlock.y;
const arenaCol = col + fallingBlock.x;
if (arenaRow >= 0 && arenaRow < height &&
arenaCol >= 0 && arenaCol < width
) {
mergedArena[arenaRow][arenaCol] = blockMatrix[row][col];
}
}
}
}
return mergedArena;
}
/**
* Função que checa se o espaço aonde o bloco que está caindo vai ser inserido
* está de fato livre para inserção.
* @param {Readonly<number[][]>} arena matriz que represente a arena
* @param {Readonly<FallingBlock>} block Bloco que está sendo testado
* @param {number} width largura da arena
* @param {number} height altura da arena
* @returns {boolean}
*/
function isFallingBlockInFreeSpace(arena, block, width, height) {
const blockMatrix = block.matrix;
for (let row = blockMatrix.length; row--;) {
for (let col = blockMatrix[row].length; col--;) {
if (blockMatrix[row][col] !== 0) {
const arenaRow = row + block.y;
const arenaCol = col + block.x;
if (arenaRow >= height || arenaRow < 0 ||
arenaCol >= width || arenaCol < 0 ||
arena[arenaRow][arenaCol] !== 0)
{
return false;
}
}
}
}
return true;
}
/**
* Função que rotacionado os elementos de uma matriz no sentido horário
* e anti-horário.
* @todo João, analisar e verificar se o comportamento da função de rotação
* está condizente com o que ela se propõe.
*
* @param {Readonly<number[][]>} matrix Matriz original que será usada para produzir a nova
* @param {-1|1} dir Direção da rotação: 1 para sentido horário e -1 para sentido anti-horário
* @returns {number[][]} Retorna uma versão nova com os elementos rotacionados
*/
function rotateMatrix(matrix, dir) {
const height = matrix.length;
const width = matrix[0].length;
const rotatedMatrix = createMatrix(height, width);
for (let row = rotatedMatrix.length; row--;) {
for (let col = rotatedMatrix[row].length; col--;) {
rotatedMatrix[row][col] = matrix[(dir === -1) ? height - 1 - col : col][(dir === -1) ? row : width - 1 - row];
}
}
return rotatedMatrix;
}
export class TetrisArena {
/**
* @param {number} width Largura da arena
* @param {number} height Altura da arena
* @param {number} [initialSpeed] Velocidade de queda inicial
*/
constructor(width, height, initialSpeed = 1000) {
/**
* @readonly
* @type {number}
*/
this.width = width;
/**
* @readonly
* @type {number}
*/
this.height = height;
/**
* @see {@link ARENA_STATE}
* @type {0|1|2}
*/
this.state = ARENA_STATE.RUNNING;
/**
* @type {number[][]}
*/
this.filledMatrix = createMatrix(width, height);
/**
* @type {number[][]}
*/
this.arenaMatrix = createMatrix(width, height);
this.newBlock(); // Inicializa primeiro bloco
/**
* @type {number}
*/
this.score = 0;
/**
* @type {number}
*/
this.cumulatedTime = 0;
/**
* @type {number}
*/
this.fallInterval = initialSpeed;
}
/**
* Método que contém a lógica de atualização da arena
* @this TetrisArena
* @param {number} deltatime
* @returns {void}
*/
update = (deltatime) => {
this.cumulatedTime += deltatime;
if (this.state !== ARENA_STATE.RUNNING) return;
if (this.cumulatedTime > this.fallInterval) {
this.blockFall();
} else {
this.arenaMatrix = mergeArenaAndBlock(this.filledMatrix, this.fallingBlock, this.width, this.height);
}
}
/**
* Método que reinicia a arena para uma nova partida
* @returns {void}
*/
reset() {
this.state = ARENA_STATE.RUNNING;
this.filledMatrix = createMatrix(this.width, this.height);
this.arenaMatrix = createMatrix(this.width, this.height);
this.newBlock(); // Inicializa primeiro bloco
this.score = 0;
}
tryRotate(dir) {
const oldMatrix = this.fallingBlock.matrix;
this.fallingBlock.matrix = rotateMatrix(oldMatrix, dir);
if (!isFallingBlockInFreeSpace(this.filledMatrix, this.fallingBlock, this.width, this.height)) {
this.fallingBlock.matrix = oldMatrix;
}
}
tryMove(dir) {
const oldX = this.fallingBlock.x;
this.fallingBlock.x += dir;
if (!isFallingBlockInFreeSpace(this.filledMatrix, this.fallingBlock, this.width, this.height)) {
this.fallingBlock.x = oldX;
}
}
blockFall() {
this.cumulatedTime = 0;
this.fallingBlock.y++;
if (isFallingBlockInFreeSpace(this.filledMatrix, this.fallingBlock, this.width, this.height)) {
this.arenaMatrix = mergeArenaAndBlock(this.filledMatrix, this.fallingBlock, this.width, this.height);
} else {
this.fallingBlock.y--;
this.filledMatrix = mergeArenaAndBlock(this.filledMatrix, this.fallingBlock, this.width, this.height);
this.clearAndComputeScore();
this.newBlock();
this.arenaMatrix = mergeArenaAndBlock(this.filledMatrix, this.fallingBlock, this.width, this.height);
}
}
clearAndComputeScore() {
let rowsCleared = 0 ;
const newFilledMatrix = createMatrix(this.width, this.height);
for (let row of this.filledMatrix) {
if (!row.some(value => value === 0)) {
rowsCleared++;
row.fill(0);
}
}
for (let row = this.filledMatrix.length, rowNewFilled = this.filledMatrix.length - 1; row--;) {
if (this.filledMatrix[row].some(value => value > 0)) {
for (let col = this.filledMatrix[row].length; col--;) {
newFilledMatrix[rowNewFilled][col] = this.filledMatrix[row][col];
}
rowNewFilled--;
}
}
this.score += 15**rowsCleared;
this.filledMatrix = newFilledMatrix;
}
newBlock() {
const blockMatrix = TetrisBlockManager.getRandomBlockMatrix();
const sx = (this.width / 2 | 0) - (blockMatrix.matrix[0].length / 2 | 0);
const sy = 0;
this.fallingBlock = new FallingBlock(sx, sy, blockMatrix);
if (!isFallingBlockInFreeSpace(this.filledMatrix, this.fallingBlock, this.width, this.height)) {
this.state = ARENA_STATE.ENDSCREEN;
}
}
get colorMap() {
return [
rgba(0, 0, 0), // Não é usado geralmente
rgba(255, 0, 0),
rgba(0, 255, 0),
rgba(0, 0, 255),
rgba(0, 255, 255),
rgba(255, 0, 255),
rgba(255, 255, 0),
rgba(255, 255, 255),
];
}
}
export class TetrisShell {
constructor(config, debugInfoOn = false) {
this.debugInfoOn = debugInfoOn;
/** @type {typeof import('./config.js').ArenaConfig} */
this.config = config;
/** @type {HTMLCanvasElement} */
this.canvas = null;
}
[Symbol.iterator] () {
const length = this.pipeline.length;
let i = 0;
return {
next: () => {
return {
value: this.pipeline[i],
done: i++ === length,
}
}
}
}
setup() {
const { width, height, blockSize, initialSpeed } = this.config;
const canvas = createCanvas(width + 300, height, document.body);
this.canvas = canvas;
// Temporário
// canvas.style.width = '60vw';
canvas.style.margin = 'auto';
canvas.style.display = 'block';
const context = canvas.getContext('2d');
const offsetLeft = 150;
const arena = new TetrisArena(this.config.arena.x, this.config.arena.y, initialSpeed);
this.arena = arena;
const labels = [];
labels[ARENA_STATE.ENDSCREEN] = 'endscreen';
labels[ARENA_STATE.PAUSED] = 'paused';
labels[ARENA_STATE.RUNNING] = 'running';
const renderArena = (deltaTime) => {
drawRect(context, 0, 0, width + 300, height, rgba(255, 100, 200));
drawRect(context, offsetLeft + 0, 0, width, height, rgba(0, 0, 0));
drawFilledMatrix(context, arena.arenaMatrix, offsetLeft + 0, 0, blockSize, arena.colorMap);
drawMonospaceText(context, 18, 5, 20, `score: ${arena.score}`, 'white');
if (this.debugInfoOn) {
drawMonospaceText(context, 18, 5, 40, `state: ${labels[arena.state]}`, 'white');
}
if (this.arena.state === ARENA_STATE.ENDSCREEN) {
drawMonospaceText(context, 18, 5, 60, 'Fim de jogo', 'white');
}
// Desenhando instruções
/**
* @todo João, melhorar isso aqui
*/
[
'Movimento',
'← → ↑ ↓',
'Rotação',
'q: ↻',
'e: ↺',
'r: reiniciar',
'p: pausar/jogar',
].forEach((text, index) => {
drawMonospaceText(context, 16, 7, height - 170 + index * 22, text, 'white');
});
}
this.pipeline = [ arena.update, renderArena ];
this.listen();
}
listen() {
window.addEventListener('keydown', (event) => {
if (event.key === 'p' && this.arena.state !== ARENA_STATE.ENDSCREEN) {
this.arena.state = (this.arena.state === ARENA_STATE.RUNNING) ? ARENA_STATE.PAUSED : ARENA_STATE.RUNNING;
}
/**
* @todo João, mover esse componente de prompt para dentro da UI da aplicação
*/
if (event.key === 'r' &&
window.confirm(
ARENA_STATE.ENDSCREEN === this.arena.state
? 'Jogar mais uma partida?'
: 'Reiniciar partida?'
)
) {
this.arena.reset();
}
if (this.arena.state !== ARENA_STATE.RUNNING) return;
if (event.key === 'q') {
this.arena.tryRotate(-1);
}
if (event.key === 'e') {
this.arena.tryRotate(1);
}
// <--
if (event.keyCode === 37) {
this.arena.tryMove(-1);
}
// -->
if (event.keyCode === 39) {
this.arena.tryMove(1);
}
// baixo
if (event.keyCode === 40) {
this.arena.blockFall();
}
})
}
}