Simple HTML Tetris Game - Play Now!
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style>
#game {
border: 1px solid black;
width: 200px;
height: 400px;
}
</style>
</head>
<body>
<h1>Tetris</h1>
<div id='game'></div>
<script>
// Create an array of Tetrominos
const tetrominos = [
[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]
];
<pre><code> // Generate a random number between 0 and 6
let random = Math.floor(Math.random()*7);
// Generate a random tetromino
let currentPosition = 4;
let current = tetrominos[random][currentPosition];
// Create the game grid
let gameGrid = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
// Draw the game
function draw() {
let game = document.getElementById('game');
let output = '';
for (let i = 0; i < gameGrid.length; i++) {
output += '<div class='row'>';
for (let j = 0; j < gameGrid[i].length; j++) {
if (gameGrid[i][j] == 0) {
output += '<div class='empty'></div>';
} else if (gameGrid[i][j] == 1) {
output += '<div class='tetromino'></div>';
}
}
output += '</div>';
}
game.innerHTML = output;
}
// Update the game
function update() {
currentPosition++;
if (currentPosition == current.length) {
currentPosition = 0;
}
current = tetrominos[random][currentPosition];
}
// Move the tetromino left
function moveLeft() {
currentPosition--;
if (currentPosition == -1) {
currentPosition = current.length - 1;
}
current = tetrominos[random][currentPosition];
}
// Move the tetromino right
function moveRight() {
currentPosition++;
if (currentPosition == current.length) {
currentPosition = 0;
}
current = tetrominos[random][currentPosition];
}
// Move the tetromino down
function moveDown() {
// Clear the current position on the grid
for (let i = 0; i < gameGrid.length; i++) {
for (let j = 0; j < gameGrid[i].length; j++) {
if (gameGrid[i][j] == 1) {
gameGrid[i][j] = 0;
}
}
}
// Update the grid with the new position
for (let i = 0; i < current.length; i++) {
gameGrid[i][currentPosition] = current[i];
}
draw();
update();
}
// Start the game
draw();
setInterval(moveDown, 1000);
document.onkeydown = function(e) {
if (e.keyCode == 37) {
moveLeft();
} else if (e.keyCode == 39) {
moveRight();
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmo3 著作权归作者所有。请勿转载和采集!