Simple HTML Tetris Game - Play Now!
<!DOCTYPE html>
<html>
<head>
<title>Simple Tetris Game</title>
</head>
<style>
body {
font-family: Arial;
}
<pre><code>#game {
width: 400px;
margin: 0 auto;
border: 1px solid #444;
}
#next {
float: right;
width: 150px;
}
#score {
font-size: 12px;
}
</code></pre>
</style>
<body>
<h1>Tetris</h1>
<pre><code><div id='game'>
<div id='score'></div>
<div id='next'></div>
<div id='stage'></div>
</div>
<script>
var pieces = [
// O
[
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
],
// I
[
[0, 0, 0, 0],
[2, 2, 2, 2],
[0, 0, 0, 0],
[0, 0, 0, 0]
],
// S
[
[0, 0, 0],
[0, 3, 3],
[3, 3, 0],
[0, 0, 0]
],
// Z
[
[0, 0, 0],
[4, 4, 0],
[0, 4, 4],
[0, 0, 0]
],
// L
[
[0, 0, 0],
[5, 5, 5],
[5, 0, 0],
[0, 0, 0]
],
// J
[
[0, 0, 0],
[6, 6, 6],
[0, 0, 6],
[0, 0, 0]
],
// T
[
[0, 0, 0],
[7, 7, 7],
[0, 7, 0],
[0, 0, 0]
]
];
var Stage = function(){
this.width = 10;
this.height = 20;
this.spaces = [];
for (var y = 0; y < this.height; y++) {
this.spaces[y] = [];
for (var x = 0; x < this.width; x++) {
this.spaces[y][x] = 0;
}
}
};
Stage.prototype.addPiece = function(piece, x, y) {
for (var yy = 0; yy < piece.length; yy++) {
for (var xx = 0; xx < piece[yy].length; xx++) {
if (piece[yy][xx] !== 0) {
this.spaces[y + yy][x + xx] = piece[yy][xx];
}
}
}
};
var Game = function(){
this.score = 0;
this.stage = new Stage();
this.currentPiece = null;
this.nextPiece = null;
this.intervalId = null;
this.gameOver = false;
this.setNextPiece();
};
Game.prototype.setNextPiece = function() {
this.currentPiece = this.nextPiece;
this.nextPiece = this.getRandomPiece();
};
Game.prototype.getRandomPiece = function() {
var randomIndex = Math.floor(Math.random() * pieces.length);
return pieces[randomIndex];
};
Game.prototype.start = function() {
this.intervalId = setInterval(function(){
if (this.gameOver) {
clearInterval(this.intervalId);
alert('Game over! Your score is ' + this.score);
return;
}
this.update();
this.render();
}.bind(this), 1000);
};
Game.prototype.update = function() {
// ...
};
Game.prototype.render = function() {
// ...
};
var game = new Game();
game.start();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmpp 著作权归作者所有。请勿转载和采集!