Simple HTML Tetris Game - Build Your Own
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style>
#game {
width: 250px;
height: 400px;
margin: 0 auto;
border: 1px solid black;
position: relative;
}
.block {
width: 20px;
height: 20px;
position: absolute;
background-color: #000;
}
</style>
</head>
<body>
<h1>Tetris</h1>
<pre><code><div id='game'></div>
<script>
// game parameters
var x = 0;
var y = 0;
var blockSize = 20;
var boardWidth = 250;
var boardHeight = 400;
var game = document.getElementById('game');
// create the game board
for (var i = 0; i < boardWidth; i += blockSize) {
for (var j = 0; j < boardHeight; j += blockSize) {
var block = document.createElement('div');
block.classList.add('block');
block.style.left = i + 'px';
block.style.top = j + 'px';
game.appendChild(block);
}
}
// create blocks
document.addEventListener('keydown', function(event) {
if (event.keyCode === 37) {
x -= blockSize;
}
if (event.keyCode === 39) {
x += blockSize;
}
if (event.keyCode === 40) {
y += blockSize;
}
if (x < 0) {
x = 0;
}
if (x > (boardWidth - blockSize)) {
x = boardWidth - blockSize;
}
if (y > (boardHeight - blockSize)) {
y = boardHeight - blockSize;
}
var block = document.createElement('div');
block.classList.add('block');
block.style.left = x + 'px';
block.style.top = y + 'px';
game.appendChild(block);
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmdr 著作权归作者所有。请勿转载和采集!