Simple HTML Tetris Game - Play Now!
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style type="text/css">
.container {
width: 300px;
height: 600px;
border: 1px solid #000;
margin: 0 auto;
position: relative;
}
.square {
width: 30px;
height: 30px;
background-color: #ededed;
position: absolute;
}
.active {
background-color: #000;
}
</style>
</head>
<body>
<div class="container">
<div class="square active"></div>
</div>
<script type="text/javascript">
// Get the container element
const container = document.querySelector('.container');
// Get the active square element
const activeSquare = document.querySelector('.active');
// Variables for position of active square
let xPosition = 0;
let yPosition = 0;
<pre><code> // Create an array of squares
const squares = [];
// Create a function to create the squares
function createSquare(x, y) {
const square = document.createElement('div');
square.classList.add('square');
square.style.top = `${y * 30}px`;
square.style.left = `${x * 30}px`;
container.appendChild(square);
squares.push(square);
}
// Create a function to move the active square
function moveActiveSquare(x, y) {
activeSquare.style.top = `${y * 30}px`;
activeSquare.style.left = `${x * 30}px`;
xPosition = x;
yPosition = y;
}
// Create a function to rotate the active square
function rotateActiveSquare() {
activeSquare.classList.toggle('active');
}
// Create a function to move the active square down
function moveActiveSquareDown() {
moveActiveSquare(xPosition, yPosition + 1);
}
// Create an event listener to move the active square left
document.addEventListener('keydown', e => {
if(e.keyCode === 37) {
moveActiveSquare(xPosition - 1, yPosition);
}
});
// Create an event listener to move the active square right
document.addEventListener('keydown', e => {
if(e.keyCode === 39) {
moveActiveSquare(xPosition + 1, yPosition);
}
});
// Create an event listener to rotate the active square
document.addEventListener('keydown', e => {
if(e.keyCode === 40) {
rotateActiveSquare();
}
});
// Create an interval to move the active square down
setInterval(moveActiveSquareDown, 1000);
</script>
</code></pre>
</body>
</html>
<h2>Instructions on How to Play:</h2>
<ol>
<li>
<p>Use the left and right arrow keys to move the active square left and right.</p>
</li>
<li>
<p>Use the down arrow key to rotate the active square.</p>
</li>
<li>
<p>The active square will move down automatically over time.</p>
</li>
<li>
<p>The goal is to create complete rows of squares before the active square reaches the bottom of the game board.</p>
</li>
<li>
<p>If a row of squares is completed, it will be removed and the squares above it will move down.</p>
</li>
<li>
<p>The game ends when the active square reaches the bottom of the game board.</p>
</li>
</ol>
原文地址: https://www.cveoy.top/t/topic/lmjw 著作权归作者所有。请勿转载和采集!