Video Tutorial | 'Tetris' Game With AI
The Video
In the 5-minute video below, I showcase a Tetris Game and explain the steps to build it.
Premise
We want a browser-friendly, two-player Tetris game that one can play against a Computer (what it was called in the 90s) or AI (your everyday opponent these days :p). The game features two side-by-side Tetris boards: one controlled by the player using keyboard inputs and the other by an AI. The game includes standard Tetris mechanics (piece movement, rotation, line clearing, scoring), audio effects, a play/pause music button, and a game-over condition with a winner declaration based on scores. The AI uses a heuristic-based evaluation to make intelligent moves.
What is heuristic-based evaluation?
In very easy words, imagine you made a toy. Let’s say it’s a drawing app on a tablet and now you want to know if other kids will like using it.
Heuristic-based evaluation is like asking a group of really smart grown-ups who know a lot about toys and kids to try out your drawing app and tell you if anything feels weird, confusing, or hard to use.
But instead of just saying “I like it” or “I don’t like it,” they use a special checklist, like:
Is it easy to understand what to do?
Can I undo a mistake?
Does it feel safe and friendly?
Can I find buttons where I expect them?
These smart grown-ups look at your app and compare it to that checklist. Then they say, “Hmm, maybe make the color button bigger,” or “This part is hard to understand.”
So, in short:
Heuristic-based evaluation is when experts test something (like an app or website) using simple rules to spot problems, even before real users try it.
It helps make things better and easier to use — kind of like fixing a toy before putting it on the shelf!
Prompt (The thought behind the build)
Game Setup:
Create a full-screen Tetris game using canvas that adjusts dynamically to window resizing. (We have been using canvas in all our games. You can refer to the previous articles for code and context.
Implement two 10x20 grid boards (10 columns, 20 rows) for the player and AI.
Define seven standard Tetris piece shapes (I, O, T, L, J, S, Z) with distinct neon colors:
I: Cyan ([0, 255, 255])
O: Yellow ([255, 255, 0])
T: Magenta ([255, 0, 255])
L: Orange ([255, 165, 0])
J: Blue ([0, 0, 255])
S: Green ([0, 255, 0])
Z: Red ([255, 0, 0])
Initialize each board with a random starting piece for both the player and AI.
Game Mechanics:
Piece Movement:
Pieces fall automatically every 20 frames (approximately every 1/3 second at 60 FPS).
Player controls their piece using:
Left Arrow: Move piece left.
Right Arrow: Move piece right.
Down Arrow: Move piece down faster.
Up Arrow: Rotate piece clockwise.
AI controls its piece autonomously (detailed below).
Collision Detection:
Prevent pieces from moving outside the grid or overlapping with existing blocks.
When a piece cannot move down further, place it on the grid and spawn a new random piece.
If a new piece cannot spawn without collision, trigger game over.
Line Clearing:
Check for and clear completed rows (rows fully filled with blocks).
Shift remaining rows down after clearing.
Award points based on lines cleared:
1 line: 100 points
2 lines: 200 points
3 lines: 300 points
4 lines: 800 points
Scoring:
Track separate scores for the player and AI, displayed above their respective boards.
End the game when either player cannot place a new piece, declaring the winner based on the higher score (or a tie if equal).
Visuals:
Render each grid with a block size scaled to the window (minimum of windowWidth/30 or windowHeight/25).
Position the player’s grid at 10% of the window width and the AI’s grid at 60% of the window width, both at 10% of the window height from the top.
Draw pieces and grid blocks with their assigned colors and a black stroke.
Add a glowing effect (shadowBlur = 10) matching the block’s color for visual appeal.
Draw grid lines (gray, stroke weight 1) to outline the 10x20 grid.
Display scores with white text, size scaled to 3% of window height, above each grid.
On game over, display a centered message with the winner (“Player”, “AI”, or “Tie”), using text size 5% of window height, white with a black stroke.
Audio:
Include four audio files:
background-tetris.mp3: Looping background music (volume 0.3).
block-placed.mp3: Played when a piece is placed.
user-scores.mp3: Played when the player clears lines.
enemy-scores.mp3: Played when the AI clears lines.
Create a centered “Play/Pause Music” button at the top of the screen:
Styled with a green background (#4CAF50), white text, rounded corners, and hover effect (#45a049).
Toggles all audio (pauses/resumes background music, disables/enables sound effects).
Button text changes to “Pause Music” when playing and “Play Music” when paused.
AI Logic:
The AI controls the second board, making moves every 20 frames.
For each piece, evaluate all possible positions and rotations by:
Simulating all horizontal positions and up to four rotations (90° clockwise each).
Dropping the piece to the lowest valid position for each configuration.
Scoring each final position using a heuristic evaluation function (detailed below).
Selecting the position/rotation with the highest score.
Execute the best move by rotating the piece the required number of times and moving it left or right to the target position.
Evaluation Function:
Lines Cleared: +5000 for 4 lines, +2000 for 3, +800 for 2, +200 for 1.
Holes: -100 per hole (empty cell below a filled cell in a column).
Aggregate Height: -10 per unit of total column height (distance from top to first block).
Bumpiness: -20 per unit of height difference between adjacent columns.
Left-Right Balance: -25 per unit of height difference between left and right halves of the grid.
Wall/Floor Contacts: +50 per contact with grid edges or blocks below.
I-Piece Flatness: +200 per column where the I-piece aligns with the column height.
Center Preference: -5 per unit distance from the grid’s horizontal center.
Responsive Design:
Adjust the canvas and block size on window resize to maintain proportions.
Ensure text, grids, and the music button remain properly positioned and scaled.
Implementation Notes:
Use p5.js functions (setup, draw, keyPressed, windowResized) for core game loop and input handling.
Structure pieces as a Piece class with methods for movement (moveDown, moveLeft, moveRight), rotation (rotate), collision checking (canMove), placement (place), and resetting (reset).
Use a grid array to track placed blocks, storing color information for rendering.
Optimize AI performance to evaluate moves efficiently within the 20-frame cycle.
Deliverables:
A single HTML file containing:
HTML structure with p5.js CDN link, audio elements, and CSS for the music button.
JavaScript code implementing the game logic, AI, and rendering using p5.js.
External audio files (assumed available: background-tetris.mp3, block-placed.mp3, user-scores.mp3, enemy-scores.mp3).
Constraints:
The game must run smoothly in a modern browser with p5.js support.
Audio files must be in MP3 format and correctly referenced.
The AI must make intelligent moves without causing performance lag.
The game must handle edge cases (e.g., invalid moves, game over conditions) gracefully.
Code
You can download the game files through this link and build upon it or use it for custom projects -
https://drive.google.com/drive/folders/1TIEIIIp1crB0G0e2KRU8CoCGOACIahs0?usp=sharing