Alright, let's design a "simple Tetris-like game." As a seasoned game developer, I always start with the core loop and Minimum Viable Product (MVP) to ensure we build something playable quickly, then iterate. We'll call this game "Blockfall Classic."
Game Design Document: Blockfall Classic
Game Title: Blockfall Classic
Genre: Puzzle, Falling Block
Target Platform: Conceptual (easily implementable on PC via Python/Pygame, JavaScript/Canvas, or even Unity/Godot for a simple prototype)
1. Concept Overview
"Blockfall Classic" is a simple, grid-based puzzle game where players manipulate falling blocks (tetrominoes) to clear horizontal lines. The goal is to score as many points as possible before the blocks stack up to the top of the playfield. It's designed to capture the addictive core loop of the genre without unnecessary complexity.
2. Core Mechanics
Playfield: A fixed-size grid (e.g., 10 cells wide x 20 cells high).
Blocks (Tetrominoes): Seven distinct shapes (I, J, L, O, S, T, Z), each composed of four square cells. Each shape will have a distinct color.
Gravity/Descent: Blocks automatically fall one row per fixed time interval.
Player Control:
Move Left/Right: Shift the active falling block horizontally one cell.
Rotate: Rotate the active block 90 degrees clockwise.
Soft Drop: Accelerate the block's descent. The block still locks normally upon contact.
Hard Drop: Instantly drop the block to its lowest possible position and immediately lock it into place.
Collision Detection: Blocks cannot move into occupied cells or outside the playfield boundaries.
Locking: When a falling block makes contact with the bottom of the playfield or an already-locked block, it "locks" into place, becoming part of the static playfield.
Line Clearing: When a horizontal line is completely filled with locked blocks, that line clears, and all blocks above it shift down by one row.
Scoring: Points awarded for clearing lines. More lines cleared simultaneously yield higher points.
Next Piece: A small display showing the next block that will fall.
Game Over: The game ends when a newly spawned block collides immediately with existing locked blocks, meaning it cannot fully enter the playfield.
3. Game Elements
Game Grid: A 2D array (or similar data structure) representing the playfield. Each cell can be empty or contain a block type/color.
Active Block: Current position, shape, and rotation state of the falling block.
Locked Blocks: The static blocks accumulated at the bottom of the playfield.
Score Counter: Integer variable tracking the player's score.
Next Block Display: A small preview area.
4. User Interface (UI)
Main Play Area: Dominant part of the screen, showing the 10x20 grid.
Score Display: Clearly visible text displaying the current score.
Next Piece Display: A small square to the side of the play area showing the next block.
Game Over Screen: A simple overlay displaying "GAME OVER," the final score, and a "Press [Key] to Restart" prompt.
Start Screen (Optional MVP): A simple "Blockfall Classic - Press [Key] to Start" screen.
5. Game Flow / States
Initialize Game:
Clear the playfield grid.
Reset score to 0.
Generate first two random blocks (one active, one for "next").
Start Screen (Optional): Wait for player input to begin.
Playing State (Main Game Loop):
Input Handling: Check for player input (move, rotate, soft/hard drop). Apply movement if valid (no collisions).
Gravity: If auto-fall timer elapses, move active block down one row.
Collision Check: If the active block cannot move down (hits bottom or other locked blocks):
Lock Block: Transfer the active block's cells to the main playfield grid.
Line Clear Check: Iterate through all rows. If a row is full, clear it and shift all rows above down. Award points.
Spawn New Block: Take the "next" block, make it active, and generate a new "next" block.
Game Over Check: If the newly spawned block immediately collides (cannot spawn), transition to Game Over state.
Game Over State:
Stop game logic.
Display "GAME OVER" and final score.
Wait for player input to restart.
Restart: Return to Initialize Game state.
6. Scoring System (Simple)
Single Line: 100 points
Double Line: 250 points
Triple Line: 400 points
Tetris (Quadruple Line): 800 points
Soft Drop: 1 point per row descended
Hard Drop: 2 points per row descended
(Self-correction: For a simple game, we won't implement progressive levels (speed increase) initially, but that's a natural extension for future iteration.)
7. Technical Considerations (for a prototype)
Data Structure: The playfield can be a 2D list/array, e.g., grid[row][col], where 0 means empty and 1-7 (or colors) represent locked block types. Each tetromino shape can be stored as a list of 2D coordinates relative to its origin point.
Collision Logic: This is the trickiest part. When moving or rotating, check each cell of the proposed new block position against the playfield boundaries and existing locked blocks. If any cell is invalid, the move/rotation is invalid.
Rotation: Implement a simple rotation matrix or pre-define all rotation states for each block. Be mindful of "wall kicks" (how blocks behave when rotating near walls or other blocks) – for a simple version, a basic "if collision, don't rotate" is fine, but advanced versions need more sophisticated kick rules.
Game Loop: A standard while running: loop that handles Input -> Update Game State -> Render Graphics.
Graphics: Simple colored squares for blocks, black background for the grid.
8. MVP Scope (What we absolutely need for a playable game)
Functional 10x20 playfield.
All 7 block types, spawning randomly.
Basic left/right movement and 90-degree clockwise rotation.
Automatic gravity.
Soft Drop and Hard Drop.
Accurate collision detection for movement, rotation, and locking.
Line clearing logic.
Basic scoring.
Game Over condition and restart option.
Next Piece preview.
9. Potential Future Enhancements (Post-MVP)
Difficulty Levels: Increase gravity speed over time or with score.
Hold Queue: Allow players to "hold" a piece for later use.
Ghost Piece: Show a transparent outline of where the active block will land.
Sound Effects & Music: Essential for player feedback and immersion.
Visual Effects: Line clear animations, particle effects, etc.
Advanced Wall Kicks: Implement more nuanced Super Rotation System (SRS) rules for rotation near walls.
Combo/T-Spin Scoring: Reward advanced maneuvers.
High Score Table: Save scores locally.
This design prioritizes getting the core mechanics working smoothly. From a 10-year dev's perspective, this means starting lean, focusing on the fundamental challenge of handling grid logic, collisions, and state management cleanly, before adding any "nice-to-haves." This approach reduces scope creep and delivers a fun, albeit simple, experience efficiently.
User
and something in html?
Assistant
Okay, let's build "Blockfall Classic" using HTML, CSS, and JavaScript. We'll aim for a clean, simple structure, focusing on the core mechanics outlined in the design document.
This is where the magic happens. I'll comment extensively to explain the logic.
javascript
// --- Game Configuration ---
const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 20;
const BLOCK_SIZE = 30; // Pixels per block
const GAME_SPEED = 500; // Milliseconds per fall (gravity)
// --- HTML Elements ---
const gameCanvas = document.getElementById('gameCanvas');
const gameCtx = gameCanvas.getContext('2d');
const nextPieceCanvas = document.getElementById('nextPieceCanvas');
const nextPieceCtx = nextPieceCanvas.getContext('2d');
const scoreDisplay = document.getElementById('scoreDisplay');
const gameOverScreen = document.getElementById('gameOverScreen');
const finalScoreDisplay = document.getElementById('finalScoreDisplay');
const startScreen = document.getElementById('startScreen');
// --- Game State Variables ---
let board = []; // 2D array representing the game grid
let currentPiece = null;
let nextPiece = null;
let score = 0;
let gameOver = true; // Start as true, so start screen is shown
let gameInterval = null;
let isGameRunning = false; // Flag to prevent multiple game loops
// --- Block Definitions (Tetrominoes) ---
// Each piece is an array of rotations. Each rotation is an array of [x, y] offsets from its origin.
// Colors are simple strings compatible with canvas fillStyle.
const PIECES = [
// I (Cyan)
{ shape: [[[0,0],[1,0],[2,0],[3,0]], [[1,0],[1,1],[1,2],[1,3]]], color: 'cyan' },
// J (Blue)
{ shape: [[[0,1],[1,1],[2,1],[2,0]], [[1,0],[1,1],[1,2],[2,2]], [[0,1],[0,2],[1,1],[2,1]], [[0,0],[1,0],[1,1],[1,2]]], color: 'blue' },
// L (Orange)
{ shape: [[[0,1],[1,1],[2,1],[0,0]], [[1,0],[1,1],[1,2],[2,0]], [[0,1],[2,1],[2,2],[1,1]], [[0,2],[1,0],[1,1],[1,2]]], color: 'orange' },
// O (Yellow) - no rotation needed
{ shape: [[[0,0],[1,0],[0,1],[1,1]]], color: 'yellow' },
// S (Green)
{ shape: [[[1,0],[2,0],[0,1],[1,1]], [[1,0],[1,1],[2,1],[2,2]]], color: 'green' },
// T (Purple)
{ shape: [[[0,1],[1,0],[1,1],[2,1]], [[1,0],[1,1],[1,2],[2,1]], [[0,1],[1,1],[1,2],[2,1]], [[0,1],[1,0],[1,1],[1,2]]], color: 'purple' },
// Z (Red)
{ shape: [[[0,0],[1,0],[1,1],[2,1]], [[2,0],[1,1],[2,1],[1,2]]], color: 'red' }
];
// --- Drawing Functions ---
// Draws a single square block on a given context
function drawSquare(ctx, x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
ctx.strokeStyle = '#222'; // Dark border for blocks
ctx.strokeRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
}
// Draws the entire game board, including locked blocks
function drawBoard() {
gameCtx.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
for (let row = 0; row < BOARD_HEIGHT; row++) {
for (let col = 0; col < BOARD_WIDTH; col++) {
if (board[row][col] !== 0) { // If cell is not empty
drawSquare(gameCtx, col, row, board[row][col]);
}
}
}
}
// Draws a given piece (active or next) on its respective canvas
function drawPiece(piece, ctx) {
if (!piece) return;
// Clear the canvas first
if (ctx === gameCtx) {
// Main game canvas cleared by drawBoard, but we can draw current piece over it
// This function will draw it _onto_ the board, so no specific clear needed here
// as drawBoard() covers it, and then we draw the active piece.
} else if (ctx === nextPieceCtx) {
ctx.clearRect(0, 0, nextPieceCanvas.width, nextPieceCanvas.height);
}
const shape = PIECES[piece.type].shape[piece.rotation];
const color = PIECES[piece.type].color;
// For next piece canvas, offset to center it. For game canvas, use piece.x, piece.y
const offsetX = (ctx === nextPieceCtx) ? 0.5 : piece.x; // Small offset to center next piece preview
const offsetY = (ctx === nextPieceCtx) ? 0.5 : piece.y; // Adjust as needed for specific pieces
shape.forEach(segment => {
drawSquare(ctx, segment[0] + offsetX, segment[1] + offsetY, color);
});
}
// --- Game Logic ---
// Initializes the game board with empty cells
function initBoard() {
board = Array(BOARD_HEIGHT).fill(0).map(() => Array(BOARD_WIDTH).fill(0));
}
// Generates a new random piece and sets its initial position
function generateNewPiece() {
const type = Math.floor(Math.random() * PIECES.length);
return {
type: type,
rotation: 0,
x: Math.floor(BOARD_WIDTH / 2) - 2, // Spawn near top-center
y: 0
};
}
// Checks if a given piece's position and rotation are valid (no collisions, in bounds)
function isValidMove(piece) {
const shape = PIECES[piece.type].shape[piece.rotation];
for (const segment of shape) {
const boardX = piece.x + segment[0];
const boardY = piece.y + segment[1];
// Check boundaries
if (boardX < 0 || boardX >= BOARD_WIDTH || boardY < 0 || boardY >= BOARD_HEIGHT) {
return false;
}
// Check for collision with locked blocks
if (board[boardY][boardX] !== 0) {
return false;
}
}
return true;
}
// Attempts to move the current piece
function movePiece(dx, dy) {
if (gameOver) return false;
const newPiece = { ...currentPiece,
x: currentPiece.x + dx,
y: currentPiece.y + dy
};
if (isValidMove(newPiece)) {
currentPiece = newPiece;
return true;
}
return false;
}
// Attempts to rotate the current piece
function rotatePiece() {
if (gameOver) return;
const newRotation = (currentPiece.rotation + 1) % PIECES[currentPiece.type].shape.length;
const newPiece = { ...currentPiece,
rotation: newRotation
};
// Simple wall kick: try to shift X by 1 if rotation fails
if (!isValidMove(newPiece)) {
newPiece.x++; // Try moving right
if (isValidMove(newPiece)) {
currentPiece = newPiece;
return;
}
newPiece.x -= 2; // Try moving left (original + 1 - 2)
if (isValidMove(newPiece)) {
currentPiece = newPiece;
return;
}
// If still no valid position, revert X and don't rotate
newPiece.x++; // Reset X
}
if (isValidMove(newPiece)) {
currentPiece = newPiece;
}
}
// Locks the current piece into the board and checks for line clears
function lockPiece() {
const shape = PIECES[currentPiece.type].shape[currentPiece.rotation];
const color = PIECES[currentPiece.type].color;
shape.forEach(segment => {
const boardX = currentPiece.x + segment[0];
const boardY = currentPiece.y + segment[1];
if (boardY >= 0 && boardY < BOARD_HEIGHT && boardX >= 0 && boardX < BOARD_WIDTH) { // Safety check
board[boardY][boardX] = color;
}
});
checkLines();
spawnNewPiece();
}
// Checks for and clears completed lines
function checkLines() {
let linesCleared = 0;
for (let row = BOARD_HEIGHT - 1; row >= 0; row--) {
if (board[row].every(cell => cell !== 0)) { // If the row is full
linesCleared++;
// Remove the full row and add a new empty row at the top
board.splice(row, 1);
board.unshift(Array(BOARD_WIDTH).fill(0));
row++; // Re-check the current row, as rows above have shifted down
}
}
if (linesCleared > 0) {
updateScore(linesCleared);
}
}
// Updates the score based on lines cleared
function updateScore(linesCleared) {
let points = 0;
switch (linesCleared) {
case 1: points = 100; break;
case 2: points = 250; break;
case 3: points = 400; break;
case 4: points = 800; break; // Tetris!
}
score += points;
scoreDisplay.textContent = score;
}
// Spawns the next piece, and checks for game over
function spawnNewPiece() {
currentPiece = nextPiece;
nextPiece = generateNewPiece();
drawPiece(nextPiece, nextPieceCtx); // Update next piece preview
if (!isValidMove(currentPiece)) {
endGame();
}
}
// Main game loop: handles gravity and updates
function gameLoop() {
if (gameOver) return;
if (!movePiece(0, 1)) { // Try to move down
lockPiece(); // If cannot move down, lock it
}
drawGame();
}
// Draws everything on the game canvas
function drawGame() {
drawBoard(); // Draw the static board
drawPiece(currentPiece, gameCtx); // Draw the active falling piece on top
}
// --- Game Control Functions ---
function startGame() {
if (isGameRunning) return; // Prevent starting multiple times
isGameRunning = true;
gameOver = false;
score = 0;
scoreDisplay.textContent = score;
initBoard();
gameOverScreen.classList.add('hidden');
startScreen.classList.add('hidden');
nextPiece = generateNewPiece(); // Generate first 'next' piece
spawnNewPiece(); // This will move 'next' to 'current' and generate a new 'next'
// Start the game loop
if (gameInterval) clearInterval(gameInterval); // Clear any old interval
gameInterval = setInterval(gameLoop, GAME_SPEED);
drawGame(); // Initial draw
}
function endGame() {
gameOver = true;
isGameRunning = false;
clearInterval(gameInterval);
finalScoreDisplay.textContent = score;
gameOverScreen.classList.remove('hidden');
}
// --- Input Handling ---
document.addEventListener('keydown', e => {
if (gameOver) {
if (e.code === 'Space') {
startGame();
}
return;
}
switch (e.code) {
case 'ArrowLeft':
movePiece(-1, 0);
break;
case 'ArrowRight':
movePiece(1, 0);
break;
case 'ArrowUp': // Or 'KeyX' for some Tetris versions
rotatePiece();
break;
case 'ArrowDown': // Soft Drop
if (movePiece(0, 1)) {
score += 1; // 1 point per row descended by soft drop
scoreDisplay.textContent = score;
}
// Reset the interval to make it fall immediately again, but then resume normal speed
clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, GAME_SPEED);
break;
case 'Space': // Hard Drop
let rowsDropped = 0;
while (movePiece(0, 1)) {
rowsDropped++;
}
lockPiece();
score += rowsDropped * 2; // 2 points per row descended by hard drop
scoreDisplay.textContent = score;
// Immediately trigger next game loop cycle to render locked piece
gameLoop();
break;
}
drawGame(); // Redraw after any input
});
// Initial setup to show the start screen
startScreen.classList.remove('hidden');