Tetris Game HTML Code: Complete Tutorial and Source Code
<html>
<head>
<title>Tetris Game: Complete HTML Code</title>
<style>
#game-board {
width: 500px;
height: 500px;
border: 1px solid black;
position: relative;
}
.tetromino {
position: absolute;
width: 50px;
height: 50px;
}
.tetromino.I { background-color: #00f; }
.tetromino.J { background-color: #f00; }
.tetromino.L { background-color: #0f0; }
.tetromino.O { background-color: #fa0; }
.tetromino.S { background-color: #f0f; }
.tetromino.T { background-color: #444; }
.tetromino.Z { background-color: #0ff; }
</style>
</head>
<body>
<div id='game-board'></div>
<script>
const gameBoard = document.getElementById('game-board');
let tetrominos = [
[
[1, 1, 1, 1], // I
],
[
[1, 0, 0],
[1, 1, 1], // J
],
[
[0, 0, 1],
[1, 1, 1], // L
],
[
[1, 1],
[1, 1], // O
],
[
[0, 1, 1],
[1, 1, 0], // S
],
[
[1, 1, 1],
[0, 1, 0], // T
],
[
[1, 1, 0],
[0, 1, 1], // Z
],
];
<pre><code> let activeTetromino = null;
let activeTetrominoType = Math.floor(Math.random() * tetrominos.length);
let activeTetrominoPosition = { x: 3, y: 0 };
function draw() {
// draw active tetromino
if (activeTetromino !== null) {
activeTetromino.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
let div = document.createElement('div');
div.classList.add('tetromino');
div.classList.add(Object.keys(tetrominos)[activeTetrominoType]);
div.style.top = activeTetrominoPosition.y * 50 + 'px';
div.style.left = activeTetrominoPosition.x * 50 + 'px';
gameBoard.appendChild(div);
}
});
});
}
};
function moveDown() {
activeTetrominoPosition.y += 1;
draw();
};
function moveLeft() {
activeTetrominoPosition.x -= 1;
draw();
};
function moveRight() {
activeTetrominoPosition.x += 1;
draw();
};
function rotate() {
let newTetromino = [];
activeTetromino.forEach((row, y) => {
newTetromino[y] = [];
row.forEach((value, x) => {
newTetromino[y][x] = activeTetromino[x][row.length - 1 - y];
});
});
activeTetromino = newTetromino;
draw();
};
function startGame() {
activeTetromino = tetrominos[activeTetrominoType];
draw();
setInterval(moveDown, 1000);
};
document.addEventListener('keydown', (e) => {
if (e.keyCode === 37) {
moveLeft();
} else if (e.keyCode === 38) {
rotate();
} else if (e.keyCode === 39) {
moveRight();
}
});
startGame();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/losD 著作权归作者所有。请勿转载和采集!