-
-
Save csorlandi/b208e0d413a5e8388fb1abf0e6585ef4 to your computer and use it in GitHub Desktop.
código de tetris criado durante a live
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.getElementById('board'); | |
const ctx = canvas.getContext('2d'); | |
ctx.scale(36, 36); | |
const piece = { | |
x: 3, | |
y: 0, | |
matrix: [ | |
[0, 0, 0], | |
[1, 1, 1], | |
[0, 1, 0], | |
], | |
rotate() { | |
this.matrix = this.matrix.map((line, i) => | |
line.map((_, j) => | |
this.matrix[j][i] | |
).reverse() | |
); | |
} | |
}; | |
function renderPiece(piece) { | |
piece.matrix.forEach((line, i) => { | |
line.forEach((square, j) => { | |
ctx.fillStyle = 'yellow'; | |
square && ctx.fillRect(piece.x + j, piece.y + i, 1, 1); | |
}); | |
}); | |
} | |
let baseTime = 0; | |
function renderBoard(time = 0) { | |
ctx.clearRect(0, 0, 360, 720); | |
renderPiece(piece); | |
if(time - baseTime >= 1000) { | |
baseTime = time; | |
piece.y++; | |
} | |
requestAnimationFrame(renderBoard); | |
} | |
window.addEventListener('keydown', ({ keyCode }) => { | |
switch (keyCode) { | |
case 39: | |
piece.x++; | |
break; | |
case 37: | |
piece.x--; | |
break; | |
case 32: | |
piece.rotate(); | |
break; | |
} | |
}); | |
renderBoard(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment