用 JavaScript 实现简单的俄罗斯方块游戏
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style>
#tetris {
width: 300px;
height: 600px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="tetris"></div>
<script>
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
function draw() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(player.matrix, player.pos);
}
function drawMatrix(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 player = {
pos: {x: 5, y: 5},
matrix: [
[0, 0, 0],
[1, 1, 1],
[0, 1, 0]
]
};
function update() {
draw();
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/qzxC 著作权归作者所有。请勿转载和采集!