🔬 AI発明ギャラリー › りい › ちいかわおばけやしき
🔒 サンドボックス内で実行中 ⛶ 全画面で遊ぶ
HTML / CSS / JS
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>映画ちいかわ:オバケ屋敷とセイレーンの大冒険 3D 〜なんとかなれ〜</title>
  <!-- Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Three.js (r128) -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  <!-- Google Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Mochiy+Pop+One&family=Zen+Maru+Gothic:wght@500;700;900&display=swap" rel="stylesheet">

  <style>
    body {
      font-family: 'Zen Maru Gothic', sans-serif;
      touch-action: none;
      user-select: none;
      -webkit-user-select: none;
      overflow: hidden;
      background-color: #1e1b4b;
    }
    .font-pop {
      font-family: 'Mochiy+Pop One', cursive;
    }
    /* アニメーション */
    @keyframes eeriePulse {
      0%, 100% { opacity: 0.9; filter: drop-shadow(0 0 15px rgba(236, 72, 153, 0.5)); }
      50% { opacity: 1; filter: drop-shadow(0 0 25px rgba(56, 189, 248, 0.8)); }
    }
    .eerie-glow {
      animation: eeriePulse 3s infinite ease-in-out;
    }
    /* 恐怖時の画面赤ビネット演出 */
    .fright-vignette {
      box-shadow: inset 0 0 80px rgba(220, 38, 38, 0.85);
      pointer-events: none;
    }
    /* 明るい映画風の周辺フレーム */
    .film-frame {
      border: 3px solid rgba(244, 114, 182, 0.2);
      pointer-events: none;
    }
    ::-webkit-scrollbar {
      display: none;
    }
  </style>
</head>
<body class="w-screen h-screen relative text-slate-100 flex flex-col justify-between">

  <!-- ==================== 3Dキャンバス描画コンテナ ==================== -->
  <div id="canvasContainer" class="absolute inset-0 w-full h-full z-0 cursor-grab active:cursor-grabbing"></div>

  <!-- 明るい映画フレーム調オーバーレイ -->
  <div id="vignetteOverlay" class="absolute inset-0 z-10 film-frame pointer-events-none"></div>
  <div id="panicOverlay" class="absolute inset-0 z-10 fright-vignette opacity-0 transition-opacity duration-300 pointer-events-none"></div>

  <!-- ==================== 探索中UIヘッダー ==================== -->
  <header id="gameHeader" class="hidden absolute top-0 left-0 right-0 z-20 px-3 sm:px-6 py-2.5 flex items-center justify-between bg-slate-900/85 backdrop-blur-md border-b border-pink-400/30 shadow-lg">
    <div class="flex items-center gap-3">
      <!-- 操作中キャラのアイコン -->
      <div id="statusAvatar" class="w-11 h-11 rounded-full bg-slate-800 border-2 border-pink-400 flex items-center justify-center font-bold text-lg shadow-inner overflow-hidden">
        ち
      </div>
      <div>
        <div class="flex items-center gap-2">
          <span id="charNameDisplay" class="font-bold text-sm sm:text-base text-pink-200">ちいかわ</span>
          <span id="roomNameBadge" class="text-xs bg-purple-900/80 text-purple-200 px-2.5 py-0.5 rounded-full border border-purple-400/40">🚪 エントランス</span>
        </div>
        <!-- ゆうきゲージ -->
        <div class="flex items-center gap-1.5 mt-1">
          <span class="text-[11px] text-pink-300 font-bold">ゆうき:</span>
          <div class="w-28 sm:w-44 h-2.5 bg-slate-800 rounded-full overflow-hidden border border-slate-700">
            <div id="courageBar" class="h-full bg-gradient-to-r from-pink-500 to-amber-400 w-full transition-all duration-300 rounded-full"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- おふだ収集数 & セイレーン警告 & 音声トグル -->
    <div class="flex items-center gap-2.5">
      <!-- セイレーン接近アラート -->
      <div id="sirenWarning" class="hidden flex items-center gap-1 bg-cyan-900/80 border border-cyan-400/60 px-2.5 py-1 rounded-xl text-cyan-200 text-xs font-bold animate-pulse shadow">
        <span>🧜‍♀️🎶</span>
        <span class="hidden sm:inline">セイレーンの歌声が近い…!</span>
      </div>
      <div class="flex items-center gap-1.5 bg-amber-950/70 border border-amber-500/60 px-3 py-1 rounded-xl shadow">
        <span class="text-amber-400 text-sm">📜</span>
        <span class="text-xs text-amber-200 font-bold">おふだ:</span>
        <span id="talismanCounter" class="text-sm font-pop text-amber-300">0 / 4</span>
      </div>
      <button id="soundToggleBtn" class="w-9 h-9 rounded-full bg-slate-800/90 border border-slate-600 flex items-center justify-center text-sm hover:bg-slate-700 active:scale-95 transition shadow">
        🔊
      </button>
    </div>
  </header>

  <!-- 3Dワールド内のセリフ吹き出し -->
  <div id="speechBubble" class="absolute pointer-events-none transition-all duration-200 opacity-0 transform -translate-y-4 z-20 flex flex-col items-center">
    <div class="bg-white/95 text-slate-800 text-xs sm:text-sm font-bold px-3.5 py-1.5 rounded-2xl shadow-2xl border-2 border-purple-400 flex items-center gap-1.5 max-w-xs text-center">
      <span id="bubbleEmotion">💧</span>
      <span id="bubbleText">ワッ…!</span>
    </div>
    <div class="w-2.5 h-2.5 bg-white rotate-45 -mt-1 border-r-2 border-b-2 border-purple-400"></div>
  </div>

  <!-- 近くのアイテム調べ可能インジケーター -->
  <div id="interactPrompt" class="hidden absolute top-20 left-1/2 -translate-x-1/2 z-20 bg-amber-500 text-slate-950 font-bold text-xs sm:text-sm px-4 py-1.5 rounded-full shadow-lg border-2 border-white animate-bounce flex items-center gap-1.5">
    <span>🔍</span>
    <span id="interactPromptText">おふだを調べる [Space / E]</span>
  </div>

  <!-- ==================== モバイル用タッチUI ==================== -->
  <div id="mobileControls" class="hidden absolute bottom-4 left-0 right-0 z-30 px-4 flex justify-between items-end pointer-events-none">
    <!-- バーチャルD-Pad -->
    <div class="relative w-36 h-36 bg-slate-900/75 backdrop-blur-md rounded-full border border-purple-500/40 p-2 pointer-events-auto shadow-2xl">
      <button id="btnUp" class="absolute top-1 left-1/2 -translate-x-1/2 w-11 h-11 bg-slate-800/90 active:bg-pink-600 rounded-xl flex items-center justify-center text-purple-200 font-bold text-lg border border-purple-400/30">▲</button>
      <button id="btnDown" class="absolute bottom-1 left-1/2 -translate-x-1/2 w-11 h-11 bg-slate-800/90 active:bg-pink-600 rounded-xl flex items-center justify-center text-purple-200 font-bold text-lg border border-purple-400/30">▼</button>
      <button id="btnLeft" class="absolute left-1 top-1/2 -translate-y-1/2 w-11 h-11 bg-slate-800/90 active:bg-pink-600 rounded-xl flex items-center justify-center text-purple-200 font-bold text-lg border border-purple-400/30">◀</button>
      <button id="btnRight" class="absolute right-1 top-1/2 -translate-y-1/2 w-11 h-11 bg-slate-800/90 active:bg-pink-600 rounded-xl flex items-center justify-center text-purple-200 font-bold text-lg border border-purple-400/30">▶</button>
      <div class="absolute inset-0 m-auto w-9 h-9 rounded-full bg-purple-950/70 border border-purple-500/30 flex items-center justify-center text-[10px] text-pink-300 font-bold">歩く</div>
    </div>

    <!-- アクションボタン群 -->
    <div class="flex flex-col gap-2.5 pointer-events-auto items-end">
      <!-- スキルボタン -->
      <button id="btnSkill" class="w-16 h-16 rounded-full bg-gradient-to-tr from-purple-700 via-pink-600 to-amber-500 active:scale-90 text-white font-bold text-xs flex flex-col items-center justify-center shadow-2xl border-2 border-pink-300">
        <span class="text-lg" id="skillIconDisplay">✨</span>
        <span class="text-[10px]">スキル</span>
      </button>
      <!-- しらべるボタン -->
      <button id="btnAction" class="w-14 h-14 rounded-full bg-amber-600 active:bg-amber-500 active:scale-90 text-white font-bold text-xs flex flex-col items-center justify-center shadow-xl border-2 border-amber-300">
        <span class="text-base">🔍</span>
        <span class="text-[10px]">しらべる</span>
      </button>
    </div>
  </div>

  <!-- PC用キーボード操作ヒント -->
  <div id="pcHint" class="hidden sm:block absolute bottom-3 left-4 text-xs text-slate-300/90 bg-slate-900/80 backdrop-blur px-3.5 py-1.5 rounded-xl border border-purple-500/30 z-20 pointer-events-none">
    ⌨️ 移動: <span class="text-purple-300 font-bold">[W A S D]</span> / 視点回転: <span class="text-cyan-300 font-bold">[画面ドラッグ]</span> / しらべる: <span class="text-amber-300 font-bold">[Space / E]</span> / 特技: <span class="text-pink-300 font-bold">[Q / F]</span>
  </div>

  <!-- ==================== スタート画面:3Dキャラ選択 ==================== -->
  <div id="startScreen" class="absolute inset-0 z-40 bg-slate-950/92 backdrop-blur-md flex flex-col items-center justify-center p-4 overflow-y-auto">
    <div class="max-w-md w-full text-center my-auto flex flex-col items-center">
      <!-- 映画バナー -->
      <div class="mb-3 inline-block">
        <div class="text-[11px] tracking-widest text-cyan-300 font-bold uppercase mb-1 border border-cyan-500/40 rounded-full px-3 py-0.5 bg-cyan-950/50">
          🎬 映画ちいかわ 巨大セイレーン登場 3D 🎬
        </div>
        <h1 class="font-pop text-2xl sm:text-3xl text-transparent bg-clip-text bg-gradient-to-r from-pink-300 via-cyan-200 to-amber-200 eerie-glow drop-shadow leading-tight">
          映画ちいかわ<br>オバケ屋敷とセイレーンの大冒険
        </h1>
        <p class="text-xs text-purple-200/90 mt-1">〜 美しく歌う巨大セイレーンとオバケ屋敷から脱出せよ! 〜</p>
      </div>

      <!-- 遊び方あらすじ -->
      <div class="bg-slate-900/85 border border-cyan-500/30 p-3.5 rounded-2xl mb-4 text-left text-xs text-slate-200 leading-relaxed shadow-lg">
        <p class="text-pink-300 font-bold mb-1">🌟 映画の3D特設スタジオがライトアップ!</p>
        <p>屋敷の回廊には、妖しい歌声で迫る<span class="text-cyan-300 font-bold">【巨大セイレーン】</span>が泳ぎ回っています!</p>
        <p class="mt-1 text-amber-300 font-bold">📜 屋敷に散らばる【4枚のおふだ】を集めて、奥の映写室から脱出を目指そう!</p>
      </div>
        <h1 class="font-pop text-2xl sm:text-3xl text-transparent bg-clip-text bg-gradient-to-r from-pink-300 via-purple-200 to-amber-200 eerie-glow drop-shadow leading-tight">
          映画ちいかわ<br>オバケ屋敷の大冒険 3D
        </h1>
        <p class="text-xs text-purple-300/90 mt-1">〜 4枚のおふだを見つけて、3Dの映写室から脱出せよ! 〜</p>
      </div>

      <!-- 遊び方あらすじ -->
      <div class="bg-slate-900/80 border border-purple-500/30 p-3 rounded-2xl mb-4 text-left text-xs text-slate-300 leading-relaxed shadow-lg">
        <p>オバケ映画の3D撮影スタジオで迷子になっちゃった…!</p>
        <p class="mt-1 text-pink-300 font-bold">🔦 懐中電灯を持って3Dの洋館を歩き、隠された<span class="text-amber-300">【4枚のおふだ】</span>を集めて出口の扉を開けよう!</p>
      </div>

      <!-- キャラクター選択カード -->
      <p class="text-xs font-bold text-pink-200 mb-2">▼ いっしょに探索するキャラクターを選択</p>
      <div class="grid grid-cols-2 gap-2.5 w-full mb-4" id="charSelectGrid">
        <!-- 悪魔うさぎ (画像キャラクター・新主人公) -->
        <button class="char-card selected relative p-2.5 rounded-xl border-2 border-purple-400 bg-purple-950/70 hover:bg-purple-900/80 flex flex-col items-center transition active:scale-95 text-left ring-2 ring-purple-300" data-char="devil_usagi">
          <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center mb-1 border-2 border-purple-400 shadow overflow-hidden">
            <span class="text-2xl">🦇🐰</span>
          </div>
          <span class="font-bold text-sm text-purple-200">悪魔うさぎ</span>
          <span class="text-[10px] text-purple-300 font-bold">特技: 漆黒の怪鳥波 (画像主役)</span>
        </button>

        <!-- ちいかわ -->
        <button class="char-card relative p-2.5 rounded-xl border-2 border-slate-700 bg-slate-900/60 hover:bg-slate-800 flex flex-col items-center transition active:scale-95 text-left" data-char="chiikawa">
          <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center mb-1 border-2 border-slate-300 shadow">
            <span class="text-2xl">🥺</span>
          </div>
          <span class="font-bold text-sm text-pink-200">ちいかわ</span>
          <span class="text-[10px] text-pink-300/80">特技: 勇気の一閃(オバケ消去)</span>
        </button>

        <!-- ハチワレ -->
        <button class="char-card relative p-2.5 rounded-xl border-2 border-slate-700 bg-slate-900/60 hover:bg-slate-800 flex flex-col items-center transition active:scale-95 text-left" data-char="hachiware">
          <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-1 border-2 border-blue-400 shadow">
            <span class="text-2xl">🐱</span>
          </div>
          <span class="font-bold text-sm text-blue-200">ハチワレ</span>
          <span class="text-[10px] text-blue-300/80">特技: なんとかなれダッシュ</span>
        </button>

        <!-- モモンガ -->
        <button class="char-card relative p-2.5 rounded-xl border-2 border-slate-700 bg-slate-900/60 hover:bg-slate-800 flex flex-col items-center transition active:scale-95 text-left" data-char="momonga">
          <div class="w-12 h-12 bg-cyan-100 rounded-full flex items-center justify-center mb-1 border-2 border-cyan-400 shadow">
            <span class="text-2xl">🐿️</span>
          </div>
          <span class="font-bold text-sm text-cyan-200">モモンガ</span>
          <span class="text-[10px] text-cyan-300/80">特技: ほめろ!(オバケ停止)</span>
        </button>
      </div>

      <!-- スタートボタン -->
      <button id="startGameBtn" class="w-full py-3.5 px-6 rounded-2xl bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-600 text-white font-pop text-lg shadow-xl hover:opacity-95 active:scale-95 transition-all border-2 border-pink-300/60 eerie-glow">
        🔦 3Dオバケ屋敷に入るッ!
      </button>
    </div>
  </div>

  <!-- ==================== ゲームクリアモーダル ==================== -->
  <div id="clearModal" class="hidden absolute inset-0 z-50 bg-slate-950/92 backdrop-blur-md flex flex-col items-center justify-center p-4">
    <div class="max-w-md w-full bg-slate-900 border-2 border-amber-400 rounded-3xl p-6 text-center shadow-2xl relative">
      <div class="text-5xl mb-2">🎬🎉✨</div>
      <h2 class="font-pop text-2xl text-amber-300 mb-1">映画撮影クランクアップ!</h2>
      <p class="text-xs text-purple-200 font-bold mb-4">3Dオバケ屋敷から無事に脱出成功!</p>
      
      <div class="bg-slate-800/80 rounded-2xl p-4 mb-4 text-xs text-slate-300 space-y-2.5 border border-slate-700 text-left">
        <p class="flex justify-between"><span>脱出した仲間:</span> <span id="clearCharName" class="font-bold text-pink-300">ちいかわ</span></p>
        <p class="flex justify-between"><span>集めたおふだ:</span> <span class="font-bold text-amber-300">4 / 4 枚 完全回収</span></p>
        <p class="flex justify-between"><span>のこり勇気:</span> <span id="clearCourageLeft" class="font-bold text-green-400">100%</span></p>
        <div class="pt-2 border-t border-slate-700 text-center font-bold text-amber-200 text-sm">
          🏆 特別称号: <span id="clearTitleText">「3Dなんとかなった大スター」</span>
        </div>
      </div>

      <button id="restartBtn" class="w-full py-3 rounded-xl bg-gradient-to-r from-amber-500 to-pink-500 text-white font-bold text-sm shadow-lg active:scale-95 transition">
        もういちど遊ぶ(キャラクター変更)
      </button>
    </div>
  </div>

  <!-- ==================== ゲームオーバー/気絶モーダル ==================== -->
  <div id="faintModal" class="hidden absolute inset-0 z-50 bg-purple-950/92 backdrop-blur-md flex flex-col items-center justify-center p-4">
    <div class="max-w-md w-full bg-slate-900 border-2 border-pink-500 rounded-3xl p-6 text-center shadow-2xl">
      <div class="text-5xl mb-2">😭💦</div>
      <h2 class="font-pop text-2xl text-pink-400 mb-2">こわすぎて泣いちゃった…!</h2>
      <p class="text-xs text-slate-300 mb-4 leading-relaxed">
        3Dオバケに囲まれて勇気がゼロになっちゃいました。<br>入口の安全なランタンまで戻ってひと休みします…!
      </p>
      <button id="retryBtn" class="w-full py-3 rounded-xl bg-gradient-to-r from-pink-600 to-purple-600 text-white font-bold text-sm shadow-lg active:scale-95 transition">
        泣き止んで再挑戦するッ!
      </button>
    </div>
  </div>

  <!-- トースト通知 -->
  <div id="toast" class="absolute top-16 left-1/2 -translate-x-1/2 bg-slate-900/95 border border-amber-400/80 text-amber-200 text-xs sm:text-sm font-bold px-4 py-2 rounded-full shadow-2xl opacity-0 pointer-events-none transition-all duration-300 z-30 flex items-center gap-2">
    <span id="toastIcon">💡</span>
    <span id="toastMsg">ここにメッセージ</span>
  </div>

  <!-- ==================== ゲームスクリプト (Three.js & ロジック) ==================== -->
  <script>
    /* ------------------------------------------------------------------
       Web Audio API によるレトロ&キュートなサウンド合成エンジン
       ------------------------------------------------------------------ */
    class SoundEngine {
      constructor() {
        this.ctx = null;
        this.muted = false;
      }
      init() {
        if (!this.ctx) {
          const AudioContext = window.AudioContext || window.webkitAudioContext;
          if (AudioContext) this.ctx = new AudioContext();
        }
        if (this.ctx && this.ctx.state === 'suspended') {
          this.ctx.resume();
        }
      }
      playStep() {
        if (this.muted || !this.ctx) return;
        try {
          const osc = this.ctx.createOscillator();
          const gain = this.ctx.createGain();
          osc.type = 'triangle';
          osc.frequency.setValueAtTime(120 + Math.random() * 30, this.ctx.currentTime);
          gain.gain.setValueAtTime(0.04, this.ctx.currentTime);
          gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.08);
          osc.connect(gain);
          gain.connect(this.ctx.destination);
          osc.start();
          osc.stop(this.ctx.currentTime + 0.08);
        } catch(e) {}
      }
      playGhostScare() {
        if (this.muted || !this.ctx) return;
        try {
          const osc = this.ctx.createOscillator();
          const gain = this.ctx.createGain();
          osc.type = 'sawtooth';
          osc.frequency.setValueAtTime(320, this.ctx.currentTime);
          osc.frequency.exponentialRampToValueAtTime(80, this.ctx.currentTime + 0.35);
          gain.gain.setValueAtTime(0.12, this.ctx.currentTime);
          gain.gain.linearRampToValueAtTime(0.001, this.ctx.currentTime + 0.4);
          osc.connect(gain);
          gain.connect(this.ctx.destination);
          osc.start();
          osc.stop(this.ctx.currentTime + 0.4);
        } catch(e) {}
      }
      playTalisman() {
        if (this.muted || !this.ctx) return;
        try {
          const notes = [523.25, 659.25, 783.99, 1046.50];
          notes.forEach((freq, idx) => {
            const osc = this.ctx.createOscillator();
            const gain = this.ctx.createGain();
            osc.type = 'sine';
            const t = this.ctx.currentTime + idx * 0.08;
            osc.frequency.setValueAtTime(freq, t);
            gain.gain.setValueAtTime(0.1, t);
            gain.gain.exponentialRampToValueAtTime(0.001, t + 0.3);
            osc.connect(gain);
            gain.connect(this.ctx.destination);
            osc.start(t);
            osc.stop(t + 0.3);
          });
        } catch(e) {}
      }
      playSkillSound(charType) {
        if (this.muted || !this.ctx) return;
        try {
          const osc = this.ctx.createOscillator();
          const gain = this.ctx.createGain();
          if (charType === 'devil_usagi') {
            // 悪魔うさぎのダーク&鋭い怪鳥音サウンド
            osc.type = 'sawtooth';
            osc.frequency.setValueAtTime(320, this.ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(1600, this.ctx.currentTime + 0.35);
            gain.gain.setValueAtTime(0.24, this.ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.45);
          } else if (charType === 'usagi') {
            osc.type = 'square';
            osc.frequency.setValueAtTime(450, this.ctx.currentTime);
            osc.frequency.linearRampToValueAtTime(1400, this.ctx.currentTime + 0.3);
            gain.gain.setValueAtTime(0.16, this.ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.38);
          } else if (charType === 'hachiware') {
            osc.type = 'triangle';
            osc.frequency.setValueAtTime(350, this.ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(950, this.ctx.currentTime + 0.28);
            gain.gain.setValueAtTime(0.18, this.ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.35);
          } else if (charType === 'momonga') {
            osc.type = 'sine';
            osc.frequency.setValueAtTime(900, this.ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(1500, this.ctx.currentTime + 0.2);
            gain.gain.setValueAtTime(0.16, this.ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.3);
          } else {
            osc.type = 'sine';
            osc.frequency.setValueAtTime(600, this.ctx.currentTime);
            osc.frequency.linearRampToValueAtTime(1200, this.ctx.currentTime + 0.25);
            gain.gain.setValueAtTime(0.2, this.ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.4);
          }
          osc.connect(gain);
          gain.connect(this.ctx.destination);
          osc.start();
          osc.stop(this.ctx.currentTime + 0.45);
        } catch(e) {}
      }
      playVictory() {
        if (this.muted || !this.ctx) return;
        try {
          const notes = [440, 554.37, 659.25, 880, 1108.73];
          notes.forEach((freq, idx) => {
            const osc = this.ctx.createOscillator();
            const gain = this.ctx.createGain();
            osc.type = 'triangle';
            const t = this.ctx.currentTime + idx * 0.12;
            osc.frequency.setValueAtTime(freq, t);
            gain.gain.setValueAtTime(0.15, t);
            gain.gain.exponentialRampToValueAtTime(0.001, t + 0.5);
            osc.connect(gain);
            gain.connect(this.ctx.destination);
            osc.start(t);
            osc.stop(t + 0.5);
          });
        } catch(e) {}
      }
      playSirenSong() {
        if (this.muted || !this.ctx) return;
        try {
          // セイレーンの妖しく美しい歌声アルペジオ
          const pitches = [587.33, 659.25, 783.99, 880.00, 1046.50];
          pitches.forEach((freq, idx) => {
            const osc = this.ctx.createOscillator();
            const gain = this.ctx.createGain();
            osc.type = 'sine';
            const t = this.ctx.currentTime + idx * 0.15;
            osc.frequency.setValueAtTime(freq, t);
            gain.gain.setValueAtTime(0.06, t);
            gain.gain.exponentialRampToValueAtTime(0.001, t + 0.5);
            osc.connect(gain);
            gain.connect(this.ctx.destination);
            osc.start(t);
            osc.stop(t + 0.55);
          });
        } catch(e) {}
      }
    }
    const sound = new SoundEngine();

    /* ------------------------------------------------------------------
       キャラクター定義
       ------------------------------------------------------------------ */
    const CHARACTERS = {
      devil_usagi: {
        id: 'devil_usagi',
        name: '悪魔うさぎ',
        bodyColor: 0xfaf5ee, // 画像のクリームホワイトの毛並み
        earColor: 0xfaf5ee,
        earInnerColor: 0xf3e8ff,
        wingColor: 0x27272a, // 背中の悪魔の翼
        chestFurColor: 0xffffff, // 胸元のモフモフファー
        speed: 7.2,
        maxCourage: 160,
        skillName: '漆黒の怪鳥波',
        skillIcon: '🦇',
        skillCooldown: 4500,
        skillVoice: 'ウララララァーーッッ!!(禍々しい叫び)',
        dialogues: {
          scared: ['ハァ!?(威嚇)', 'フゥーーン!', 'プルャッ!'],
          foundTalisman: ['ヤハッ!おふだァ!', 'フゥーーッハハハ!'],
          idle: ['こんなんなっちゃったァ…!', 'ウラ…ウララ…']
        }
      },
      chiikawa: {
        id: 'chiikawa',
        name: 'ちいかわ',
        bodyColor: 0xffffff,
        earColor: 0xffffff,
        earInnerColor: 0xfbcfe8,
        speed: 5.4,
        maxCourage: 100,
        skillName: '勇気の一閃',
        skillIcon: '✨',
        skillCooldown: 7000,
        skillVoice: 'ワ、ワァーーーッ!!',
        dialogues: {
          scared: ['フ…フッ…!', 'ワッ…!', 'こ、こわい…!', 'エッ…!?'],
          foundTalisman: ['わァ…!おふだあった!', 'やったァ…!'],
          idle: ['フッ…(ドキドキ)', 'なんとかなるかな…']
        }
      },
      hachiware: {
        id: 'hachiware',
        name: 'ハチワレ',
        bodyColor: 0xffffff,
        earColor: 0x60a5fa,
        earInnerColor: 0xffffff,
        speed: 6.0,
        maxCourage: 120,
        skillName: 'なんとかなれダッシュ',
        skillIcon: '💨',
        skillCooldown: 6000,
        skillVoice: 'なんとかなれーーッ!',
        dialogues: {
          scared: ['ひゃあッ!', 'オバケだッ!', 'びっくりしたァ…!'],
          foundTalisman: ['よし!おふだゲット!', 'これで一歩前進だね!'],
          idle: ['探検、ちょっと怖いけど楽しいね!', 'カメラ回ってるのかな?']
        }
      },
      usagi: {
        id: 'usagi',
        name: 'うさぎ',
        bodyColor: 0xfef08a,
        earColor: 0xfef08a,
        earInnerColor: 0xfbcfe8,
        speed: 6.8,
        maxCourage: 140,
        skillName: '怪鳥音アタック',
        skillIcon: '⚡',
        skillCooldown: 5000,
        skillVoice: 'ウララララァーーッ!',
        dialogues: {
          scared: ['ハァ!?', 'ウラ!', 'プルャッ!'],
          foundTalisman: ['ヤハッ!おふだ!', 'フゥーーン!'],
          idle: ['ハァ〜?', 'プルルル…!']
        }
      },
      momonga: {
        id: 'momonga',
        name: 'モモンガ',
        bodyColor: 0xffffff,
        earColor: 0x7dd3fc,
        earInnerColor: 0xffffff,
        speed: 5.7,
        maxCourage: 110,
        skillName: 'みつめろ!',
        skillIcon: '💖',
        skillCooldown: 6000,
        skillVoice: 'おいッ!私を褒めろッ!',
        dialogues: {
          scared: ['な、なんだコイツは!', '無礼者めッ!', 'ひっ…!'],
          foundTalisman: ['ふん、私のおかげで発見したぞ!', '褒めろ!おふだだ!'],
          idle: ['もっと可愛く撮れ!', 'チヤホヤしろ!']
        }
      }
    };

    /* ------------------------------------------------------------------
       マップ設定(3D空間グリッド: 1グリッド = 4m)
       0: 床, 1: 壁, 2: 部屋の扉枠, 3: 映写室ゴール出口
       ------------------------------------------------------------------ */
    const GRID_SIZE = 4.0;
    const MAP_DATA = [
      [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
      [1,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,3,1],
      [1,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,3,1],
      [1,0,0,0,2,0,0,0,0,2,0,0,0,0,2,0,0,0,0,1],
      [1,1,2,1,1,1,1,2,1,1,1,1,2,1,1,1,1,2,1,1],
      [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
      [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
      [1,1,2,1,1,0,0,1,1,1,1,0,0,1,1,2,1,1,1,1],
      [1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,1],
      [1,0,0,0,2,0,0,2,0,0,2,0,0,2,0,0,0,0,0,1],
      [1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,1],
      [1,1,2,1,1,1,1,1,0,0,1,1,1,1,1,1,2,1,1,1],
      [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
      [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
      [1,1,2,1,1,1,2,1,1,1,1,2,1,1,1,2,1,1,1,1],
      [1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1],
      [1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1],
      [1,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,1],
      [1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1],
      [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
    ];
    const MAP_ROWS = MAP_DATA.length;
    const MAP_COLS = MAP_DATA[0].length;

    function getRoomTitle(wx, wz) {
      const gx = Math.floor(wx / GRID_SIZE);
      const gz = Math.floor(wz / GRID_SIZE);
      if (gx >= 16 && gz <= 3) return '📽️ 映写室 (脱出ゴール)';
      if (gz >= 5 && gz <= 6) return '🧜‍♀️ セイレーンの遊泳回廊';
      if (gx <= 4 && gz <= 4) return '🚪 始まりのエントランス';
      if (gx <= 4 && gz >= 15) return '🧸 呪われた人形の部屋';
      if (gx >= 13 && gz >= 15) return '🪞 合わせ鏡の儀式の間';
      if (gx >= 7 && gx <= 11 && gz >= 8 && gz <= 11) return '📜 古代の書庫';
      return '✨ 明るくライトアップされた洋館回廊';
    }

    /* ------------------------------------------------------------------
       ゲームステート
       ------------------------------------------------------------------ */
    const state = {
      selectedCharId: 'devil_usagi', // 画像の悪魔うさぎをデフォルト主人公に設定
      isPlaying: false,
      talismansFound: 0,
      totalTalismans: 4,
      courage: 160,
      maxCourage: 160,
      skillReady: true,
      skillActive: false,
      skillEndTime: 0,
      keys: { up: false, down: false, left: false, right: false },
      playerPos: new THREE.Vector3(2 * GRID_SIZE, 0, 2 * GRID_SIZE),
      playerRot: 0,
      cameraAngleH: Math.PI,
      cameraAngleV: 0.28,
      cameraDist: 6.5,
      isMouseDown: false,
      lastMouseX: 0,
      lastMouseY: 0,
      invincibleTimer: 0,
      walkCycle: 0
    };

    /* ------------------------------------------------------------------
       プロシージャルテクスチャ生成(外部画像不要)
       ------------------------------------------------------------------ */
    // キャラクターの顔テクスチャ
    function createFaceCanvas(charId) {
      const cv = document.createElement('canvas');
      cv.width = 512;
      cv.height = 512;
      const ctx = cv.getContext('2d');

      // 背景透明
      ctx.clearRect(0, 0, 512, 512);

      // 画像の悪魔うさぎのダークで神秘的な瞳
      if (charId === 'devil_usagi') {
        // 妖しい濃紫〜ブラックの切れ長オーバル瞳(画像完全再現)
        ctx.fillStyle = '#26132b';
        ctx.beginPath();
        // ほんの少し吊り上がった魅惑の目
        ctx.save();
        ctx.translate(160, 255);
        ctx.rotate(-0.08);
        ctx.ellipse(0, 0, 36, 24, 0, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();

        ctx.save();
        ctx.translate(352, 255);
        ctx.rotate(0.08);
        ctx.ellipse(0, 0, 36, 24, 0, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();

        // 目の奥の淡い紫の輝き
        ctx.fillStyle = '#a855f7';
        ctx.beginPath();
        ctx.arc(172, 253, 9, 0, Math.PI * 2);
        ctx.arc(340, 253, 9, 0, Math.PI * 2);
        ctx.fill();

        // ほっぺの薄いチーク
        ctx.fillStyle = 'rgba(244, 114, 182, 0.35)';
        ctx.beginPath();
        ctx.ellipse(125, 305, 30, 16, 0, 0, Math.PI * 2);
        ctx.ellipse(387, 305, 30, 16, 0, 0, Math.PI * 2);
        ctx.fill();

        // 小さな鼻とニヤリ口
        ctx.strokeStyle = '#26132b';
        ctx.lineWidth = 8;
        ctx.lineCap = 'round';
        // 鼻
        ctx.beginPath();
        ctx.arc(256, 280, 5, 0, Math.PI * 2);
        ctx.fillStyle = '#26132b';
        ctx.fill();

        // 口(ωの口元)
        ctx.beginPath();
        ctx.arc(242, 300, 14, 0.1 * Math.PI, 0.9 * Math.PI, false);
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(270, 300, 14, 0.1 * Math.PI, 0.9 * Math.PI, false);
        ctx.stroke();

        const texture = new THREE.CanvasTexture(cv);
        return texture;
      }

      // ハチワレの前髪ブルー
      if (charId === 'hachiware') {
        ctx.fillStyle = '#60a5fa';
        ctx.beginPath();
        ctx.moveTo(30, 220);
        ctx.quadraticCurveTo(256, 80, 482, 220);
        ctx.quadraticCurveTo(256, 170, 30, 220);
        ctx.fill();
      }

      // 目
      ctx.fillStyle = '#1e1b4b';
      ctx.beginPath();
      ctx.ellipse(170, 260, 22, 30, 0, 0, Math.PI * 2);
      ctx.ellipse(342, 260, 22, 30, 0, 0, Math.PI * 2);
      ctx.fill();

      // 目のハイライト
      ctx.fillStyle = '#ffffff';
      ctx.beginPath();
      ctx.arc(162, 250, 9, 0, Math.PI * 2);
      ctx.arc(334, 250, 9, 0, Math.PI * 2);
      ctx.fill();

      // ほっぺのチーク
      ctx.fillStyle = '#f472b6';
      ctx.beginPath();
      ctx.ellipse(130, 310, 32, 18, 0, 0, Math.PI * 2);
      ctx.ellipse(382, 310, 32, 18, 0, 0, Math.PI * 2);
      ctx.fill();

      // 口
      ctx.strokeStyle = '#1e1b4b';
      ctx.lineWidth = 10;
      ctx.lineCap = 'round';
      if (charId === 'hachiware') {
        // ω 口
        ctx.beginPath();
        ctx.arc(235, 300, 20, 0.1 * Math.PI, 0.9 * Math.PI, false);
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(277, 300, 20, 0.1 * Math.PI, 0.9 * Math.PI, false);
        ctx.stroke();
      } else if (charId === 'usagi') {
        // 開いた口
        ctx.fillStyle = '#be185d';
        ctx.beginPath();
        ctx.ellipse(256, 315, 20, 16, 0, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();
      } else {
        // ちいかわ・モモンガのきゅっとした口
        ctx.beginPath();
        ctx.arc(256, 310, 16, 0.2 * Math.PI, 0.8 * Math.PI, false);
        ctx.stroke();
      }

      // ちいかわの涙
      if (charId === 'chiikawa') {
        ctx.fillStyle = '#67e8f9';
        ctx.beginPath();
        ctx.arc(155, 290, 8, 0, Math.PI * 2);
        ctx.fill();
      }

      const texture = new THREE.CanvasTexture(cv);
      return texture;
    }

    // 古い洋館の木製床テクスチャ
    function createWoodFloorTexture() {
      const cv = document.createElement('canvas');
      cv.width = 256;
      cv.height = 256;
      const ctx = cv.getContext('2d');
      // 明るく温かみのあるアンティークウッド床
      ctx.fillStyle = '#473a5a';
      ctx.fillRect(0, 0, 256, 256);

      // 板目ライン
      ctx.strokeStyle = '#322842';
      ctx.lineWidth = 3;
      for (let i = 0; i <= 256; i += 64) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(256, i);
        ctx.stroke();
      }
      ctx.strokeStyle = '#5b4c73';
      ctx.lineWidth = 1.5;
      for (let i = 32; i <= 256; i += 64) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, 256);
        ctx.stroke();
      }

      const tex = new THREE.CanvasTexture(cv);
      tex.wrapS = THREE.RepeatWrapping;
      tex.wrapT = THREE.RepeatWrapping;
      tex.repeat.set(12, 12);
      return tex;
    }

    // 洋館の壁テクスチャ
    function createWallTexture() {
      const cv = document.createElement('canvas');
      cv.width = 256;
      cv.height = 256;
      const ctx = cv.getContext('2d');
      // 上半分ラベンダーピンク壁紙、下半分木製パネル
      ctx.fillStyle = '#58437a';
      ctx.fillRect(0, 0, 256, 160);
      ctx.fillStyle = '#392954';
      ctx.fillRect(0, 160, 256, 96);

      // モールディング境界線
      ctx.fillStyle = '#a881d4';
      ctx.fillRect(0, 155, 256, 8);

      // 可愛い星&ダイヤ柄
      ctx.fillStyle = '#7a60a3';
      for (let y = 25; y < 150; y += 32) {
        for (let x = 20; x < 256; x += 32) {
          ctx.beginPath();
          ctx.arc(x, y, 5, 0, Math.PI * 2);
          ctx.fill();
        }
      }

      const tex = new THREE.CanvasTexture(cv);
      tex.wrapS = THREE.RepeatWrapping;
      tex.wrapT = THREE.RepeatWrapping;
      return tex;
    }

    // おふだテクスチャ
    function createTalismanTexture() {
      const cv = document.createElement('canvas');
      cv.width = 128;
      cv.height = 256;
      const ctx = cv.getContext('2d');
      ctx.fillStyle = '#fef08a';
      ctx.fillRect(0, 0, 128, 256);
      ctx.strokeStyle = '#dc2626';
      ctx.lineWidth = 6;
      ctx.strokeRect(8, 8, 112, 240);

      ctx.fillStyle = '#dc2626';
      ctx.font = 'bold 36px serif';
      ctx.textAlign = 'center';
      ctx.fillText('封', 64, 70);
      ctx.fillText('印', 64, 130);
      ctx.fillText('札', 64, 190);

      const tex = new THREE.CanvasTexture(cv);
      return tex;
    }

    /* ------------------------------------------------------------------
       Three.js 3Dワールド構築
       ------------------------------------------------------------------ */
    let scene, camera, renderer;
    let playerGroup, playerMesh, playerFaceMesh, earL, earR, handL, handR, flashlightMesh, spotLight;
    const ghosts = [];
    const talismanObjects = [];
    const candyObjects = [];
    let exitDoorMesh;
    let sirenObj = null; // セイレーンの3Dオブジェクト

    function initThree() {
      const container = document.getElementById('canvasContainer');
      scene = new THREE.Scene();

      // 明るい映画スタジオ風のパステルパープル・ナイトスカイ
      scene.background = new THREE.Color(0x312e81);
      // 薄く見通しの良いフォグに変更
      scene.fog = new THREE.FogExp2(0x312e81, 0.012);

      camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 100);
      renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
      renderer.shadowMap.enabled = true;
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;
      container.appendChild(renderer.domElement);

      // 明るい環境光(大幅増光)
      const ambientLight = new THREE.AmbientLight(0xfdf4ff, 1.25);
      scene.add(ambientLight);

      // スタジオ全体を明るく照らす主ディレクショナルライト
      const dirLight = new THREE.DirectionalLight(0xfffbeb, 0.85);
      dirLight.position.set(40, 60, 40);
      dirLight.castShadow = true;
      dirLight.shadow.mapSize.width = 1024;
      dirLight.shadow.mapSize.height = 1024;
      scene.add(dirLight);

      // 屋敷の壁・床の生成
      buildMansion();

      // プレイヤー3Dモデルの生成
      createPlayer3D();

      // セイレーン、オバケ、アイテムの生成
      spawnEntities();

      // リサイズ対応
      window.addEventListener('resize', onWindowResize);

      // マウス/タッチによるカメラ操作イベント
      setupCameraControls(container);
    }

    function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }

    /* ------------------------------------------------------------------
       洋館の3Dモデル(壁、床、天井、扉)
       ------------------------------------------------------------------ */
    function buildMansion() {
      const wallTex = createWallTexture();
      const floorTex = createWoodFloorTexture();

      // 床
      const floorGeo = new THREE.PlaneGeometry(MAP_COLS * GRID_SIZE, MAP_ROWS * GRID_SIZE);
      const floorMat = new THREE.MeshStandardMaterial({
        map: floorTex,
        roughness: 0.8,
        metalness: 0.1
      });
      const floor = new THREE.Mesh(floorGeo, floorMat);
      floor.rotation.x = -Math.PI / 2;
      floor.position.set((MAP_COLS * GRID_SIZE) / 2, 0, (MAP_ROWS * GRID_SIZE) / 2);
      floor.receiveShadow = true;
      scene.add(floor);

      // 天井(少し高め)
      const ceilMat = new THREE.MeshStandardMaterial({ color: 0x1e1b4b, roughness: 0.9 });
      const ceiling = new THREE.Mesh(floorGeo, ceilMat);
      ceiling.rotation.x = Math.PI / 2;
      ceiling.position.set((MAP_COLS * GRID_SIZE) / 2, 4.0, (MAP_ROWS * GRID_SIZE) / 2);
      scene.add(ceiling);

      // 壁・出口・柱の配置
      const wallGeo = new THREE.BoxGeometry(GRID_SIZE, 3.8, GRID_SIZE);
      const wallMat = new THREE.MeshStandardMaterial({
        map: wallTex,
        roughness: 0.75
      });

      for (let r = 0; r < MAP_ROWS; r++) {
        for (let c = 0; c < MAP_COLS; c++) {
          const type = MAP_DATA[r][c];
          const px = c * GRID_SIZE + GRID_SIZE / 2;
          const pz = r * GRID_SIZE + GRID_SIZE / 2;

          if (type === 1) {
            // 壁ブロック
            const wall = new THREE.Mesh(wallGeo, wallMat);
            wall.position.set(px, 1.9, pz);
            wall.castShadow = true;
            wall.receiveShadow = true;
            scene.add(wall);
          } else if (type === 3) {
            // 映写室の脱出ゲート
            const doorGeo = new THREE.BoxGeometry(GRID_SIZE * 0.9, 3.2, 0.4);
            const doorMat = new THREE.MeshStandardMaterial({
              color: 0x9d174d,
              emissive: 0x701a75,
              roughness: 0.3
            });
            exitDoorMesh = new THREE.Mesh(doorGeo, doorMat);
            exitDoorMesh.position.set(px, 1.6, pz);
            exitDoorMesh.castShadow = true;
            scene.add(exitDoorMesh);

            // ゴール上の誘導灯
            const signLight = new THREE.PointLight(0xf472b6, 2.5, 12);
            signLight.position.set(px, 3.0, pz);
            scene.add(signLight);
          }
        }
      }

      // 屋敷内を華やかに灯すシャンデリア照明群
      const lightPositions = [
        [2 * GRID_SIZE, 2 * GRID_SIZE, 0xfde047],
        [10 * GRID_SIZE, 6 * GRID_SIZE, 0x38bdf8],
        [3 * GRID_SIZE, 16 * GRID_SIZE, 0xf472b6],
        [15 * GRID_SIZE, 16 * GRID_SIZE, 0xa78bfa],
        [10 * GRID_SIZE, 13 * GRID_SIZE, 0xfbbf24]
      ];
      lightPositions.forEach(pos => {
        const pLight = new THREE.PointLight(pos[2], 1.8, 16);
        pLight.position.set(pos[0], 3.0, pos[1]);
        scene.add(pLight);

        // クリスタルシャンデリアの輝き球体
        const lanternMesh = new THREE.Mesh(
          new THREE.SphereGeometry(0.35, 12, 12),
          new THREE.MeshBasicMaterial({ color: 0xffffff })
        );
        lanternMesh.position.set(pos[0], 3.0, pos[1]);
        scene.add(lanternMesh);
      });
    }

    /* ------------------------------------------------------------------
       ちいかわキャラクターの3Dモデル生成
       ------------------------------------------------------------------ */
    let playerWingL = null, playerWingR = null;

    function createPlayer3D() {
      playerGroup = new THREE.Group();
      playerWingL = null;
      playerWingR = null;

      const char = CHARACTERS[state.selectedCharId];

      // 1. 体(コロンとした球体カプセル形)
      const bodyGeo = new THREE.SphereGeometry(0.65, 24, 20);
      const bodyMat = new THREE.MeshStandardMaterial({
        color: char.bodyColor,
        roughness: 0.4,
        metalness: 0.05
      });
      playerMesh = new THREE.Mesh(bodyGeo, bodyMat);
      playerMesh.position.y = 0.7;
      playerMesh.scale.set(1.0, 0.95, 0.95);
      playerMesh.castShadow = true;
      playerGroup.add(playerMesh);

      // 画像の悪魔うさぎ専用:胸元のふさふさファー(白いモフモフ胸毛)
      if (char.id === 'devil_usagi') {
        const furGroup = new THREE.Group();
        const furMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.8 });
        // 大きな胸毛の房
        const mainFur = new THREE.Mesh(new THREE.ConeGeometry(0.35, 0.65, 12), furMat);
        mainFur.rotation.x = Math.PI * 0.85;
        mainFur.position.set(0, 0.52, 0.58);
        furGroup.add(mainFur);

        const subFurL = new THREE.Mesh(new THREE.ConeGeometry(0.2, 0.45, 10), furMat);
        subFurL.rotation.x = Math.PI * 0.82;
        subFurL.rotation.z = -0.3;
        subFurL.position.set(-0.2, 0.6, 0.54);
        furGroup.add(subFurL);

        const subFurR = new THREE.Mesh(new THREE.ConeGeometry(0.2, 0.45, 10), furMat);
        subFurR.rotation.x = Math.PI * 0.82;
        subFurR.rotation.z = 0.3;
        subFurR.position.set(0.2, 0.6, 0.54);
        furGroup.add(subFurR);

        playerGroup.add(furGroup);
      }

      // 2. 顔のテクスチャプレート
      const faceTex = createFaceCanvas(state.selectedCharId);
      const faceGeo = new THREE.PlaneGeometry(0.85, 0.85);
      const faceMat = new THREE.MeshBasicMaterial({
        map: faceTex,
        transparent: true,
        depthWrite: false
      });
      playerFaceMesh = new THREE.Mesh(faceGeo, faceMat);
      playerFaceMesh.position.set(0, 0.72, 0.62);
      playerGroup.add(playerFaceMesh);

      // 3. 耳
      const earMat = new THREE.MeshStandardMaterial({ color: char.earColor, roughness: 0.4 });
      if (state.selectedCharId === 'devil_usagi') {
        // 画像の悪魔うさぎ:大きく広がった長耳
        const earGeo = new THREE.CylinderGeometry(0.12, 0.22, 1.15, 14);
        earL = new THREE.Mesh(earGeo, earMat);
        earL.position.set(-0.35, 1.55, 0);
        earL.rotation.z = -0.4;
        earL.rotation.x = -0.1;
        earR = new THREE.Mesh(earGeo, earMat);
        earR.position.set(0.35, 1.55, 0);
        earR.rotation.z = 0.4;
        earR.rotation.x = -0.1;
      } else if (state.selectedCharId === 'usagi') {
        // うさぎの長耳
        const earGeo = new THREE.CylinderGeometry(0.12, 0.16, 0.9, 12);
        earL = new THREE.Mesh(earGeo, earMat);
        earL.position.set(-0.28, 1.45, 0);
        earL.rotation.z = -0.15;
        earR = new THREE.Mesh(earGeo, earMat);
        earR.position.set(0.28, 1.45, 0);
        earR.rotation.z = 0.15;
      } else {
        // まるい耳
        const earGeo = new THREE.SphereGeometry(0.2, 12, 12);
        earL = new THREE.Mesh(earGeo, earMat);
        earL.position.set(-0.45, 1.2, 0);
        earR = new THREE.Mesh(earGeo, earMat);
        earR.position.set(0.45, 1.2, 0);
      }
      playerGroup.add(earL);
      playerGroup.add(earR);

      // 画像の悪魔うさぎ専用:背中の黒い悪魔・コウモリの翼(バットウィング)
      if (char.id === 'devil_usagi') {
        const wingMat = new THREE.MeshStandardMaterial({
          color: char.wingColor,
          roughness: 0.3,
          side: THREE.DoubleSide
        });

        // 翼の形状(コウモリの羽)
        const createWingMesh = (isLeft) => {
          const wingPivot = new THREE.Group();
          const shape = new THREE.Shape();
          shape.moveTo(0, 0);
          shape.lineTo(isLeft ? -0.8 : 0.8, 0.4);
          shape.lineTo(isLeft ? -0.65 : 0.65, 0.1);
          shape.lineTo(isLeft ? -0.9 : 0.9, -0.1);
          shape.lineTo(isLeft ? -0.45 : 0.45, -0.15);
          shape.lineTo(isLeft ? -0.55 : 0.55, -0.4);
          shape.lineTo(0, -0.1);
          shape.closePath();

          const wingGeo = new THREE.ShapeGeometry(shape);
          const wMesh = new THREE.Mesh(wingGeo, wingMat);
          wingPivot.add(wMesh);
          return wingPivot;
        };

        playerWingL = createWingMesh(true);
        playerWingL.position.set(-0.25, 0.75, -0.45);
        playerWingR = createWingMesh(false);
        playerWingR.position.set(0.25, 0.75, -0.45);

        playerGroup.add(playerWingL);
        playerGroup.add(playerWingR);
      }

      // 4. 手 & 懐中電灯 & 爪
      const handGeo = new THREE.SphereGeometry(0.16, 10, 10);
      handL = new THREE.Mesh(handGeo, bodyMat);
      handL.position.set(-0.55, 0.55, 0.25);
      handR = new THREE.Mesh(handGeo, bodyMat);
      handR.position.set(0.55, 0.55, 0.25);

      // 悪魔うさぎの鋭い爪(クロー)
      if (char.id === 'devil_usagi') {
        const clawMat = new THREE.MeshStandardMaterial({ color: 0xfde047, roughness: 0.2 });
        const clawGeo = new THREE.ConeGeometry(0.04, 0.16, 8);
        for (let i = -1; i <= 1; i++) {
          const clawL = new THREE.Mesh(clawGeo, clawMat);
          clawL.rotation.x = Math.PI / 2;
          clawL.position.set(i * 0.06, -0.05, 0.14);
          handL.add(clawL);

          const clawR = new THREE.Mesh(clawGeo, clawMat);
          clawR.rotation.x = Math.PI / 2;
          clawR.position.set(i * 0.06, -0.05, 0.14);
          handR.add(clawR);
        }
      }

      playerGroup.add(handL);
      playerGroup.add(handR);

      // 懐中電灯
      const flashGeo = new THREE.CylinderGeometry(0.08, 0.12, 0.4, 10);
      const flashMat = new THREE.MeshStandardMaterial({ color: 0xf59e0b, roughness: 0.3 });
      flashlightMesh = new THREE.Mesh(flashGeo, flashMat);
      flashlightMesh.rotation.x = Math.PI / 2;
      flashlightMesh.position.set(0.48, 0.55, 0.5);
      playerGroup.add(flashlightMesh);

      // 5. 懐中電灯の3Dスポットライト(明るく広範囲を照らす)
      spotLight = new THREE.SpotLight(char.id === 'devil_usagi' ? 0xf5d0fe : 0xfffbeb, 4.5, 24, Math.PI / 4.5, 0.4, 1.1);
      spotLight.position.set(0.48, 0.6, 0.6);
      spotLight.castShadow = true;
      spotLight.shadow.mapSize.width = 1024;
      spotLight.shadow.mapSize.height = 1024;
      spotLight.shadow.bias = -0.001;

      // ライトのターゲット
      const targetObj = new THREE.Object3D();
      targetObj.position.set(0.48, 0.5, 8);
      playerGroup.add(targetObj);
      spotLight.target = targetObj;
      playerGroup.add(spotLight);

      // 足元の安全ランタン(さらに明るく広範囲)
      const feetLight = new THREE.PointLight(char.id === 'devil_usagi' ? 0xe9d5ff : 0xffedd5, 1.4, 6.5);
      feetLight.position.set(0, 1.0, 0);
      playerGroup.add(feetLight);

      playerGroup.position.copy(state.playerPos);
      scene.add(playerGroup);
    }

    // キャラクター切り替え時の3Dモデル再更新
    function switchCharacter3D(charId) {
      if (playerGroup) scene.remove(playerGroup);
      state.selectedCharId = charId;
      createPlayer3D();
    }

    /* ------------------------------------------------------------------
       巨大ボス:セイレーンの3Dモデル生成
       ------------------------------------------------------------------ */
    function createSiren3D() {
      const sirenGroup = new THREE.Group();

      // 1. セイレーンの上半身(エメラルドブルーの人魚の肉体)
      const skinMat = new THREE.MeshStandardMaterial({
        color: 0x67e8f9,
        emissive: 0x0e7490,
        emissiveIntensity: 0.25,
        roughness: 0.35
      });
      const torso = new THREE.Mesh(new THREE.CylinderGeometry(0.7, 0.85, 1.8, 16), skinMat);
      torso.position.y = 1.9;
      sirenGroup.add(torso);

      // 2. セイレーンの頭部
      const head = new THREE.Mesh(new THREE.SphereGeometry(0.85, 20, 20), skinMat);
      head.position.y = 3.2;
      sirenGroup.add(head);

      // 3. セイレーンの長い髪(青〜水色の豊かな髪)
      const hairMat = new THREE.MeshStandardMaterial({ color: 0x0284c7, roughness: 0.3 });
      const hairBack = new THREE.Mesh(new THREE.ConeGeometry(1.2, 3.2, 16), hairMat);
      hairBack.position.set(0, 2.4, -0.6);
      hairBack.rotation.x = -0.3;
      sirenGroup.add(hairBack);

      // 4. 頭の黄金のティアラ / 装飾
      const crownMat = new THREE.MeshStandardMaterial({
        color: 0xfacc15,
        emissive: 0xca8a04,
        metalness: 0.8,
        roughness: 0.2
      });
      const crown = new THREE.Mesh(new THREE.TorusGeometry(0.65, 0.12, 8, 16), crownMat);
      crown.rotation.x = Math.PI / 2;
      crown.position.set(0, 3.8, 0);
      sirenGroup.add(crown);

      // 5. 妖しいつぶらな目 & 口
      const eyeMat = new THREE.MeshBasicMaterial({ color: 0x0f172a });
      const eyeL = new THREE.Mesh(new THREE.SphereGeometry(0.12, 8, 8), eyeMat);
      eyeL.position.set(-0.35, 3.3, 0.75);
      const eyeR = new THREE.Mesh(new THREE.SphereGeometry(0.12, 8, 8), eyeMat);
      eyeR.position.set(0.35, 3.3, 0.75);
      sirenGroup.add(eyeL);
      sirenGroup.add(eyeR);

      // 歌う開いた口
      const mouthMat = new THREE.MeshBasicMaterial({ color: 0x881337 });
      const mouth = new THREE.Mesh(new THREE.CylinderGeometry(0.12, 0.12, 0.2, 8), mouthMat);
      mouth.rotation.x = Math.PI / 2;
      mouth.position.set(0, 2.9, 0.8);
      sirenGroup.add(mouth);

      // 6. 巨大な人魚の尾びれ(しなやかに揺れるアニメーション用に関節グループ化)
      const tailGroup = new THREE.Group();
      tailGroup.position.set(0, 1.1, 0);

      const tailMat = new THREE.MeshStandardMaterial({
        color: 0x059669,
        emissive: 0x047857,
        roughness: 0.25,
        metalness: 0.1
      });
      const tailUpper = new THREE.Mesh(new THREE.ConeGeometry(0.85, 2.0, 16), tailMat);
      tailUpper.rotation.x = Math.PI;
      tailUpper.position.set(0, -0.6, 0.2);
      tailGroup.add(tailUpper);

      // 尾びれの先端(扇形のヒレ)
      const finMat = new THREE.MeshStandardMaterial({
        color: 0x34d399,
        side: THREE.DoubleSide,
        roughness: 0.3
      });
      const fin = new THREE.Mesh(new THREE.PlaneGeometry(1.6, 1.2), finMat);
      fin.position.set(0, -1.8, 0.4);
      fin.rotation.x = 0.5;
      tailGroup.add(fin);
      sirenGroup.add(tailGroup);

      // 7. 両腕(優雅に歌うポーズ)
      const armGeo = new THREE.CylinderGeometry(0.16, 0.2, 1.4, 8);
      const armL = new THREE.Mesh(armGeo, skinMat);
      armL.position.set(-1.1, 2.0, 0.3);
      armL.rotation.z = 0.6;
      armL.rotation.x = 0.3;
      const armR = new THREE.Mesh(armGeo, skinMat);
      armR.position.set(1.1, 2.0, 0.3);
      armR.rotation.z = -0.6;
      armR.rotation.x = 0.3;
      sirenGroup.add(armL);
      sirenGroup.add(armR);

      // 8. セイレーンを包む神秘的なターコイズの光
      const sirenLight = new THREE.PointLight(0x22d3ee, 3.0, 14);
      sirenLight.position.set(0, 2.5, 0);
      sirenGroup.add(sirenLight);

      // 9. 歌声の音符(浮遊スプライト)
      const noteCanvas = document.createElement('canvas');
      noteCanvas.width = 128; noteCanvas.height = 128;
      const nCtx = noteCanvas.getContext('2d');
      nCtx.fillStyle = '#38bdf8';
      nCtx.font = 'bold 80px sans-serif';
      nCtx.textAlign = 'center';
      nCtx.fillText('🎶', 64, 96);
      const noteTex = new THREE.CanvasTexture(noteCanvas);
      const noteMat = new THREE.SpriteMaterial({ map: noteTex, transparent: true });
      const noteSprite = new THREE.Sprite(noteMat);
      noteSprite.position.set(0, 4.4, 0);
      noteSprite.scale.set(1.2, 1.2, 1.2);
      sirenGroup.add(noteSprite);

      sirenGroup.position.set(10 * GRID_SIZE, 0, 5.5 * GRID_SIZE);
      scene.add(sirenGroup);

      return {
        group: sirenGroup,
        tail: tailGroup,
        note: noteSprite,
        vx: 0.05,
        vz: 0,
        singTimer: 0
      };
    }

    /* ------------------------------------------------------------------
       オバケ & アイテム & セイレーン生成
       ------------------------------------------------------------------ */
    function spawnEntities() {
      // 巨大ボス「セイレーン」の召喚
      sirenObj = createSiren3D();

      // 1. 3Dオバケの生成(ふわふわ浮くキュートな布お化け)
      const ghostSpawns = [
        { x: 10 * GRID_SIZE, z: 6 * GRID_SIZE, vx: 0.04, vz: 0 },
        { x: 14 * GRID_SIZE, z: 6 * GRID_SIZE, vx: -0.04, vz: 0 },
        { x: 3 * GRID_SIZE, z: 12 * GRID_SIZE, vx: 0, vz: 0.035 },
        { x: 14 * GRID_SIZE, z: 12 * GRID_SIZE, vx: 0.04, vz: 0.02 },
        { x: 17 * GRID_SIZE, z: 9 * GRID_SIZE, vx: 0, vz: 0.04 }
      ];

      const ghostMat = new THREE.MeshStandardMaterial({
        color: 0xf5f3ff,
        emissive: 0x6366f1,
        roughness: 0.2,
        transparent: true,
        opacity: 0.9
      });

      ghostSpawns.forEach(sp => {
        const gGroup = new THREE.Group();

        // 頭部
        const head = new THREE.Mesh(new THREE.SphereGeometry(0.55, 16, 16), ghostMat);
        head.position.y = 1.0;
        gGroup.add(head);

        // スカート状の裾
        const skirt = new THREE.Mesh(new THREE.CylinderGeometry(0.55, 0.7, 0.8, 16, 1, true), ghostMat);
        skirt.position.y = 0.55;
        gGroup.add(skirt);

        // つぶらな黒目
        const eyeMat = new THREE.MeshBasicMaterial({ color: 0x1e1b4b });
        const eyeL = new THREE.Mesh(new THREE.SphereGeometry(0.08, 8, 8), eyeMat);
        eyeL.position.set(-0.18, 1.05, 0.48);
        const eyeR = new THREE.Mesh(new THREE.SphereGeometry(0.08, 8, 8), eyeMat);
        eyeR.position.set(0.18, 1.05, 0.48);
        gGroup.add(eyeL);
        gGroup.add(eyeR);

        // オバケの淡い光
        const gLight = new THREE.PointLight(0xc084fc, 1.2, 6);
        gLight.position.y = 1.0;
        gGroup.add(gLight);

        gGroup.position.set(sp.x, 0, sp.z);
        scene.add(gGroup);

        ghosts.push({
          mesh: gGroup,
          vx: sp.vx,
          vz: sp.vz,
          state: 'normal',
          charmedTimer: 0,
          baseY: 0.8,
          floatOffset: Math.random() * Math.PI * 2
        });
      });

      // 2. 4枚のおふだ(金色の光る浮遊巻物)
      const talismanTex = createTalismanTexture();
      const talismanSpawns = [
        { id: 1, x: 2 * GRID_SIZE, z: 17 * GRID_SIZE, name: '【北の封印札】' },
        { id: 2, x: 9 * GRID_SIZE, z: 9 * GRID_SIZE, name: '【書庫の封印札】' },
        { id: 3, x: 17 * GRID_SIZE, z: 17 * GRID_SIZE, name: '【鏡の封印札】' },
        { id: 4, x: 17 * GRID_SIZE, z: 2 * GRID_SIZE, name: '【映写室前のおふだ】' }
      ];

      const talisGeo = new THREE.PlaneGeometry(0.7, 1.4);
      const talisMat = new THREE.MeshStandardMaterial({
        map: talismanTex,
        roughness: 0.3,
        side: THREE.DoubleSide,
        emissive: 0xca8a04,
        emissiveIntensity: 0.4
      });

      talismanSpawns.forEach(item => {
        const group = new THREE.Group();
        const mesh = new THREE.Mesh(talisGeo, talisMat);
        group.add(mesh);

        // オーラ光
        const light = new THREE.PointLight(0xfef08a, 1.8, 6);
        group.add(light);

        group.position.set(item.x, 1.2, item.z);
        scene.add(group);

        talismanObjects.push({
          group: group,
          id: item.id,
          name: item.name,
          collected: false
        });
      });

      // 3. 回復用ピンクキャンディ
      const candySpawns = [
        { x: 6 * GRID_SIZE, z: 6 * GRID_SIZE },
        { x: 2 * GRID_SIZE, z: 9 * GRID_SIZE },
        { x: 17 * GRID_SIZE, z: 13 * GRID_SIZE }
      ];
      const candyGeo = new THREE.SphereGeometry(0.28, 12, 12);
      const candyMat = new THREE.MeshStandardMaterial({
        color: 0xf472b6,
        emissive: 0xec4899,
        roughness: 0.2
      });

      candySpawns.forEach(pos => {
        const cMesh = new THREE.Mesh(candyGeo, candyMat);
        cMesh.position.set(pos.x, 0.6, pos.z);
        scene.add(cMesh);
        candyObjects.push({ mesh: cMesh, collected: false });
      });
    }

    /* ------------------------------------------------------------------
       当たり判定 (Grid Collisions)
       ------------------------------------------------------------------ */
    function isWallAt(wx, wz) {
      const gx = Math.floor(wx / GRID_SIZE);
      const gz = Math.floor(wz / GRID_SIZE);
      if (gx < 0 || gx >= MAP_COLS || gz < 0 || gz >= MAP_ROWS) return true;
      const tile = MAP_DATA[gz][gx];
      if (tile === 1) return true;
      // 出口扉がおふだ未完了なら壁扱い
      if (tile === 3 && state.talismansFound < state.totalTalismans) return true;
      return false;
    }

    function canMoveTo(nextX, nextZ, radius = 0.5) {
      // プレイヤーの周囲4点をサンプリング
      if (isWallAt(nextX + radius, nextZ)) return false;
      if (isWallAt(nextX - radius, nextZ)) return false;
      if (isWallAt(nextX, nextZ + radius)) return false;
      if (isWallAt(nextX, nextZ - radius)) return false;
      return true;
    }

    /* ------------------------------------------------------------------
       カメラ操作(マウス/タッチドラッグによる自由な視点回転)
       ------------------------------------------------------------------ */
    function setupCameraControls(dom) {
      dom.addEventListener('mousedown', e => {
        state.isMouseDown = true;
        state.lastMouseX = e.clientX;
        state.lastMouseY = e.clientY;
      });

      window.addEventListener('mouseup', () => {
        state.isMouseDown = false;
      });

      window.addEventListener('mousemove', e => {
        if (!state.isMouseDown) return;
        const dx = e.clientX - state.lastMouseX;
        const dy = e.clientY - state.lastMouseY;
        state.lastMouseX = e.clientX;
        state.lastMouseY = e.clientY;

        state.cameraAngleH -= dx * 0.006;
        state.cameraAngleV = Math.max(0.1, Math.min(1.2, state.cameraAngleV + dy * 0.005));
      });

      // タッチスワイプによる視点回転
      let touchStartX = 0, touchStartY = 0;
      dom.addEventListener('touchstart', e => {
        if (e.touches.length === 1) {
          touchStartX = e.touches[0].clientX;
          touchStartY = e.touches[0].clientY;
        }
      }, { passive: true });

      dom.addEventListener('touchmove', e => {
        if (e.touches.length === 1) {
          const dx = e.touches[0].clientX - touchStartX;
          const dy = e.touches[0].clientY - touchStartY;
          touchStartX = e.touches[0].clientX;
          touchStartY = e.touches[0].clientY;

          state.cameraAngleH -= dx * 0.008;
          state.cameraAngleV = Math.max(0.1, Math.min(1.2, state.cameraAngleV + dy * 0.006));
        }
      }, { passive: true });
    }

    /* ------------------------------------------------------------------
       キーボード & モバイル操作バインド
       ------------------------------------------------------------------ */
    window.addEventListener('keydown', e => {
      sound.init();
      if (!state.isPlaying) return;
      if (['ArrowUp', 'KeyW'].includes(e.code)) state.keys.up = true;
      if (['ArrowDown', 'KeyS'].includes(e.code)) state.keys.down = true;
      if (['ArrowLeft', 'KeyA'].includes(e.code)) state.keys.left = true;
      if (['ArrowRight', 'KeyD'].includes(e.code)) state.keys.right = true;
      if (['Space', 'KeyE'].includes(e.code)) handleAction();
      if (['KeyQ', 'KeyF'].includes(e.code)) triggerSkill();
    });

    window.addEventListener('keyup', e => {
      if (['ArrowUp', 'KeyW'].includes(e.code)) state.keys.up = false;
      if (['ArrowDown', 'KeyS'].includes(e.code)) state.keys.down = false;
      if (['ArrowLeft', 'KeyA'].includes(e.code)) state.keys.left = false;
      if (['ArrowRight', 'KeyD'].includes(e.code)) state.keys.right = false;
    });

    // モバイルボタンイベント
    const bindTouch = (id, keyName) => {
      const btn = document.getElementById(id);
      if (!btn) return;
      const setKey = (val) => {
        sound.init();
        state.keys[keyName] = val;
      };
      btn.addEventListener('touchstart', (e) => { e.preventDefault(); setKey(true); });
      btn.addEventListener('touchend', (e) => { e.preventDefault(); setKey(false); });
      btn.addEventListener('mousedown', () => setKey(true));
      btn.addEventListener('mouseup', () => setKey(false));
      btn.addEventListener('mouseleave', () => setKey(false));
    };

    bindTouch('btnUp', 'up');
    bindTouch('btnDown', 'down');
    bindTouch('btnLeft', 'left');
    bindTouch('btnRight', 'right');

    document.getElementById('btnAction').addEventListener('click', () => {
      sound.init();
      handleAction();
    });
    document.getElementById('btnSkill').addEventListener('click', () => {
      sound.init();
      triggerSkill();
    });
    document.getElementById('soundToggleBtn').addEventListener('click', () => {
      sound.init();
      sound.muted = !sound.muted;
      document.getElementById('soundToggleBtn').textContent = sound.muted ? '🔇' : '🔊';
    });

    /* ------------------------------------------------------------------
       UI & トースト・吹き出し更新
       ------------------------------------------------------------------ */
    const courageBar = document.getElementById('courageBar');
    const talismanCounter = document.getElementById('talismanCounter');
    const roomNameBadge = document.getElementById('roomNameBadge');
    const speechBubble = document.getElementById('speechBubble');
    const bubbleText = document.getElementById('bubbleText');
    const bubbleEmotion = document.getElementById('bubbleEmotion');
    const interactPrompt = document.getElementById('interactPrompt');
    const interactPromptText = document.getElementById('interactPromptText');
    const panicOverlay = document.getElementById('panicOverlay');

    let toastTimer = null;
    function showToast(icon, msg, dur = 2600) {
      if (toastTimer) clearTimeout(toastTimer);
      const toast = document.getElementById('toast');
      document.getElementById('toastIcon').textContent = icon;
      document.getElementById('toastMsg').textContent = msg;
      toast.classList.remove('opacity-0', '-translate-y-2');
      toast.classList.add('opacity-100', 'translate-y-0');
      toastTimer = setTimeout(() => {
        toast.classList.remove('opacity-100', 'translate-y-0');
        toast.classList.add('opacity-0', '-translate-y-2');
      }, dur);
    }

    let bubbleTimer = null;
    function showBubble(emotion, text, dur = 2200) {
      if (bubbleTimer) clearTimeout(bubbleTimer);
      bubbleEmotion.textContent = emotion;
      bubbleText.textContent = text;
      speechBubble.classList.remove('opacity-0');
      speechBubble.classList.add('opacity-100');
      bubbleTimer = setTimeout(() => {
        speechBubble.classList.remove('opacity-100');
        speechBubble.classList.add('opacity-0');
      }, dur);
    }

    function updateUI() {
      // 勇気ゲージ
      const pct = Math.max(0, Math.min(100, (state.courage / state.maxCourage) * 100));
      courageBar.style.width = `${pct}%`;
      if (pct < 30) {
        courageBar.className = 'h-full bg-gradient-to-r from-red-600 to-rose-500 transition-all duration-300 rounded-full';
        panicOverlay.style.opacity = (1 - pct / 30) * 0.8;
      } else {
        courageBar.className = 'h-full bg-gradient-to-r from-pink-500 to-amber-400 transition-all duration-300 rounded-full';
        panicOverlay.style.opacity = '0';
      }

      talismanCounter.textContent = `${state.talismansFound} / ${state.totalTalismans}`;
      roomNameBadge.textContent = getRoomTitle(state.playerPos.x, state.playerPos.z);
    }

    /* ------------------------------------------------------------------
       ゲーム開始 & リトライフロー
       ------------------------------------------------------------------ */
    const startScreen = document.getElementById('startScreen');
    const clearModal = document.getElementById('clearModal');
    const faintModal = document.getElementById('faintModal');
    const gameHeader = document.getElementById('gameHeader');
    const mobileControls = document.getElementById('mobileControls');

    // キャラクターカード選択
    const charCards = document.querySelectorAll('.char-card');
    charCards.forEach(card => {
      card.addEventListener('click', () => {
        charCards.forEach(c => {
          c.classList.remove('border-pink-500', 'bg-pink-950/50', 'selected');
          c.classList.add('border-slate-700', 'bg-slate-900/60');
        });
        card.classList.remove('border-slate-700', 'bg-slate-900/60');
        card.classList.add('border-pink-500', 'bg-pink-950/50', 'selected');
        const cId = card.getAttribute('data-char');
        switchCharacter3D(cId);
      });
    });

    document.getElementById('startGameBtn').addEventListener('click', () => {
      sound.init();
      const char = CHARACTERS[state.selectedCharId];
      state.maxCourage = char.maxCourage;
      state.courage = char.maxCourage;
      state.talismansFound = 0;
      state.playerPos.set(2 * GRID_SIZE, 0, 2 * GRID_SIZE);
      state.cameraAngleH = Math.PI;

      document.getElementById('charNameDisplay').textContent = char.name;
      document.getElementById('statusAvatar').textContent = char.name[0];
      document.getElementById('statusAvatar').style.borderColor = char.id === 'hachiware' ? '#60a5fa' : (char.id === 'usagi' ? '#f59e0b' : '#ec4899');
      document.getElementById('skillIconDisplay').textContent = char.skillIcon;

      startScreen.classList.add('hidden');
      clearModal.classList.add('hidden');
      faintModal.classList.add('hidden');
      gameHeader.classList.remove('hidden');
      mobileControls.classList.remove('hidden');

      state.isPlaying = true;
      updateUI();

      showToast('🎬', `${char.name}と3Dオバケ屋敷の撮影スタート!`);
      setTimeout(() => {
        showBubble('🔦', `${char.name}: 「探検スタート…!」`);
      }, 600);
    });

    document.getElementById('restartBtn').addEventListener('click', () => {
      clearModal.classList.add('hidden');
      startScreen.classList.remove('hidden');
    });

    document.getElementById('retryBtn').addEventListener('click', () => {
      faintModal.classList.add('hidden');
      state.courage = state.maxCourage;
      state.playerPos.set(2 * GRID_SIZE, 0, 2 * GRID_SIZE);
      state.isPlaying = true;
      updateUI();
      showToast('🏮', '入口の安全なランタンで勇気を取り戻した!');
    });

    /* ------------------------------------------------------------------
       アクション(おふだ収集 / ゴール脱出)
       ------------------------------------------------------------------ */
    function handleAction() {
      if (!state.isPlaying) return;
      const char = CHARACTERS[state.selectedCharId];
      const p = state.playerPos;

      // 近くのおふだチェック
      let found = false;
      talismanObjects.forEach(t => {
        if (!t.collected) {
          const dist = p.distanceTo(t.group.position);
          if (dist < 2.5) {
            found = true;
            t.collected = true;
            scene.remove(t.group);
            state.talismansFound++;
            sound.playTalisman();
            updateUI();

            const says = char.dialogues.foundTalisman;
            showBubble('📜', `${char.name}: 「${says[Math.floor(Math.random() * says.length)]}」`);
            showToast('📜', `${t.name} を手に入れた!(残り ${state.totalTalismans - state.talismansFound} 枚)`);

            // 全て集めたら扉解放
            if (state.talismansFound >= state.totalTalismans) {
              if (exitDoorMesh) {
                exitDoorMesh.material.color.setHex(0x10b981);
                exitDoorMesh.material.emissive.setHex(0x047857);
              }
              setTimeout(() => {
                showToast('🚪', '全ての封印が解かれた!映写室の扉が開いたぞ!!', 4000);
              }, 1200);
            }
          }
        }
      });

      // 出口扉チェック
      if (!found && exitDoorMesh) {
        const distDoor = p.distanceTo(exitDoorMesh.position);
        if (distDoor < 3.0) {
          if (state.talismansFound >= state.totalTalismans) {
            triggerClear();
          } else {
            showBubble('🔒', `${char.name}: 「4枚のおふだを集めないと開かない…!」`);
            showToast('🔒', `あと ${state.totalTalismans - state.talismansFound} 枚のおふだが必要です!`);
          }
          return;
        }
      }

      if (!found) {
        showBubble('👀', `${char.name}: 「なにかあるかな…?」`, 1200);
      }
    }

    /* ------------------------------------------------------------------
       固有スキル発動
       ------------------------------------------------------------------ */
    function triggerSkill() {
      if (!state.isPlaying || !state.skillReady) return;
      const char = CHARACTERS[state.selectedCharId];
      state.skillReady = false;
      state.skillActive = true;
      state.skillEndTime = Date.now() + 3200;
      sound.playSkillSound(char.id);

      showBubble('🔥', char.skillVoice, 2400);
      showToast(char.skillIcon, `${char.name}の特技【${char.skillName}】発動!`);

      if (char.id === 'chiikawa') {
        // ちいかわ: 懐中電灯が超強力ストロボ閃光になり、周囲のオバケを退散
        if (spotLight) {
          spotLight.intensity = 18.0;
          spotLight.color.setHex(0xfbcfe8);
        }
        ghosts.forEach(g => {
          const d = state.playerPos.distanceTo(g.mesh.position);
          if (d < 10) {
            // 安全な遠くへワープ退散
            g.mesh.position.x = 10 * GRID_SIZE;
            g.mesh.position.z = 10 * GRID_SIZE;
          }
        });
      } else if (char.id === 'devil_usagi') {
        // 悪魔うさぎ:怪鳥音の漆黒衝撃波で周囲の全オバケとセイレーンを遠方へ一掃!
        if (spotLight) {
          spotLight.intensity = 14.0;
          spotLight.color.setHex(0xc084fc);
        }
        ghosts.forEach(g => {
          const dir = new THREE.Vector3().subVectors(g.mesh.position, state.playerPos);
          if (dir.length() < 12) {
            dir.normalize().multiplyScalar(10);
            g.mesh.position.add(dir);
          }
        });
        if (sirenObj) {
          const sDir = new THREE.Vector3().subVectors(sirenObj.group.position, state.playerPos);
          if (sDir.length() < 10) {
            sDir.normalize().multiplyScalar(6);
            sirenObj.group.position.add(sDir);
          }
        }
      } else if (char.id === 'usagi') {
        // うさぎ: 叫びの衝撃波でオバケを吹き飛ばす
        ghosts.forEach(g => {
          const dir = new THREE.Vector3().subVectors(g.mesh.position, state.playerPos);
          if (dir.length() < 9) {
            dir.normalize().multiplyScalar(7);
            g.mesh.position.add(dir);
          }
        });
      } else if (char.id === 'momonga') {
        // モモンガ: オバケたちを一定時間メロメロ停止
        ghosts.forEach(g => {
          g.state = 'charmed';
          g.charmedTimer = 3500;
        });
      }

      const btn = document.getElementById('btnSkill');
      btn.classList.add('opacity-40', 'pointer-events-none');
      setTimeout(() => {
        state.skillReady = true;
        btn.classList.remove('opacity-40', 'pointer-events-none');
        showToast('✨', `${char.name}のスキルが再チャージ完了!`, 1500);
      }, char.skillCooldown);
    }

    /* ------------------------------------------------------------------
       ゲームクリア & 気絶
       ------------------------------------------------------------------ */
    function triggerClear() {
      state.isPlaying = false;
      sound.playVictory();
      const char = CHARACTERS[state.selectedCharId];
      document.getElementById('clearCharName').textContent = char.name;
      document.getElementById('clearCourageLeft').textContent = `${Math.round((state.courage / state.maxCourage) * 100)}%`;

      let title = '「3Dなんとかなった大スター」';
      if (char.id === 'devil_usagi') title = '「こんなんなっちゃった最強の怪異大スター」';
      if (char.id === 'usagi') title = '「叫びと跳躍の3D怪異バスター」';
      if (char.id === 'hachiware') title = '「ピンチを乗り越えた大英雄」';
      if (char.id === 'momonga') title = '「オバケもメロメロの最高峰スター」';
      document.getElementById('clearTitleText').textContent = title;

      clearModal.classList.remove('hidden');
    }

    function triggerFaint() {
      state.isPlaying = false;
      faintModal.classList.remove('hidden');
    }

    /* ------------------------------------------------------------------
       ゲームループ(更新 & 描画)
       ------------------------------------------------------------------ */
    let lastTime = performance.now();
    let stepSoundTimer = 0;

    function animate(time) {
      requestAnimationFrame(animate);

      const dt = Math.min((time - lastTime) / 1000, 0.1);
      lastTime = time;

      if (state.isPlaying) {
        const char = CHARACTERS[state.selectedCharId];
        let moveSpeed = char.speed;

        // ハチワレダッシュ効果
        if (state.skillActive && char.id === 'hachiware') {
          moveSpeed *= 1.8;
        }

        // スキル終了判定
        if (state.skillActive && Date.now() > state.skillEndTime) {
          state.skillActive = false;
          if (char.id === 'chiikawa' && spotLight) {
            spotLight.intensity = 4.0;
            spotLight.color.setHex(0xfef08a);
          }
        }

        // カメラ向きに応じた移動ベクトル計算
        let inputX = 0, inputZ = 0;
        if (state.keys.up) inputZ -= 1;
        if (state.keys.down) inputZ += 1;
        if (state.keys.left) inputX -= 1;
        if (state.keys.right) inputX += 1;

        const isMoving = inputX !== 0 || inputZ !== 0;

        if (isMoving) {
          // 入力ベクトルの正規化
          const len = Math.hypot(inputX, inputZ);
          inputX /= len;
          inputZ /= len;

          // カメラの水平回転角に合わせて移動方向を決定
          const forward = new THREE.Vector3(-Math.sin(state.cameraAngleH), 0, -Math.cos(state.cameraAngleH));
          const right = new THREE.Vector3(Math.cos(state.cameraAngleH), 0, -Math.sin(state.cameraAngleH));

          const moveDir = new THREE.Vector3()
            .addScaledVector(forward, -inputZ)
            .addScaledVector(right, inputX)
            .normalize();

          // 移動先チェック & 当たり判定
          const nextPos = state.playerPos.clone().addScaledVector(moveDir, moveSpeed * dt);
          if (canMoveTo(nextPos.x, state.playerPos.z, 0.45)) {
            state.playerPos.x = nextPos.x;
          }
          if (canMoveTo(state.playerPos.x, nextPos.z, 0.45)) {
            state.playerPos.z = nextPos.z;
          }

          // キャラクターの向きを滑らかに回転
          const targetRot = Math.atan2(moveDir.x, moveDir.z);
          state.playerRot = targetRot;

          // 歩行モーション(上下ボブ & 手の振り & 悪魔の翼羽ばたき)
          state.walkCycle += dt * 14;
          if (playerMesh) {
            playerMesh.position.y = 0.7 + Math.sin(state.walkCycle) * 0.08;
            if (handL && handR) {
              handL.position.z = 0.25 + Math.sin(state.walkCycle) * 0.15;
              handR.position.z = 0.25 - Math.sin(state.walkCycle) * 0.15;
            }
          }

          // 悪魔の翼の羽ばたき(歩行時は激しく羽ばたく)
          if (playerWingL && playerWingR) {
            const wingFlap = Math.sin(state.walkCycle * 1.5) * 0.45;
            playerWingL.rotation.y = -wingFlap;
            playerWingR.rotation.y = wingFlap;
          }

          // 足音再生
          stepSoundTimer += dt;
          if (stepSoundTimer > 0.32) {
            sound.playStep();
            stepSoundTimer = 0;
          }
        } else {
          // アイドル時の呼吸モーション & ゆったりした翼の羽ばたき
          if (playerMesh) {
            playerMesh.position.y = 0.7 + Math.sin(time * 0.003) * 0.03;
          }
          if (playerWingL && playerWingR) {
            const idleFlap = Math.sin(time * 0.005) * 0.22;
            playerWingL.rotation.y = -idleFlap;
            playerWingR.rotation.y = idleFlap;
          }
        }

        // プレイヤーグループの同期
        if (playerGroup) {
          playerGroup.position.copy(state.playerPos);
          playerGroup.rotation.y = state.playerRot;

          // 被ダメ時の無敵点滅
          if (state.invincibleTimer > 0) {
            state.invincibleTimer -= dt * 1000;
            playerMesh.visible = Math.floor(state.invincibleTimer / 100) % 2 === 0;
          } else {
            playerMesh.visible = true;
          }
        }

        // カメラをプレイヤー背後に滑らかに追従
        const camDistH = state.cameraDist * Math.cos(state.cameraAngleV);
        const camHeight = state.cameraDist * Math.sin(state.cameraAngleV);
        const targetCamX = state.playerPos.x + Math.sin(state.cameraAngleH) * camDistH;
        const targetCamZ = state.playerPos.z + Math.cos(state.cameraAngleH) * camDistH;
        const targetCamY = state.playerPos.y + camHeight + 1.2;

        camera.position.lerp(new THREE.Vector3(targetCamX, targetCamY, targetCamZ), 0.12);
        camera.lookAt(state.playerPos.x, state.playerPos.y + 1.0, state.playerPos.z);

        // 吹き出しの位置を3Dからスクリーン座標にマッピング
        if (speechBubble.classList.contains('opacity-100')) {
          const screenPos = state.playerPos.clone().setY(state.playerPos.y + 1.7);
          screenPos.project(camera);
          const sx = (screenPos.x * 0.5 + 0.5) * window.innerWidth;
          const sy = (-(screenPos.y * 0.5) + 0.5) * window.innerHeight;
          speechBubble.style.left = `${sx}px`;
          speechBubble.style.top = `${sy}px`;
        }

        // アイテム浮遊アニメーション
        talismanObjects.forEach(t => {
          if (!t.collected) {
            t.group.rotation.y += 0.02;
            t.group.position.y = 1.2 + Math.sin(time * 0.003 + t.id) * 0.15;
          }
        });

        // キャンディ回収判定
        candyObjects.forEach(c => {
          if (!c.collected) {
            c.mesh.rotation.y += 0.03;
            if (state.playerPos.distanceTo(c.mesh.position) < 1.4) {
              c.collected = true;
              scene.remove(c.mesh);
              state.courage = Math.min(state.maxCourage, state.courage + 30);
              sound.playTalisman();
              updateUI();
              showBubble('🍬', 'キャンディで勇気回復!', 1500);
            }
          }
        });

        // 近くのアイテム調べるプロンプト
        let canInteract = false;
        talismanObjects.forEach(t => {
          if (!t.collected && state.playerPos.distanceTo(t.group.position) < 2.5) {
            canInteract = true;
            interactPromptText.textContent = `${t.name} を調べる [Space / E]`;
          }
        });
        if (!canInteract && exitDoorMesh && state.playerPos.distanceTo(exitDoorMesh.position) < 3.0) {
          canInteract = true;
          interactPromptText.textContent = state.talismansFound >= state.totalTalismans ? '映写室から脱出する! [Space / E]' : '扉を調べる [Space / E]';
        }
        interactPrompt.classList.toggle('hidden', !canInteract);

        // ==================== 巨大ボス:セイレーンの動作 ====================
        if (sirenObj) {
          // 尾びれと音符の浮遊・くねりアニメーション
          sirenObj.tail.rotation.z = Math.sin(time * 0.005) * 0.35;
          sirenObj.group.position.y = Math.sin(time * 0.003) * 0.3;
          sirenObj.note.position.y = 4.4 + Math.sin(time * 0.006) * 0.25;

          // 回廊をゆったりと遊泳
          const nextSx = sirenObj.group.position.x + sirenObj.vx;
          if (nextSx < 4 * GRID_SIZE || nextSx > 16 * GRID_SIZE) {
            sirenObj.vx *= -1;
          } else {
            sirenObj.group.position.x = nextSx;
          }

          // セイレーンの向き
          sirenObj.group.rotation.y = sirenObj.vx > 0 ? Math.PI / 2 : -Math.PI / 2;

          // プレイヤーとの距離判定
          const sirenDist = state.playerPos.distanceTo(sirenObj.group.position);
          const sirenWarningEl = document.getElementById('sirenWarning');

          if (sirenDist < 12.0) {
            sirenWarningEl.classList.remove('hidden');
            // 定期的に歌声を再生
            sirenObj.singTimer += dt;
            if (sirenObj.singTimer > 3.8) {
              sound.playSirenSong();
              showBubble('🎶', 'セイレーン: 「ルラララ〜♪ 逃がさないよォ…」', 2500);
              sirenObj.singTimer = 0;
            }

            // 接近時の勇気ダメージ(歌声による威圧)
            if (sirenDist < 2.8 && state.invincibleTimer <= 0) {
              state.invincibleTimer = 2000;
              state.courage -= 30;
              sound.playGhostScare();
              updateUI();
              showBubble('😱', `${char.name}: 「セイレーンだァッ!!こ、こわいッ!」`, 2000);
              const push = new THREE.Vector3().subVectors(state.playerPos, sirenObj.group.position).normalize().multiplyScalar(1.5);
              state.playerPos.add(push);

              if (state.courage <= 0) {
                triggerFaint();
              }
            }
          } else {
            sirenWarningEl.classList.add('hidden');
          }
        }

        // 3Dオバケの自律徘徊 & 接触判定
        ghosts.forEach(g => {
          if (g.state === 'charmed') {
            g.charmedTimer -= dt * 1000;
            if (g.charmedTimer <= 0) g.state = 'normal';
            return;
          }

          // 浮遊モーション
          g.mesh.position.y = g.baseY + Math.sin(time * 0.004 + g.floatOffset) * 0.2;

          // 移動と壁反転
          const nextGx = g.mesh.position.x + g.vx;
          const nextGz = g.mesh.position.z + g.vz;
          if (isWallAt(nextGx, nextGz)) {
            g.vx *= -1;
            g.vz *= -1;
          } else {
            g.mesh.position.x = nextGx;
            g.mesh.position.z = nextGz;
          }

          // プレイヤーに向かって顔を向ける
          g.mesh.lookAt(state.playerPos.x, g.mesh.position.y, state.playerPos.z);

          // プレイヤー接触判定
          const dist = state.playerPos.distanceTo(g.mesh.position);
          if (dist < 1.3) {
            // ハチワレダッシュ中はすり抜け
            if (state.skillActive && char.id === 'hachiware') return;

            if (state.invincibleTimer <= 0) {
              state.invincibleTimer = 1800;
              state.courage -= 25;
              sound.playGhostScare();
              updateUI();

              const scares = char.dialogues.scared;
              showBubble('👻', `${char.name}: 「${scares[Math.floor(Math.random() * scares.length)]}」`, 2000);

              // プレイヤー反発ノックバック
              const pushBack = new THREE.Vector3().subVectors(state.playerPos, g.mesh.position).normalize().multiplyScalar(0.8);
              state.playerPos.add(pushBack);

              if (state.courage <= 0) {
                triggerFaint();
              }
            }
          }
        });
      }

      renderer.render(scene, camera);
    }

    // 画面ロード時に3D初期化 & ループ開始
    window.onload = function() {
      initThree();
      lastTime = performance.now();
      requestAnimationFrame(animate);
    };

  </script>
</body>
</html>

ちいかわおばけやしき

by りい

お化け屋敷ゲーム

🤖 使用したAI
Gemini
👁 36 回閲覧
📅 投稿:2026年10月24日 🔄 更新:2026年11月14日
応援スタンプを押してみよう!