Thompson gun

Pasted Nov 22, 2026, 10:04 AM1 file1,310 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgrzd7gfra0kra7
sin-titulo
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simulador de Disparo 2D - Thompson M1928</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Chakra+Petch:ital,wght@0,500;0,700;1,700&family=Inter:wght@400;600;800&display=swap');

        body {
            font-family: 'Inter', sans-serif;
            background-color: #0d1117;
            color: #e6edf3;
            overflow: hidden;
            user-select: none;
            -webkit-user-select: none;
        }

        .font-tactical {
            font-family: 'Chakra Petch', sans-serif;
        }

        canvas {
            display: block;
            width: 100%;
            height: 100%;
            cursor: crosshair;
        }

        /* Custom subtle scanline & tactical grid background */
        .tactical-bg {
            background-color: #11161d;
            background-image: 
                radial-gradient(circle at 50% 45%, rgba(45, 58, 75, 0.35) 0%, rgba(13, 17, 23, 0.95) 85%),
                linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
                linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
            background-size: 100% 100%, 40px 40px, 40px 40px;
        }

        .btn-tactical {
            transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .btn-tactical:active {
            transform: scale(0.95);
        }
    </style>
</head>
<body class="w-screen h-screen flex flex-col tactical-bg relative">

    <!-- Top HUD Bar -->
    <header class="w-full px-4 py-3 sm:px-8 sm:py-4 flex flex-wrap items-center justify-between gap-3 z-10 pointer-events-none">
        <div class="flex items-center gap-3 pointer-events-auto bg-slate-900/80 backdrop-blur-md border border-slate-700/70 px-4 py-2 rounded-xl shadow-lg">
            <div class="w-3 h-3 rounded-full bg-amber-500 animate-pulse"></div>
            <div>
                <h1 class="font-tactical font-bold text-base sm:text-xl tracking-wider text-amber-400 uppercase leading-none">
                    THOMPSON M1928A1
                </h1>
                <p class="text-[11px] sm:text-xs text-slate-400 mt-0.5">Calibre .45 ACP • Tambor 50 Balas</p>
            </div>
        </div>

        <!-- Ammo & Controls HUD -->
        <div class="flex items-center gap-2 sm:gap-3 pointer-events-auto">
            <!-- Fire Mode Selector -->
            <button id="fireModeBtn" class="btn-tactical bg-slate-900/85 hover:bg-slate-800 backdrop-blur-md border border-slate-700 px-3 py-2 rounded-xl text-xs sm:text-sm font-tactical font-bold text-emerald-400 shadow-lg flex items-center gap-1.5" title="Cambiar modo de disparo (B)">
                <span class="w-2 h-2 rounded-full bg-emerald-400"></span>
                <span id="fireModeText">AUTO</span>
            </button>

            <!-- Sound Toggle -->
            <button id="muteBtn" class="btn-tactical bg-slate-900/85 hover:bg-slate-800 backdrop-blur-md border border-slate-700 p-2.5 rounded-xl text-slate-200 shadow-lg" title="Silenciar / Activar Sonido (M)">
                <svg id="iconSoundOn" class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"></path>
                </svg>
                <svg id="iconSoundOff" class="w-5 h-5 text-rose-500 hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15zM17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"></path>
                </svg>
            </button>

            <!-- Reload Button -->
            <button id="reloadBtn" class="btn-tactical bg-amber-500 hover:bg-amber-400 text-slate-950 font-tactical font-bold px-3.5 py-2 rounded-xl text-xs sm:text-sm shadow-lg shadow-amber-500/20 flex items-center gap-1.5">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
                <span>RECARGAR [R]</span>
            </button>
        </div>
    </header>

    <!-- Main Interactive Canvas -->
    <main class="flex-1 w-full h-full relative">
        <canvas id="gameCanvas"></canvas>

        <!-- Reload Status Banner -->
        <div id="reloadOverlay" class="hidden absolute top-1/4 left-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none bg-slate-900/90 border border-amber-500/60 px-6 py-2.5 rounded-full shadow-2xl flex items-center gap-3">
            <div class="w-4 h-4 border-2 border-amber-400 border-t-transparent rounded-full animate-spin"></div>
            <span class="font-tactical font-bold text-amber-400 tracking-widest text-sm sm:text-base">RECARGANDO TAMBOR...</span>
        </div>
    </main>

    <!-- Bottom Status & Controls Bar -->
    <footer class="w-full px-4 py-3 sm:px-8 sm:py-4 flex flex-wrap items-center justify-between gap-3 z-10 pointer-events-none">
        <!-- Instructions -->
        <div class="bg-slate-900/80 backdrop-blur-md border border-slate-700/70 px-4 py-2 rounded-xl text-xs text-slate-300 flex flex-wrap items-center gap-x-4 gap-y-1 shadow-lg">
            <span><strong class="text-amber-400">Clic / Espacio:</strong> Disparar</span>
            <span class="hidden sm:inline text-slate-600">|</span>
            <span><strong class="text-amber-400">Ratón / Toque:</strong> Apuntar</span>
            <span class="hidden sm:inline text-slate-600">|</span>
            <span><strong class="text-amber-400">[R]:</strong> Recargar</span>
            <span class="hidden sm:inline text-slate-600">|</span>
            <span><strong class="text-amber-400">[B]:</strong> Modo</span>
        </div>

        <!-- Ammo Counter Display -->
        <div class="bg-slate-900/90 backdrop-blur-md border border-slate-700/80 px-5 py-2.5 rounded-2xl shadow-xl flex items-center gap-4 pointer-events-auto">
            <div class="flex flex-col">
                <span class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Munición</span>
                <div class="flex items-baseline gap-1 font-tactical">
                    <span id="ammoCount" class="text-2xl sm:text-3xl font-bold text-amber-400">50</span>
                    <span class="text-sm text-slate-500 font-bold">/ 50</span>
                </div>
            </div>
            <!-- Visual Ammo Bar -->
            <div class="w-24 sm:w-32 h-3 bg-slate-800 rounded-full overflow-hidden border border-slate-700 p-0.5">
                <div id="ammoBar" class="h-full bg-gradient-to-r from-amber-500 to-yellow-300 rounded-full transition-all duration-75" style="width: 100%;"></div>
            </div>
        </div>
    </footer>

    <script>
        /**
         * ============================================================================
         * SIMULADOR DE DISPARO 2D - THOMPSON M1928A1 (ESTILO VECTORIAL CARTOON)
         * ============================================================================
         * Incluye:
         * - Dibujo vectorial detallado fiel a la imagen de referencia (culata y empuñaduras
         *   de madera marrón con ranuras para dedos, cuerpo metálico gris oscuro, tambor
         *   circular con relieves, cañón largo con compensador Cutts y contornos negros).
         * - Mecánica de retroceso físico (kickback + elevación angular).
         * - Cerrojo animado que retrocede en cada disparo.
         * - Fogonazo multicapa dinámico y luz ambiental proyectada.
         * - Trazadoras de alta velocidad con estela luminosa y chispas de impacto.
         * - Expulsión física de casquillos de latón giratorios con rebote y sonido metálico.
         * - Partículas de humo flotante desde el cañón y la recámara.
         * - Sintetizador de audio Web Audio API (sin archivos externos).
         */

        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');

        // UI Elements
        const ammoCountEl = document.getElementById('ammoCount');
        const ammoBarEl = document.getElementById('ammoBar');
        const reloadBtn = document.getElementById('reloadBtn');
        const reloadOverlay = document.getElementById('reloadOverlay');
        const muteBtn = document.getElementById('muteBtn');
        const iconSoundOn = document.getElementById('iconSoundOn');
        const iconSoundOff = document.getElementById('iconSoundOff');
        const fireModeBtn = document.getElementById('fireModeBtn');
        const fireModeText = document.getElementById('fireModeText');

        // Audio System (Web Audio API Synthesizer)
        class SoundEngine {
            constructor() {
                this.ctx = null;
                this.muted = false;
            }

            init() {
                if (!this.ctx) {
                    const AudioCtx = window.AudioContext || window.webkitAudioContext;
                    this.ctx = new AudioCtx();
                }
                if (this.ctx.state === 'suspended') {
                    this.ctx.resume();
                }
            }

            toggleMute() {
                this.muted = !this.muted;
                iconSoundOn.classList.toggle('hidden', this.muted);
                iconSoundOff.classList.toggle('hidden', !this.muted);
            }

            playGunshot() {
                if (this.muted) return;
                this.init();
                const now = this.ctx.currentTime;

                // 1. Punchy Low-End Thump (Oscillator)
                const osc = this.ctx.createOscillator();
                const oscGain = this.ctx.createGain();
                osc.type = 'triangle';
                osc.frequency.setValueAtTime(165, now);
                osc.frequency.exponentialRampToValueAtTime(38, now + 0.09);

                oscGain.gain.setValueAtTime(0.65, now);
                oscGain.gain.exponentialRampToValueAtTime(0.001, now + 0.11);

                osc.connect(oscGain);
                oscGain.connect(this.ctx.destination);
                osc.start(now);
                osc.stop(now + 0.12);

                // 2. Sharp Powder Crack (Filtered White Noise)
                const bufferSize = this.ctx.sampleRate * 0.16;
                const noiseBuffer = this.ctx.createBuffer(1, bufferSize, this.ctx.sampleRate);
                const output = noiseBuffer.getChannelData(0);
                for (let i = 0; i < bufferSize; i++) {
                    output[i] = (Math.random() * 2 - 1) * Math.exp(-i / (this.ctx.sampleRate * 0.035));
                }

                const whiteNoise = this.ctx.createBufferSource();
                whiteNoise.buffer = noiseBuffer;

                const filter = this.ctx.createBiquadFilter();
                filter.type = 'bandpass';
                filter.frequency.setValueAtTime(1100, now);
                filter.Q.value = 0.85;

                const noiseGain = this.ctx.createGain();
                noiseGain.gain.setValueAtTime(0.85, now);
                noiseGain.gain.exponentialRampToValueAtTime(0.01, now + 0.15);

                whiteNoise.connect(filter);
                filter.connect(noiseGain);
                noiseGain.connect(this.ctx.destination);
                whiteNoise.start(now);

                // 3. Metallic Bolt Clack
                const boltOsc = this.ctx.createOscillator();
                const boltGain = this.ctx.createGain();
                boltOsc.type = 'square';
                boltOsc.frequency.setValueAtTime(920, now + 0.015);
                boltOsc.frequency.exponentialRampToValueAtTime(320, now + 0.05);
                boltGain.gain.setValueAtTime(0.14, now + 0.015);
                boltGain.gain.exponentialRampToValueAtTime(0.001, now + 0.055);

                boltOsc.connect(boltGain);
                boltGain.connect(this.ctx.destination);
                boltOsc.start(now + 0.015);
                boltOsc.stop(now + 0.06);
            }

            playDryFire() {
                if (this.muted) return;
                this.init();
                const now = this.ctx.currentTime;
                const osc = this.ctx.createOscillator();
                const gain = this.ctx.createGain();
                osc.type = 'square';
                osc.frequency.setValueAtTime(1250, now);
                osc.frequency.exponentialRampToValueAtTime(450, now + 0.03);
                gain.gain.setValueAtTime(0.22, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.035);
                osc.connect(gain);
                gain.connect(this.ctx.destination);
                osc.start(now);
                osc.stop(now + 0.04);
            }

            playCasingBounce() {
                if (this.muted || !this.ctx) return;
                const now = this.ctx.currentTime;
                const osc = this.ctx.createOscillator();
                const gain = this.ctx.createGain();
                osc.type = 'sine';
                const pitch = 3600 + Math.random() * 900;
                osc.frequency.setValueAtTime(pitch, now);
                osc.frequency.exponentialRampToValueAtTime(pitch * 0.75, now + 0.035);
                gain.gain.setValueAtTime(0.045, now);
                gain.gain.exponentialRampToValueAtTime(0.0008, now + 0.04);
                osc.connect(gain);
                gain.connect(this.ctx.destination);
                osc.start(now);
                osc.stop(now + 0.045);
            }

            playReload() {
                if (this.muted) return;
                this.init();
                const now = this.ctx.currentTime;

                // Drum detach click
                this._mechClick(now + 0.05, 650, 280, 0.25);
                // Drum attach clunk
                this._mechClick(now + 0.65, 320, 780, 0.35);
                // Bolt pull & release
                this._mechClick(now + 1.05, 850, 1350, 0.25);
                this._mechClick(now + 1.22, 1200, 420, 0.3);
            }

            _mechClick(time, startFreq, endFreq, vol) {
                const osc = this.ctx.createOscillator();
                const gain = this.ctx.createGain();
                osc.type = 'sawtooth';
                osc.frequency.setValueAtTime(startFreq, time);
                osc.frequency.exponentialRampToValueAtTime(endFreq, time + 0.06);
                gain.gain.setValueAtTime(vol, time);
                gain.gain.exponentialRampToValueAtTime(0.001, time + 0.07);
                osc.connect(gain);
                gain.connect(this.ctx.destination);
                osc.start(time);
                osc.stop(time + 0.075);
            }
        }

        const sound = new SoundEngine();

        // Game & Physics State
        const state = {
            width: 0,
            height: 0,
            floorY: 0,
            mouseX: 0,
            mouseY: 0,
            hasMouseMoved: false,
            isTriggerHeld: false,
            fireMode: 'AUTO', // 'AUTO' | 'SEMI'
            canFireSemi: true,

            // Weapon Properties
            maxAmmo: 50,
            ammo: 50,
            isReloading: false,
            reloadProgress: 0,
            reloadDuration: 1.45, // seconds

            fireRate: 0.082, // ~730 RPM (authentic M1928A1 rate of fire)
            fireTimer: 0,

            // Gun Transform & Physics
            gunX: 0,
            gunY: 0,
            gunAngle: -0.22, // Default slight upward angle like reference
            targetAngle: -0.22,
            gunScale: 1,

            // Recoil & Animation Springs
            recoilOffset: 0,      // Backward kick along barrel axis
            recoilVelocity: 0,
            muzzleClimb: 0,       // Angular kick upward
            climbVelocity: 0,
            boltOffset: 0,        // Bolt reciprocation
            muzzleFlashTimer: 0,
            muzzleFlashAngle: 0,
            muzzleFlashScale: 1,
            screenShake: 0,

            // Particle Arrays
            bullets: [],
            casings: [],
            smoke: [],
            sparks: []
        };

        // Resize Handler
        function resizeCanvas() {
            const rect = canvas.parentElement.getBoundingClientRect();
            const dpr = window.devicePixelRatio || 1;
            canvas.width = rect.width * dpr;
            canvas.height = rect.height * dpr;
            ctx.scale(dpr, dpr);

            state.width = rect.width;
            state.height = rect.height;
            state.floorY = state.height * 0.86;

            // Position gun in lower-left/center-left area so bullets fly across screen
            state.gunX = Math.max(130, state.width * 0.28);
            state.gunY = state.height * 0.56;

            // Responsive scaling for mobile vs desktop
            const baseScale = Math.min(state.width / 720, state.height / 520);
            state.gunScale = Math.max(0.68, Math.min(1.45, baseScale * 1.15));

            if (!state.hasMouseMoved) {
                state.mouseX = state.gunX + 400;
                state.mouseY = state.gunY - 120;
            }
        }

        window.addEventListener('resize', resizeCanvas);

        // Input Listeners
        function updatePointer(clientX, clientY) {
            const rect = canvas.getBoundingClientRect();
            state.mouseX = clientX - rect.left;
            state.mouseY = clientY - rect.top;
            state.hasMouseMoved = true;
        }

        canvas.addEventListener('mousemove', (e) => {
            updatePointer(e.clientX, e.clientY);
        });

        canvas.addEventListener('mousedown', (e) => {
            if (e.button !== 0) return;
            updatePointer(e.clientX, e.clientY);
            state.isTriggerHeld = true;
            state.canFireSemi = true;
            sound.init();
        });

        window.addEventListener('mouseup', () => {
            state.isTriggerHeld = false;
            state.canFireSemi = true;
        });

        // Touch Support
        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            if (e.touches.length > 0) {
                updatePointer(e.touches[0].clientX, e.touches[0].clientY);
                state.isTriggerHeld = true;
                state.canFireSemi = true;
                sound.init();
            }
        }, { passive: false });

        canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (e.touches.length > 0) {
                updatePointer(e.touches[0].clientX, e.touches[0].clientY);
            }
        }, { passive: false });

        canvas.addEventListener('touchend', () => {
            state.isTriggerHeld = false;
            state.canFireSemi = true;
        });

        // Keyboard Controls
        window.addEventListener('keydown', (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                if (!state.isTriggerHeld) {
                    state.isTriggerHeld = true;
                    state.canFireSemi = true;
                    sound.init();
                }
            } else if (e.code === 'KeyR') {
                triggerReload();
            } else if (e.code === 'KeyM') {
                sound.toggleMute();
            } else if (e.code === 'KeyB') {
                toggleFireMode();
            }
        });

        window.addEventListener('keyup', (e) => {
            if (e.code === 'Space') {
                state.isTriggerHeld = false;
                state.canFireSemi = true;
            }
        });

        // UI Button Listeners
        reloadBtn.addEventListener('click', triggerReload);
        muteBtn.addEventListener('click', () => sound.toggleMute());
        fireModeBtn.addEventListener('click', toggleFireMode);

        function toggleFireMode() {
            state.fireMode = state.fireMode === 'AUTO' ? 'SEMI' : 'AUTO';
            fireModeText.textContent = state.fireMode;
            fireModeBtn.classList.toggle('text-emerald-400', state.fireMode === 'AUTO');
            fireModeBtn.classList.toggle('text-sky-400', state.fireMode === 'SEMI');
        }

        function triggerReload() {
            if (state.isReloading || state.ammo === state.maxAmmo) return;
            state.isReloading = true;
            state.reloadProgress = 0;
            reloadOverlay.classList.remove('hidden');
            sound.playReload();
        }

        function updateAmmoUI() {
            ammoCountEl.textContent = state.ammo;
            const pct = (state.ammo / state.maxAmmo) * 100;
            ammoBarEl.style.width = `${pct}%`;

            if (state.ammo <= 10) {
                ammoCountEl.className = 'text-2xl sm:text-3xl font-bold text-rose-500 animate-pulse';
                ammoBarEl.className = 'h-full bg-rose-500 rounded-full transition-all duration-75';
            } else {
                ammoCountEl.className = 'text-2xl sm:text-3xl font-bold text-amber-400';
                ammoBarEl.className = 'h-full bg-gradient-to-r from-amber-500 to-yellow-300 rounded-full transition-all duration-75';
            }
        }

        // Firing Mechanics
        function fireShot() {
            if (state.isReloading) return;

            if (state.ammo <= 0) {
                sound.playDryFire();
                state.fireTimer = 0.22;
                // Automatically trigger reload if user keeps clicking empty
                triggerReload();
                return;
            }

            state.ammo--;
            updateAmmoUI();
            sound.playGunshot();

            // Apply Recoil & Muzzle Climb
            state.recoilVelocity += 240; // Kick backward
            state.climbVelocity -= (0.045 + Math.random() * 0.035); // Kick upward
            state.boltOffset = 28; // Bolt slams back
            state.muzzleFlashTimer = 0.045;
            state.muzzleFlashAngle = (Math.random() - 0.5) * 0.45;
            state.muzzleFlashScale = 0.85 + Math.random() * 0.45;
            state.screenShake = Math.min(10, state.screenShake + 4.5);

            // Calculate World Coordinates of Muzzle & Ejection Port
            const currentAngle = state.gunAngle + state.muzzleClimb;
            const cos = Math.cos(currentAngle);
            const sin = Math.sin(currentAngle);

            // Local coordinates relative to gun pivot (0,0)
            const muzzleLocalX = (195 - state.recoilOffset) * state.gunScale;
            const muzzleLocalY = -12 * state.gunScale;

            const muzzleWorldX = state.gunX + (muzzleLocalX * cos - muzzleLocalY * sin);
            const muzzleWorldY = state.gunY + (muzzleLocalX * sin + muzzleLocalY * cos);

            // Spawn High-Velocity Tracer Bullet
            const spread = (Math.random() - 0.5) * 0.035;
            const bulletAngle = currentAngle + spread;
            const speed = 2600 + Math.random() * 300;

            state.bullets.push({
                x: muzzleWorldX,
                y: muzzleWorldY,
                vx: Math.cos(bulletAngle) * speed,
                vy: Math.sin(bulletAngle) * speed,
                angle: bulletAngle,
                length: 65 + Math.random() * 30,
                life: 1.0
            });

            // Spawn Muzzle Sparks
            for (let i = 0; i < 6; i++) {
                const sparkAngle = currentAngle + (Math.random() - 0.5) * 0.85;
                const sparkSpeed = 280 + Math.random() * 520;
                state.sparks.push({
                    x: muzzleWorldX,
                    y: muzzleWorldY,
                    vx: Math.cos(sparkAngle) * sparkSpeed,
                    vy: Math.sin(sparkAngle) * sparkSpeed,
                    life: 0.14 + Math.random() * 0.12,
                    maxLife: 0.26,
                    size: 2 + Math.random() * 2.5
                });
            }

            // Spawn Barrel Smoke
            for (let i = 0; i < 3; i++) {
                state.smoke.push({
                    x: muzzleWorldX + (Math.random() - 0.5) * 8,
                    y: muzzleWorldY + (Math.random() - 0.5) * 8,
                    vx: Math.cos(currentAngle) * (45 + Math.random() * 60) + (Math.random() - 0.5) * 20,
                    vy: Math.sin(currentAngle) * (45 + Math.random() * 60) - 25 - Math.random() * 25,
                    radius: (6 + Math.random() * 6) * state.gunScale,
                    alpha: 0.35 + Math.random() * 0.2,
                    life: 0.8 + Math.random() * 0.6,
                    maxLife: 1.4
                });
            }

            // Spawn Spinning Brass Shell Casing from Ejection Port
            const ejectLocalX = (18 - state.recoilOffset) * state.gunScale;
            const ejectLocalY = -20 * state.gunScale;
            const ejectWorldX = state.gunX + (ejectLocalX * cos - ejectLocalY * sin);
            const ejectWorldY = state.gunY + (ejectLocalX * sin + ejectLocalY * cos);

            // Eject upward and slightly backward/right
            const ejectAngle = currentAngle - Math.PI * 0.55 + (Math.random() - 0.5) * 0.35;
            const ejectSpeed = 210 + Math.random() * 110;

            state.casings.push({
                x: ejectWorldX,
                y: ejectWorldY,
                vx: Math.cos(ejectAngle) * ejectSpeed - 30,
                vy: Math.sin(ejectAngle) * ejectSpeed - 80,
                angle: Math.random() * Math.PI * 2,
                vAngle: (Math.random() > 0.5 ? 1 : -1) * (14 + Math.random() * 12),
                bounces: 0,
                alpha: 1.0,
                life: 4.5
            });

            // Small Chamber Smoke Puff
            state.smoke.push({
                x: ejectWorldX,
                y: ejectWorldY,
                vx: -15 + (Math.random() - 0.5) * 20,
                vy: -35 - Math.random() * 20,
                radius: 4 * state.gunScale,
                alpha: 0.25,
                life: 0.65,
                maxLife: 0.65
            });
        }

        // Update Loop
        function update(dt) {
            // Smooth Aiming toward Mouse Cursor
            const dx = state.mouseX - state.gunX;
            const dy = state.mouseY - state.gunY;
            let desiredAngle = Math.atan2(dy, dx);

            // Clamp angle so gun points generally forward (-75 deg to +45 deg)
            const minAngle = -Math.PI * 0.42;
            const maxAngle = Math.PI * 0.25;
            if (desiredAngle < minAngle && desiredAngle > -Math.PI) desiredAngle = minAngle;
            if (desiredAngle > maxAngle || desiredAngle <= -Math.PI) desiredAngle = maxAngle;

            state.targetAngle = desiredAngle;
            state.gunAngle += (state.targetAngle - state.gunAngle) * Math.min(1, dt * 18);

            // Reload Logic
            if (state.isReloading) {
                state.reloadProgress += dt / state.reloadDuration;
                if (state.reloadProgress >= 1) {
                    state.isReloading = false;
                    state.reloadProgress = 0;
                    state.ammo = state.maxAmmo;
                    updateAmmoUI();
                    reloadOverlay.classList.add('hidden');
                }
            }

            // Trigger & Fire Rate Logic
            if (state.fireTimer > 0) {
                state.fireTimer -= dt;
            }

            if (state.isTriggerHeld && !state.isReloading && state.fireTimer <= 0) {
                if (state.fireMode === 'AUTO') {
                    fireShot();
                    state.fireTimer = state.fireRate;
                } else if (state.fireMode === 'SEMI' && state.canFireSemi) {
                    fireShot();
                    state.fireTimer = state.fireRate;
                    state.canFireSemi = false;
                }
            }

            // Spring Physics for Recoil Kickback
            const springK = 260;
            const damping = 18;
            const accel = -springK * state.recoilOffset - damping * state.recoilVelocity;
            state.recoilVelocity += accel * dt;
            state.recoilOffset += state.recoilVelocity * dt;
            if (state.recoilOffset < 0) {
                state.recoilOffset = 0;
                state.recoilVelocity = 0;
            }

            // Spring Physics for Muzzle Climb
            const climbK = 140;
            const climbDamping = 14;
            const climbAccel = -climbK * state.muzzleClimb - climbDamping * state.climbVelocity;
            state.climbVelocity += climbAccel * dt;
            state.muzzleClimb += state.climbVelocity * dt;

            // Bolt Return
            if (state.boltOffset > 0) {
                state.boltOffset = Math.max(0, state.boltOffset - dt * 340);
            }

            // Muzzle Flash Decay
            if (state.muzzleFlashTimer > 0) {
                state.muzzleFlashTimer -= dt;
            }

            // Screen Shake Decay
            if (state.screenShake > 0) {
                state.screenShake = Math.max(0, state.screenShake - dt * 45);
            }

            // Update Tracer Bullets
            for (let i = state.bullets.length - 1; i >= 0; i--) {
                const b = state.bullets[i];
                b.x += b.vx * dt;
                b.y += b.vy * dt;
                b.life -= dt * 1.5;

                // Floor impact sparks if aimed downward
                if (b.y >= state.floorY) {
                    for (let s = 0; s < 5; s++) {
                        state.sparks.push({
                            x: b.x,
                            y: state.floorY,
                            vx: (Math.random() - 0.3) * 320,
                            vy: -Math.random() * 280 - 60,
                            life: 0.2,
                            maxLife: 0.2,
                            size: 2.2
                        });
                    }
                    state.bullets.splice(i, 1);
                    continue;
                }

                if (b.x > state.width + 200 || b.x < -200 || b.y < -200 || b.life <= 0) {
                    state.bullets.splice(i, 1);
                }
            }

            // Update Brass Shell Casings
            const gravity = 980;
            for (let i = state.casings.length - 1; i >= 0; i--) {
                const c = state.casings[i];
                c.vy += gravity * dt;
                c.x += c.vx * dt;
                c.y += c.vy * dt;
                c.angle += c.vAngle * dt;
                c.life -= dt;

                // Floor Bounce
                if (c.y >= state.floorY - 4) {
                    c.y = state.floorY - 4;
                    if (Math.abs(c.vy) > 45) {
                        c.vy = -c.vy * (0.42 + Math.random() * 0.15);
                        c.vx *= 0.68;
                        c.vAngle *= 0.65;
                        if (c.bounces < 2) {
                            sound.playCasingBounce();
                        }
                        c.bounces++;
                    } else {
                        c.vy = 0;
                        c.vx *= 0.85;
                        c.vAngle *= 0.8;
                    }
                }

                if (c.life < 1.0) {
                    c.alpha = Math.max(0, c.life);
                }

                if (c.life <= 0) {
                    state.casings.splice(i, 1);
                }
            }

            // Update Smoke Particles
            for (let i = state.smoke.length - 1; i >= 0; i--) {
                const p = state.smoke[i];
                p.x += p.vx * dt;
                p.y += p.vy * dt;
                p.vx *= 0.96;
                p.vy -= 12 * dt; // Buoyancy
                p.radius += 18 * dt;
                p.life -= dt;
                if (p.life <= 0) {
                    state.smoke.splice(i, 1);
                }
            }

            // Update Sparks
            for (let i = state.sparks.length - 1; i >= 0; i--) {
                const s = state.sparks[i];
                s.vy += 450 * dt;
                s.x += s.vx * dt;
                s.y += s.vy * dt;
                s.life -= dt;
                if (s.life <= 0) {
                    state.sparks.splice(i, 1);
                }
            }
        }

        // ============================================================================
        // VECTOR DRAWING FUNCTIONS (MATCHING REFERENCE IMAGE)
        // ============================================================================

        function drawEnvironment() {
            // Subtle Range Floor Line & Reflection
            const floorGrad = ctx.createLinearGradient(0, state.floorY, 0, state.height);
            floorGrad.addColorStop(0, 'rgba(30, 41, 59, 0.75)');
            floorGrad.addColorStop(1, 'rgba(13, 17, 23, 0.98)');
            ctx.fillStyle = floorGrad;
            ctx.fillRect(0, state.floorY, state.width, state.height - state.floorY);

            // Floor Horizon Line
            ctx.strokeStyle = 'rgba(148, 163, 184, 0.25)';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(0, state.floorY);
            ctx.lineTo(state.width, state.floorY);
            ctx.stroke();

            // Distance Markers on Floor
            ctx.fillStyle = 'rgba(148, 163, 184, 0.2)';
            ctx.font = '600 11px "Chakra Petch", sans-serif';
            for (let x = 100; x < state.width; x += 180) {
                ctx.fillRect(x, state.floorY, 2, 8);
                ctx.fillText(`${Math.round(x / 35)}m`, x - 8, state.floorY + 22);
            }
        }

        /**
         * Draws the Thompson M1928A1 in exact cartoon vector style matching the reference:
         * - Dark brown contoured wooden buttstock
         * - Dark brown vertical foregrip & rear pistol grip with finger grooves
         * - Gunmetal gray receiver with top bolt handle, rear sight, and cooling fins
         * - Iconic circular drum magazine with stamped concentric ribs
         * - Long black/gunmetal barrel with Cutts compensator at muzzle
         * - Crisp bold black vector outlines
         */
        function drawThompsonGun() {
            ctx.save();

            // Apply Screen Shake
            const shakeX = (Math.random() - 0.5) * state.screenShake;
            const shakeY = (Math.random() - 0.5) * state.screenShake;

            // Reload animation tilt & dip
            let reloadAngleOffset = 0;
            let reloadYOffset = 0;
            let drumDropOffset = 0;

            if (state.isReloading) {
                const p = state.reloadProgress;
                // Tilt gun up during reload
                reloadAngleOffset = -Math.sin(p * Math.PI) * 0.38;
                reloadYOffset = Math.sin(p * Math.PI) * 18;
                // Drum drops out and new drum slams in
                if (p < 0.5) {
                    drumDropOffset = Math.pow(p * 2, 2) * 130;
                } else {
                    drumDropOffset = Math.pow((1 - p) * 2, 2) * 130;
                }
            }

            const totalAngle = state.gunAngle + state.muzzleClimb + reloadAngleOffset;

            ctx.translate(state.gunX + shakeX, state.gunY + reloadYOffset + shakeY);
            ctx.rotate(totalAngle);
            ctx.scale(state.gunScale, state.gunScale);

            // Apply Recoil Kickback along local X axis
            ctx.translate(-state.recoilOffset, 0);

            // Dynamic Muzzle Glow Illumination on the Gun Metal
            const isFlashing = state.muzzleFlashTimer > 0;

            // Shared Vector Styling
            ctx.lineJoin = 'round';
            ctx.lineCap = 'round';
            const outlineColor = '#090b0e';
            const woodBase = '#734229';
            const woodHighlight = '#8d5336';
            const woodShadow = '#4e2b19';
            const metalDark = '#2d3239';
            const metalMid = '#434a54';
            const metalLight = '#656d78';
            const barrelDark = '#1d2025';

            // ---------------------------------------------------------
            // 1. WOODEN BUTTSTOCK (Culata trasera inclinada)
            // ---------------------------------------------------------
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(-42, 4);
            ctx.lineTo(-132, 34);
            ctx.quadraticCurveTo(-138, 37, -135, 44);
            ctx.lineTo(-124, 68);
            ctx.quadraticCurveTo(-120, 73, -113, 69);
            ctx.quadraticCurveTo(-80, 46, -42, 22);
            ctx.closePath();

            ctx.fillStyle = woodBase;
            ctx.fill();

            // Wood Shading & Highlight
            ctx.save();
            ctx.clip();
            ctx.fillStyle = woodHighlight;
            ctx.beginPath();
            ctx.moveTo(-42, 4);
            ctx.lineTo(-134, 35);
            ctx.lineTo(-130, 43);
            ctx.lineTo(-42, 11);
            ctx.fill();

            ctx.fillStyle = woodShadow;
            ctx.beginPath();
            ctx.moveTo(-124, 68);
            ctx.lineTo(-42, 22);
            ctx.lineTo(-42, 16);
            ctx.lineTo(-128, 60);
            ctx.fill();
            ctx.restore();

            ctx.lineWidth = 3.5;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();
            ctx.restore();

            // ---------------------------------------------------------
            // 2. REAR PISTOL GRIP (Empuñadura trasera con ranuras)
            // ---------------------------------------------------------
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(-26, 12);
            ctx.lineTo(-28, 42);
            ctx.quadraticCurveTo(-28, 47, -21, 47);
            ctx.lineTo(-13, 47);
            // Finger grooves on front edge
            ctx.quadraticCurveTo(-9, 43, -13, 39);
            ctx.quadraticCurveTo(-9, 34, -13, 30);
            ctx.quadraticCurveTo(-9, 25, -13, 21);
            ctx.lineTo(-11, 12);
            ctx.closePath();

            ctx.fillStyle = woodBase;
            ctx.fill();
            ctx.lineWidth = 3.2;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();
            ctx.restore();

            // Trigger & Trigger Guard
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(-12, 12);
            ctx.quadraticCurveTo(-5, 25, 6, 12);
            ctx.lineWidth = 2.6;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();

            // Trigger blade
            ctx.beginPath();
            ctx.moveTo(-5, 11);
            ctx.quadraticCurveTo(-7, 17, -4, 19);
            ctx.lineWidth = 2.2;
            ctx.stroke();
            ctx.restore();

            // ---------------------------------------------------------
            // 3. VERTICAL FOREGRIP (Empuñadura delantera de madera)
            // ---------------------------------------------------------
            ctx.save();
            ctx.beginPath();
            // Horizontal mounting rail under barrel
            ctx.moveTo(52, -5);
            ctx.lineTo(95, -9);
            ctx.lineTo(95, 2);
            // Finger grooves on front of foregrip
            ctx.quadraticCurveTo(99, 7, 94, 12);
            ctx.quadraticCurveTo(99, 17, 94, 22);
            ctx.quadraticCurveTo(99, 27, 94, 32);
            ctx.quadraticCurveTo(93, 36, 87, 36);
            ctx.lineTo(80, 36);
            ctx.quadraticCurveTo(76, 35, 76, 30);
            ctx.lineTo(76, 6);
            ctx.lineTo(52, 6);
            ctx.closePath();

            ctx.fillStyle = woodBase;
            ctx.fill();

            // Highlight strip
            ctx.save();
            ctx.clip();
            ctx.fillStyle = woodHighlight;
            ctx.fillRect(52, -5, 44, 5);
            ctx.restore();

            ctx.lineWidth = 3.2;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();
            ctx.restore();

            // ---------------------------------------------------------
            // 4. LONG BARREL & CUTTS COMPENSATOR (Cañón y freno de boca)
            // ---------------------------------------------------------
            ctx.save();
            // Barrel cooling fins near receiver
            ctx.fillStyle = barrelDark;
            ctx.strokeStyle = outlineColor;
            ctx.lineWidth = 3;

            // Main long barrel tube
            ctx.beginPath();
            ctx.rect(42, -16, 134, 8);
            ctx.fill();
            ctx.stroke();

            // Top specular highlight on barrel
            ctx.fillStyle = isFlashing ? '#fbbf24' : '#525b66';
            ctx.fillRect(44, -14.5, 130, 2);

            // Cutts Compensator & Front Sight at Muzzle Tip
            ctx.beginPath();
            ctx.moveTo(172, -18);
            ctx.lineTo(194, -19);
            ctx.lineTo(196, -7);
            ctx.lineTo(172, -7);
            ctx.closePath();
            ctx.fillStyle = metalMid;
            ctx.fill();
            ctx.stroke();

            // Front sight blade
            ctx.beginPath();
            ctx.moveTo(186, -19);
            ctx.lineTo(190, -24);
            ctx.lineTo(193, -19);
            ctx.closePath();
            ctx.fillStyle = metalDark;
            ctx.fill();
            ctx.stroke();

            // Compensator vertical vents
            ctx.fillStyle = outlineColor;
            ctx.fillRect(178, -17, 2.5, 5);
            ctx.fillRect(183, -17, 2.5, 5);
            ctx.restore();

            // ---------------------------------------------------------
            // 5. RECEIVER BODY & ANIMATED BOLT (Cajón de mecanismos)
            // ---------------------------------------------------------
            ctx.save();
            // Lower receiver frame
            ctx.beginPath();
            ctx.moveTo(-42, 4);
            ctx.lineTo(42, 2);
            ctx.lineTo(42, 11);
            ctx.lineTo(-42, 14);
            ctx.closePath();
            ctx.fillStyle = metalDark;
            ctx.fill();
            ctx.lineWidth = 3;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();

            // Upper Receiver Block
            ctx.beginPath();
            ctx.moveTo(-46, -12);
            ctx.lineTo(44, -19);
            ctx.lineTo(44, 3);
            ctx.lineTo(-44, 6);
            ctx.closePath();
            ctx.fillStyle = metalMid;
            ctx.fill();

            // Top metallic highlight (reacts to muzzle flash!)
            ctx.save();
            ctx.clip();
            ctx.fillStyle = isFlashing ? '#fde68a' : metalLight;
            ctx.beginPath();
            ctx.moveTo(-46, -12);
            ctx.lineTo(44, -19);
            ctx.lineTo(44, -13);
            ctx.lineTo(-46, -6);
            ctx.fill();
            ctx.restore();

            ctx.lineWidth = 3.5;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();

            // Rear Lyman Sight assembly
            ctx.beginPath();
            ctx.rect(-43, -18, 16, 6);
            ctx.fillStyle = metalDark;
            ctx.fill();
            ctx.stroke();

            // Animated Reciprocating Bolt Handle (moves backward on every shot!)
            ctx.save();
            ctx.translate(-state.boltOffset, 0);
            ctx.beginPath();
            ctx.arc(8, -19, 4.5, 0, Math.PI * 2);
            ctx.fillStyle = metalLight;
            ctx.fill();
            ctx.lineWidth = 2.5;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();
            ctx.restore();

            // Ejection Port Slot
            ctx.fillStyle = '#101216';
            ctx.beginPath();
            ctx.roundRect(10 - state.boltOffset * 0.4, -13, 18, 5, 2);
            ctx.fill();
            ctx.restore();

            // ---------------------------------------------------------
            // 6. DRUM MAGAZINE (Cargador de tambor de 50 balas)
            // ---------------------------------------------------------
            ctx.save();
            ctx.translate(0, drumDropOffset);

            // Drum Side Cylinder Depth (3D angled perspective like reference)
            ctx.beginPath();
            ctx.moveTo(14, -4);
            ctx.lineTo(31, -6);
            ctx.quadraticCurveTo(46, 15, 36, 44);
            ctx.lineTo(20, 48);
            ctx.closePath();
            ctx.fillStyle = metalDark;
            ctx.fill();
            ctx.lineWidth = 3.2;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();

            // Drum Front Angled Face
            ctx.beginPath();
            ctx.ellipse(19, 21, 13, 27, -0.25, 0, Math.PI * 2);
            ctx.fillStyle = metalMid;
            ctx.fill();
            ctx.lineWidth = 3.2;
            ctx.strokeStyle = outlineColor;
            ctx.stroke();

            // Inner Stamped Drum Rings
            ctx.beginPath();
            ctx.ellipse(19, 21, 8, 18, -0.25, 0, Math.PI * 2);
            ctx.lineWidth = 2;
            ctx.strokeStyle = '#252930';
            ctx.stroke();

            ctx.beginPath();
            ctx.ellipse(19, 21, 3.5, 8, -0.25, 0, Math.PI * 2);
            ctx.fillStyle = metalLight;
            ctx.fill();
            ctx.stroke();
            ctx.restore();

            // ---------------------------------------------------------
            // 7. MULTI-LAYERED MUZZLE FLASH (Fogonazo de disparo)
            // ---------------------------------------------------------
            if (isFlashing) {
                ctx.save();
                ctx.translate(197, -13);
                ctx.rotate(state.muzzleFlashAngle);
                ctx.scale(state.muzzleFlashScale, state.muzzleFlashScale);

                // Radial ambient glow
                const glowGrad = ctx.createRadialGradient(25, 0, 4, 25, 0, 95);
                glowGrad.addColorStop(0, 'rgba(255, 240, 170, 0.75)');
                glowGrad.addColorStop(0.4, 'rgba(251, 146, 60, 0.35)');
                glowGrad.addColorStop(1, 'rgba(251, 146, 60, 0)');
                ctx.fillStyle = glowGrad;
                ctx.beginPath();
                ctx.arc(25, 0, 95, 0, Math.PI * 2);
                ctx.fill();

                // Outer Orange/Red Starburst Flame
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(24, -28);
                ctx.lineTo(36, -10);
                ctx.lineTo(88, -14);
                ctx.lineTo(52, 0);
                ctx.lineTo(84, 15);
                ctx.lineTo(35, 11);
                ctx.lineTo(22, 27);
                ctx.closePath();
                ctx.fillStyle = '#f97316';
                ctx.fill();

                // Middle Bright Yellow Flame
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(16, -17);
                ctx.lineTo(26, -6);
                ctx.lineTo(62, -7);
                ctx.lineTo(38, 0);
                ctx.lineTo(58, 8);
                ctx.lineTo(25, 6);
                ctx.lineTo(15, 16);
                ctx.closePath();
                ctx.fillStyle = '#facc15';
                ctx.fill();

                // Inner White-Hot Core
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(12, -8);
                ctx.lineTo(36, 0);
                ctx.lineTo(12, 8);
                ctx.closePath();
                ctx.fillStyle = '#ffffff';
                ctx.fill();

                ctx.restore();
            }

            ctx.restore();
        }

        function drawParticles() {
            // 1. Smoke Clouds
            for (const p of state.smoke) {
                const progress = 1 - (p.life / p.maxLife);
                const currentAlpha = p.alpha * (1 - progress);
                ctx.save();
                ctx.fillStyle = `rgba(180, 192, 208, ${currentAlpha})`;
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                ctx.fill();
                ctx.restore();
            }

            // 2. High-Velocity Glowing Tracer Bullets
            for (const b of state.bullets) {
                ctx.save();
                ctx.translate(b.x, b.y);
                ctx.rotate(b.angle);

                // Tracer Trail Gradient
                const grad = ctx.createLinearGradient(-b.length, 0, 8, 0);
                grad.addColorStop(0, 'rgba(251, 191, 36, 0)');
                grad.addColorStop(0.5, 'rgba(251, 191, 36, 0.55)');
                grad.addColorStop(0.85, 'rgba(254, 240, 138, 0.95)');
                grad.addColorStop(1, '#ffffff');

                ctx.fillStyle = grad;
                ctx.beginPath();
                ctx.roundRect(-b.length, -2.5, b.length + 8, 5, 2.5);
                ctx.fill();

                // Hot Bullet Tip
                ctx.fillStyle = '#ffffff';
                ctx.beginPath();
                ctx.ellipse(4, 0, 6, 2.2, 0, 0, Math.PI * 2);
                ctx.fill();

                ctx.restore();
            }

            // 3. Spinning Brass Shell Casings
            for (const c of state.casings) {
                ctx.save();
                ctx.globalAlpha = c.alpha;
                ctx.translate(c.x, c.y);
                ctx.rotate(c.angle);
                ctx.scale(state.gunScale, state.gunScale);

                // Brass Casing Body (.45 ACP)
                ctx.fillStyle = '#eab308';
                ctx.strokeStyle = '#0f172a';
                ctx.lineWidth = 1.5;

                ctx.beginPath();
                ctx.roundRect(-6, -2.5, 12, 5, 1);
                ctx.fill();
                ctx.stroke();

                // Casing Rim & Highlight
                ctx.fillStyle = '#fef08a';
                ctx.fillRect(-4, -1.5, 8, 1.5);
                ctx.fillStyle = '#a16207';
                ctx.fillRect(-6, -2.5, 2.5, 5);

                ctx.restore();
            }

            // 4. Hot Sparks
            for (const s of state.sparks) {
                const alpha = Math.max(0, s.life / s.maxLife);
                ctx.save();
                ctx.fillStyle = `rgba(253, 224, 71, ${alpha})`;
                ctx.beginPath();
                ctx.arc(s.x, s.y, s.size, 0, Math.PI * 2);
                ctx.fill();
                ctx.restore();
            }
        }

        // Main Animation Loop
        let lastTime = 0;
        function animate(timestamp) {
            if (!lastTime) lastTime = timestamp;
            const dt = Math.min(0.05, (timestamp - lastTime) / 1000);
            lastTime = timestamp;

            // Clear Canvas
            ctx.clearRect(0, 0, state.width, state.height);

            // Update Physics & Particles
            update(dt);

            // Render Layers
            drawEnvironment();
            drawThompsonGun();
            drawParticles();

            requestAnimationFrame(animate);
        }

        // Initialize on Window Load
        window.onload = function () {
            resizeCanvas();
            updateAmmoUI();
            requestAnimationFrame(animate);
        };
    </script>
</body>
</html>

51,602 chars · codepastes.com