Simple Tetris Game HTML Code: Build Your Own Tetris Game
<html>
<head>
<title>Simple Tetris Game</title>
<style>
#game {
width: 500px;
height: 500px;
background-color: #000;
position: relative;
}
.block {
width: 25px;
height: 25px;
background-color: #eee;
position: absolute;
}
</style>
</head>
<body>
<div id='game'></div>
<script>
var game = document.getElementById('game');
var blocks = [
{ x: 0, y: 0 },
{ x: 25, y: 0 },
{ x: 0, y: 25 },
{ x: 25, y: 25 }
];
// draw blocks
for (var i=0; i<blocks.length; i++) {
var block = document.createElement('div');
block.className = 'block';
block.style.left = blocks[i].x + 'px';
block.style.top = blocks[i].y + 'px';
game.appendChild(block);
}
// move blocks
function move(x, y) {
for (var i=0; i<blocks.length; i++) {
blocks[i].x += x;
blocks[i].y += y;
game.children[i].style.left = blocks[i].x + 'px';
game.children[i].style.top = blocks[i].y + 'px';
}
}
document.onkeydown = function(e) {
// left
if (e.keyCode === 37) {
move(-25, 0);
}
// right
else if (e.keyCode === 39) {
move(25, 0);
}
// down
else if (e.keyCode === 40) {
move(0, 25);
}
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmdo 著作权归作者所有。请勿转载和采集!