Simple HTML Tetris Game: Build Your Own Classic Puzzle Game
<!DOCTYPE html>
<html>
<head>
<title>Simple Tetris Game</title>
<style type="text/css">
#tetris {
position: relative;
width: 400px;
height: 600px;
background: #000;
}
<pre><code> #tetris div {
position: absolute;
width: 20px;
height: 20px;
background: #ccc;
}
</style>
<script type="text/javascript">
// This is the main logic for the game
function tetris() {
var i, j, rows, cols, squares;
// Set up the board
board = document.getElementById('tetris');
rows = 15;
cols = 10;
squares = [];
// Create the squares
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
var square = document.createElement('div');
square.style.top = i * 20 + 'px';
square.style.left = j * 20 + 'px';
board.appendChild(square);
squares.push(square);
}
}
// Create the pieces
pieces = [
[1, 1, 1, 1],
[1, 1, 1, 0,
1],
[1, 1, 1, 0,
0, 0, 1],
[1, 1, 0, 0,
1, 1],
[1, 1, 0, 0,
0, 1, 1],
[0, 1, 1, 0,
1, 1],
[0, 1, 0, 0,
1, 1, 1]
];
// Draw the pieces
currentPiece = randomPiece();
draw();
// Move the pieces
function move(dir) {
switch (dir) {
case 'left':
currentPiece.x--;
break;
case 'right':
currentPiece.x++;
break;
case 'down':
currentPiece.y++;
break;
}
}
// Draw the board
function draw() {
// Reset all of the squares on the board
for (i = 0; i < rows * cols; i++) {
squares[i].style.background = '#000';
}
// Redraw the current piece
for (i = 0; i < currentPiece.layout.length; i++) {
if (currentPiece.layout[i]) {
squares[currentPiece.y + Math.floor(i / 4) * cols + currentPiece.x + i % 4].style.background = '#ccc';
}
}
}
// Select a random piece
function randomPiece() {
var r = Math.floor(Math.random() * pieces.length);
return {
layout: pieces[r],
x: Math.floor(cols / 2 - 2),
y: 0
};
}
}
</script>
</code></pre>
</head>
<body onload="tetris()">
<pre><code><div id="tetris"></div>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmpc 著作权归作者所有。请勿转载和采集!