Spaces:
Running

title / index.html
filipp2003456's picture
Add 1 files
e12243d verified
Raw History Blame Contribute Delete
24.8 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Retro Tetris</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
#game-board {
border: 3px solid #4a5568;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}
.block-I { background-color: #63b3ed; }
.block-J { background-color: #4299e1; }
.block-L { background-color: #f6ad55; }
.block-O { background-color: #f6e05e; }
.block-S { background-color: #68d391; }
.block-T { background-color: #9f7aea; }
.block-Z { background-color: #f687b3; }
.cell {
width: 30px;
height: 30px;
border: 1px solid rgba(255, 255, 255, 0.1);
box-sizing: border-box;
}
.ghost {
opacity: 0.3;
}
.tetris-title {
text-shadow: 3px 3px 0 #4a5568;
letter-spacing: 2px;
}
@keyframes flash {
0% { background-color: white; }
50% { background-color: transparent; }
100% { background-color: white; }
}
.flash-effect {
animation: flash 0.1s 4;
}
</style>
</head>
<body class="bg-gray-900 text-white min-h-screen flex flex-col items-center justify-center p-4">
<div class="max-w-4xl w-full">
<header class="mb-8 text-center">
<h1 class="tetris-title text-5xl font-bold text-purple-400 mb-2 font-mono">TETRIS</h1>
<p class="text-gray-400">Use arrow keys to move, space to drop, and up arrow to rotate</p>
</header>
<div class="flex flex-col md:flex-row gap-8 items-center md:items-start justify-center">
<div class="relative">
<canvas id="game-board" width="300" height="600" class="bg-gray-800 rounded"></canvas>
<div id="game-over" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70 hidden flex-col">
<h2 class="text-3xl font-bold text-red-500 mb-4">GAME OVER</h2>
<button id="restart-btn" class="px-6 py-2 bg-purple-600 hover:bg-purple-700 rounded font-bold">
Play Again
</button>
</div>
</div>
<div class="flex flex-col gap-6 w-full max-w-xs">
<div class="bg-gray-800 rounded-lg p-4 shadow-lg">
<h2 class="text-xl font-bold text-purple-300 mb-2">Next Piece</h2>
<canvas id="next-piece" width="120" height="120" class="mx-auto bg-gray-700 rounded"></canvas>
</div>
<div class="bg-gray-800 rounded-lg p-4 shadow-lg">
<h2 class="text-xl font-bold text-purple-300 mb-4">Stats</h2>
<div class="space-y-4">
<div>
<p class="text-gray-400">Score</p>
<p id="score" class="text-2xl font-bold">0</p>
</div>
<div>
<p class="text-gray-400">Level</p>
<p id="level" class="text-2xl font-bold">1</p>
</div>
<div>
<p class="text-gray-400">Lines</p>
<p id="lines" class="text-2xl font-bold">0</p>
</div>
</div>
</div>
<div class="bg-gray-800 rounded-lg p-4 shadow-lg">
<h2 class="text-xl font-bold text-purple-300 mb-2">Controls</h2>
<div class="grid grid-cols-2 gap-3 text-sm">
<div class="bg-gray-700 p-2 rounded">
<p class="font-bold text-amber-300">← →</p>
<p class="text-gray-300">Move</p>
</div>
<div class="bg-gray-700 p-2 rounded">
<p class="font-bold text-amber-300">↑</p>
<p class="text-gray-300">Rotate</p>
</div>
<div class="bg-gray-700 p-2 rounded">
<p class="font-bold text-amber-300">↓</p>
<p class="text-gray-300">Soft Drop</p>
</div>
<div class="bg-gray-700 p-2 rounded">
<p class="font-bold text-amber-300">Space</p>
<p class="text-gray-300">Hard Drop</p>
</div>
<div class="bg-gray-700 p-2 rounded col-span-2">
<p class="font-bold text-amber-300">P</p>
<p class="text-gray-300">Pause Game</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="mt-8 text-gray-500">
<p>Classic Tetris game with modern styling</p>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// Game constants
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const NEXT_PIECE_SIZE = 4;
// Game elements
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const nextPieceCanvas = document.getElementById('next-piece');
const nextPieceCtx = nextPieceCanvas.getContext('2d');
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const linesElement = document.getElementById('lines');
const gameOverElement = document.getElementById('game-over');
const restartBtn = document.getElementById('restart-btn');
// Game variables
let score = 0;
let level = 1;
let lines = 0;
let gameBoard = createMatrix(COLS, ROWS);
let currentPiece = null;
let nextPiece = null;
let gameOver = false;
let dropCounter = 0;
let dropInterval = 1000; // 1 second
let lastTime = 0;
let isPaused = false;
let animationId = null;
// Tetrimino shapes and colors
const SHAPES = [
{ shape: [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], class: 'block-I' }, // I
{ shape: [[2, 0, 0], [2, 2, 2], [0, 0, 0]], class: 'block-J' }, // J
{ shape: [[0, 0, 3], [3, 3, 3], [0, 0, 0]], class: 'block-L' }, // L
{ shape: [[4, 4], [4, 4]], class: 'block-O' }, // O
{ shape: [[0, 5, 5], [5, 5, 0], [0, 0, 0]], class: 'block-S' }, // S
{ shape: [[0, 6, 0], [6, 6, 6], [0, 0, 0]], class: 'block-T' }, // T
{ shape: [[7, 7, 0], [0, 7, 7], [0, 0, 0]], class: 'block-Z' } // Z
];
const COLORS = [
'#63b3ed', // I
'#4299e1', // J
'#f6ad55', // L
'#f6e05e', // O
'#68d391', // S
'#9f7aea', // T
'#f687b3' // Z
];
// Initialize the game
function init() {
score = 0;
level = 1;
lines = 0;
gameBoard = createMatrix(COLS, ROWS);
currentPiece = null;
nextPiece = null;
gameOver = false;
dropInterval = 1000;
isPaused = false;
updateScore();
spawnPiece();
spawnNextPiece();
if (animationId) {
cancelAnimationFrame(animationId);
}
animationId = requestAnimationFrame(gameLoop);
// Hide game over screen
gameOverElement.classList.add('hidden');
}
// Game loop
function gameLoop(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
if (!gameOver && !isPaused) {
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
moveDown();
dropCounter = 0;
}
draw();
}
animationId = requestAnimationFrame(gameLoop);
}
// Create a matrix (2D array) filled with zeros
function createMatrix(width, height) {
const matrix = [];
while (height--) {
matrix.push(new Array(width).fill(0));
}
return matrix;
}
// Spawn a new random piece
function spawnPiece() {
if (!nextPiece) {
// If there's no next piece (first piece of the game), create one randomly
const shape = SHAPES[Math.floor(Math.random() * SHAPES.length)];
currentPiece = {
position: { x: Math.floor(COLS / 2) - Math.floor(shape.shape[0].length / 2), y: 0 },
shape: shape.shape,
color: shape.class,
originalShape: JSON.parse(JSON.stringify(shape.shape))
};
} else {
// Use the next piece that was already generated
currentPiece = {
position: { x: Math.floor(COLS / 2) - Math.floor(nextPiece.shape[0].length / 2), y: 0 },
shape: nextPiece.shape,
color: nextPiece.class,
originalShape: JSON.parse(JSON.stringify(nextPiece.shape))
};
spawnNextPiece();
}
// Game over if the new piece collides immediately
if (collide()) {
gameOver = true;
gameOverElement.classList.remove('hidden');
}
}
// Spawn the next piece (shown in the preview)
function spawnNextPiece() {
const shape = SHAPES[Math.floor(Math.random() * SHAPES.length)];
nextPiece = {
shape: shape.shape,
class: shape.class
};
drawNextPiece();
}
// Draw the game board and current piece
function draw() {
// Clear the canvas
ctx.fillStyle = '#1a202c';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the game board
drawMatrix(gameBoard, { x: 0, y: 0 });
// Draw the ghost piece (where the piece would land)
drawGhost();
// Draw the current piece
drawMatrix(currentPiece.shape, currentPiece.position, currentPiece.color);
// Draw the grid lines
drawGrid();
}
// Draw a matrix (board or piece)
function drawMatrix(matrix, offset, color) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
const fillStyle = color || COLORS[value - 1];
ctx.fillStyle = fillStyle;
ctx.fillRect(
(x + offset.x) * BLOCK_SIZE,
(y + offset.y) * BLOCK_SIZE,
BLOCK_SIZE,
BLOCK_SIZE
);
// Add border for better visibility
ctx.strokeStyle = '#1a202c';
ctx.lineWidth = 1;
ctx.strokeRect(
(x + offset.x) * BLOCK_SIZE,
(y + offset.y) * BLOCK_SIZE,
BLOCK_SIZE,
BLOCK_SIZE
);
}
});
});
}
// Draw the grid lines
function drawGrid() {
ctx.strokeStyle = '#2d3748';
ctx.lineWidth = 1;
// Vertical lines
for (let i = 0; i <= COLS; i++) {
ctx.beginPath();
ctx.moveTo(i * BLOCK_SIZE, 0);
ctx.lineTo(i * BLOCK_SIZE, ROWS * BLOCK_SIZE);
ctx.stroke();
}
// Horizontal lines
for (let i = 0; i <= ROWS; i++) {
ctx.beginPath();
ctx.moveTo(0, i * BLOCK_SIZE);
ctx.lineTo(COLS * BLOCK_SIZE, i * BLOCK_SIZE);
ctx.stroke();
}
}
// Draw the next piece preview
function drawNextPiece() {
// Clear the next piece canvas
nextPieceCtx.fillStyle = '#2d3748';
nextPieceCtx.clearRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
// Center the piece in the preview
const centerX = (NEXT_PIECE_SIZE - nextPiece.shape[0].length) / 2;
const centerY = (NEXT_PIECE_SIZE - nextPiece.shape.length) / 2;
// Draw the piece
nextPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
nextPieceCtx.fillStyle = COLORS[value - 1];
nextPieceCtx.fillRect(
(x + centerX) * BLOCK_SIZE,
(y + centerY) * BLOCK_SIZE,
BLOCK_SIZE,
BLOCK_SIZE
);
// Add border for better visibility
nextPieceCtx.strokeStyle = '#1a202c';
nextPieceCtx.lineWidth = 1;
nextPieceCtx.strokeRect(
(x + centerX) * BLOCK_SIZE,
(y + centerY) * BLOCK_SIZE,
BLOCK_SIZE,
BLOCK_SIZE
);
}
});
});
}
// Draw the ghost piece (shows where the current piece will land)
function drawGhost() {
const ghost = {
position: { ...currentPiece.position },
shape: currentPiece.shape,
color: currentPiece.color
};
while (!collide(ghost.position.x, ghost.position.y + 1, ghost.shape)) {
ghost.position.y++;
}
// Draw with transparency
ctx.globalAlpha = 0.3;
drawMatrix(ghost.shape, ghost.position, ghost.color);
ctx.globalAlpha = 1.0;
}
// Check for collisions
function collide(offsetX = currentPiece.position.x, offsetY = currentPiece.position.y, shape = currentPiece.shape) {
for (let y = 0; y < shape.length; y++) {
for (let x = 0; x < shape[y].length; x++) {
if (shape[y][x] !== 0) {
// Check if outside the game board
if (offsetX + x < 0 ||
offsetX + x >= COLS ||
offsetY + y >= ROWS) {
return true;
}
// Check if collides with existing blocks
if (gameBoard[offsetY + y]?.[offsetX + x] !== 0) {
return true;
}
}
}
}
return false;
}
// Merge the current piece with the game board
function merge() {
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
gameBoard[y + currentPiece.position.y][x + currentPiece.position.x] = value;
}
});
});
}
// Rotate the current piece
function rotate() {
const originalShape = currentPiece.shape;
const rotated = originalShape[0].map((_, i) =>
originalShape.map(row => row[i]).reverse()
);
// Check if rotation is valid
if (!collide(currentPiece.position.x, currentPiece.position.y, rotated)) {
currentPiece.shape = rotated;
}
}
// Move the piece left
function moveLeft() {
if (!collide(currentPiece.position.x - 1, currentPiece.position.y)) {
currentPiece.position.x--;
}
}
// Move the piece right
function moveRight() {
if (!collide(currentPiece.position.x + 1, currentPiece.position.y)) {
currentPiece.position.x++;
}
}
// Move the piece down (soft drop)
function moveDown() {
if (!collide(currentPiece.position.x, currentPiece.position.y + 1)) {
currentPiece.position.y++;
} else {
// If we can't move down, merge the piece and check for cleared lines
merge();
clearLines();
spawnPiece();
}
dropCounter = 0;
}
// Hard drop - immediately place the piece
function hardDrop() {
while (!collide(currentPiece.position.x, currentPiece.position.y + 1)) {
currentPiece.position.y++;
}
merge();
clearLines();
spawnPiece();
}
// Clear completed lines
function clearLines() {
let linesCleared = 0;
for (let y = ROWS - 1; y >= 0; y--) {
// Check if the line is complete
const isLineComplete = gameBoard[y].every(cell => cell !== 0);
if (isLineComplete) {
// Remove the line
gameBoard.splice(y, 1);
// Add a new empty line at the top
gameBoard.unshift(new Array(COLS).fill(0));
linesCleared++;
y++; // Check the same row again since we moved everything down
}
}
if (linesCleared > 0) {
// Update score based on lines cleared
addScore(linesCleared);
// Add a visual effect for line clearing (flashing the game board)
canvas.classList.add('flash-effect');
setTimeout(() => {
canvas.classList.remove('flash-effect');
}, 400);
}
}
// Update the score
function addScore(lines) {
// Score calculation based on original Tetris scoring
const points = [0, 40, 100, 300, 1200]; // Points for 0, 1, 2, 3, 4 lines
score += points[lines] * level;
this.lines += lines;
// Level up every 10 lines
const newLevel = Math.floor(this.lines / 10) + 1;
if (newLevel > level) {
level = newLevel;
// Increase the game speed
dropInterval = Math.max(100, 1000 - (level * 50));
}
updateScore();
}
// Update the score display
function updateScore() {
scoreElement.textContent = score;
levelElement.textContent = level;
linesElement.textContent = lines;
}
// Keyboard controls
document.addEventListener('keydown', event => {
if (gameOver) return;
if (event.key === 'p' || event.key === 'P') {
isPaused = !isPaused;
return;
}
if (isPaused) return;
switch (event.key) {
case 'ArrowLeft':
moveLeft();
break;
case 'ArrowRight':
moveRight();
break;
case 'ArrowDown':
moveDown();
break;
case 'ArrowUp':
rotate();
break;
case ' ':
hardDrop();
break;
default:
break;
}
});
// Touch controls for mobile
let touchStartX = 0;
let touchStartY = 0;
canvas.addEventListener('touchstart', e => {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
}, false);
canvas.addEventListener('touchmove', e => {
if (gameOver || isPaused) return;
e.preventDefault();
const touchEndX = e.touches[0].clientX;
const touchEndY = e.touches[0].clientY;
const dx = touchEndX - touchStartX;
const dy = touchEndY - touchStartY;
// Swipe left/right
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > 0) moveRight();
else moveLeft();
} else {
// Swipe down (hard drop)
if (dy > 0) hardDrop();
}
// Reset touch positions to prevent multiple moves from one swipe
touchStartX = touchEndX;
touchStartY = touchEndY;
}, false);
// Double tap to rotate
let lastTap = 0;
canvas.addEventListener('touchend', e => {
if (gameOver || isPaused) return;
const currentTime = new Date().getTime();
const tapLength = currentTime - lastTap;
if (tapLength < 300 && tapLength > 0) {
// Double tap detected - rotate
rotate();
}
lastTap = currentTime;
}, false);
// Restart button
restartBtn.addEventListener('click', init);
// Start the game
init();
});
</script>
</body>
</html>