HTML Tetris Game: Build Your Own Classic Puzzle Game
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style>
#game-board {
width: 200px;
height: 400px;
background-color: #000;
border: 1px solid #000;
}
.block {
width: 20px;
height: 20px;
background-color: #FFF;
display: inline-block;
margin: 0px;
border: 1px solid #000;
}
</style>
</head>
<body>
<pre><code> <div id='game-board'>
</div>
<script>
let board = document.querySelector('#game-board');
let block;
// Shapes
let shapes = [
[1, 1, 1, 1],
[1, 1, 1, 0,
1],
[1, 1, 1, 0,
0, 0, 1],
[1, 1, 0, 0,
1, 1],
[1, 1, 0, 0,
0, 1, 1],
[0, 1, 1, 0,
1, 1],
[0, 1, 0, 0,
1, 1, 1]
];
// Randomly Select Shape
let shape = shapes[Math.floor(Math.random() * shapes.length)];
// Position
let x = 3;
let y = 0;
// Create Block
function createBlock(x, y) {
block = document.createElement('div');
block.setAttribute('class', 'block');
block.style.top = y * 20 + 'px';
block.style.left = x * 20 + 'px';
board.appendChild(block);
}
// Draw Shape
function draw() {
for (let i = 0; i < shape.length; i++) {
if (shape[i]) {
createBlock(x + i % 2, y + Math.floor(i / 2));
}
}
}
// Move Right
document.addEventListener('keydown', (e) => {
if (e.keyCode == 39) {
if (x < 10 - shape.length % 2) {
x++;
draw();
}
}
// Move Left
if (e.keyCode == 37) {
if (x > 0) {
x--;
draw();
}
}
// Move Down
if (e.keyCode == 40) {
if (y < 20 - shape.length / 2) {
y++;
draw();
}
}
});
draw();
</script>
</body>
</code></pre>
</html>
原文地址: https://www.cveoy.top/t/topic/lmuv 著作权归作者所有。请勿转载和采集!