build a full featured tetris game. each block movement should make a sound - 8-bit note from the super-mario bros classic theme . exactly one note from the sequence (maintain an internal counter m, inc+1 on each play such that every note pitch will be the m-th note from the start of the theme sequence. reset to 0 on finish - aka Loop). single file, html.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, this is a fun challenge! Building a full-featured Tetris game with custom sound effects from the Super Mario Bros. theme in a single HTML file is quite an undertaking.
Here's the plan:
HTML Structure: Basic layout with a main game canvas, a "next piece" canvas, score/level display, and start/pause buttons.
CSS Styling: Minimal styling for presentation.
JavaScript Core Logic:
Game Board: A 2D array representing the grid.
Tetrominoes: Definitions for all 7 shapes (I, O, L, J, S, Z, T) including their colors and rotation states.
Game State: Current piece, next piece, score, level, lines cleared, game over status, paused status.
Rendering: Functions to draw the board, current piece, next piece, and locked pieces onto the canvases.
Piece Movement: Functions for moving left, right, down (soft drop), and rotating.
Collision Detection: Check for collisions with walls, the bottom, or other locked pieces.
Locking: When a piece lands, lock it into the board.
Line Clearing: Detect and clear full lines, shifting rows above down.
Scoring & Leveling: Implement a scoring system and increase game speed (level) based on lines cleared.
Game Loop:requestAnimationFrame or setInterval for game updates and rendering.
Controls: Keyboard event listeners for player input.
Sound Engine (Web Audio API):
AudioContext for sound generation.
OscillatorNode (square wave for 8-bit feel).
A list of Super Mario Bros. theme notes (frequencies and durations, or just pitches).
A counter m to cycle through the notes.
A function playNote() that takes the current note index m, plays the corresponding sound, and increments m.
Super Mario Bros. Theme Notes:
I'll use a simplified version of the opening melody. Note durations will be very short for quick feedback.
Sequence: E5, E5, (rest), E5, (rest), C5, E5, (rest), G5, (rest), (rest), (rest), G4 (octave lower)
Let's map these to frequencies. Rests will be silent.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Tetris with Mario Sounds</title>
<style>
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background-color: #222;
color: #eee;
margin-top: 20px;
}
#game-container {
display: flex;
align-items: flex-start;
gap: 20px;
border: 2px solid #555;
padding: 20px;
background-color: #333;
border-radius: 10px;
box-shadow: 0 0 15px rgba(0,0,0,0.5);
}
canvas {
border: 1px solid #777;
background-color: #111;
}
#game-board {
box-shadow: 0 0 10px #0ff;
}
#info-panel {
display: flex;
flex-direction: column;
align-items: center;
width: 150px;
padding: 10px;
background-color: #2a2a2a;
border-radius: 5px;
border: 1px solid #444;
}
#info-panel h3 {
margin-top: 0;
margin-bottom: 10px;
color: #0ff;
font-size: 1.2em;
}
#info-panel div {
margin-bottom: 10px;
font-size: 1em;
width: 100%;
text-align: center;
padding: 5px 0;
background-color: #383838;
border-radius: 3px;
}
#next-piece-canvas {
margin-top: 5px;
border: 1px solid #666;
background-color: #1a1a1a;
}
#controls {
margin-top: 20px;
text-align: center;
}
button {
padding: 10px 20px;
font-size: 1em;
background-color: #0af;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 0 5px;
transition: background-color 0.2s;
}
button:hover {
background-color: #08d;
}
button:disabled {
background-color: #555;
cursor: not-allowed;
}
#instructions {
margin-top: 15px;
font-size: 0.9em;
color: #aaa;
}
</style>
</head>
<body>
<h1>8-Bit Tetris</h1>
<div id="game-container">
<canvas id="game-board"></canvas>
<div id="info-panel">
<h3>NEXT</h3>
<canvas id="next-piece-canvas"></canvas>
<h3>SCORE</h3>
<div id="score">0</div>
<h3>LINES</h3>
<div id="lines">0</div>
<h3>LEVEL</h3>
<div id="level">1</div>
</div>
</div>
<div id="controls">
<button id="startButton">Start</button>
<button id="pauseButton" disabled>Pause</button>
</div>
<div id="instructions">
Controls: Arrow Keys (Move/Rotate), Space (Hard Drop), P (Pause)
</div>
<script>
const canvas = document.getElementById('game-board');
const context = canvas.getContext('2d');
const nextCanvas = document.getElementById('next-piece-canvas');
const nextContext = nextCanvas.getContext('2d');
const scoreDisplay = document.getElementById('score');
const linesDisplay = document.getElementById('lines');
const levelDisplay = document.getElementById('level');
const startButton = document.getElementById('startButton');
const pauseButton = document.getElementById('pauseButton');
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30; // Size of each block in pixels
const NEXT_BLOCK_SIZE = 20;
canvas.width = COLS * BLOCK_SIZE;
canvas.height = ROWS * BLOCK_SIZE;
nextCanvas.width = 4 * NEXT_BLOCK_SIZE;
nextCanvas.height = 4 * NEXT_BLOCK_SIZE;
context.scale(BLOCK_SIZE, BLOCK_SIZE);
nextContext.scale(NEXT_BLOCK_SIZE, NEXT_BLOCK_SIZE);
const COLORS = [
null, // 0 - Empty
'#FF0D72', // 1 - I (Cyan in classic, using vibrant pink)
'#0DC2FF', // 2 - L (Blue)
'#0DFF72', // 3 - J (Orange)
'#F538FF', // 4 - O (Yellow)
'#FF8E0D', // 5 - S (Green)
'#FFE138', // 6 - T (Purple)
'#3877FF' // 7 - Z (Red)
];
const SHAPES = [
[], // Dummy for 0 index
[[[1,1,1,1]], [[1],[1],[1],[1]]], // I
[[[2,0,0],[2,2,2]], [[2,2],[2,0],[2,0]], [[2,2,2],[0,0,2]], [[0,2],[0,2],[2,2]]], // L
[[[0,0,3],[3,3,3]], [[3,0],[3,0],[3,3]], [[3,3,3],[3,0,0]], [[3,3],[0,3],[0,3]]], // J
[[[4,4],[4,4]]], // O
[[[0,5,5],[5,5,0]], [[5,0],[5,5],[0,5]]], // S
[[[0,6,0],[6,6,6]], [[6,0],[6,6],[6,0]], [[6,6,6],[0,6,0]], [[0,6],[6,6],[0,6]]], // T
[[[7,7,0],[0,7,7]], [[0,7],[7,7],[7,0]]] // Z
];
let board = createBoard(COLS, ROWS);
let currentPiece;
let nextPiece;
let score = 0;
let lines = 0;
let level = 1;
let dropCounter = 0;
let dropInterval = 1000; // Milliseconds
let lastTime = 0;
let gameOver = false;
let isPaused = false;
// --- Sound Engine ---
let audioContext;
let marioNoteIndex = 0;
const marioThemeNotes = [
// Note, Octave, Duration (duration is less critical here as we just play a short blip)
// Frequencies for: E5, C5, G5, G4
// Null means rest (no sound)
{ freq: 659.25 }, // E5
{ freq: 659.25 }, // E5
null, // Rest
{ freq: 659.25 }, // E5
null, // Rest
{ freq: 523.25 }, // C5
{ freq: 659.25 }, // E5
null, // Rest
{ freq: 783.99 }, // G5
null, null, null, // Rests
{ freq: 392.00 }, // G4
null, null, null,
{ freq: 523.25 }, // C5
null, null,
{ freq: 392.00 }, // G4
null, null,
{ freq: 329.63 }, // E4
null, null,
{ freq: 440.00 }, // A4
null,
{ freq: 493.88 }, // B4
null,
{ freq: 466.16 }, // Bb4
{ freq: 440.00 }, // A4
null,
{ freq: 392.00 }, // G4 (triplet start)
{ freq: 659.25 }, // E5
{ freq: 783.99 }, // G5 (triplet end)
{ freq: 440.00 }, // A5 (should be A5=880, using A4 to keep it lower)
null,
{ freq: 739.99 }, // F#5 (using F5=698.46 or F#5=739.99) -- F5
{ freq: 783.99 }, // G5
null,
{ freq: 659.25 }, // E5
null,
{ freq: 523.25 }, // C5
{ freq: 587.33 }, // D5
{ freq: 493.88 } // B4
];
function initAudio() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
}
function playMarioNote() {
if (!audioContext || isPaused || gameOver) return;
const noteData = marioThemeNotes[marioNoteIndex];
marioNoteIndex = (marioNoteIndex + 1) % marioThemeNotes.length;
if (noteData && noteData.freq) {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.type = 'square'; // 8-bit sound
oscillator.frequency.setValueAtTime(noteData.freq, audioContext.currentTime);
gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Volume
gainNode.gain.exponentialRampToValueAtTime(0.00001, audioContext.currentTime + 0.15); // Quick decay
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.15); // Note duration
}
}
// --- Game Logic ---
function createBoard(cols, rows) {
const matrix = [];
while (rows--) {
matrix.push(new Array(cols).fill(0));
}
return matrix;
}
function createPiece() {
const typeId = Math.floor(Math.random() * (SHAPES.length -1)) + 1;
const shape = SHAPES[typeId][0]; // First rotation state
return {
x: Math.floor(COLS / 2) - Math.floor(shape[0].length / 2),
y: 0,
shape: shape,
shapeId: typeId,
rotationIndex: 0
};
}
function spawnNewPiece() {
currentPiece = nextPiece || createPiece();
nextPiece = createPiece();
if (checkCollision(currentPiece.shape, currentPiece.x, currentPiece.y)) {
gameOver = true;
pauseButton.disabled = true;
startButton.textContent = "Restart";
startButton.disabled = false;
alert("Game Over! Score: " + score);
}
drawNextPiece();
}
function draw() {
// Clear board
context.fillStyle = '#111';
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw locked pieces
drawMatrix(board, {x: 0, y: 0}, context);
// Draw current piece
if (currentPiece) {
drawMatrix(currentPiece.shape, currentPiece, context);
}
}
function drawNextPiece() {
nextContext.fillStyle = '#1a1a1a';
nextContext.fillRect(0, 0, nextCanvas.width, nextCanvas.height);
if (nextPiece) {
// Center the piece in the nextCanvas
const shape = nextPiece.shape;
const shapeWidth = shape[0].length;
const shapeHeight = shape.length;
const offsetX = (4 - shapeWidth) / 2;
const offsetY = (4 - shapeHeight) / 2;
drawMatrix(shape, { x: offsetX, y: offsetY }, nextContext, true);
}
}
function drawMatrix(matrix, offset, ctx, isNext = false) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
ctx.fillStyle = COLORS[value];
ctx.fillRect(x + offset.x, y + offset.y, 1, 1);
// Add a slight border to blocks for better visibility
ctx.strokeStyle = isNext ? '#333' : '#000'; // Darker border for next piece
ctx.lineWidth = isNext ? 0.05 : 0.1;
ctx.strokeRect(x + offset.x, y + offset.y, 1, 1);
}
});
});
}
function pieceMove(dx, dy) {
if (gameOver || isPaused) return;
if (!checkCollision(currentPiece.shape, currentPiece.x + dx, currentPiece.y + dy)) {
currentPiece.x += dx;
currentPiece.y += dy;
if (dy > 0) { // Soft drop
dropCounter = 0; // Reset soft drop counter
}
playMarioNote();
} else if (dy > 0) { // Tried to move down but collided
lockPiece();
spawnNewPiece();
}
}
function pieceRotate() {
if (gameOver || isPaused) return;
const rotations = SHAPES[currentPiece.shapeId];
let nextRotationIndex = (currentPiece.rotationIndex + 1) % rotations.length;
let newShape = rotations[nextRotationIndex];
// Basic wall kick (can be improved with SRS)
let kickOffset = 0;
if (checkCollision(newShape, currentPiece.x, currentPiece.y)) {
kickOffset = currentPiece.x + newShape[0].length > COLS ? -1 : (currentPiece.x < 0 ? 1 : 0);
if (kickOffset !== 0 && checkCollision(newShape, currentPiece.x + kickOffset, currentPiece.y)) {
kickOffset = currentPiece.x + newShape[0].length > COLS ? -2 : (currentPiece.x < -1 ? 2 : 0); // Try kicking further
}
}
if (!checkCollision(newShape, currentPiece.x + kickOffset, currentPiece.y)) {
currentPiece.shape = newShape;
currentPiece.rotationIndex = nextRotationIndex;
currentPiece.x += kickOffset;
playMarioNote();
}
}
function hardDrop() {
if (gameOver || isPaused) return;
while (!checkCollision(currentPiece.shape, currentPiece.x, currentPiece.y + 1)) {
currentPiece.y++;
// playMarioNote(); // Play note for each step of hard drop - can be too much
}
playMarioNote(); // Play one note for the hard drop action
lockPiece();
spawnNewPiece();
}
function checkCollision(shape, offsetX, offsetY) {
for (let y = 0; y < shape.length; y++) {
for (let x = 0; x < shape[y].length; x++) {
if (shape[y][x] !== 0) { // If it's a block of the piece
let boardX = offsetX + x;
let boardY = offsetY + y;
if (
boardX < 0 || // Left wall
boardX >= COLS || // Right wall
boardY >= ROWS || // Bottom wall
(boardY >= 0 && board[boardY] && board[boardY][boardX] !== 0) // Collides with another piece
) {
return true;
}
}
}
}
return false;
}
function lockPiece() {
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
// Ensure piece is within board bounds before locking (can happen if game over at top)
if (currentPiece.y + y >= 0 && currentPiece.y + y < ROWS &&
currentPiece.x + x >= 0 && currentPiece.x + x < COLS) {
board[currentPiece.y + y][currentPiece.x + x] = value;
}
}
});
});
clearLines();
}
function clearLines() {
let linesClearedThisTurn = 0;
outer: for (let y = ROWS - 1; y >= 0; y--) {
for (let x = 0; x < COLS; x++) {
if (board[y][x] === 0) {
continue outer; // Row is not full
}
}
// If we reach here, the row is full
const row = board.splice(y, 1)[0].fill(0); // Remove row
board.unshift(row); // Add empty row at top
linesClearedThisTurn++;
y++; // Re-check the same row index as it's now a new row
}
if (linesClearedThisTurn > 0) {
lines += linesClearedThisTurn;
// Scoring: 1 line = 40, 2 lines = 100, 3 lines = 300, 4 lines (Tetris) = 1200, times level
let points = 0;
if (linesClearedThisTurn === 1) points = 40;
else if (linesClearedThisTurn === 2) points = 100;
else if (linesClearedThisTurn === 3) points = 300;
else if (linesClearedThisTurn >= 4) points = 1200;
score += points * level;
updateScoreDisplay();
// Level up every 10 lines
if (lines >= level * 10) {
level++;
dropInterval = Math.max(100, 1000 - (level - 1) * 75); // Decrease interval, min 100ms
levelDisplay.textContent = level;
}
}
}
function updateScoreDisplay() {
scoreDisplay.textContent = score;
linesDisplay.textContent = lines;
levelDisplay.textContent = level;
}
function gameLoop(time = 0) {
if (gameOver) {
return; // Stop the loop
}
if (isPaused) {
requestAnimationFrame(gameLoop); // Keep requesting frame to check for unpause
return;
}
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
pieceMove(0, 1); // Soft drop
dropCounter = 0;
}
draw();
requestAnimationFrame(gameLoop);
}
function startGame() {
initAudio(); // Important to initialize audio on user interaction
board = createBoard(COLS, ROWS);
score = 0;
lines = 0;
level = 1;
dropInterval = 1000;
gameOver = false;
isPaused = false;
marioNoteIndex = 0; // Reset sound sequence
spawnNewPiece(); // This sets currentPiece and nextPiece
spawnNewPiece(); // Call again to properly populate nextPiece display initially
updateScoreDisplay();
startButton.textContent = "Restart";
startButton.disabled = true;
pauseButton.disabled = false;
pauseButton.textContent = "Pause";
lastTime = 0; // Reset time for game loop
dropCounter = 0; // Reset drop counter
gameLoop();
}
function togglePause() {
if (gameOver) return;
initAudio(); // Ensure audio context is running if paused then resumed
isPaused = !isPaused;
pauseButton.textContent = isPaused ? "Resume" : "Pause";
if (!isPaused) { // When resuming
lastTime = performance.now(); // Prevent large deltaTime jump
gameLoop(); // Make sure game loop continues if it was stopped by pause logic
}
}
// Event Listeners
document.addEventListener('keydown', event => {
if (gameOver) return;
if (event.key === 'p' || event.key === 'P') {
togglePause();
return;
}
if (isPaused) return;
switch (event.key) {
case 'ArrowLeft':
pieceMove(-1, 0);
break;
case 'ArrowRight':
pieceMove(1, 0);
break;
case 'ArrowDown':
pieceMove(0, 1); // Soft drop
break;
case 'ArrowUp': // Or 'w', 'x', 'z' for different rotation schemes
pieceRotate();
break;
case ' ': // Space for hard drop
event.preventDefault(); // Prevent page scroll
hardDrop();
break;
}
});
startButton.addEventListener('click', () => {
startGame();
});
pauseButton.addEventListener('click', () => {
togglePause();
});
// Initial setup for display before game starts
draw(); // Draw empty board
drawNextPiece(); // Draw empty next piece area
updateScoreDisplay();
</script>
</body>
</html>
Key Features Implemented:
Core Tetris Mechanics:
Random piece generation (7 types).
Piece movement (left, right, soft drop).
Piece rotation (basic, with simple wall kick).
Hard drop (spacebar).
Collision detection (walls, bottom, other pieces).
Piece locking.
Line clearing (single, double, triple, Tetris).
Scoring & Leveling:
Score based on lines cleared and level.
Level increases every 10 lines, speeding up the game.
UI:
Main game board.
Next piece preview.
Score, Lines, Level display.
Start/Restart and Pause/Resume buttons.
Basic instructions.
Sound:
Web Audio API for sound generation.
OscillatorNode with square wave for an 8-bit feel.
A sequence of notes from the Super Mario Bros. theme.
A counter marioNoteIndex (named marioNoteIndex in the code) that increments and loops through the note sequence.
playMarioNote() function called on each block movement (move, rotate, hard drop completion).
AudioContext initialization tied to user interaction (start button).
Single HTML File: All CSS and JavaScript are embedded.
Game States: Handles game over, playing, and paused states.
How to Run:
Copy the entire code block.
Save it as an .html file (e.g., mario_tetris.html).
Open the file in a modern web browser (Chrome, Firefox, Edge, Safari).
Notes on Sound Implementation:
The marioThemeNotes array contains objects with frequencies. null entries are used for rests (no sound played).
The playMarioNote function selects the current note, plays a short square wave at that frequency, and then increments marioNoteIndex to prepare for the next sound.
The sound duration is short (0.15s) to make it feel like a quick "blip" for each movement.
AudioContext is initialized on the first user interaction (clicking "Start") as required by modern browsers.
This should provide a pretty comprehensive and fun Tetris experience with the requested sound feature!