Created
May 3, 2019 08:14
-
-
Save heygema/298426d7f05416fbc9191deb3a2df64c to your computer and use it in GitHub Desktop.
Tetris with Canvas
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>tetris</title> | |
</head> | |
<body> | |
<style> | |
body, html { | |
display: flex; | |
background-color: "#000"; | |
} | |
</style> | |
<canvas id="main-canvas" height="400" width="240"></canvas> | |
<script src="./tetris.js"></script> | |
</body> | |
</html> |
This file contains hidden or 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
let canvas = document.getElementById('main-canvas'); | |
let context = canvas.getContext('2d'); | |
context.scale(20, 20); | |
function cr(first = false, second = false, third = false) { | |
let _getBinary = position => (position ? 1 : 0); | |
return [_getBinary(first), _getBinary(second), _getBinary(third)]; | |
} | |
function renderMatrix(matrix, offset) { | |
matrix.forEach((row, y) => { | |
row.forEach((value, x) => { | |
if (value !== 0) { | |
(context.fillStyle = 'red'), | |
context.fillRect(x + offset.x, y + offset.y, 1, 1); | |
} | |
}); | |
}); | |
} | |
const T = [cr(), cr(true, true, true), cr(false, true)]; | |
const player = { | |
pos: {x: 0, y: -1}, | |
matrix: T, | |
}; | |
function draw() { | |
context.fillStyle = '#000'; | |
context.fillRect(0, 0, canvas.width, canvas.height); | |
renderMatrix(player.matrix, player.pos); | |
} | |
let dropCounter = 0; | |
let dropInterval = 1000; | |
let lastTime = 0; | |
function update(time = 0) { | |
let deltaTime = time - lastTime; | |
lastTime = time; | |
dropCounter += deltaTime; | |
if (dropCounter > dropInterval) { | |
player.pos.y < 17 && player.pos.y++; | |
dropCounter = 0; | |
} | |
draw(); | |
requestAnimationFrame(update); | |
} | |
document.addEventListener('keydown', e => { | |
let notBottom = player.pos.y < 17; | |
let notRightMost = player.pos.x < 9; | |
let notLeftMost = player.pos.x > 0; | |
switch (e.key) { | |
case 'ArrowRight': { | |
notBottom && notRightMost && player.pos.x++; | |
break; | |
} | |
case 'ArrowLeft': { | |
notBottom && notLeftMost && player.pos.x--; | |
break; | |
} | |
case 'ArrowDown': { | |
if (notBottom) { | |
if (17 - player.pos.y === 1) { | |
player.pos.y = 15; | |
} | |
player.pos.y += 2; | |
} | |
break; | |
} | |
default: | |
break; | |
} | |
}); | |
update(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment