Simple HTML Tetris Game: Build Your Own Classic
<!DOCTYPE html>
<html>
<head>
<title>Simple Tetris Game</title>
<style>
#game {
width: 400px;
height: 400px;
background-color: #CCC;
margin: auto;
border: 1px solid #000;
position: relative;
}
<pre><code>.tetromino {
position: absolute;
width: 100px;
height: 100px;
background-color: #000;
}
</code></pre>
</style>
</head>
<body>
<h1>Simple Tetris Game</h1>
<div id='game'></div>
<script>
// create the game board
let game = document.getElementById('game');
<pre><code>// create the tetromino
let tetromino = document.createElement('div');
tetromino.className = 'tetromino';
game.appendChild(tetromino);
// move the tetromino left and right
let left = false;
let right = false;
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
left = true;
}
else if (event.keyCode === 39) {
right = true;
}
});
document.addEventListener('keyup', event => {
if (event.keyCode === 37) {
left = false;
}
else if (event.keyCode === 39) {
right = false;
}
});
// move the tetromino
let xPos = 0;
let yPos = 0;
let speed = 5;
let gameLoop = setInterval(() => {
if (left && xPos > 0) {
xPos -= speed;
}
if (right && xPos < (game.offsetWidth - tetromino.offsetWidth)) {
xPos += speed;
}
tetromino.style.left = xPos + 'px';
tetromino.style.top = yPos + 'px';
yPos += speed;
}, 1000/60);
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmjU 著作权归作者所有。请勿转载和采集!