HTML Tetris Game: Complete Source Code and Tutorial
<html>
<head>
<title>Tetris</title>
<style>
body {
background-color: #dfdfdf;
}
#game-container {
width: 400px;
height: 600px;
background-color: #000;
}
#score {
font-family: Arial;
font-size: 15px;
color: #fff;
position: absolute;
top: 10px;
right: 10px;
}
.block {
width: 20px;
height: 20px;
background-color: #fff;
margin: 1px;
float: left;
}
</style>
</head>
<body>
<div id='game-container'></div>
<div id='score'>Score: 0</div>
<script>
let score = 0;
let gameContainer = document.getElementById('game-container');
let scoreElement = document.getElementById('score');
<pre><code>let shapes = [
// I shape
[
[1, 1, 1, 1]
],
// L shape
[
[1, 0, 0],
[1, 1, 1]
],
// J shape
[
[0, 0, 1],
[1, 1, 1]
],
// O shape
[
[1, 1],
[1, 1]
],
// S shape
[
[0, 1, 1],
[1, 1, 0]
],
// T shape
[
[1, 1, 1],
[0, 1, 0]
],
// Z shape
[
[1, 1, 0],
[0, 1, 1]
]
]
let currentShape = shapes[Math.floor(Math.random() * shapes.length)];
let currentX = 0;
let currentY = 0;
let interval = null;
// draw the current shape
let draw = () => {
// clear the board
gameContainer.innerHTML = '';
// draw the current shape
for (let y = 0; y < currentShape.length; y++) {
for (let x = 0; x < currentShape[y].length; x++) {
if (currentShape[y][x] == 1) {
let block = document.createElement('div');
block.className = 'block';
block.style.top = (y + currentY) * 20 + 'px';
block.style.left = (x + currentX) * 20 + 'px';
gameContainer.appendChild(block);
}
}
}
}
// move the current shape down
let moveDown = () => {
currentY++;
draw();
}
// move the current shape left
let moveLeft = () => {
currentX--;
draw();
}
// move the current shape right
let moveRight = () => {
currentX++;
draw();
}
// rotate the current shape
let rotate = () => {
let newShape = [];
for (let x = 0; x < currentShape[0].length; x++) {
let column = [];
for (let y = currentShape.length - 1; y >= 0; y--) {
column.push(currentShape[y][x]);
}
newShape.push(column);
}
currentShape = newShape;
draw();
}
// start the game
let startGame = () => {
interval = setInterval(moveDown, 500);
}
// pause the game
let pauseGame = () => {
clearInterval(interval);
}
// update the score
let updateScore = () => {
score++;
scoreElement.innerHTML = 'Score: ' + score;
}
// handle key presses
document.onkeydown = (e) => {
if (e.keyCode == 37) { // left
moveLeft();
} else if (e.keyCode == 39) { // right
moveRight();
} else if (e.keyCode == 38) { // up
rotate();
} else if (e.keyCode == 32) { // space
pauseGame();
}
}
// start the game
startGame();
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/losG 著作权归作者所有。请勿转载和采集!