🎮ArcadeLab

NES DR. MARIO - ArcadeLab

by PixelStar14
1013 lines35.7 KB
▶ Play
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NES DR. MARIO - ArcadeLab</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Courier New', Courier, monospace, sans-serif;
            font-weight: bold;
            image-rendering: pixelated;
            user-select: none;
            -webkit-user-select: none;
        }
        body {
            background-color: #000000;
            color: #ffffff;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            overflow: hidden;
            touch-action: manipulation;
        }
        .arcade-cabinet {
            background: #101028;
            border: 4px solid #52527a;
            box-shadow: 0 0 0 4px #000, 0 0 18px rgba(0, 252, 252, 0.15);
            padding: 16px;
            display: flex;
            flex-direction: column;
            align-items: center;
            max-width: 460px;
            width: 100%;
        }
        .header-box {
            display: flex;
            justify-content: space-between;
            width: 100%;
            margin-bottom: 10px;
            font-size: 0.75rem;
            color: #00fcfc;
            letter-spacing: 1px;
        }
        .game-container {
            display: flex;
            gap: 12px;
            position: relative;
            background-color: #000;
            border: 4px solid #3c3c64;
            padding: 8px;
        }
        canvas {
            background-color: #050510;
            display: block;
            border: 2px solid #7878a8;
        }
        .side-panel {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            gap: 8px;
            width: 135px;
        }
        .stats-box {
            background: #000;
            border: 2px solid #52527a;
            padding: 8px;
            text-align: left;
        }
        .stats-box h3 {
            font-size: 0.6rem;
            color: #9898c8;
            margin-bottom: 4px;
        }
        .stats-box p {
            font-size: 0.85rem;
            color: #fcbc00;
            text-align: right;
            letter-spacing: 2px;
            text-shadow: 2px 2px #3c1400;
        }
        .preview-container {
            background: #000;
            border: 2px solid #52527a;
            padding: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 85px;
        }
        .preview-container h3 {
            font-size: 0.6rem;
            color: #9898c8;
            margin-bottom: 6px;
            align-self: flex-start;
        }
        #nextCanvas {
            background-color: #000;
            border: none;
        }
        .controls-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 6px;
            margin-top: 14px;
            width: 100%;
        }
        .ctrl-btn {
            background: #202040;
            border: 2px solid #52527a;
            color: #fff;
            padding: 12px 0;
            font-size: 0.75rem;
            font-weight: bold;
            text-align: center;
        }
        .ctrl-btn.active-touch {
            background: #fcbc00;
            color: #000;
            border-color: #fcbc00;
        }
        .ctrl-btn.wide {
            grid-column: span 3;
            background: #0078f8;
            border-color: #00fcfc;
        }
        .ctrl-btn.wide.active-touch {
            background: #00fcfc;
            color: #000;
        }
        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 15, 0.95);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            z-index: 10;
        }
        .overlay h2 {
            font-size: 1.05rem;
            color: #f83800;
            margin-bottom: 14px;
            line-height: 1.5;
            text-shadow: 2px 2px #fcbc00;
        }
        .overlay p {
            font-size: 0.65rem;
            color: #c0c0c0;
            margin-bottom: 16px;
            padding: 0 10px;
            line-height: 1.7;
        }
        .menu-options {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 18px;
            width: 88%;
        }
        .menu-row {
            background: #000;
            color: #7878a8;
            border: 2px solid #3c3c64;
            padding: 9px;
            font-size: 0.65rem;
            text-align: left;
            display: flex;
            justify-content: space-between;
        }
        .menu-row.selected {
            border-color: #fcbc00;
            color: #fcbc00;
            background: #1a1a00;
        }
        .footer-credits {
            margin-top: 12px;
            font-size: 0.7rem;
            color: #fcbc00;
            text-align: center;
            letter-spacing: 1px;
            text-shadow: 2px 2px #521800;
        }
        .hidden {
            display: none !important;
        }
    </style>
</head>
<body>

<div class="arcade-cabinet">
    <div class="header-box">
        <span>NES DR. MARIO</span>
        <span>© 1990 NINTENDO</span>
    </div>

    <div class="game-container">
        <div style="position: relative;">
            <canvas id="bottle" width="192" height="384"></canvas>
            
            <!-- Main Menu Overlay -->
            <div id="menuOverlay" class="overlay">
                <h2>NES DR. MARIO</h2>
                <div class="menu-options">
                    <div class="menu-row selected" id="rowLevel">
                        <span>VIRUS LVL:</span> <span id="valLevel" style="color:#00fcfc;">01</span>
                    </div>
                    <div class="menu-row" id="rowSpeed">
                        <span>SPEED:</span> <span id="valSpeed" style="color:#f83800;">MED</span>
                    </div>
                    <div class="menu-row" id="rowMusic">
                        <span>AUDIO/MUSIC:</span> <span id="valMusic" style="color:#00f800;">ON</span>
                    </div>
                </div>
                <p>PRESS [↑/↓] TO SELECT<br>PRESS [←/→] TO CHANGE<br>PRESS [ENTER / SPACE] START</p>
            </div>

            <!-- Stage Clear Overlay -->
            <div id="stageClearOverlay" class="overlay hidden">
                <h2 style="color: #00f800; text-shadow: 2px 2px #004400;">STAGE CLEAR!</h2>
                <p id="clearScoreText">SCORE: 000000</p>
                <p style="color: #fcbc00; font-size: 0.6rem;">PRESS [ENTER / SPACE]<br>FOR NEXT LEVEL</p>
            </div>

            <!-- Game Over Overlay -->
            <div id="gameOverOverlay" class="overlay hidden">
                <h2 style="color: #f83800;">GAME OVER</h2>
                <p id="finalScoreText">SCORE: 000000</p>
                <p style="color: #fcbc00; font-size: 0.6rem;">PRESS [ENTER / SPACE]<br>FOR MAIN MENU</p>
            </div>
        </div>

        <div class="side-panel">
            <div class="preview-container">
                <h3>NEXT</h3>
                <canvas id="nextCanvas" width="96" height="48"></canvas>
            </div>
            <div class="stats-box">
                <h3>SCORE</h3>
                <p id="scoreVal">000000</p>
            </div>
            <div class="stats-box">
                <h3>LEVEL</h3>
                <p id="levelVal">01</p>
            </div>
            <div class="stats-box">
                <h3>SPEED</h3>
                <p id="speedVal">MED</p>
            </div>
            <div class="stats-box">
                <h3>VIRUS</h3>
                <p id="virusVal" style="color: #f83800;">04</p>
            </div>
        </div>
    </div>

    <!-- Onscreen Touch Controls -->
    <div class="controls-grid">
        <div class="ctrl-btn" id="btnLeft">←</div>
        <div class="ctrl-btn" id="btnRotate">↻ (SPACE)</div>
        <div class="ctrl-btn" id="btnRight">→</div>
        <div class="ctrl-btn" id="btnDown">↓ SOFT</div>
        <div class="ctrl-btn wide" id="btnRotateWide">ROTATE CAPSULE [ SPACE ]</div>
    </div>

    <div class="footer-credits">
        PORT BY BLUEDEV - NOV 24, 2026
    </div>
</div>

<script>
    // --- WEB AUDIO API SYNTHESIZER & FEVER THEME ---
    let audioCtx = null;
    let audioEnabled = true;
    let musicInterval = null;

    function initAudio() {
        if (!audioCtx) {
            audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        }
        if (audioCtx.state === 'suspended') {
            audioCtx.resume();
        }
    }

    function playSound(type) {
        if (!audioEnabled || !audioCtx) return;
        try {
            const osc = audioCtx.createOscillator();
            const gain = audioCtx.createGain();
            osc.connect(gain);
            gain.connect(audioCtx.destination);
            const now = audioCtx.currentTime;

            if (type === 'move') {
                osc.type = 'square';
                osc.frequency.setValueAtTime(180, now);
                osc.frequency.exponentialRampToValueAtTime(120, now + 0.04);
                gain.gain.setValueAtTime(0.2, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.04);
                osc.start(now);
                osc.stop(now + 0.04);
            } else if (type === 'rotate') {
                osc.type = 'triangle';
                osc.frequency.setValueAtTime(350, now);
                osc.frequency.exponentialRampToValueAtTime(550, now + 0.07);
                gain.gain.setValueAtTime(0.24, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.07);
                osc.start(now);
                osc.stop(now + 0.07);
            } else if (type === 'land') {
                osc.type = 'square';
                osc.frequency.setValueAtTime(130, now);
                osc.frequency.exponentialRampToValueAtTime(45, now + 0.08);
                gain.gain.setValueAtTime(0.28, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.08);
                osc.start(now);
                osc.stop(now + 0.08);
            } else if (type === 'clear') {
                osc.type = 'square';
                osc.frequency.setValueAtTime(440, now);
                osc.frequency.setValueAtTime(587.33, now + 0.07);
                osc.frequency.setValueAtTime(783.99, now + 0.14);
                gain.gain.setValueAtTime(0.28, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.28);
                osc.start(now);
                osc.stop(now + 0.28);
            } else if (type === 'virusKill') {
                osc.type = 'sawtooth';
                osc.frequency.setValueAtTime(600, now);
                osc.frequency.exponentialRampToValueAtTime(950, now + 0.15);
                gain.gain.setValueAtTime(0.3, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
                osc.start(now);
                osc.stop(now + 0.15);
            } else if (type === 'win') {
                osc.type = 'square';
                [523.25, 659.25, 783.99, 1046.5].forEach((freq, i) => {
                    osc.frequency.setValueAtTime(freq, now + i * 0.1);
                });
                gain.gain.setValueAtTime(0.3, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.5);
                osc.start(now);
                osc.stop(now + 0.5);
            } else if (type === 'gameover') {
                osc.type = 'sawtooth';
                osc.frequency.setValueAtTime(240, now);
                osc.frequency.linearRampToValueAtTime(65, now + 0.6);
                gain.gain.setValueAtTime(0.3, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.6);
                osc.start(now);
                osc.stop(now + 0.6);
            } else if (type === 'menu') {
                osc.type = 'sine';
                osc.frequency.setValueAtTime(440, now);
                osc.frequency.exponentialRampToValueAtTime(660, now + 0.05);
                gain.gain.setValueAtTime(0.22, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
                osc.start(now);
                osc.stop(now + 0.05);
            }
        } catch(e) {}
    }

    // Upbeat Dr. Mario "Fever"-inspired Chiptune Loop
    const feverMelody = [
        {f: 466.16, d: 140}, {f: 493.88, d: 140}, {f: 466.16, d: 140}, {f: 493.88, d: 140},
        {f: 440.00, d: 140}, {f: 392.00, d: 140}, {f: 392.00, d: 140}, {f: 440.00, d: 140},
        {f: 466.16, d: 140}, {f: 493.88, d: 140}, {f: 440.00, d: 140}, {f: 392.00, d: 280},
        {f: 0, d: 140},
        {f: 466.16, d: 140}, {f: 493.88, d: 140}, {f: 466.16, d: 140}, {f: 493.88, d: 140},
        {f: 440.00, d: 140}, {f: 392.00, d: 140}, {f: 392.00, d: 140}, {f: 440.00, d: 140},
        {f: 587.33, d: 280}, {f: 523.25, d: 280}, {f: 0, d: 140}
    ];
    let noteIndex = 0;

    function startBackgroundMusic() {
        if (!audioEnabled || musicInterval) return;
        musicInterval = setInterval(() => {
            if (!audioEnabled || !gameStarted || gameOver || stageCleared || !audioCtx) return;
            const note = feverMelody[noteIndex];
            noteIndex = (noteIndex + 1) % feverMelody.length;
            if (note.f > 0) {
                try {
                    const osc = audioCtx.createOscillator();
                    const gain = audioCtx.createGain();
                    osc.type = 'triangle';
                    osc.frequency.setValueAtTime(note.f, audioCtx.currentTime);
                    gain.gain.setValueAtTime(0.08, audioCtx.currentTime);
                    gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + (note.d / 1000) * 0.9);
                    osc.connect(gain);
                    gain.connect(audioCtx.destination);
                    osc.start();
                    osc.stop(audioCtx.currentTime + note.d / 1000);
                } catch(e) {}
            }
        }, 165);
    }

    function stopBackgroundMusic() {
        if (musicInterval) {
            clearInterval(musicInterval);
            musicInterval = null;
        }
        noteIndex = 0;
    }

    // --- GAME CONSTANTS & GRID SETUP ---
    const canvas = document.getElementById('bottle');
    const ctx = canvas.getContext('2d');
    const nextCanvas = document.getElementById('nextCanvas');
    const nextCtx = nextCanvas.getContext('2d');

    const COLS = 8;
    const ROWS = 16;
    const CELL = 24; // 8 * 24 = 192px width, 16 * 24 = 384px height

    // Colors: 1 = Red, 2 = Yellow, 3 = Blue
    const PALETTE = {
        1: { main: '#f83800', light: '#ff9878', dark: '#a81000' }, // Red
        2: { main: '#fcbc00', light: '#ffe878', dark: '#a87000' }, // Yellow
        3: { main: '#0078f8', light: '#78b8ff', dark: '#0038a8' }  // Blue
    };

    // Grid cell object: null or { color: 1|2|3, type: 'virus'|'pill', id: number }
    let grid = [];
    let nextPillId = 1;

    // Active falling capsule (2 halves)
    let capsule = null;
    let nextCapsuleColors = [1, 3];

    // Game State
    let score = 0;
    let level = 1;
    let speedIndex = 1; // 0: LOW, 1: MED, 2: HI
    const SPEED_NAMES = ['LOW', 'MED', 'HI'];
    const SPEED_DELAYS = [750, 480, 260];

    let dropCounter = 0;
    let dropInterval = 480;
    let normalDropInterval = 480;
    let softDropping = false;
    let lastTime = 0;
    let animTick = 0;

    let gameStarted = false;
    let gameOver = false;
    let stageCleared = false;
    let isResolving = false; // True while clearing matches & dropping loose pill halves
    let menuSelection = 0;

    function updateMenuDisplay() {
        document.getElementById('valLevel').innerText = String(level).padStart(2, '0');
        document.getElementById('valSpeed').innerText = SPEED_NAMES[speedIndex];
        document.getElementById('valMusic').innerText = audioEnabled ? 'ON' : 'OFF';

        ['rowLevel', 'rowSpeed', 'rowMusic'].forEach((id, idx) => {
            const el = document.getElementById(id);
            if (idx === menuSelection) el.classList.add('selected');
            else el.classList.remove('selected');
        });
    }

    function createEmptyGrid() {
        grid = Array.from({ length: ROWS }, () => Array(COLS).fill(null));
    }

    function populateViruses(lvl) {
        createEmptyGrid();
        // Number of viruses scales with level (capped so top 4 rows stay clear)
        const virusCount = Math.min(48, lvl * 4);
        const minRow = Math.max(4, 13 - Math.floor(lvl / 2));

        let placed = 0;
        let attempts = 0;
        while (placed < virusCount && attempts < 2000) {
            attempts++;
            const r = Math.floor(Math.random() * (ROWS - minRow)) + minRow;
            const c = Math.floor(Math.random() * COLS);
            if (grid[r][c] !== null) continue;

            const color = Math.floor(Math.random() * 3) + 1;

            // Avoid creating 3-in-a-row of the same color right on spawn
            const hMatch = (c >= 2 && grid[r][c-1]?.color === color && grid[r][c-2]?.color === color) ||
                           (c <= COLS-3 && grid[r][c+1]?.color === color && grid[r][c+2]?.color === color) ||
                           (c >= 1 && c <= COLS-2 && grid[r][c-1]?.color === color && grid[r][c+1]?.color === color);
            const vMatch = (r >= 2 && grid[r-1][c]?.color === color && grid[r-2][c]?.color === color) ||
                           (r <= ROWS-3 && grid[r+1][c]?.color === color && grid[r+2][c]?.color === color) ||
                           (r >= 1 && r <= ROWS-2 && grid[r-1][c]?.color === color && grid[r+1][c]?.color === color);

            if (!hMatch && !vMatch) {
                grid[r][c] = { color, type: 'virus', id: 0 };
                placed++;
            }
        }
        updateHUD();
    }

    function countViruses() {
        let count = 0;
        for (let r = 0; r < ROWS; r++) {
            for (let c = 0; c < COLS; c++) {
                if (grid[r][c] && grid[r][c].type === 'virus') count++;
            }
        }
        return count;
    }

    function randomColor() {
        return Math.floor(Math.random() * 3) + 1;
    }

    function spawnCapsule() {
        const c1 = nextCapsuleColors[0];
        const c2 = nextCapsuleColors[1];
        nextCapsuleColors = [randomColor(), randomColor()];

        // Spawn horizontally at columns 3 & 4, row 0
        capsule = {
            x: 3,
            y: 0,
            dir: 0, // 0: horizontal (right), 1: vertical (down), 2: horizontal (left), 3: vertical (up)
            colors: [c1, c2],
            id: nextPillId++
        };

        // Check bottle neck clog (Game Over)
        const cells = getCapsuleCells(capsule);
        for (const cell of cells) {
            if (grid[cell.y][cell.x] !== null) {
                gameOver = true;
                stopBackgroundMusic();
                playSound('gameover');
                document.getElementById('finalScoreText').innerText = `SCORE: ${String(score).padStart(6, '0')}`;
                document.getElementById('gameOverOverlay').classList.remove('hidden');
                return;
            }
        }
        drawNextPreview();
    }

    function getCapsuleCells(cap) {
        const { x, y, dir, colors } = cap;
        if (dir === 0) return [{ x, y, color: colors[0] }, { x: x + 1, y, color: colors[1] }];
        if (dir === 1) return [{ x, y, color: colors[0] }, { x, y: y + 1, color: colors[1] }];
        if (dir === 2) return [{ x: x + 1, y, color: colors[0] }, { x, y, color: colors[1] }];
        if (dir === 3) return [{ x, y: y + 1, color: colors[0] }, { x, y, color: colors[1] }];
    }

    function isValidPosition(cap) {
        const cells = getCapsuleCells(cap);
        for (const cell of cells) {
            if (cell.x < 0 || cell.x >= COLS || cell.y < 0 || cell.y >= ROWS) return false;
            if (grid[cell.y][cell.x] !== null) return false;
        }
        return true;
    }

    function moveCapsule(dx) {
        if (!capsule || isResolving) return;
        capsule.x += dx;
        if (!isValidPosition(capsule)) {
            capsule.x -= dx;
        } else {
            playSound('move');
        }
    }

    function rotateCapsule() {
        if (!capsule || isResolving) return;
        const oldDir = capsule.dir;
        const oldX = capsule.x;
        capsule.dir = (capsule.dir + 1) % 4;

        // Basic wall kick if rotating horizontally against the right wall
        if (!isValidPosition(capsule)) {
            capsule.x -= 1;
            if (!isValidPosition(capsule)) {
                capsule.x = oldX;
                capsule.dir = oldDir;
                return;
            }
        }
        playSound('rotate');
    }

    async function lockAndResolve() {
        isResolving = true;
        const cells = getCapsuleCells(capsule);
        for (const cell of cells) {
            grid[cell.y][cell.x] = {
                color: cell.color,
                type: 'pill',
                id: capsule.id
            };
        }
        capsule = null;
        playSound('land');
        draw();

        let chainMultiplier = 1;
        while (true) {
            const matched = findAndClearMatches(chainMultiplier);
            if (!matched) break;

            chainMultiplier++;
            updateHUD();
            draw();
            await sleep(220);

            // Apply gravity to unsupported pill halves until everything settles
            while (applyCascadeGravity()) {
                draw();
                await sleep(110);
            }
        }

        if (countViruses() === 0) {
            stageCleared = true;
            stopBackgroundMusic();
            playSound('win');
            document.getElementById('clearScoreText').innerText = `SCORE: ${String(score).padStart(6, '0')}`;
            document.getElementById('stageClearOverlay').classList.remove('hidden');
            isResolving = false;
            return;
        }

        isResolving = false;
        spawnCapsule();
    }

    function findAndClearMatches(multiplier) {
        const toClear = Array.from({ length: ROWS }, () => Array(COLS).fill(false));
        let foundAny = false;

        // Horizontal 4+ check
        for (let r = 0; r < ROWS; r++) {
            let streak = 1;
            for (let c = 1; c <= COLS; c++) {
                const curr = c < COLS ? grid[r][c]?.color : null;
                const prev = grid[r][c - 1]?.color;
                if (curr && curr === prev) {
                    streak++;
                } else {
                    if (streak >= 4) {
                        foundAny = true;
                        for (let k = c - streak; k < c; k++) toClear[r][k] = true;
                    }
                    streak = 1;
                }
            }
        }

        // Vertical 4+ check
        for (let c = 0; c < COLS; c++) {
            let streak = 1;
            for (let r = 1; r <= ROWS; r++) {
                const curr = r < ROWS ? grid[r][c]?.color : null;
                const prev = grid[r - 1][c]?.color;
                if (curr && curr === prev) {
                    streak++;
                } else {
                    if (streak >= 4) {
                        foundAny = true;
                        for (let k = r - streak; k < r; k++) toClear[k][c] = true;
                    }
                    streak = 1;
                }
            }
        }

        if (!foundAny) return false;

        let virusesEliminated = 0;
        for (let r = 0; r < ROWS; r++) {
            for (let c = 0; c < COLS; c++) {
                if (toClear[r][c]) {
                    if (grid[r][c]?.type === 'virus') virusesEliminated++;
                    grid[r][c] = null;
                }
            }
        }

        if (virusesEliminated > 0) {
            score += virusesEliminated * 100 * multiplier;
            playSound('virusKill');
        } else {
            score += 40 * multiplier;
            playSound('clear');
        }

        return true;
    }

    function applyCascadeGravity() {
        let moved = false;
        // Scan bottom-up
        for (let r = ROWS - 2; r >= 0; r--) {
            for (let c = 0; c < COLS; c++) {
                const item = grid[r][c];
                if (!item || item.type === 'virus') continue;

                // Check if connected horizontally to its partner pill half
                const leftPartner = c > 0 && grid[r][c - 1]?.type === 'pill' && grid[r][c - 1]?.id === item.id;
                const rightPartner = c < COLS - 1 && grid[r][c + 1]?.type === 'pill' && grid[r][c + 1]?.id === item.id;

                if (leftPartner) {
                    // Handled when scanning c - 1
                    continue;
                } else if (rightPartner) {
                    // Horizontal full capsule: needs BOTH cells below empty
                    if (grid[r + 1][c] === null && grid[r + 1][c + 1] === null) {
                        grid[r + 1][c] = item;
                        grid[r + 1][c + 1] = grid[r][c + 1];
                        grid[r][c] = null;
                        grid[r][c + 1] = null;
                        moved = true;
                    }
                } else {
                    // Single pill half or vertical stack
                    if (grid[r + 1][c] === null) {
                        grid[r + 1][c] = item;
                        grid[r][c] = null;
                        moved = true;
                    }
                }
            }
        }
        return moved;
    }

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function stepDrop() {
        if (!capsule || isResolving) return;
        capsule.y += 1;
        if (!isValidPosition(capsule)) {
            capsule.y -= 1;
            lockAndResolve();
        }
        dropCounter = 0;
    }

    // --- RENDERING ---
    function drawCell(context, x, y, colorIdx, type, animFrame) {
        const pal = PALETTE[colorIdx];
        const px = x * CELL;
        const py = y * CELL;

        if (type === 'virus') {
            // Animated retro virus sprite
            const bounce = animFrame % 2 === 0 ? 0 : 1;
            context.fillStyle = pal.main;
            context.fillRect(px + 3, py + 4 + bounce, CELL - 6, CELL - 7);
            context.fillRect(px + 2, py + 7 + bounce, CELL - 4, CELL - 12);

            // Horns / Antennae
            context.fillStyle = pal.light;
            context.fillRect(px + 4, py + 2 + bounce, 3, 3);
            context.fillRect(px + CELL - 7, py + 2 + bounce, 3, 3);

            // Eyes
            context.fillStyle = '#ffffff';
            context.fillRect(px + 6, py + 8 + bounce, 4, 4);
            context.fillRect(px + CELL - 10, py + 8 + bounce, 4, 4);
            context.fillStyle = '#000000';
            context.fillRect(px + 7, py + 9 + bounce, 2, 2);
            context.fillRect(px + CELL - 9, py + 9 + bounce, 2, 2);

            // Mouth
            context.fillStyle = '#000000';
            context.fillRect(px + 7, py + 15 + bounce, CELL - 14, 2);
        } else {
            // Glossy NES Pill Segment
            context.fillStyle = pal.main;
            context.fillRect(px + 2, py + 2, CELL - 4, CELL - 4);

            // Top-left highlight
            context.fillStyle = pal.light;
            context.fillRect(px + 4, py + 4, CELL - 10, 3);
            context.fillRect(px + 4, py + 4, 3, CELL - 10);

            // Bottom-right shadow
            context.fillStyle = pal.dark;
            context.fillRect(px + 3, py + CELL - 5, CELL - 5, 3);
            context.fillRect(px + CELL - 5, py + 3, 3, CELL - 5);
        }
    }

    function drawNextPreview() {
        nextCtx.fillStyle = '#000000';
        nextCtx.fillRect(0, 0, nextCanvas.width, nextCanvas.height);

        // Center 2-cell pill inside 96x48 canvas (4x2 cells of 24px)
        drawCell(nextCtx, 1, 0.5, nextCapsuleColors[0], 'pill', 0);
        drawCell(nextCtx, 2, 0.5, nextCapsuleColors[1], 'pill', 0);
    }

    function draw() {
        ctx.fillStyle = '#050510';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // Subtle grid dots for spatial clarity
        ctx.fillStyle = '#141428';
        for (let r = 1; r < ROWS; r++) {
            for (let c = 1; c < COLS; c++) {
                ctx.fillRect(c * CELL - 1, r * CELL - 1, 2, 2);
            }
        }

        const animFrame = Math.floor(animTick / 350);

        for (let r = 0; r < ROWS; r++) {
            for (let c = 0; c < COLS; c++) {
                const cell = grid[r][c];
                if (cell) {
                    drawCell(ctx, c, r, cell.color, cell.type, animFrame);
                }
            }
        }

        if (capsule) {
            const cells = getCapsuleCells(capsule);
            for (const cell of cells) {
                drawCell(ctx, cell.x, cell.y, cell.color, 'pill', animFrame);
            }
        }
    }

    function updateHUD() {
        document.getElementById('scoreVal').innerText = String(score).padStart(6, '0');
        document.getElementById('levelVal').innerText = String(level).padStart(2, '0');
        document.getElementById('speedVal').innerText = SPEED_NAMES[speedIndex];
        document.getElementById('virusVal').innerText = String(countViruses()).padStart(2, '0');
    }

    function startStage() {
        normalDropInterval = SPEED_DELAYS[speedIndex];
        dropInterval = softDropping ? 45 : normalDropInterval;
        stageCleared = false;
        gameOver = false;
        isResolving = false;
        nextCapsuleColors = [randomColor(), randomColor()];
        populateViruses(level);
        spawnCapsule();
        lastTime = performance.now();
        requestAnimationFrame(update);
        if (audioEnabled) startBackgroundMusic();
    }

    function update(time = 0) {
        if (!gameStarted || gameOver || stageCleared) return;

        const deltaTime = time - lastTime;
        lastTime = time;
        animTick += deltaTime;

        if (!isResolving) {
            dropCounter += deltaTime;
            if (dropCounter > dropInterval) {
                stepDrop();
            }
        }

        draw();
        requestAnimationFrame(update);
    }

    // --- CONTROLS ---
    document.addEventListener('keydown', event => {
        initAudio();

        const menuOverlay = document.getElementById('menuOverlay');
        const gameOverOverlay = document.getElementById('gameOverOverlay');
        const stageClearOverlay = document.getElementById('stageClearOverlay');

        const isMenu = !menuOverlay.classList.contains('hidden');
        const isOver = !gameOverOverlay.classList.contains('hidden');
        const isClear = !stageClearOverlay.classList.contains('hidden');

        if (isMenu) {
            if (event.key === 'ArrowUp') {
                menuSelection = (menuSelection + 2) % 3;
                playSound('menu');
                updateMenuDisplay();
            } else if (event.key === 'ArrowDown') {
                menuSelection = (menuSelection + 1) % 3;
                playSound('menu');
                updateMenuDisplay();
            } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
                const dir = event.key === 'ArrowRight' ? 1 : -1;
                if (menuSelection === 0) {
                    level = Math.max(1, Math.min(20, level + dir));
                } else if (menuSelection === 1) {
                    speedIndex = (speedIndex + dir + 3) % 3;
                } else {
                    audioEnabled = !audioEnabled;
                }
                playSound('menu');
                updateMenuDisplay();
            } else if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                playSound('rotate');
                score = 0;
                menuOverlay.classList.add('hidden');
                gameStarted = true;
                startStage();
            }
            return;
        }

        if (isClear) {
            if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                stageClearOverlay.classList.add('hidden');
                level++;
                startStage();
            }
            return;
        }

        if (isOver) {
            if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                gameOverOverlay.classList.add('hidden');
                menuOverlay.classList.remove('hidden');
                gameStarted = false;
                updateMenuDisplay();
            }
            return;
        }

        if (!gameStarted || gameOver || isResolving) return;

        if (event.key === 'ArrowLeft') {
            moveCapsule(-1);
        } else if (event.key === 'ArrowRight') {
            moveCapsule(1);
        } else if (event.key === 'ArrowDown') {
            if (!softDropping) {
                softDropping = true;
                dropInterval = 45;
            }
        } else if (event.key === 'ArrowUp' || event.key === 'x' || event.key === 'z' || event.key === ' ') {
            event.preventDefault();
            rotateCapsule();
        }
    });

    document.addEventListener('keyup', event => {
        if (event.key === 'ArrowDown') {
            softDropping = false;
            dropInterval = normalDropInterval;
        }
    });

    function bindTouchButton(id, actionPress, actionRelease) {
        const btn = document.getElementById(id);
        if (!btn) return;

        btn.addEventListener('touchstart', (e) => {
            e.preventDefault();
            initAudio();
            btn.classList.add('active-touch');
            if (actionPress) actionPress();
        }, { passive: false });

        btn.addEventListener('touchend', (e) => {
            e.preventDefault();
            btn.classList.remove('active-touch');
            if (actionRelease) actionRelease();
        }, { passive: false });

        btn.addEventListener('pointerdown', () => {
            initAudio();
            btn.classList.add('active-touch');
            if (actionPress) actionPress();
        });

        btn.addEventListener('pointerup', () => {
            btn.classList.remove('active-touch');
            if (actionRelease) actionRelease();
        });
    }

    bindTouchButton('btnLeft', () => { if (gameStarted && !gameOver) moveCapsule(-1); });
    bindTouchButton('btnRight', () => { if (gameStarted && !gameOver) moveCapsule(1); });
    bindTouchButton('btnRotate', () => { if (gameStarted && !gameOver) rotateCapsule(); });
    bindTouchButton('btnRotateWide', () => { if (gameStarted && !gameOver) rotateCapsule(); });
    bindTouchButton('btnDown',
        () => { if (gameStarted && !gameOver) { softDropping = true; dropInterval = 45; } },
        () => { softDropping = false; dropInterval = normalDropInterval; }
    );

    updateMenuDisplay();
</script>

</body>
</html>

Game Source: NES DR. MARIO - ArcadeLab

Creator: PixelStar14

Libraries: none

Complexity: complex (1013 lines, 35.7 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: nes-dr-mario-arcadelab-pixelstar14" to link back to the original. Then publish at arcadelab.ai/publish.