HTML Tetris Game Code: Build Your Own Classic Puzzle Game
<html>
<head>
<title>Tetris</title>
<style type="text/css">
/* CSS code to style the game */
#tetris-container{
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-color: #000;
}
#tetris-game-board{
width: 200px;
height: 400px;
position: absolute;
left: 150px;
top: 50px;
background-color: #ccc;
}
.tetris-block{
width: 25px;
height: 25px;
position: absolute;
background-color: #fff;
}
</style>
</head>
<body>
<div id="tetris-container">
<div id="tetris-game-board">
</div>
</div>
<script type="text/javascript">
// JavaScript code to control the game
// Set up the board
var board = document.getElementById('tetris-game-board');
<pre><code> // Create the blocks
for (var row = 0; row < 16; row++) {
for (var col = 0; col < 10; col++) {
var block = document.createElement('div');
block.className = 'tetris-block';
block.style.top = (row * 25) + 'px';
block.style.left = (col * 25) + 'px';
board.appendChild(block);
}
}
// Create a random shape
var shapes = [
// I-shape
[1,1,1,1],
// J-shape
[1,0,0],
[1,1,1],
[0,0,1],
// L-shape
[0,0,1],
[1,1,1],
[1,0,0],
// O-shape
[1,1],
[1,1],
// S-shape
[0,1,1],
[1,1,0],
// T-shape
[1,0,0],
[1,1,1],
[0,0,1],
// Z-shape
[1,1,0],
[0,1,1]
];
// Choose a random shape
var randomShape = Math.floor(Math.random() * shapes.length);
// Create the shape
for (var row = 0; row < shapes[randomShape].length; row++) {
for (var col = 0; col < shapes[randomShape][row].length; col++) {
if (shapes[randomShape][row][col]) {
// Create a block
var block = document.createElement('div');
block.className = 'tetris-block';
block.style.top = (row * 25) + 'px';
block.style.left = (col * 25) + 'px';
board.appendChild(block);
}
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnQG 著作权归作者所有。请勿转载和采集!