<!DOCTYPE html>
<html>
<head>
<title>Complex Tetris</title>
<style>
body {
background-color: #222;
color: #eee;
font-family: monospace;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
overflow: hidden; /* Prevent scrollbars during animation */
}
#gameContainer {
display: flex;
flex-direction: row; /* Arrange canvas and UI horizontally */
background-color: #333;
border: 5px solid #555;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0,0,0,0.8);
}
#gameCanvas {
background-color: #111;
border: 2px solid #444;
margin-right: 20px; /* Spacing between canvas and UI */
}
#uiContainer {
display: flex;
flex-direction: column;
justify-content: space-around; /* Distribute UI elements vertically */
min-width: 200px; /* Ensure UI container has some width */
}
.uiElement {
background-color: #444;
color: #eee;
padding: 10px;
border-radius: 5px;
margin-bottom: 10px; /* Spacing between UI elements */
text-align: center;
}
.uiElement h2 {
margin-top: 0;
margin-bottom: 5px;
}
#nextPieceCanvas {
background-color: #222;
border: 1px solid #555;
margin: 10px auto; /* Center next piece canvas */
display: block; /* Remove extra bottom spacing */
}
#holdPieceCanvas {
background-color: #222;
border: 1px solid #555;
margin: 10px auto; /* Center hold piece canvas */
display: block; /* Remove extra bottom spacing */
}
#controls {
margin-top: 15px;
text-align: center;
}
#controls p {
margin: 5px 0;
}
#gameOverOverlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: none; /* Initially hidden */
justify-content: center;
align-items: center;
flex-direction: column;
z-index: 10; /* Ensure overlay is on top */
}
#gameOverMessage {
background-color: #555;
color: #eee;
padding: 30px;
border-radius: 15px;
text-align: center;
font-size: 1.5em;
}
#gameOverMessage h2 {
margin-top: 0;
}
#gameOverMessage button {
padding: 10px 20px;
font-size: 1em;
background-color: #777;
color: #eee;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 20px;
}
#pauseOverlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: none; /* Initially hidden */
justify-content: center;
align-items: center;
z-index: 5; /* Below game over overlay but above canvas */
color: #eee;
font-size: 2em;
}
</style>
</head>
<body>
<div id="gameContainer">
<canvas id="gameCanvas" width="300" height="600"></canvas>
<div id="uiContainer">
<div class="uiElement">
<h2>Score</h2>
<p id="scoreDisplay">0</p>
</div>
<div class="uiElement">
<h2>Level</h2>
<p id="levelDisplay">1</p>
</div>
<div class="uiElement">
<h2>Lines</h2>
<p id="linesDisplay">0</p>
</div>
<div class="uiElement">
<h2>Next Piece</h2>
<canvas id="nextPieceCanvas" width="100" height="100"></canvas>
</div>
<div class="uiElement">
<h2>Hold Piece</h2>
<canvas id="holdPieceCanvas" width="100" height="100"></canvas>
</div>
<div id="controls" class="uiElement">
<h2>Controls</h2>
<p>←/→ : Move Left/Right</p>
<p>↓ : Soft Drop</p>
<p>↑/Space : Rotate</p>
<p>Shift : Hold Piece</p>
<p>P : Pause</p>
</div>
</div>
</div>
<div id="gameOverOverlay">
<div id="gameOverMessage">
<h2>Game Over</h2>
<p id="finalScoreDisplay">Your Score: 0</p>
<button id="restartButton">Restart</button>
</div>
</div>
<div id="pauseOverlay">
<p>PAUSED</p>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('scoreDisplay');
const levelDisplay = document.getElementById('levelDisplay');
const linesDisplay = document.getElementById('linesDisplay');
const nextPieceCanvas = document.getElementById('nextPieceCanvas');
const nextPieceCtx = nextPieceCanvas.getContext('2d');
const holdPieceCanvas = document.getElementById('holdPieceCanvas');
const holdPieceCtx = holdPieceCanvas.getContext('2d');
const gameOverOverlay = document.getElementById('gameOverOverlay');
const finalScoreDisplay = document.getElementById('finalScoreDisplay');
const restartButton = document.getElementById('restartButton');
const pauseOverlay = document.getElementById('pauseOverlay');
const gridSize = 30; // Size of each grid cell
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const boardWidth = canvasWidth / gridSize; // 10 cells wide
const boardHeight = canvasHeight / gridSize; // 20 cells high
const colors = [
null, // 0: Empty
'cyan', // 1: I
'blue', // 2: J
'orange', // 3: L
'yellow', // 4: O
'green', // 5: S
'purple', // 6: T
'red' // 7: Z
];
const shapes = [
[], // 0: Empty (for easier indexing)
[ // 1: I
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
[0,0,0,0]
],
[ // 2: J
[1,0,0],
[1,1,1],
[0,0,0]
],
[ // 3: L
[0,0,1],
[1,1,1],
[0,0,0]
],
[ // 4: O
[1,1],
[1,1]
],
[ // 5: S
[0,1,1],
[1,1,0],
[0,0,0]
],
[ // 6: T
[0,1,0],
[1,1,1],
[0,0,0]
],
[ // 7: Z
[1,1,0],
[0,1,1],
[0,0,0]
]
];
let board = createBoard();
let currentPiece = null;
let nextPiece = generatePiece();
let heldPiece = null;
let canHold = true;
let pieceX, pieceY;
let score = 0;
let level = 1;
let linesCleared = 0;
let dropCounter = 0;
let dropInterval = 1000; // Milliseconds for piece drop
let lastTime = 0;
let gameRunning = true;
let isPaused = false;
function createBoard() {
return Array(boardHeight).fill(null).map(() => Array(boardWidth).fill(0));
}
function generatePiece() {
const pieceIndex = Math.floor(Math.random() * (shapes.length - 1)) + 1; // 1 to 7
return {
shape: shapes[pieceIndex],
color: colors[pieceIndex],
index: pieceIndex
};
}
function resetPiece() {
currentPiece = nextPiece;
nextPiece = generatePiece();
pieceX = boardWidth / 2 - Math.ceil(currentPiece.shape[0].length / 2); // Center piece horizontally
pieceY = 0;
canHold = true; // Reset hold ability when new piece spawns
drawNextPiecePreview(); // Update next piece display
if (checkCollision()) {
gameOver();
}
}
function drawBlock(x, y, color, context = ctx) {
context.fillStyle = color;
context.fillRect(x * gridSize, y * gridSize, gridSize, gridSize);
context.strokeStyle = '#333';
context.strokeRect(x * gridSize, y * gridSize, gridSize, gridSize); // Add grid lines for visibility
}
function drawBoard() {
board.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
drawBlock(x, y, colors[value]);
}
});
});
}
function drawPiece() {
if (!currentPiece) return;
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
drawBlock(pieceX + x, pieceY + y, currentPiece.color);
}
});
});
}
function drawNextPiecePreview() {
nextPieceCtx.clearRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
nextPieceCtx.fillStyle = '#222'; // Background color for next piece preview
nextPieceCtx.fillRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
const piece = nextPiece;
const offsetX = Math.floor((5 - piece.shape[0].length) / 2); // Center in 5x5 grid
const offsetY = Math.floor((5 - piece.shape.length) / 2);
piece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
drawBlock(offsetX + x, offsetY + y, piece.color, nextPieceCtx);
}
});
});
}
function drawHoldPiecePreview() {
holdPieceCtx.clearRect(0, 0, holdPieceCanvas.width, holdPieceCanvas.height);
holdPieceCtx.fillStyle = '#222'; // Background color for hold piece preview
holdPieceCtx.fillRect(0, 0, holdPieceCanvas.width, holdPieceCanvas.height);
if (!heldPiece) return;
const piece = heldPiece;
const offsetX = Math.floor((5 - piece.shape[0].length) / 2); // Center in 5x5 grid
const offsetY = Math.floor((5 - piece.shape.length) / 2);
piece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
drawBlock(offsetX + x, offsetY + y, piece.color, holdPieceCtx);
}
});
});
}
function rotatePiece(direction) { // direction: 1 for clockwise, -1 for counter-clockwise
if (!currentPiece) return;
const originalShape = currentPiece.shape;
const rotatedShape = originalShape[0].map((val, index) => originalShape.map(row => row[index]).reverse()); // Clockwise rotation
if (direction === -1) { // Counter-clockwise rotation - rotate clockwise 3 times (or reverse more efficiently)
for (let i = 0; i < 3; i++) {
rotatedShape = rotatedShape[0].map((val, index) => rotatedShape.map(row => row[index]).reverse());
}
}
currentPiece.shape = rotatedShape;
if (checkCollision()) { // If rotation causes collision, revert rotation (simple wall kick, can be improved)
currentPiece.shape = originalShape;
}
}
function movePiece(offsetX) {
pieceX += offsetX;
if (checkCollision()) {
pieceX -= offsetX; // Move back if collision
}
}
function movePieceDown() {
pieceY++;
if (checkCollision()) {
pieceY--; // Move back up
solidifyPiece();
clearLines();
resetPiece();
}
dropCounter = 0; // Reset drop counter on manual down movement
}
function checkCollision() {
if (!currentPiece) return false;
return currentPiece.shape.some((row, y) => {
return row.some((value, x) => {
if (value) {
let boardX = pieceX + x;
let boardY = pieceY + y;
return boardX < 0 || boardX >= boardWidth || boardY >= boardHeight || (boardY >= 0 && board[boardY][boardX] !== 0);
}
return false;
});
});
}
function solidifyPiece() {
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
board[pieceY + y][pieceX + x] = currentPiece.index;
}
});
});
}
function clearLines() {
let linesThisTurn = 0;
board = board.filter(row => !row.every(value => value !== 0)); // Remove full rows
linesThisTurn = boardHeight - board.length; // Number of lines cleared
if (linesThisTurn > 0) {
score += calculateScore(linesThisTurn, level);
linesCleared += linesThisTurn;
level = Math.floor(linesCleared / 10) + 1; // Level up every 10 lines (example)
dropInterval = Math.max(100, 1000 - (level - 1) * 75); // Increase speed (reduce drop interval) as level increases, min 100ms
board = Array(linesThisTurn).fill(null).map(() => Array(boardWidth).fill(0)).concat(board); // Add empty rows at the top
updateUI();
}
}
function calculateScore(lines, currentLevel) {
const lineClearScores = [0, 100, 300, 500, 800]; // Single, Double, Triple, Tetris (can customize)
return lineClearScores[lines] * currentLevel;
}
function holdPiece() {
if (!canHold) return; // Can only hold once per piece spawn
canHold = false;
if (heldPiece) {
const tempPiece = heldPiece;
heldPiece = currentPiece;
currentPiece = tempPiece;
pieceX = boardWidth / 2 - Math.ceil(currentPiece.shape[0].length / 2); // Center piece horizontally
pieceY = 0;
} else {
heldPiece = currentPiece;
resetPiece(); // Get a new piece immediately
}
drawHoldPiecePreview();
}
function updateUI() {
scoreDisplay.textContent = score;
levelDisplay.textContent = level;
linesDisplay.textContent = linesCleared;
}
function gameOver() {
gameRunning = false;
finalScoreDisplay.textContent = "Your Score: " + score;
gameOverOverlay.style.display = 'flex'; // Show game over overlay
}
function restartGame() {
board = createBoard();
score = 0;
level = 1;
linesCleared = 0;
dropInterval = 1000;
gameRunning = true;
gameOverOverlay.style.display = 'none'; // Hide game over overlay
heldPiece = null;
drawHoldPiecePreview(); // Clear hold piece display on restart
updateUI();
resetPiece();
gameLoop(); // Restart the game loop
}
function pauseGame() {
isPaused = !isPaused;
pauseOverlay.style.display = isPaused ? 'flex' : 'none';
}
function updateGame(time = 0) {
if (!gameRunning || isPaused) {
requestAnimationFrame(updateGame); // Keep loop running for pause/game over handling
return;
}
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
movePieceDown();
}
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
drawBoard();
drawPiece();
requestAnimationFrame(updateGame);
}
restartButton.addEventListener('click', restartGame);
document.addEventListener('keydown', event => {
if (!gameRunning) return; // Ignore input if game over
switch (event.key) {
case 'ArrowLeft':
movePiece(-1);
break;
case 'ArrowRight':
movePiece(1);
break;
case 'ArrowDown':
movePieceDown();
score += 1; // Soft drop score (optional)
updateUI();
break;
case 'ArrowUp': // Rotate clockwise
case ' ': // Rotate clockwise with spacebar
rotatePiece(1);
break;
case 'Shift': // Hold piece
holdPiece();
break;
case 'z': // Rotate counter-clockwise (optional - more complex control)
rotatePiece(-1);
break;
case 'p': // Pause game
case 'P':
pauseGame();
break;
}
});
resetPiece(); // Initial piece
drawNextPiecePreview();
updateGame(); // Start game loop
</script>
</body>
</html>
Explanation of the Code and "Complexity":
-
HTML Structure:
- Sets up the basic HTML document structure.
- Includes inline CSS for styling (as requested for a single HTML file).
- Uses a
<canvas> element (gameCanvas) for the main game board drawing.
- Creates a
uiContainer div to hold UI elements:
- Score, Level, Lines cleared displays.
nextPieceCanvas and holdPieceCanvas for previews.
- Controls information.
gameOverOverlay and pauseOverlay divs are created for game over and pause screens (initially hidden).
-
CSS Styling:
- Basic styling for the body, game container, canvas, UI elements, overlays, etc., to make the game visually appealing (within the constraints of simple CSS).
- Uses
flexbox for layout to center the game and arrange UI elements.
-
JavaScript Logic (<script> block):
-
Constants and Variables:
gridSize: Defines the size of each square block in pixels.
canvasWidth, canvasHeight, boardWidth, boardHeight: Define the dimensions of the game board and canvas in cells and pixels.
colors, shapes: Arrays to store colors and the 7 Tetris piece shapes (I, J, L, O, S, T, Z).
board: 2D array representing the game board. 0 for empty, numbers 1-7 for different piece colors.
currentPiece, nextPiece, heldPiece: Objects to store the currently falling piece, the next piece, and the held piece (for "hold" feature).
pieceX, pieceY: Coordinates of the top-left of the current piece on the board.
score, level, linesCleared: Game statistics.
dropCounter, dropInterval: Used to control the automatic piece dropping speed. dropInterval decreases as the level increases, making the game faster.
lastTime: For frame-rate independent movement.
gameRunning, isPaused, canHold: Game state flags.
"Complexity" Features Included:
- 7 Tetromino Shapes: All standard Tetris pieces are implemented.
- Rotation: Clockwise and counter-clockwise rotation (counter-clockwise is optional and bound to 'z').
- Movement: Left, Right, Soft Drop (Down arrow).
- Collision Detection: Prevents pieces from going out of bounds or overlapping.
- Solidifying Pieces: Pieces become part of the board grid when they reach the bottom or collide.
- Line Clearing: Detects and clears full horizontal lines, awarding score and increasing level.
- Scoring and Leveling: Score is calculated based on lines cleared and level. Level increases as lines are cleared, making the game faster by reducing
dropInterval.
- Next Piece Preview: Shows the next piece to appear.
- Hold Piece Feature: Allows the player to hold one piece in reserve and swap it with the current piece (controlled by Shift key). Limited to one hold per piece spawn.
- Game Over: Detects when a new piece can't fit at the top and ends the game, displaying a game over screen with the final score.
- Restart Functionality: Allows restarting the game from the game over screen.
- Pause Functionality: Pauses the game when 'p' or 'P' is pressed.
- Basic UI: Score, Level, Lines cleared displays, next and hold piece previews, and controls information.
- Frame-Rate Independent Movement: Uses
deltaTime in the game loop to make the falling speed consistent across different frame rates.
- Grid Lines: Added grid lines for better visual clarity of the board.
Possible Further Enhancements (To Increase "Complexity" even more):
- Wall Kicks (Rotation Refinement): Implement wall kicks for rotation. In real Tetris, when a rotation would cause a collision, the piece is slightly shifted left or right to try and make the rotation valid. This would make rotation feel smoother and less restrictive.
- Hard Drop: A feature where you can instantly drop a piece to the bottom (usually with the Spacebar).
- Ghost Piece: A faint visual representation of where the piece will land if dropped straight down.
- More Sophisticated Scoring System: More complex scoring based on combos, T-spins, etc.
- Sound Effects and Music: Add sound effects for piece placement, line clears, and game over, and background music.
- Visual Effects: More elaborate visual effects for line clearing, piece placement, etc.
- Game Modes: Add different game modes (e.g., timed mode, challenge mode).
- High Score Tracking: Implement local storage to save and display high scores.
- Touch Controls (for mobile): Add touch controls for mobile devices.
- Customizable Controls: Allow players to reconfigure keyboard controls.
- Different Block Skins/Themes: Allow customization of the block appearance.
This code provides a solid foundation for a complex Tetris game within a single HTML file. You can copy and paste this code into an HTML file (.html extension) and open it in a web browser to play.