HTML Tetris Game: Complete Code and Tutorial
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Tetris</title>
<style>
body {
margin: 0;
padding: 0;
}
#game {
margin: 0 auto;
width: 200px;
height: 400px;
background-color: #ccc;
border: 3px solid #333;
}
.block {
width: 10px;
height: 10px;
background-color: #000;
margin: 0 auto;
}
</style>
</head>
<body>
<div id='game'></div>
<script>
// Variables
let game = document.getElementById('game');
let blocks = [];
let blockSize = 10;
let width = 10;
let height = 20;
let currentBlock = {
x: 4,
y: 0,
shape: [[1, 1], [1, 1]]
};
let nextBlock = {
x: 4,
y: 0,
shape: [[1, 1], [1, 1]]
};
// Functions
function drawBlock(x, y) {
let block = document.createElement('div');
block.className = 'block';
block.style.top = y * blockSize + 'px';
block.style.left = x * blockSize + 'px';
game.appendChild(block);
}
function draw() {
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
if (blocks[y][x] === 1) {
drawBlock(x, y);
}
}
}
}
function update() {
if (currentBlock.y + currentBlock.shape.length < height) {
currentBlock.y++;
} else {
// Add block to blocks array
for (let y = 0; y < currentBlock.shape.length; y++) {
for (let x = 0; x < currentBlock.shape[y].length; x++) {
if (currentBlock.shape[y][x] === 1) {
blocks[currentBlock.y + y][currentBlock.x + x] = 1;
}
}
}
// Get new block
currentBlock = nextBlock;
// Generate new next block
nextBlock = {
x: 4,
y: 0,
shape: [[1, 1], [1, 1]]
};
}
}
function init() {
// Initialize blocks array
for (let y = 0; y < height; y++) {
blocks[y] = [];
for (let x = 0; x < width; x++) {
blocks[y][x] = 0;
}
}
setInterval(function() {
update();
draw();
}, 500);
}
// Onload
window.onload = init;
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/losH 著作权归作者所有。请勿转载和采集!