Simple HTML Tetris Game - Play Now!
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style>
#game {
margin: auto;
width: 320px;
border: 1px solid black;
}
.cell {
width: 20px;
height: 20px;
background-color: #eeeeee;
border: 1px solid black;
float: left;
}
.piece {
width: 20px;
height: 20px;
float: left;
}
</style>
</head>
<body>
<h1>Tetris</h1>
<div id='game'>
</div>
<script>
let game = document.getElementById('game');
let cells = [];
let colors = ['#FF0000', '#0000FF', '#00FF00', '#FFFF00', '#FF00FF', '#00FFFF'];
for (let i = 0; i < 20; i++) {
let row = [];
for (let j = 0; j < 10; j++) {
let cell = document.createElement('div');
let color = colors[Math.floor(Math.random() * colors.length)];
cell.classList.add('cell');
cell.style.backgroundColor = color;
row.push(cell);
game.appendChild(cell);
}
cells.push(row);
}
let currentPiece;
function generatePiece() {
let color = colors[Math.floor(Math.random() * colors.length)];
let piece = document.createElement('div');
piece.classList.add('piece');
piece.style.backgroundColor = color;
game.appendChild(piece);
currentPiece = piece;
}
generatePiece();
let x = 0;
let y = 0;
document.addEventListener('keydown', function(event) {
if (event.key === 'ArrowRight') {
x++;
if (x > 9) {
x = 9;
}
} else if (event.key === 'ArrowLeft') {
x--;
if (x < 0) {
x = 0;
}
} else if (event.key === 'ArrowDown') {
y++;
if (y > 19) {
y = 19;
}
}
currentPiece.style.left = x * 20 + 'px';
currentPiece.style.top = y * 20 + 'px';
});
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmoX 著作权归作者所有。请勿转载和采集!