How to Make a Simple HTML Tetris Game
<p>Instructions:</p>
<ol>
<li>Open your favorite text editor and paste the following code into a new file:</li>
</ol>
<!DOCTYPE html>
<html>
<head>
<title>Tetris</title>
<style>
#board {
width: 300px;
height: 600px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id='board'></div>
<pre><code><script>
// create a 10x20 grid
let board = [];
for (let i = 0; i < 20; i++) {
board[i] = [];
for (let j = 0; j < 10; j++) {
board[i][j] = 0;
}
}
// draw the board
let boardDiv = document.getElementById('board');
for (let i = 0; i < 20; i++) {
for (let j = 0; j < 10; j++) {
let div = document.createElement('div');
div.style.width = '30px';
div.style.height = '30px';
div.style.backgroundColor = 'white';
div.style.border = '1px solid black';
div.style.float = 'left';
boardDiv.appendChild(div);
}
}
// create the pieces
let pieces = [
[[1,1], [1,0], [0,1], [0,0]],
[[2,2], [2,1], [1,1], [1,2]],
[[3,1], [3,2], [2,2], [2,3]],
[[4,2], [4,3], [3,3], [3,4]],
[[5,2], [4,2], [4,3], [5,3]],
[[6,1], [6,2], [5,2], [5,3]],
[[7,2], [6,2], [6,3], [7,3]]
];
// draw the pieces
function drawPiece(piece) {
for (let i = 0; i < 4; i++) {
let div = document.createElement('div');
div.style.width = '30px';
div.style.height = '30px';
div.style.backgroundColor = piece[i][0];
div.style.border = '1px solid black';
div.style.float = 'left';
div.style.position = 'absolute';
div.style.left = piece[i][1]*30 + 'px';
div.style.top = piece[i][2]*30 + 'px';
boardDiv.appendChild(div);
}
}
// select a random piece
let piece = pieces[Math.floor(Math.random()*pieces.length)];
drawPiece(piece);
// add the controls
document.addEventListener('keydown', function(e) {
switch (e.keyCode) {
case 37:
// left arrow
break;
case 38:
// up arrow
break;
case 39:
// right arrow
break;
case 40:
// down arrow
break;
}
});
</script>
</code></pre>
</body>
</html>
<ol start="2">
<li>
<p>Save the file and open it in your web browser.</p>
</li>
<li>
<p>Use the arrow keys on your keyboard to move the pieces around the board.</p>
</li>
<li>
<p>Try to fit the pieces together to create complete rows.</p>
</li>
<li>
<p>When a row is complete it will disappear and you will get points.</p>
</li>
<li>
<p>Keep playing until you can't fit any more pieces on the board.</p>
</li>
</ol>
原文地址: https://www.cveoy.top/t/topic/lmjx 著作权归作者所有。请勿转载和采集!