• 个人简介

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>林间尸潮 · 第一人称丧尸射击</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      html, body {
        width: 100%; height: 100%; overflow: hidden;
        background: #081209; color: #dcefd8;
        font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
        cursor: default;
      }
      #app { position: relative; width: 100vw; height: 100vh; }
      canvas { display: block; }
    
      .hud { position: absolute; pointer-events: none; z-index: 5; }
    
      #hpBox { left: 28px; bottom: 28px; width: 240px; }
      #hpLabel { font-size: 12px; letter-spacing: 3px; color: #86efac; margin-bottom: 6px; }
      #hpTrack {
        height: 14px; border-radius: 8px; background: rgba(255,255,255,.08);
        border: 1px solid rgba(134,239,172,.3); overflow: hidden;
      }
      #hpFill {
        height: 100%; width: 100%; border-radius: 8px;
        background: linear-gradient(90deg, #22c55e, #65a30d, #a3e635);
        transition: width .18s ease, background .3s;
      }
      #hpNum { font-size: 26px; font-weight: 800; margin-top: 6px; color: #ecfdf5; }
      #hpNum small { font-size: 13px; color: #6b7280; font-weight: 400; }
    
      #armorLabel { font-size: 12px; letter-spacing: 3px; color: #7dd3fc; margin: 12px 0 6px; }
      #armorTrack {
        height: 12px; border-radius: 8px; background: rgba(255,255,255,.08);
        border: 1px solid rgba(125,211,252,.35); overflow: hidden;
      }
      #armorFill {
        height: 100%; width: 100%; border-radius: 8px;
        background: linear-gradient(90deg, #38bdf8, #818cf8);
        transition: width .18s ease;
      }
      #armorNum { font-size: 15px; font-weight: 700; margin-top: 6px; color: #bae6fd; letter-spacing: 1px; }
      #infNum { font-size: 12px; font-weight: 600; margin-top: 5px; color: #a3e635; letter-spacing: 2px; }
    
      .hudBtn {
        pointer-events: auto; cursor: pointer; border: 1px solid rgba(134,239,172,.45);
        background: rgba(10,24,14,.72); color: #d7f7df; border-radius: 10px;
        font-family: inherit; font-size: 13px; font-weight: 700; letter-spacing: 2px;
        padding: 9px 16px; transition: background .15s, transform .12s, border-color .15s;
      }
      .hudBtn:hover { background: rgba(34,80,48,.9); transform: translateY(-1px); }
      #restartBtn { margin-top: 14px; }
      #lockBtn {
        margin-top: 14px; display: flex; align-items: center; gap: 8px; justify-content: flex-end;
        border-color: rgba(125,211,252,.4); color: #cfd9e2;
      }
      #lockBtn.on {
        border-color: #fbbf24; color: #fff7d6;
        background: linear-gradient(90deg, rgba(120,60,10,.85), rgba(160,90,10,.85));
        box-shadow: 0 0 22px rgba(251,191,36,.45);
      }
      #lockBtn small { font-size: 11px; opacity: .75; letter-spacing: 1px; }
    
      #searchTip {
        position: absolute; left: 50%; bottom: 150px; transform: translateX(-50%);
        z-index: 8; pointer-events: none; display: none;
        padding: 8px 18px; border-radius: 10px;
        background: rgba(10,26,16,.85); border: 1px solid rgba(163,230,53,.5);
        color: #e5ffd2; font-size: 14px; letter-spacing: 2px;
      }
      #toast {
        position: absolute; left: 50%; top: 22%; transform: translateX(-50%);
        z-index: 8; pointer-events: none; opacity: 0; transition: opacity .3s;
        padding: 8px 20px; border-radius: 10px;
        background: rgba(12,30,18,.9); border: 1px solid rgba(134,239,172,.5);
        color: #d9ffd3; font-size: 15px; letter-spacing: 2px;
      }
    
      #ammoBox { right: 28px; bottom: 24px; text-align: right; }
      #ammoNum { font-size: 44px; font-weight: 900; color: #fbbf24; letter-spacing: 1px; line-height: 1; }
      #ammoNum small { font-size: 16px; color: #78716c; font-weight: 500; }
      #ammoState { font-size: 12px; letter-spacing: 2px; color: #a8a29e; margin-top: 6px; }
    
      #scoreBox { right: 28px; top: 24px; text-align: right; }
      #scoreNum { font-size: 30px; font-weight: 800; color: #f87171; line-height: 1; }
      #waveNum { font-size: 13px; color: #a8a29e; margin-top: 8px; letter-spacing: 2px; }
    
      #radar { position: absolute; left: 24px; top: 24px; z-index: 5; pointer-events: none; }
    
      #cross {
        position: absolute; left: 50%; top: 50%; width: 26px; height: 26px;
        transform: translate(-50%, -50%); z-index: 6; pointer-events: none;
        transition: transform .08s ease;
      }
      #cross::before, #cross::after {
        content: ''; position: absolute; background: #b6f0c6;
        box-shadow: 0 0 6px rgba(180,240,198,.9);
      }
      #cross::before { left: 50%; top: 0; width: 2px; height: 100%; margin-left: -1px; }
      #cross::after { top: 50%; left: 0; height: 2px; width: 100%; margin-top: -1px; }
      #cross i {
        position: absolute; left: 50%; top: 50%; width: 8px; height: 8px;
        margin: -4px 0 0 -4px; border: 1px solid rgba(180,240,198,.5); border-radius: 50%;
      }
      #cross.kick { transform: translate(-50%, -50%) scale(1.5); }
    
      #hitmark {
        position: absolute; left: 50%; top: 50%; width: 30px; height: 30px;
        transform: translate(-50%, -50%) rotate(45deg); z-index: 6;
        opacity: 0; pointer-events: none;
      }
      #hitmark::before, #hitmark::after {
        content: ''; position: absolute; background: #fff;
        box-shadow: 0 0 8px #f87171;
      }
      #hitmark::before { left: 50%; top: 0; width: 2px; height: 100%; margin-left: -1px; }
      #hitmark::after { top: 50%; left: 0; height: 2px; width: 100%; margin-top: -1px; }
    
      #damage {
        position: absolute; inset: 0; z-index: 4; pointer-events: none; opacity: 0;
        background: radial-gradient(ellipse at center, rgba(190,18,60,0) 42%, rgba(159,18,57,.9) 100%);
      }
    
      .overlay {
        position: absolute; inset: 0; z-index: 20;
        display: flex; flex-direction: column; align-items: center; justify-content: center;
        gap: 16px; text-align: center;
        background: radial-gradient(ellipse at center, rgba(6,20,10,.72), rgba(2,8,4,.95));
        backdrop-filter: blur(3px);
      }
      .overlay.hidden { display: none; }
      .title {
        font-size: 46px; font-weight: 900; letter-spacing: 8px;
        background: linear-gradient(90deg, #22c55e, #a3e635, #f87171);
        -webkit-background-clip: text; background-clip: text;
        -webkit-text-fill-color: transparent;
        filter: drop-shadow(0 0 26px rgba(34,197,94,.45));
      }
      .desc { font-size: 14px; color: #a3b8a4; line-height: 2.1; }
      .desc b { color: #86efac; font-weight: 700; }
      kbd {
        display: inline-block; padding: 1px 8px; border-radius: 5px;
        background: #12261a; border: 1px solid #24402e;
        font-size: 12px; color: #cfd9cf;
      }
      .btn {
        padding: 13px 46px; font-size: 18px; font-weight: 800; letter-spacing: 4px;
        color: #04160a; border: none; border-radius: 999px; cursor: pointer;
        background: linear-gradient(90deg, #4ade80, #a3e635);
        box-shadow: 0 0 30px rgba(74,222,128,.45);
        transition: transform .15s ease, box-shadow .15s ease;
      }
      .btn:hover { transform: scale(1.06); box-shadow: 0 0 42px rgba(74,222,128,.75); }
      .statRow { display: flex; gap: 46px; margin: 6px 0 4px; }
      .stat { font-size: 30px; font-weight: 800; color: #fbbf24; }
      .stat span { display: block; font-size: 12px; color: #78716c; letter-spacing: 2px; margin-top: 4px; font-weight: 400; }
      #err { color: #fca5a5; font-size: 14px; display: none; }
    </style>
    </head>
    <body>
    <div id="app">
      <div id="radar" class="hud"></div>
    
      <div id="hpBox" class="hud">
        <div id="hpLabel">生命</div>
        <div id="hpTrack"><div id="hpFill"></div></div>
        <div id="hpNum">500<small> / 500</small></div>
        <div id="armorLabel">护甲</div>
        <div id="armorTrack"><div id="armorFill"></div></div>
        <div id="armorNum">150 / 150</div>
        <div id="infNum">感染 0%</div>
      </div>
    
      <div id="ammoBox" class="hud">
        <div id="ammoNum">60<small> / 60</small></div>
        <div id="ammoState">突击步枪</div>
        <button class="hudBtn" id="lockBtn"><span id="lockIcon">🔓</span><span>锁头<small> L</small></span></button>
      </div>
    
      <div id="scoreBox" class="hud">
        <div id="scoreNum">0</div>
        <div id="waveNum">波次 1</div>
        <button class="hudBtn" id="restartBtn">重新再来一次<small> T</small></button>
      </div>
    
      <div id="searchTip">按 <kbd>F</kbd> 搜索补给</div>
      <div id="toast"></div>
    
      <div id="cross"><i></i></div>
      <div id="hitmark"></div>
      <div id="damage"></div>
    
      <div id="menu" class="overlay">
        <div class="title">林间尸潮</div>
        <div class="desc">
          <b>鼠标</b> 转动视角 · <b>W A S D</b> 移动 · <b>左键</b> 射击 · <b>R</b> 换弹 · <b>F</b> 搜索补给<br>
          500 生命 + 护甲,丧尸每抓一下只扣 1 点血。右下角开「锁头」,子弹全打头。右上角可重新开始
        </div>
        <button class="btn" id="startBtn">进入森林</button>
        <div class="desc" style="font-size:12px;color:#4b5f4d">点击后鼠标将被锁定,按 <kbd>Esc</kbd> 暂停</div>
        <div id="err">引擎加载失败,请检查网络后刷新页面</div>
      </div>
    
      <div id="pause" class="overlay hidden">
        <div class="title" style="font-size:34px">已暂停</div>
        <div class="desc">点击下方按钮继续战斗</div>
        <button class="btn" id="resumeBtn">继续</button>
      </div>
    
      <div id="over" class="overlay hidden">
        <div class="title" style="font-size:34px">你倒在了林子里</div>
        <div class="statRow">
          <div class="stat" id="finalScore">0<span>得分</span></div>
          <div class="stat" id="finalKills">0<span>击杀</span></div>
          <div class="stat" id="bestScore">0<span>最高分</span></div>
        </div>
        <button class="btn" id="againBtn">再来一次</button>
      </div>
    </div>
    
    <script>
    /* ============================================================
     * 林间尸潮 · 第一人称丧尸射击(Three.js + Canvas 2D 雷达)
     * 单文件,除 three.js 库外无外部依赖
     * ============================================================ */
    
    /* ---------- 依赖加载(jsDelivr 优先,cdnjs 兜底) ---------- */
    (function loadEngine() {
      const urls = [
        'https://fastly.jsdelivr.net/npm/three@0.128.0/build/three.min.js',
        'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js',
      ];
      let idx = 0;
      function next() {
        if (idx >= urls.length) {
          document.getElementById('err').style.display = 'block';
          return;
        }
        const s = document.createElement('script');
        s.src = urls[idx++];
        s.onload = function () {
          if (window.THREE) {
            try { boot(); } catch (e) { console.error(e); document.getElementById('err').style.display = 'block'; }
          } else next();
        };
        s.onerror = next;
        document.head.appendChild(s);
      }
      next();
    })();
    
    /* ---------- 主程序状态 ---------- */
    let renderer, scene, camera, clock, gunGroup, muzzle, muzzleLight;
    let glowTexFlash = null;
    let glowTexZ = null;
    
    const HALF = 30;                 // 森林边界
    const TREE_R = 0.55;             // 树干碰撞半径
    let trees = [];                  // 树干碰撞 {x,z,r}
    let crates = [];                 // 可搜索的补给箱
    let enemies = [];
    let corpses = [];
    let stains = [];
    let particles = [];
    let rings = [];
    
    const DMG = 150;                 // 玩家单发伤害(远超丧尸血量)
    const HEAD_MULT = 3;             // 锁头命中时的爆头倍率
    
    const player = {
      pos: null, yaw: 0, pitch: 0,
      hp: 500, maxHp: 500,
      armor: 150, maxArmor: 150,
      infection: 0,
      ammo: 60, mag: 60,
      reloading: false, reloadT: 0,
      fireCd: 0, alive: true, moveBob: 0, recoil: 0, shake: 0,
      armorDelay: 0,
    };
    
    const G = {
      state: 'menu',
      score: 0, kills: 0, wave: 1, spawnT: 0,
      best: Number(localStorage.getItem('forestHordeBest') || 0),
      dmgFlash: 0,
      lockHead: false,
      headShots: 0,
    };
    
    const keys = {};
    let locked = false;
    let firing = false;
    
    /* ============================================================
     * 程序化纹理
     * ============================================================ */
    function makeGrassTexture() {
      const size = 512;
      const c = document.createElement('canvas');
      c.width = c.height = size;
      const g = c.getContext('2d');
    
      g.fillStyle = '#1a2c14';
      g.fillRect(0, 0, size, size);
    
      // 斑驳的深浅草皮
      for (let i = 0; i < 1400; i++) {
        const r = 8 + Math.random() * 34;
        const tone = Math.random();
        g.fillStyle = tone > 0.72 ? 'rgba(58,92,44,0.18)'
                     : tone > 0.4 ? 'rgba(22,44,18,0.28)'
                     : 'rgba(96,120,60,0.10)';
        g.beginPath();
        g.arc(Math.random() * size, Math.random() * size, r, 0, Math.PI * 2);
        g.fill();
      }
    
      // 草叶
      for (let i = 0; i < 1500; i++) {
        const x = Math.random() * size, y = Math.random() * size;
        const len = 4 + Math.random() * 9;
        const ang = -Math.PI / 2 + (Math.random() - 0.5) * 0.9;
        g.strokeStyle = 'rgba(' + (90 + Math.floor(Math.random() * 60)) + ',' +
          (120 + Math.floor(Math.random() * 70)) + ',60,0.35)';
        g.lineWidth = 1 + Math.random();
        g.beginPath();
        g.moveTo(x, y);
        g.lineTo(x + Math.cos(ang) * len, y + Math.sin(ang) * len);
        g.stroke();
      }
    
      // 零星落叶
      for (let i = 0; i < 120; i++) {
        g.fillStyle = Math.random() > 0.5 ? 'rgba(120,86,40,0.35)' : 'rgba(96,64,32,0.3)';
        g.beginPath();
        g.ellipse(Math.random() * size, Math.random() * size, 3 + Math.random() * 3, 1.5 + Math.random() * 2, Math.random() * Math.PI, 0, Math.PI * 2);
        g.fill();
      }
    
      const t = new THREE.CanvasTexture(c);
      t.wrapS = t.wrapT = THREE.RepeatWrapping;
      t.anisotropy = 4;
      return t;
    }
    
    function makeBarkTexture() {
      const size = 128;
      const c = document.createElement('canvas');
      c.width = size; c.height = size;
      const g = c.getContext('2d');
      g.fillStyle = '#3b2d20';
      g.fillRect(0, 0, size, size);
      for (let i = 0; i < 220; i++) {
        const x = Math.random() * size;
        g.strokeStyle = Math.random() > 0.5 ? 'rgba(24,16,10,0.6)' : 'rgba(92,74,52,0.4)';
        g.lineWidth = 1 + Math.random() * 2;
        g.beginPath();
        g.moveTo(x, 0);
        g.bezierCurveTo(x + (Math.random() - 0.5) * 8, size / 3, x + (Math.random() - 0.5) * 8, size * 2 / 3, x, size);
        g.stroke();
      }
      const t = new THREE.CanvasTexture(c);
      t.wrapS = t.wrapT = THREE.RepeatWrapping;
      return t;
    }
    
    function makeGlowTexture(inner, outer) {
      const size = 128;
      const c = document.createElement('canvas');
      c.width = c.height = size;
      const g = c.getContext('2d');
      const grd = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
      grd.addColorStop(0, inner);
      grd.addColorStop(0.4, outer);
      grd.addColorStop(1, 'rgba(0,0,0,0)');
      g.fillStyle = grd;
      g.fillRect(0, 0, size, size);
      return new THREE.CanvasTexture(c);
    }
    
    /* ============================================================
     * 音效
     * ============================================================ */
    let actx = null;
    function audio() {
      if (!actx) {
        try { actx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { actx = null; }
      }
      return actx;
    }
    function tone(freq, dur, type, vol, slideTo) {
      const a = audio(); if (!a) return;
      const o = a.createOscillator(), g = a.createGain();
      o.type = type || 'square';
      o.frequency.setValueAtTime(freq, a.currentTime);
      if (slideTo) o.frequency.exponentialRampToValueAtTime(slideTo, a.currentTime + dur);
      g.gain.setValueAtTime(vol, a.currentTime);
      g.gain.exponentialRampToValueAtTime(0.0001, a.currentTime + dur);
      o.connect(g); g.connect(a.destination);
      o.start(); o.stop(a.currentTime + dur + 0.02);
    }
    function noiseBurst(dur, vol, freq) {
      const a = audio(); if (!a) return;
      const len = Math.max(1, Math.floor(a.sampleRate * dur));
      const buf = a.createBuffer(1, len, a.sampleRate);
      const d = buf.getChannelData(0);
      for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len);
      const src = a.createBufferSource(); src.buffer = buf;
      const f = a.createBiquadFilter(); f.type = 'bandpass';
      f.frequency.value = freq || 1200; f.Q.value = 0.7;
      const g = a.createGain(); g.gain.value = vol;
      src.connect(f); f.connect(g); g.connect(a.destination);
      src.start();
    }
    const sfx = {
      shot: function () { noiseBurst(0.08, 0.17, 1400); tone(300, 0.09, 'square', 0.06, 90); },
      hit: function () { tone(900, 0.05, 'triangle', 0.06, 500); },
      kill: function () { noiseBurst(0.24, 0.2, 520); tone(120, 0.28, 'sawtooth', 0.08, 48); },
      hurt: function () { tone(110, 0.28, 'sawtooth', 0.13, 45); },
      groan: function () { tone(70 + Math.random() * 25, 0.55, 'sawtooth', 0.035, 52); },
      reload: function () { tone(240, 0.08, 'square', 0.06); setTimeout(function () { tone(460, 0.09, 'square', 0.06); }, 340); },
      empty: function () { tone(150, 0.07, 'square', 0.05); },
    };
    
    /* ============================================================
     * 场景
     * ============================================================ */
    function boot() {
      const app = document.getElementById('app');
    
      renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
      renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
      renderer.setSize(window.innerWidth, window.innerHeight);
      app.insertBefore(renderer.domElement, app.firstChild);
    
      scene = new THREE.Scene();
      scene.background = new THREE.Color(0x0b1a10);
      scene.fog = new THREE.FogExp2(0x0d2014, 0.03);
    
      camera = new THREE.PerspectiveCamera(74, window.innerWidth / window.innerHeight, 0.1, 300);
      camera.rotation.order = 'YXZ';
      camera.position.set(0, 1.65, 24);
      scene.add(camera);
      player.pos = camera.position;
    
      clock = new THREE.Clock();
    
      buildLights();
      buildForest();
      buildCrates();
      buildGun();
      buildRadar();
    
      window.addEventListener('resize', onResize);
      bindInput();
      bindUI();
      requestAnimationFrame(loop);
    }
    
    function buildLights() {
      scene.add(new THREE.AmbientLight(0x3d5c42, 0.75));
      scene.add(new THREE.HemisphereLight(0x5c8f66, 0x10180f, 0.6));
    
      // 月光
      const moon = new THREE.DirectionalLight(0xc8e6cf, 0.65);
      moon.position.set(-14, 30, 10);
      scene.add(moon);
    
      // 玩家手电(暖白,照亮近处)
      const torch = new THREE.PointLight(0xe9f7dd, 0.85, 26, 2);
      torch.position.set(0, 0.1, -1);
      camera.add(torch);
    
      const torch2 = new THREE.SpotLight(0xe9f7dd, 0.5, 38, Math.PI / 4.2, 0.5, 1.2);
      torch2.position.set(0, 0.05, 0);
      torch2.target.position.set(0, 0, -6);
      camera.add(torch2);
      camera.add(torch2.target);
    }
    
    function buildForest() {
      // 地面
      const grass = makeGrassTexture();
      grass.repeat.set(10, 10);
      const floor = new THREE.Mesh(
        new THREE.PlaneGeometry(HALF * 2.2, HALF * 2.2),
        new THREE.MeshLambertMaterial({ map: grass })
      );
      floor.rotation.x = -Math.PI / 2;
      scene.add(floor);
    
      const bark = makeBarkTexture();
      const trunkMat = new THREE.MeshLambertMaterial({ map: bark, color: 0x7a6b56 });
      const leafDark = new THREE.MeshLambertMaterial({ color: 0x1c3a20 });
      const leafMid = new THREE.MeshLambertMaterial({ color: 0x24512c });
      const leafLight = new THREE.MeshLambertMaterial({ color: 0x2c6134 });
      const bushMat = new THREE.MeshLambertMaterial({ color: 0x1a3320 });
    
      const trunkGeo = new THREE.CylinderGeometry(0.32, 0.5, 6, 8);
      const coneGeo = new THREE.ConeGeometry(1, 1, 9);
      const bushGeo = new THREE.ConeGeometry(1, 1, 7);
      const rockGeo = new THREE.DodecahedronGeometry(1, 0);
      const rockMat = new THREE.MeshLambertMaterial({ color: 0x4b5450 });
    
      function clearOfSpawn(x, z) {
        return Math.hypot(x - 0, z - 24) > 11;
      }
    
      let placed = 0, guard = 0;
      while (placed < 100 && guard < 3500) {
        guard++;
        const x = (Math.random() - 0.5) * (HALF * 2 - 3);
        const z = (Math.random() - 0.5) * (HALF * 2 - 3);
        if (!clearOfSpawn(x, z)) continue;
        // 树之间不要太挤
        let ok = true;
        for (let i = 0; i < trees.length; i++) {
          if (Math.hypot(trees[i].x - x, trees[i].z - z) < 4.2) { ok = false; break; }
        }
        if (!ok) continue;
    
        const scale = 0.9 + Math.random() * 0.7;
        const kind = Math.random();
    
        if (kind > 0.32) {
          // 松树:树干 + 多层锥形树冠
          const h = 6.6 * scale;
          const trunk = new THREE.Mesh(trunkGeo, trunkMat);
          trunk.scale.set(scale, h / 6, scale);
          trunk.position.set(x, h / 2, z);
          scene.add(trunk);
    
          const layers = 3;
          for (let li = 0; li < layers; li++) {
            const r = (1.95 - li * 0.4) * scale;
            const ch = (2.7 - li * 0.45) * scale;
            const cone = new THREE.Mesh(coneGeo, li === 0 ? leafDark : (li === 1 ? leafMid : leafLight));
            cone.scale.set(r, ch, r);
            cone.position.set(x + (Math.random() - 0.5) * 0.4, h - 0.2 + li * ch * 0.62, z + (Math.random() - 0.5) * 0.4);
            cone.rotation.y = Math.random() * Math.PI;
            scene.add(cone);
          }
          trees.push({ x: x, z: z, r: 0.75 * scale });
        } else if (kind > 0.12) {
          // 阔叶树:矮树干 + 球形树冠
          const h = 4.8 * scale;
          const trunk = new THREE.Mesh(trunkGeo, trunkMat);
          trunk.scale.set(scale * 1.05, h / 6, scale * 1.05);
          trunk.position.set(x, h / 2, z);
          scene.add(trunk);
    
          const crownGeo = new THREE.IcosahedronGeometry(1, 0);
          for (let i = 0; i < 3; i++) {
            const crown = new THREE.Mesh(crownGeo, i === 0 ? leafMid : leafLight);
            const r = (1.35 + Math.random() * 0.55) * scale;
            crown.scale.set(r, r * 0.85, r);
            crown.position.set(
              x + (Math.random() - 0.5) * 1.6 * scale,
              h + 0.3 * scale + Math.random() * 1.4 * scale,
              z + (Math.random() - 0.5) * 1.6 * scale
            );
            crown.rotation.set(Math.random() * 3, Math.random() * 3, Math.random() * 3);
            scene.add(crown);
          }
          trees.push({ x: x, z: z, r: 0.8 * scale });
        } else {
          // 灌木丛
          for (let i = 0; i < 2; i++) {
            const bush = new THREE.Mesh(bushGeo, bushMat);
            const r = (0.9 + Math.random() * 0.7) * scale;
            bush.scale.set(r, r * 1.5, r);
            bush.position.set(x + (Math.random() - 0.5) * 1.4, r * 0.75, z + (Math.random() - 0.5) * 1.4);
            bush.rotation.y = Math.random() * 3;
            scene.add(bush);
          }
          trees.push({ x: x, z: z, r: 0.9 * scale });
        }
        placed++;
      }
    
      // 石头
      for (let i = 0; i < 22; i++) {
        const x = (Math.random() - 0.5) * (HALF * 2 - 4);
        const z = (Math.random() - 0.5) * (HALF * 2 - 4);
        if (!clearOfSpawn(x, z)) continue;
        const r = 0.5 + Math.random() * 1.1;
        const rock = new THREE.Mesh(rockGeo, rockMat);
        rock.scale.set(r, r * 0.7, r);
        rock.position.set(x, r * 0.35, z);
        rock.rotation.set(Math.random() * 3, Math.random() * 3, Math.random() * 3);
        scene.add(rock);
        trees.push({ x: x, z: z, r: r * 0.8 });
      }
    
      // 远处密林剪影(视觉纵深,不参与碰撞)
      for (let i = 0; i < 34; i++) {
        const a = Math.random() * Math.PI * 2;
        const rr = HALF - 1 + Math.random() * 9;
        const x = Math.cos(a) * rr, z = Math.sin(a) * rr;
        const h = 8 + Math.random() * 8;
        const trunk = new THREE.Mesh(trunkGeo, trunkMat);
        trunk.scale.set(1.2, h / 6, 1.2);
        trunk.position.set(x, h / 2, z);
        scene.add(trunk);
        const cone = new THREE.Mesh(coneGeo, leafDark);
        cone.scale.set(2.6, 5, 2.6);
        cone.position.set(x, h, z);
        scene.add(cone);
      }
    }
    
    function buildCrates() {
      const woodMat = new THREE.MeshLambertMaterial({ color: 0x6b4f33 });
      const lidMat = new THREE.MeshLambertMaterial({ color: 0x8a6a45 });
      const boxGeo = new THREE.BoxGeometry(0.8, 0.62, 0.8);
      const lidGeo = new THREE.BoxGeometry(0.86, 0.1, 0.86);
      const markGeo = new THREE.BoxGeometry(0.2, 0.2, 0.2);
    
      let placed = 0, guard = 0;
      while (placed < 10 && guard < 800) {
        guard++;
        const x = (Math.random() - 0.5) * (HALF * 1.9);
        const z = (Math.random() - 0.5) * (HALF * 1.9);
        if (Math.hypot(x - 0, z - 24) < 8) continue;
        let ok = true;
        for (let i = 0; i < trees.length; i++) {
          if (Math.hypot(trees[i].x - x, trees[i].z - z) < 2.2) { ok = false; break; }
        }
        for (let i = 0; i < crates.length; i++) {
          if (Math.hypot(crates[i].x - x, crates[i].z - z) < 6) { ok = false; break; }
        }
        if (!ok) continue;
    
        const g = new THREE.Group();
        const box = new THREE.Mesh(boxGeo, woodMat);
        box.position.y = 0.31;
        g.add(box);
        const lid = new THREE.Mesh(lidGeo, lidMat);
        lid.position.y = 0.66;
        g.add(lid);
    
        const markMat = new THREE.MeshBasicMaterial({ color: 0x9fe870 });
        const mark = new THREE.Mesh(markGeo, markMat);
        mark.position.set(0, 0.86, 0);
        g.add(mark);
    
        g.position.set(x, 0, z);
        g.rotation.y = Math.random() * Math.PI;
        scene.add(g);
    
        crates.push({ group: g, mark: mark, markMat: markMat, x: x, z: z, used: false, spin: Math.random() });
        trees.push({ x: x, z: z, r: 0.55 });
        placed++;
      }
    }
    
    function nearestCrate(range) {
      let best = null, bestD = range || 2.8;
      for (let i = 0; i < crates.length; i++) {
        const c = crates[i];
        if (c.used) continue;
        const d = Math.hypot(c.x - player.pos.x, c.z - player.pos.z);
        if (d < bestD) { bestD = d; best = c; }
      }
      return best;
    }
    
    function searchCrate() {
      if (G.state !== 'playing') return;
      const c = nearestCrate(2.8);
      if (!c) return;
    
      c.used = true;
      c.markMat.color.set(0x3a4a36);
      c.mark.scale.setScalar(0.5);
    
      const got = [];
      if (player.ammo < player.mag) { player.ammo = player.mag; got.push('弹药补满'); }
      if (player.armor < player.maxArmor) {
        player.armor = Math.min(player.maxArmor, player.armor + 40); got.push('护甲 +40');
      }
      if (player.hp < player.maxHp) {
        player.hp = Math.min(player.maxHp, player.hp + 30); got.push('生命 +30');
      }
      if (player.infection > 0) {
        player.infection = Math.max(0, player.infection - 15); got.push('感染 -15%');
      }
      if (!got.length) got.push('箱子空了');
    
      sfx.reload();
      toast('搜到补给:' + got.join(' '));
      updateHUD(true);
    }
    
    let toastTimer = null;
    function toast(text) {
      const el = document.getElementById('toast');
      el.textContent = text;
      el.style.opacity = 1;
      clearTimeout(toastTimer);
      toastTimer = setTimeout(function () { el.style.opacity = 0; }, 1600);
    }
    
    function updateCrates(dt) {
      const near = (G.state === 'playing') ? nearestCrate(2.8) : null;
      document.getElementById('searchTip').style.display = near ? 'block' : 'none';
    
      const t = clock.elapsedTime;
      for (let i = 0; i < crates.length; i++) {
        const c = crates[i];
        if (c.used) continue;
        c.spin += dt;
        c.mark.rotation.y = c.spin * 2;
        c.mark.position.y = 0.86 + Math.sin(t * 2 + i) * 0.05;
      }
    }
    
    function buildGun() {
      gunGroup = new THREE.Group();
      gunGroup.position.set(0.2, -0.21, -0.78);
      gunGroup.rotation.y = 0.08;
      camera.add(gunGroup);
    
      const dark = new THREE.MeshStandardMaterial({ color: 0x3a3a34, emissive: 0x0e1610, metalness: 0.7, roughness: 0.45 });
      const mid = new THREE.MeshStandardMaterial({ color: 0x5c5b50, emissive: 0x16201a, metalness: 0.75, roughness: 0.35 });
      const neon = new THREE.MeshBasicMaterial({ color: 0x9fe870 });
    
      const gunLight = new THREE.PointLight(0xdff2cf, 0.55, 3.2, 2);
      gunLight.position.set(0.1, 0.15, -0.2);
      gunGroup.add(gunLight);
    
      const body = new THREE.Mesh(new THREE.BoxGeometry(0.11, 0.12, 0.5), dark);
      gunGroup.add(body);
    
      const rail = new THREE.Mesh(new THREE.BoxGeometry(0.065, 0.045, 0.44), mid);
      rail.position.set(0, 0.07, -0.04);
      gunGroup.add(rail);
    
      const barrel = new THREE.Mesh(new THREE.BoxGeometry(0.045, 0.045, 0.4), mid);
      barrel.position.set(0, 0.01, -0.49);
      gunGroup.add(barrel);
    
      const ring = new THREE.Mesh(new THREE.TorusGeometry(0.038, 0.012, 6, 12), neon);
      ring.position.set(0, 0.01, -0.69);
      gunGroup.add(ring);
    
      const strip = new THREE.Mesh(new THREE.BoxGeometry(0.012, 0.016, 0.34), neon);
      strip.position.set(-0.052, 0.01, -0.06);
      gunGroup.add(strip);
    
      const strip2 = new THREE.Mesh(new THREE.BoxGeometry(0.012, 0.016, 0.16), neon);
      strip2.position.set(-0.052, -0.038, 0.14);
      gunGroup.add(strip2);
    
      const grip = new THREE.Mesh(new THREE.BoxGeometry(0.065, 0.17, 0.08), dark);
      grip.position.set(0, -0.13, 0.13);
      grip.rotation.x = -0.22;
      gunGroup.add(grip);
    
      const magBox = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.16, 0.06), mid);
      magBox.position.set(0, -0.12, -0.06);
      gunGroup.add(magBox);
    
      const sight = new THREE.Mesh(new THREE.BoxGeometry(0.025, 0.06, 0.025), mid);
      sight.position.set(0, 0.12, -0.16);
      gunGroup.add(sight);
    
      if (!glowTexFlash) glowTexFlash = makeGlowTexture('rgba(255,244,190,1)', 'rgba(255,170,60,0.55)');
      muzzle = new THREE.Sprite(new THREE.SpriteMaterial({
        map: glowTexFlash, blending: THREE.AdditiveBlending,
        transparent: true, depthWrite: false, opacity: 0,
      }));
      muzzle.scale.setScalar(0.45);
      muzzle.position.set(0, 0.01, -0.72);
      gunGroup.add(muzzle);
    
      muzzleLight = new THREE.PointLight(0xffd27a, 0, 9, 2);
      muzzleLight.position.set(0, 0, -0.78);
      gunGroup.add(muzzleLight);
    }
    
    /* ============================================================
     * 丧尸
     * ============================================================ */
    const ZM = {};
    const ZG = {};
    
    function zombieAssets() {
      if (ZM.skin) return;
      ZM.skin = new THREE.MeshStandardMaterial({ color: 0x86a06e, roughness: 0.95, emissive: 0x1b2a16, emissiveIntensity: 0.6 });
      ZM.skinElite = new THREE.MeshStandardMaterial({ color: 0x6d8a5a, roughness: 0.95, emissive: 0x22351a, emissiveIntensity: 0.7 });
      ZM.cloth = new THREE.MeshStandardMaterial({ color: 0x40443a, roughness: 1 });
      ZM.clothElite = new THREE.MeshStandardMaterial({ color: 0x53282a, roughness: 1 });
      ZM.eye = new THREE.MeshBasicMaterial({ color: 0xff2d1f });
      ZM.mouth = new THREE.MeshBasicMaterial({ color: 0x2a1210 });
    
      ZG.torso = new THREE.BoxGeometry(0.52, 0.72, 0.3);
      ZG.head = new THREE.BoxGeometry(0.33, 0.34, 0.33);
      ZG.limb = new THREE.BoxGeometry(0.13, 0.13, 1);
      ZG.leg = new THREE.BoxGeometry(0.17, 0.72, 0.2);
      ZG.eye = new THREE.BoxGeometry(0.07, 0.05, 0.03);
      ZG.mouth = new THREE.BoxGeometry(0.16, 0.05, 0.02);
    }
    
    function buildZombie(elite) {
      zombieAssets();
      const g = new THREE.Group();
      const skin = elite ? ZM.skinElite : ZM.skin;
      const cloth = elite ? ZM.clothElite : ZM.cloth;
      const s = elite ? 1.12 : 1;
    
      // 躯干
      const torso = new THREE.Mesh(ZG.torso, cloth);
      torso.position.y = 1.12 * s;
      torso.scale.set(s, s, s);
      g.add(torso);
    
      // 头(略微前倾,丧尸姿态)
      const headPivot = new THREE.Group();
      headPivot.position.set(0, 1.5 * s, 0);
      const head = new THREE.Mesh(ZG.head, skin);
      head.position.set(0, 0.14 * s, -0.02);
      head.scale.set(s, s, s);
      headPivot.add(head);
      headPivot.rotation.x = 0.16;
      g.add(headPivot);
    
      // 眼睛(红光)
      for (let i = 0; i < 2; i++) {
        const eye = new THREE.Mesh(ZG.eye, ZM.eye);
        eye.position.set((i ? 0.085 : -0.085) * s, 0.19 * s, -0.18 * s);
        eye.scale.set(s, s, s);
        headPivot.add(eye);
      }
      // 嘴
      const mouth = new THREE.Mesh(ZG.mouth, ZM.mouth);
      mouth.position.set(0, 0.06 * s, -0.18 * s);
      mouth.scale.set(s, s, s);
      headPivot.add(mouth);
    
      // 双臂(前伸抓取)
      const armPivots = [];
      for (let i = 0; i < 2; i++) {
        const pivot = new THREE.Group();
        pivot.position.set((i ? 0.34 : -0.34) * s, 1.42 * s, 0);
        const limb = new THREE.Mesh(ZG.limb, skin);
        limb.position.z = -0.34 * s;
        limb.scale.set(s, s, 0.72 * s);
        pivot.add(limb);
        pivot.rotation.x = -1.32 + (i ? -0.14 : 0.14);
        pivot.rotation.z = (i ? -0.16 : 0.16);
        g.add(pivot);
        armPivots.push(pivot);
      }
    
      // 双腿
      const legPivots = [];
      for (let i = 0; i < 2; i++) {
        const pivot = new THREE.Group();
        pivot.position.set((i ? 0.15 : -0.15) * s, 0.76 * s, 0);
        const leg = new THREE.Mesh(ZG.leg, cloth);
        leg.position.y = -0.36 * s;
        leg.scale.set(s, s, s);
        pivot.add(leg);
        g.add(pivot);
        legPivots.push(pivot);
      }
    
      g.userData = { armL: armPivots[0], armR: armPivots[1], legL: legPivots[0], legR: legPivots[1], headPivot: headPivot, skinMat: skin };
    
      // 极淡的红色轮廓光,让丧尸在暗林里能被看见
      if (!glowTexZ) glowTexZ = makeGlowTexture('rgba(255,90,70,0.85)', 'rgba(170,30,25,0.28)');
      const halo = new THREE.Sprite(new THREE.SpriteMaterial({
        map: glowTexZ, blending: THREE.AdditiveBlending,
        transparent: true, depthWrite: false, opacity: elite ? 0.5 : 0.32,
      }));
      halo.scale.setScalar(elite ? 2.9 : 2.2);
      halo.position.y = 1.1 * s;
      g.add(halo);
    
      return g;
    }
    
    function spawnPoint() {
      // 六成概率生成在玩家正前方视野里,方便交火
      for (let i = 0; i < 30; i++) {
        const ahead = Math.random() < 0.6;
        const a = ahead
          ? player.yaw + (Math.random() - 0.5) * 2.0
          : Math.random() * Math.PI * 2;
        const r = 15 + Math.random() * 9;
        const x = player.pos.x - Math.sin(a) * r;
        const z = player.pos.z - Math.cos(a) * r;
        if (Math.abs(x) < HALF - 2 && Math.abs(z) < HALF - 2) return { x: x, z: z };
      }
      return { x: 0, z: -HALF + 6 };
    }
    
    function makeZombie(elite) {
      const g = buildZombie(elite);
      const sp = spawnPoint();
      g.position.set(sp.x, 0, sp.z);
      scene.add(g);
    
      enemies.push({
        group: g,
        elite: !!elite,
        hp: elite ? 260 : 100,       // 普通怪一发即倒
        maxHp: elite ? 260 : 100,
        speed: (elite ? 1.25 : 1.6) + Math.random() * 0.45,
        walkPhase: Math.random() * Math.PI * 2,
        attackCd: 0,
        alive: true,
        hitT: 0,
        reach: 0.25,
      });
    }
    
    /* ============================================================
     * 输入
     * ============================================================ */
    function bindInput() {
      const dom = renderer.domElement;
    
      window.addEventListener('keydown', function (e) {
        keys[e.code] = true;
        if (e.code === 'KeyR' && G.state === 'playing') reload();
        if (e.code === 'KeyP' && G.state === 'playing') pauseGame();
        if (e.code === 'KeyF' && G.state === 'playing') searchCrate();
        if (e.code === 'KeyL') toggleLock();
        if (e.code === 'KeyT') { if (G.state === 'playing' || G.state === 'paused') restart(); }
        if (e.code === 'Space' && G.state === 'over') restart();
        if (e.code === 'Enter' && G.state === 'over') restart();
        if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].indexOf(e.code) >= 0) e.preventDefault();
      });
      window.addEventListener('keyup', function (e) { keys[e.code] = false; });
    
      dom.addEventListener('click', function () {
        if (G.state === 'playing' && !locked) lockPointer();
      });
    
      dom.addEventListener('mousedown', function (e) {
        if (G.state === 'playing' && locked && e.button === 0) {
          firing = true;
          tryFire();
        }
      });
      window.addEventListener('mouseup', function () { firing = false; });
    
      document.addEventListener('mousemove', function (e) {
        if (!locked || G.state !== 'playing') return;
        player.yaw -= e.movementX * 0.0024;
        player.pitch -= e.movementY * 0.0024;
        player.pitch = Math.max(-1.2, Math.min(1.2, player.pitch));
      });
    
      document.addEventListener('pointerlockchange', function () {
        locked = document.pointerLockElement === renderer.domElement;
        if (!locked && G.state === 'playing') pauseGame();
      });
    
      let touching = null;
      dom.addEventListener('touchstart', function (e) {
        if (G.state !== 'playing') return;
        e.preventDefault();
        const t = e.touches[0];
        touching = { x: t.clientX, y: t.clientY };
        firing = true; tryFire();
      }, { passive: false });
      dom.addEventListener('touchmove', function (e) {
        if (!touching || G.state !== 'playing') return;
        e.preventDefault();
        const t = e.touches[0];
        player.yaw -= (t.clientX - touching.x) * 0.005;
        player.pitch -= (t.clientY - touching.y) * 0.005;
        player.pitch = Math.max(-1.2, Math.min(1.2, player.pitch));
        touching = { x: t.clientX, y: t.clientY };
      }, { passive: false });
      dom.addEventListener('touchend', function () { firing = false; touching = null; });
    }
    
    function lockPointer() {
      const dom = renderer.domElement;
      if (dom.requestPointerLock) {
        try { dom.requestPointerLock(); } catch (e) { /* ignore */ }
      } else {
        locked = true;
      }
    }
    
    function bindUI() {
      document.getElementById('startBtn').addEventListener('click', startGame);
      document.getElementById('resumeBtn').addEventListener('click', resumeGame);
      document.getElementById('againBtn').addEventListener('click', restart);
      document.getElementById('restartBtn').addEventListener('click', function () {
        if (G.state === 'menu') return;
        restart();
      });
      document.getElementById('lockBtn').addEventListener('click', function (e) {
        e.stopPropagation();
        toggleLock();
      });
    }
    
    function toggleLock() {
      G.lockHead = !G.lockHead;
      const btn = document.getElementById('lockBtn');
      const icon = document.getElementById('lockIcon');
      btn.classList.toggle('on', G.lockHead);
      icon.textContent = G.lockHead ? '🔒' : '🔓';
      if (G.state === 'playing') toast(G.lockHead ? '锁头已开启:所有子弹打头' : '锁头已关闭');
    }
    
    /* ============================================================
     * 流程
     * ============================================================ */
    function startGame() {
      document.getElementById('menu').classList.add('hidden');
      document.getElementById('over').classList.add('hidden');
      document.getElementById('pause').classList.add('hidden');
      G.state = 'playing';
      resetGame();
      lockPointer();
      audio();
    }
    
    function resetGame() {
      enemies.forEach(function (e) { scene.remove(e.group); });
      enemies = [];
      corpses.forEach(function (c) { scene.remove(c.group); });
      corpses = [];
      stains.forEach(function (s) { scene.remove(s.mesh); });
      stains = [];
      particles.forEach(function (p) { scene.remove(p.mesh); });
      particles = [];
      rings.forEach(function (r) { scene.remove(r.mesh); });
      rings = [];
    
      player.pos.set(0, 1.65, 24);
      player.yaw = 0;
      player.pitch = 0;
      player.hp = player.maxHp;
      player.armor = player.maxArmor;
      player.infection = 0;
      player.armorDelay = 0;
      player.ammo = player.mag;
      player.reloading = false;
      player.reloadT = 0;
      player.fireCd = 0;
      player.alive = true;
      player.recoil = 0;
      player.shake = 0;
    
      // 补给箱重置
      for (let i = 0; i < crates.length; i++) {
        crates[i].used = false;
        crates[i].markMat.color.set(0x9fe870);
        crates[i].mark.scale.setScalar(1);
      }
    
      G.score = 0;
      G.kills = 0;
      G.wave = 1;
      G.spawnT = 2.5;
      G.dmgFlash = 0;
      G.headShots = 0;
    
      updateHUD(true);
    }
    
    function pauseGame() {
      if (G.state !== 'playing') return;
      G.state = 'paused';
      firing = false;
      document.getElementById('searchTip').style.display = 'none';
      if (document.pointerLockElement) document.exitPointerLock();
      document.getElementById('pause').classList.remove('hidden');
    }
    
    function resumeGame() {
      document.getElementById('pause').classList.add('hidden');
      G.state = 'playing';
      clock.getDelta();
      lockPointer();
    }
    
    function gameOver() {
      G.state = 'over';
      firing = false;
      if (document.pointerLockElement) document.exitPointerLock();
      G.best = Math.max(G.best, G.score);
      localStorage.setItem('forestHordeBest', G.best);
      document.getElementById('finalScore').innerHTML = G.score + '<span>得分</span>';
      document.getElementById('finalKills').innerHTML = G.kills + '<span>击杀</span>';
      document.getElementById('bestScore').innerHTML = G.best + '<span>最高分</span>';
      document.getElementById('over').classList.remove('hidden');
    }
    
    function restart() {
      document.getElementById('over').classList.add('hidden');
      G.state = 'playing';
      resetGame();
      lockPointer();
    }
    
    /* ============================================================
     * 射击
     * ============================================================ */
    function rayBlockedByTrees(from, to) {
      const dx = to.x - from.x, dz = to.z - from.z;
      const a = dx * dx + dz * dz;
      if (a < 1e-6) return false;
      for (let i = 0; i < trees.length; i++) {
        const t = trees[i];
        // 只考虑树干半径内的遮挡(不遮视线)
        const fx = from.x - t.x, fz = from.z - t.z;
        const b = 2 * (fx * dx + fz * dz);
        const cc = fx * fx + fz * fz - t.r * t.r;
        if (cc <= 0) return true;
        const disc = b * b - 4 * a * cc;
        if (disc <= 0) continue;
        const s = (-b - Math.sqrt(disc)) / (2 * a);
        if (s > 0 && s < 1) return true;
      }
      return false;
    }
    
    function tryFire() {
      if (player.reloading || G.state !== 'playing') return;
      if (player.fireCd > 0) return;
      if (player.ammo <= 0) { sfx.empty(); player.fireCd = 0.22; return; }
    
      player.ammo--;
      player.fireCd = 0.075;
      player.recoil = 1;
      player.shake = 0.05;
      sfx.shot();
    
      muzzle.material.opacity = 1;
      muzzle.scale.setScalar(0.38 + Math.random() * 0.2);
      muzzleLight.intensity = 2.4;
    
      const cross = document.getElementById('cross');
      cross.classList.add('kick');
      setTimeout(function () { cross.classList.remove('kick'); }, 90);
    
      camera.updateMatrixWorld();
      const fwd = new THREE.Vector3();
      camera.getWorldDirection(fwd);
      const camPos = camera.getWorldPosition(new THREE.Vector3());
    
      // 锁头开启时:子弹自动咬到视野内丧尸的头部
      const lock = G.lockHead;
      let target = null, bestAng = lock ? 0.62 : 0.115, bestDist = 1e9;
      for (let i = 0; i < enemies.length; i++) {
        const e = enemies[i];
        if (!e.alive) continue;
        const hy = lock ? 1.72 : 1.2;
        const v = new THREE.Vector3(e.group.position.x, hy, e.group.position.z).sub(camPos);
        const d = v.length();
        if (d > 60 || d < 0.3) continue;
        v.normalize();
        const ang = Math.acos(Math.max(-1, Math.min(1, v.dot(fwd))));
        if (ang < bestAng && d < bestDist) {
          if (!rayBlockedByTrees(camPos, { x: e.group.position.x, z: e.group.position.z })) {
            bestAng = ang;
            bestDist = d;
            target = e;
          }
        }
      }
    
      if (target) damageZombie(target, lock ? DMG * HEAD_MULT : DMG, lock);
      updateHUD();
    }
    
    function damageZombie(e, dmg, head) {
      e.hp -= dmg;
      e.hitT = 0.15;
      if (head) G.headShots++;
    
      const pos = new THREE.Vector3(e.group.position.x, head ? 1.72 : 1.2, e.group.position.z);
    
      if (e.hp <= 0) {
        e.alive = false;
        G.score += (e.elite ? 400 : 120) * (head ? 2 : 1);
        G.kills++;
        sfx.kill();
        showHitmarker(head ? '#fbbf24' : '#f87171');
        spawnParticles(pos, 0x7f1024, e.elite ? 24 : 15, 1);
        spawnParticles(pos, 0x3f7a3a, e.elite ? 10 : 6, 0.7);
        spawnRing(new THREE.Vector3(e.group.position.x, 0.05, e.group.position.z), 0x7f1d1d, e.elite ? 3 : 2.2);
        addBloodStain(e.group.position.x, e.group.position.z, e.elite ? 1.7 : 1.2);
        corpses.push({ group: e.group, t: 0 });
        G.wave = 1 + Math.floor(G.kills / 10);
      } else {
        sfx.hit();
        showHitmarker('#ffffff');
        spawnParticles(pos, 0x7f1024, 5, 0.5);
        e.group.userData.skinMat.emissiveIntensity = 1.6;
      }
      updateHUD();
    }
    
    function showHitmarker(color) {
      const el = document.getElementById('hitmark');
      el.style.opacity = 1;
      el.style.filter = 'drop-shadow(0 0 8px ' + color + ')';
      setTimeout(function () { el.style.opacity = 0; }, 240);
    }
    
    /* ============================================================
     * 特效
     * ============================================================ */
    let pGeo = null;
    const pMatCache = {};
    
    function spawnParticles(pos, color, count, scale) {
      if (!pGeo) pGeo = new THREE.SphereGeometry(1, 5, 5);
      if (!pMatCache[color]) pMatCache[color] = new THREE.MeshBasicMaterial({ color: color });
      const base = 0.06 * (scale || 1);
      for (let i = 0; i < count; i++) {
        const m = new THREE.Mesh(pGeo, pMatCache[color]);
        m.position.copy(pos);
        m.scale.setScalar(base);
        scene.add(m);
        particles.push({
          mesh: m, base: base,
          vx: (Math.random() - 0.5) * 5.5,
          vy: 0.4 + Math.random() * 2.4,
          vz: (Math.random() - 0.5) * 5.5,
          life: 0.5 + Math.random() * 0.5,
          maxLife: 1,
        });
      }
    }
    
    function spawnRing(pos, color, r) {
      const ring = new THREE.Mesh(
        new THREE.TorusGeometry(r * 0.35, 0.05, 6, 24),
        new THREE.MeshBasicMaterial({ color: color, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending })
      );
      ring.position.copy(pos);
      ring.rotation.x = Math.PI / 2;
      scene.add(ring);
      rings.push({ mesh: ring, t: 0, max: 0.45 });
    }
    
    function addBloodStain(x, z, r) {
      const geo = new THREE.CircleGeometry(r, 12);
      const mesh = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
        color: 0x4a0d16, transparent: true, opacity: 0.55, depthWrite: false,
      }));
      mesh.rotation.x = -Math.PI / 2;
      mesh.position.set(x, 0.025, z);
      scene.add(mesh);
      stains.push({ mesh: mesh, t: 0 });
      if (stains.length > 45) {
        const old = stains.shift();
        scene.remove(old.mesh);
      }
    }
    
    /* ============================================================
     * 更新
     * ============================================================ */
    function update(dt) {
      if (G.state === 'playing') {
        updatePlayer(dt);
        updateEnemies(dt);
        enemies = enemies.filter(function (e) { return e.alive; });
        updateSpawner(dt);
        updateHUD();
      }
      updateCorpses(dt);
      updateGun(dt);
      updateParticles(dt);
      updateRings(dt);
      if (G.state === 'playing') updateCrates(dt);
    
      muzzle.material.opacity = Math.max(0, muzzle.material.opacity - dt * 12);
      muzzleLight.intensity = Math.max(0, muzzleLight.intensity - dt * 14);
    }
    
    function updatePlayer(dt) {
      let f = 0, s = 0;
      if (keys['KeyW'] || keys['ArrowUp']) f += 1;
      if (keys['KeyS'] || keys['ArrowDown']) f -= 1;
      if (keys['KeyD'] || keys['ArrowRight']) s += 1;
      if (keys['KeyA'] || keys['ArrowLeft']) s -= 1;
    
      const speed = 5.0 * (player.infection >= 100 ? 0.85 : 1);
      let nx = player.pos.x, nz = player.pos.z;
    
      if (f !== 0 || s !== 0) {
        const fx = -Math.sin(player.yaw), fz = -Math.cos(player.yaw);
        const rx = Math.cos(player.yaw), rz = -Math.sin(player.yaw);
        let vx = fx * f + rx * s;
        let vz = fz * f + rz * s;
        const len = Math.hypot(vx, vz) || 1;
        nx = player.pos.x + (vx / len) * speed * dt;
        nz = player.pos.z + (vz / len) * speed * dt;
        player.moveBob += dt * 9;
      } else {
        player.moveBob += dt * 1.5;
      }
    
      const R = 0.42;
      nx = Math.max(-HALF + R, Math.min(HALF - R, nx));
      nz = Math.max(-HALF + R, Math.min(HALF - R, nz));
    
      // 树干碰撞(圆形推出)
      for (let i = 0; i < trees.length; i++) {
        const t = trees[i];
        const dx = nx - t.x, dz = nz - t.z;
        const d = Math.hypot(dx, dz);
        const min = t.r + R;
        if (d < min) {
          if (d < 1e-4) { nx = t.x + min; }
          else { nx = t.x + (dx / d) * min; nz = t.z + (dz / d) * min; }
        }
      }
    
      player.pos.x = nx;
      player.pos.z = nz;
    
      camera.rotation.y = player.yaw;
      camera.rotation.x = player.pitch;
    
      let bobY = Math.sin(player.moveBob) * 0.032;
      if (player.shake > 0) {
        player.shake -= dt;
        bobY += (Math.random() - 0.5) * 0.06;
        camera.rotation.z = (Math.random() - 0.5) * 0.03;
      } else {
        camera.rotation.z *= 0.9;
      }
      camera.position.y = 1.65 + bobY;
    
      player.fireCd -= dt;
      if ((firing || keys['Space']) && player.fireCd <= 0) tryFire();
    
      if (player.reloading) {
        player.reloadT -= dt;
        if (player.reloadT <= 0) {
          player.reloading = false;
          player.ammo = player.mag;
          updateHUD(true);
        }
      }
    
      // 护甲缓慢自动修复
      if (player.armorDelay > 0) {
        player.armorDelay -= dt;
      } else if (player.armor < player.maxArmor) {
        player.armor = Math.min(player.maxArmor, player.armor + dt * 2.5);
      }
    
      if (G.dmgFlash > 0) {
        G.dmgFlash -= dt * 1.2;
        document.getElementById('damage').style.opacity = Math.max(0, G.dmgFlash);
      }
    }
    
    function updateGun(dt) {
      player.recoil = Math.max(0, player.recoil - dt * 9);
      const rec = player.recoil * player.recoil;
      gunGroup.position.z = -0.78 + rec * 0.16;
      gunGroup.position.y = -0.21 + Math.sin(player.moveBob) * 0.014 + rec * 0.03;
      gunGroup.rotation.x = -rec * 0.28;
      gunGroup.rotation.z = Math.sin(player.moveBob * 0.5) * 0.012;
    
      if (player.reloading) {
        gunGroup.rotation.x += Math.sin(clock.elapsedTime * 14) * 0.12;
        gunGroup.position.y -= 0.06;
      }
    }
    
    function updateSpawner(dt) {
      G.spawnT -= dt;
      const cap = Math.min(20, 4 + G.wave * 2);
      if (G.spawnT <= 0 && enemies.length < cap) {
        const eliteChance = Math.min(0.3, 0.05 + G.wave * 0.03);
        makeZombie(Math.random() < eliteChance);
        if (Math.random() < 0.35) sfx.groan();
        G.spawnT = Math.max(0.55, 1.8 - G.wave * 0.12);
      }
    }
    
    function updateEnemies(dt) {
      const t = clock.elapsedTime;
      const px = player.pos.x, pz = player.pos.z;
    
      for (let i = 0; i < enemies.length; i++) {
        const e = enemies[i];
        if (!e.alive) continue;
    
        const g = e.group;
        const ud = g.userData;
        const dx = px - g.position.x;
        const dz = pz - g.position.z;
        const dist = Math.hypot(dx, dz);
    
        // 朝玩家缓慢行走,带树木排斥
        if (dist > 1.15) {
          let mx = dx / dist, mz = dz / dist;
          for (let k = 0; k < trees.length; k++) {
            const tr = trees[k];
            const ox = g.position.x - tr.x, oz = g.position.z - tr.z;
            const od = Math.hypot(ox, oz);
            if (od < tr.r + 1.1 && od > 1e-4) {
              const push = (tr.r + 1.1 - od) / (tr.r + 1.1);
              mx += (ox / od) * push * 1.8;
              mz += (oz / od) * push * 1.8;
            }
          }
          const ml = Math.hypot(mx, mz) || 1;
          mx /= ml; mz /= ml;
    
          const sp = e.speed * (1 + G.wave * 0.03);
          g.position.x += mx * sp * dt;
          g.position.z += mz * sp * dt;
          e.walkPhase += dt * (2.2 + e.speed * 0.6);
        } else {
          e.walkPhase += dt * 1.1;
        }
    
        // 面向玩家
        const targetRot = Math.atan2(-dx, -dz);
        let diff = targetRot - g.rotation.y;
        while (diff > Math.PI) diff -= Math.PI * 2;
        while (diff < -Math.PI) diff += Math.PI * 2;
        g.rotation.y += diff * Math.min(1, dt * 5);
    
        // 行走动画
        const swing = Math.sin(e.walkPhase) * 0.55;
        ud.legL.rotation.x = swing;
        ud.legR.rotation.x = -swing;
        ud.armL.rotation.x = -1.32 + Math.sin(e.walkPhase * 0.5) * 0.12;
        ud.armR.rotation.x = -1.46 - Math.sin(e.walkPhase * 0.5) * 0.12;
        g.rotation.z = Math.sin(e.walkPhase) * 0.055;
        ud.headPivot.rotation.z = Math.sin(e.walkPhase * 0.7) * 0.12;
        ud.headPivot.rotation.x = 0.16 + Math.sin(t * 1.3 + e.walkPhase) * 0.05;
    
        // 受击闪白回复
        if (e.hitT > 0) {
          e.hitT -= dt;
          if (e.hitT <= 0) ud.skinMat.emissiveIntensity = e.elite ? 0.7 : 0.6;
        }
    
        // 攻击(挥爪)
        e.attackCd -= dt;
        const reach = 1.35 + e.reach;
        if (dist < reach) {
          if (e.attackCd <= 0) {
            e.attackCd = e.elite ? 1.5 : 1.9;
            ud.armL.rotation.x = -2.2;
            ud.armR.rotation.x = -2.3;
            hurtPlayer(1);
            spawnParticles(new THREE.Vector3(g.position.x, 1.1, g.position.z), 0x9f1239, 7, 0.55);
          } else if (e.attackCd < 1.2) {
            // 挥爪动作回位
            ud.armL.rotation.x += (-1.32 - ud.armL.rotation.x) * Math.min(1, dt * 8);
            ud.armR.rotation.x += (-1.46 - ud.armR.rotation.x) * Math.min(1, dt * 8);
          }
        }
      }
    }
    
    function updateCorpses(dt) {
      for (let i = corpses.length - 1; i >= 0; i--) {
        const c = corpses[i];
        c.t += dt;
        if (c.t < 1.1) {
          c.group.rotation.x = -Math.min(1.55, c.t * 4);
          c.group.position.y = -Math.min(0.18, c.t * 0.5);
        } else if (c.t > 3.2) {
          const fade = Math.max(0, 1 - (c.t - 3.2) / 0.8);
          c.group.position.y = -0.18 - (1 - fade) * 1.2;
          if (fade <= 0) {
            scene.remove(c.group);
            corpses.splice(i, 1);
          }
        }
      }
      // 血渍随时间略微变暗
      for (let i = 0; i < stains.length; i++) {
        stains[i].t += dt;
        const m = stains[i].mesh.material;
        m.opacity = Math.max(0.18, 0.55 - stains[i].t * 0.02);
      }
    }
    
    function hurtPlayer(dmg) {
      if (!player.alive) return;
      player.armorDelay = 3.5;
    
      // 护甲先扛,护甲扛完了才掉血(每次被抓只掉 1 点)
      if (player.armor > 0) {
        player.armor = Math.max(0, player.armor - dmg);
      } else {
        player.hp -= dmg;
      }
    
      // 被咬会累积感染,但不影响行动与搜索
      player.infection = Math.min(100, player.infection + (player.armor > 0 ? 2 : 6));
    
      G.dmgFlash = 0.45;
      player.shake = 0.2;
      sfx.hurt();
      if (player.hp <= 0) {
        player.hp = 0;
        player.alive = false;
        updateHUD(true);
        setTimeout(gameOver, 320);
      }
      updateHUD();
    }
    
    function updateParticles(dt) {
      for (let i = particles.length - 1; i >= 0; i--) {
        const p = particles[i];
        p.life -= dt;
        if (p.life <= 0) {
          scene.remove(p.mesh);
          particles.splice(i, 1);
          continue;
        }
        p.vy -= 4.2 * dt;
        p.mesh.position.x += p.vx * dt;
        p.mesh.position.y += p.vy * dt;
        p.mesh.position.z += p.vz * dt;
        const s = Math.max(0.02, p.life / p.maxLife);
        p.mesh.scale.setScalar(p.base * s);
      }
    }
    
    function updateRings(dt) {
      for (let i = rings.length - 1; i >= 0; i--) {
        const r = rings[i];
        r.t += dt;
        const k = r.t / r.max;
        if (k >= 1) {
          scene.remove(r.mesh);
          rings.splice(i, 1);
          continue;
        }
        r.mesh.scale.setScalar(0.4 + k * 1.8);
        r.mesh.material.opacity = 0.9 * (1 - k);
      }
    }
    
    /* ============================================================
     * HUD
     * ============================================================ */
    let lastHud = { hp: -1, ammo: -1, score: -1, wave: -1, armor: -1, inf: -1 };
    
    function updateHUD(force) {
      const hp = Math.max(0, Math.round(player.hp));
      if (force || hp !== lastHud.hp) {
        lastHud.hp = hp;
        const fill = document.getElementById('hpFill');
        fill.style.width = (hp / player.maxHp * 100) + '%';
        fill.style.background = hp > 300 ? 'linear-gradient(90deg,#22c55e,#65a30d,#a3e635)'
          : hp > 150 ? 'linear-gradient(90deg,#fbbf24,#f59e0b)'
          : 'linear-gradient(90deg,#ef4444,#dc2626)';
        document.getElementById('hpNum').innerHTML = hp + '<small> / ' + player.maxHp + '</small>';
      }
      const ar = Math.round(player.armor);
      if (force || ar !== lastHud.armor) {
        lastHud.armor = ar;
        document.getElementById('armorFill').style.width = (ar / player.maxArmor * 100) + '%';
        document.getElementById('armorNum').textContent = ar + ' / ' + player.maxArmor;
      }
      const inf = Math.round(player.infection);
      if (force || inf !== lastHud.inf) {
        lastHud.inf = inf;
        const el = document.getElementById('infNum');
        el.textContent = inf >= 100 ? '已感染 100% · 仍可移动与搜索' : '感染 ' + inf + '%';
        el.style.color = inf >= 60 ? '#fca5a5' : '#a3e635';
      }
      if (force || player.ammo !== lastHud.ammo) {
        lastHud.ammo = player.ammo;
        document.getElementById('ammoNum').innerHTML = player.ammo + '<small> / ' + player.mag + '</small>';
        document.getElementById('ammoState').textContent =
          player.reloading ? '换弹中…' : (player.ammo === 0 ? '弹匣空 · 按 R 换弹' : '突击步枪');
      }
      if (force || G.score !== lastHud.score) {
        lastHud.score = G.score;
        document.getElementById('scoreNum').textContent = G.score;
      }
      if (force || G.wave !== lastHud.wave) {
        lastHud.wave = G.wave;
        document.getElementById('waveNum').textContent = '波次 ' + G.wave;
      }
    }
    
    function reload() {
      if (player.reloading || player.ammo === player.mag) return;
      player.reloading = true;
      player.reloadT = 1.0;
      sfx.reload();
      document.getElementById('ammoState').textContent = '换弹中…';
    }
    
    /* ---------- 雷达 ---------- */
    let radarCanvas, radarCtx;
    function buildRadar() {
      const size = 132;
      radarCanvas = document.createElement('canvas');
      radarCanvas.width = radarCanvas.height = size;
      radarCanvas.style.width = radarCanvas.style.height = size + 'px';
      radarCanvas.style.opacity = '0.92';
      document.getElementById('radar').appendChild(radarCanvas);
      radarCtx = radarCanvas.getContext('2d');
    }
    
    function drawRadar() {
      if (!radarCtx) return;
      const S = radarCanvas.width, cx = S / 2, cy = S / 2, R = S / 2 - 6, range = 30;
    
      radarCtx.clearRect(0, 0, S, S);
      radarCtx.beginPath();
      radarCtx.arc(cx, cy, R, 0, Math.PI * 2);
      radarCtx.fillStyle = 'rgba(8,20,12,.75)';
      radarCtx.fill();
      radarCtx.strokeStyle = 'rgba(134,239,172,.45)';
      radarCtx.lineWidth = 1.5;
      radarCtx.stroke();
    
      radarCtx.strokeStyle = 'rgba(134,239,172,.18)';
      radarCtx.beginPath();
      radarCtx.moveTo(cx - R, cy); radarCtx.lineTo(cx + R, cy);
      radarCtx.moveTo(cx, cy - R); radarCtx.lineTo(cx, cy + R);
      radarCtx.stroke();
    
      radarCtx.beginPath();
      radarCtx.moveTo(cx, cy);
      radarCtx.arc(cx, cy, R, -Math.PI / 2 - 0.62, -Math.PI / 2 + 0.62);
      radarCtx.closePath();
      radarCtx.fillStyle = 'rgba(134,239,172,.12)';
      radarCtx.fill();
    
      for (let i = 0; i < enemies.length; i++) {
        const e = enemies[i];
        if (!e.alive) continue;
        const dx = e.group.position.x - player.pos.x;
        const dz = e.group.position.z - player.pos.z;
        const fwdC = dx * (-Math.sin(player.yaw)) + dz * (-Math.cos(player.yaw));
        const rightC = dx * Math.cos(player.yaw) + dz * (-Math.sin(player.yaw));
        const px = cx + (rightC / range) * R;
        const py = cy - (fwdC / range) * R;
        if (Math.hypot(px - cx, py - cy) > R - 2) continue;
        radarCtx.fillStyle = e.elite ? '#fb923c' : '#ef4444';
        radarCtx.beginPath();
        radarCtx.arc(px, py, e.elite ? 4 : 2.8, 0, Math.PI * 2);
        radarCtx.fill();
      }
    
      radarCtx.fillStyle = '#86efac';
      radarCtx.beginPath();
      radarCtx.moveTo(cx, cy - 7);
      radarCtx.lineTo(cx - 4, cy + 5);
      radarCtx.lineTo(cx + 4, cy + 5);
      radarCtx.closePath();
      radarCtx.fill();
    }
    
    /* ============================================================
     * 主循环
     * ============================================================ */
    function onResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }
    
    function loop() {
      const dt = Math.min(0.05, clock.getDelta());
      if (G.state === 'playing') update(dt);
      else {
        muzzle.material.opacity = Math.max(0, muzzle.material.opacity - dt * 12);
        muzzleLight.intensity = Math.max(0, muzzleLight.intensity - dt * 14);
        updateCorpses(dt);
        updateParticles(dt);
        updateRings(dt);
        updateGun(dt);
      }
      drawRadar();
      renderer.render(scene, camera);
      requestAnimationFrame(loop);
    }
    </script>
    </body>
    </html>
    
    
    
    
  • 通过的题目

  • 最近活动

  • 最近编写的题解

题目标签

语言基础
123
循环语句
74
选择语句
36
一维数组
34
字符串
30
字符数组
26
其他
22
数学知识
22
语言入门
22
竞赛
21
NOIP
20
二维数组
20
搜索
18
高精度
11
年份
10
普及组
10
贪心
9
位运算
8
数据结构
8
输入输出
8