Tetris Game in a Single HTML File
Here's a complete Tetris game implementation in a single HTML file with embedded CSS and JavaScript. This version includes:
- Classic Tetris gameplay
- Score tracking
- Level progression
- Game over detection
- Keyboard controls
- Responsive design
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
margin-bottom: 20px;
}
.game-container {
display: flex;
gap: 20px;
margin-top: 20px;
}
.game-area {
display: flex;
flex-direction: column;
gap: 20px;
}
#tetris {
border: 2px solid #333;
background-color: #111;
width: 300px;
height: 600px;
}
.side-panel {
display: flex;
flex-direction: column;
gap: 20px;
}
.panel {
background-color: #222;
color: white;
padding: 15px;
border-radius: 5px;
text-align: center;
}
.next-piece {
width: 100px;
height: 100px;
background-color: #111;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
}
.controls {
background-color: #222;
color: white;
padding: 15px;
border-radius: 5px;
text-align: center;
}
.game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
display: none;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #45a049;
}
@media (max-width: 768px) {
.game-container {
flex-direction: column;
align-items: center;
}
#tetris {
width: 250px;
height: 500px;
}
}
</style>
</head>
<body>
<h1>Tetris</h1>
<div class="game-container">
<div class="game-area">
<canvas id="tetris" width="300" height="600"></canvas>
<div class="game-over" id="gameOver">
<h2>Game Over!</h2>
<p id="finalScore">Score: 0</p>
<button id="restartBtn">Play Again</button>
</div>
</div>
<div class="side-panel">
<div class="panel">
<h3>Next Piece</h3>
<div class="next-piece" id="nextPiece"></div>
</div>
<div class="panel">
<h3>Score</h3>
<p id="score">0</p>
</div>
<div class="panel">
<h3>Level</h3>
<p id="level">1</p>
</div>
<div class="panel controls">
<h3>Controls</h3>
<p>Move: Left/Right Arrow</p>
<p>Rotate: Up Arrow</p>
<p>Drop: Down Arrow</p>
<p>Hard Drop: Space</p>
<p>Pause: P</p>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const canvas = document.getElementById('tetris');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const nextPieceElement = document.getElementById('nextPiece');
const gameOverElement = document.getElementById('gameOver');
const finalScoreElement = document.getElementById('finalScore');
const restartBtn = document.getElementById('restartBtn');
// Scale the canvas to maintain aspect ratio
function scaleCanvas() {
const scale = Math.min(
window.innerWidth / 350,
window.innerHeight / 700
);
canvas.style.width = `${300 * scale}px`;
canvas.style.height = `${600 * scale}px`;
}
window.addEventListener('resize', scaleCanvas);
scaleCanvas();
// Game constants
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const COLORS = [
null,
'#FF0D72', // I
'#0DC2FF', // J
'#0DFF72', // L
'#F538FF', // O
'#FF8E0D', // S
'#FFE138', // T
'#3877FF' // Z
];
// Tetromino shapes
const SHAPES = [
null,
[[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], // I
[[2, 0, 0], [2, 2, 2], [0, 0, 0]], // J
[[0, 0, 3], [3, 3, 3], [0, 0, 0]], // L
[[0, 4, 4], [0, 4, 4], [0, 0, 0]], // O
[[0, 5, 5], [5, 5, 0], [0, 0, 0]], // S
[[0, 6, 0], [6, 6, 6], [0, 0, 0]], // T
[[7, 7, 0], [0, 7, 7], [0, 0, 0]] // Z
];
// Game variables
let board = createMatrix(COLS, ROWS);
let player = {
pos: {x: 0, y: 0},
matrix: null,
next: null,
score: 0,
level: 1,
lines: 0,
dropCounter: 0,
dropInterval: 1000,
gameOver: false,
paused: false
};
// Initialize the game
function init() {
board = createMatrix(COLS, ROWS);
player.score = 0;
player.level = 1;
player.lines = 0;
player.dropInterval = 1000;
player.gameOver = false;
player.paused = false;
scoreElement.textContent = player.score;
levelElement.textContent = player.level;
gameOverElement.style.display = 'none';
playerReset();
update();
}
// Create a matrix (2D array)
function createMatrix(w, h) {
const matrix = [];
while (h--) {
matrix.push(new Array(w).fill(0));
}
return matrix;
}
// Create a piece
function createPiece(type) {
return SHAPES[type];
}
// Draw the matrix
function drawMatrix(matrix, offset) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
ctx.fillStyle = COLORS[value];
ctx.fillRect(
(x + offset.x) * BLOCK_SIZE,
(y + offset.y) * BLOCK_SIZE,
BLOCK_SIZE - 2,
BLOCK_SIZE - 2
);
ctx.strokeStyle = '#000';
ctx.strokeRect(
(x + offset.x) * BLOCK_SIZE,
(y + offset.y) * BLOCK_SIZE,
BLOCK_SIZE - 2,
BLOCK_SIZE - 2
);
}
});
});
}
// Draw the board
function drawBoard() {
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(board, {x: 0, y: 0});
drawMatrix(player.matrix, player.pos);
}
// Draw the next piece preview
function drawNextPiece() {
nextPieceElement.innerHTML = '';
if (player.next) {
const nextCanvas = document.createElement('canvas');
nextCanvas.width = 100;
nextCanvas.height = 100;
const nextCtx = nextCanvas.getContext('2d');
nextCtx.fillStyle = '#111';
nextCtx.fillRect(0, 0, 100, 100);
const centerX = (100 - player.next[0].length * BLOCK_SIZE) / 2;
const centerY = (100 - player.next.length * BLOCK_SIZE) / 2;
drawMatrix(player.next, {x: centerX / BLOCK_SIZE, y: centerY / BLOCK_SIZE}, nextCtx);
nextPieceElement.appendChild(nextCanvas);
}
}
// Create a piece
function playerReset() {
if (!player.next) {
player.next = createPiece(Math.floor(Math.random() * 7) + 1);
}
player.matrix = player.next;
player.next = createPiece(Math.floor(Math.random() * 7) + 1);
player.pos.y = 0;
player.pos.x = Math.floor(COLS / 2) - Math.floor(player.matrix[0].length / 2);
// Check for game over
if (collide()) {
gameOver();
}
drawNextPiece();
}
// Rotate the piece
function playerRotate(dir) {
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
while (collide()) {
player.pos.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if (offset > player.matrix[0].length) {
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
// Rotate the matrix
function rotate(matrix, dir) {
for (let y = 0; y < matrix.length; ++y) {
for (let x = 0; x < y; ++x) {
[matrix[x][y], matrix[y][x]] = [matrix[y][x], matrix[x][y]];
}
}
if (dir > 0) {
matrix.forEach(row => row.reverse());
} else {
matrix.reverse();
}
}
// Move the piece
function playerMove(dir) {
player.pos.x += dir;
if (collide()) {
player.pos.x -= dir;
}
}
// Drop the piece
function playerDrop() {
player.pos.y++;
if (collide()) {
player.pos.y--;
merge();
playerReset();
arenaSweep();
updateScore();
}
player.dropCounter = 0;
}
// Hard drop
function playerHardDrop() {
while (!collide()) {
player.pos.y++;
}
player.pos.y--;
merge();
playerReset();
arenaSweep();
updateScore();
}
// Check for collisions
function collide() {
const [m, o] = [player.matrix, player.pos];
for (let y = 0; y < m.length; ++y) {
for (let x = 0; x < m[y].length; ++x) {
if (m[y][x] !== 0 &&
(board[y + o.y] === undefined ||
board[y + o.y][x + o.x] === undefined ||
board[y + o.y][x + o.x] !== 0)) {
return true;
}
}
}
return false;
}
// Merge the piece with the board
function merge() {
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
board[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
// Clear completed lines
function arenaSweep() {
let linesCleared = 0;
outer: for (let y = board.length - 1; y >= 0; --y) {
for (let x = 0; x < board[y].length; ++x) {
if (board[y][x] === 0) {
continue outer;
}
}
// Remove the line and add a new empty one at the top
const row = board.splice(y, 1)[0].fill(0);
board.unshift(row);
++y;
linesCleared++;
}
if (linesCleared > 0) {
player.lines += linesCleared;
const linesPerLevel = 10;
player.level = Math.floor(player.lines / linesPerLevel) + 1;
player.dropInterval = 1000 / player.level;
}
}
// Update the score
function updateScore() {
const lines = player.lines;
const level = player.level;
const score = Math.floor(lines * (level + 1) * 10);
player.score = score;
scoreElement.textContent = player.score;
levelElement.textContent = player.level;
}
// Game over
function gameOver() {
player.gameOver = true;
finalScoreElement.textContent = `Score: ${player.score}`;
gameOverElement.style.display = 'block';
}
// Update the game state
function update() {
if (player.gameOver || player.paused) return;
player.dropCounter += Date.now() - lastTime;
lastTime = Date.now();
if (player.dropCounter > player.dropInterval) {
playerDrop();
}
drawBoard();
requestAnimationFrame(update);
}
// Event listeners
let lastTime = 0;
document.addEventListener('keydown', event => {
if (player.gameOver) return;
if (event.key === 'p' || event.key === 'P') {
player.paused = !player.paused;
if (!player.paused) {
lastTime = Date.now();
update();
}
return;
}
if (player.paused) return;
if (event.key === 'ArrowLeft') {
playerMove(-1);
} else if (event.key === 'ArrowRight') {
playerMove(1);
} else if (event.key === 'ArrowDown') {
playerDrop();
} else if (event.key === 'ArrowUp') {
playerRotate(1);
} else if (event.key === ' ') {
playerHardDrop();
}
});
restartBtn.addEventListener('click', init);
// Start the game
init();
});
</script>
</body>
</html>
Features of this Tetris Implementation:
-
Complete Gameplay:
- All 7 classic Tetris pieces (I, J, L, O, S, T, Z)
- Piece rotation, movement, and dropping
- Line clearing and scoring
- Level progression (speed increases with level)
-
UI Elements:
- Game board with 10x20 grid
- Next piece preview
- Score and level display
- Game over screen with final score
- Controls panel
-
Game Mechanics:
- Collision detection
- Hard drop (instant drop with spacebar)
- Pause functionality (press P)
- Responsive design that works on different screen sizes
-
Visuals:
- Color-coded pieces
- Clean, modern interface
- Responsive design that adapts to screen size
To play, simply open this HTML file in a web browser. Use the arrow keys to move and rotate pieces, and spacebar for hard drop.