Skip to content

Instantly share code, notes, and snippets.

@Santiael
Created April 8, 2020 23:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Santiael/ee8ba05160d76b4e3654bd57f7e523cb to your computer and use it in GitHub Desktop.
Save Santiael/ee8ba05160d76b4e3654bd57f7e523cb to your computer and use it in GitHub Desktop.
código de tetris criado durante a live
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