4. ひみつの手紙 ソースコード
遊ぶ一覧にもどる

HTML 1ファイルで動きます。コピーして、新しいファイル(〇〇.html)に貼ると、そのまま遊べます。このフォルダの 4_tegami/index.html と同じ中身です。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>ひみつの手紙</title>
<style>
  html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; }
  body { background: #0d1330; color: #f4f6ff; user-select: none; -webkit-user-select: none; }
  button { font-family: inherit; cursor: pointer; }
  #game { position: absolute; left: 0; top: 0; width: 960px; height: 540px; overflow: hidden;
    background: radial-gradient(circle at 22% 48%, #24306e 0, #131a44 46%, #0a0f28 100%); }
  #grid { position: absolute; inset: 0; opacity: .12;
    background-image: linear-gradient(#7fa0ff 1px, transparent 1px), linear-gradient(90deg, #7fa0ff 1px, transparent 1px);
    background-size: 40px 40px; }

  /* 上のバー */
  #top { position: absolute; left: 0; top: 0; width: 960px; height: 44px; background: #070b20; display: flex; align-items: center; box-sizing: border-box; padding: 0 12px; gap: 10px; }
  #logo { font-size: 18px; font-weight: 700; color: #ffd54f; margin-right: 6px; }
  .pill { font-size: 16px; padding: 3px 12px; border-radius: 14px; background: #1b2350; color: #8c97c9; font-weight: 700; }
  .pill.now { background: #ffd54f; color: #2a1d00; }
  .pill.done { background: #2c7a57; color: #d8ffe9; }
  #score { margin-left: auto; font-size: 22px; font-weight: 700; color: #fff; min-width: 120px; text-align: right; }
  #mute { font-size: 16px; padding: 5px 10px; border-radius: 10px; border: 2px solid #5b6aa8; background: #1b2350; color: #dfe6ff; }

  /* ダイヤル */
  #dialBox { position: absolute; left: 14px; top: 48px; width: 384px; height: 486px; transition: opacity .3s; }
  #dialBox.off { opacity: .5; }
  #dial { position: absolute; left: 12px; top: 2px; width: 360px; height: 360px; touch-action: none; cursor: grab; filter: drop-shadow(0 6px 10px rgba(0,0,0,.5)); }
  #dialBox.off #dial { cursor: default; }
  #inner { transform-origin: 200px 200px; transition: transform .2s cubic-bezier(.3, 1.7, .5, 1); }
  #inner.drag { transition: none; }
  .ot { font-size: 22px; font-weight: 700; fill: #e6deff; }
  .it { font-size: 20px; font-weight: 700; fill: #3a2c12; }
  .hl { fill: none; }
  .hl.on { fill: #ff8a3c; }
  .hl.in.on { fill: #ffd54f; }
  .ot.on { fill: #fff; }
  #dialBtns { position: absolute; left: 22px; top: 370px; width: 340px; display: flex; gap: 12px; }
  #dialBtns button { flex: 1; height: 48px; font-size: 20px; font-weight: 700; border: 0; border-radius: 14px; background: #4e5fd6; color: #fff; box-shadow: 0 4px 0 #2c3790; }
  #dialBtns button:active { transform: translateY(3px); box-shadow: 0 1px 0 #2c3790; }
  #legend { position: absolute; left: 0; top: 432px; width: 384px; text-align: center; font-size: 16px; color: #c9d2ff; line-height: 1.5; }
  .sw { display: inline-block; width: 14px; height: 14px; border-radius: 4px; vertical-align: -1px; margin-right: 4px; }

  /* セリフ */
  #talk { position: absolute; left: 408px; top: 50px; width: 540px; height: 92px; }
  #face { position: absolute; left: 0; top: 2px; width: 88px; height: 88px; }
  #bubble { position: absolute; left: 100px; top: 4px; width: 438px; height: 82px; box-sizing: border-box; padding: 12px 16px; border-radius: 16px; background: #fffdf2; color: #23263a; font-size: 18px; line-height: 29px; }
  #bubble::before { content: ""; position: absolute; left: -12px; top: 30px; border: 8px solid transparent; border-right: 12px solid #fffdf2; border-left: 0; }
  #bubble.robo { background: #ffe3e3; }
  #bubble.robo::before { border-right-color: #ffe3e3; }
  #bubble.pop { animation: pop .25s; }
  #btnNext { position: absolute; right: 10px; bottom: -20px; height: 40px; padding: 0 18px; font-size: 18px; font-weight: 700; border: 0; border-radius: 12px; background: #ff8a3c; color: #fff; box-shadow: 0 4px 0 #b3531a; animation: bob 1s infinite; z-index: 3; }
  @keyframes bob { 50% { transform: translateY(-3px); } }
  @keyframes pop { 0% { transform: scale(.9); } 60% { transform: scale(1.04); } 100% { transform: scale(1); } }

  /* 作業パネル */
  #work { position: absolute; left: 408px; top: 152px; width: 540px; height: 376px; }
  .card { position: absolute; inset: 0; box-sizing: border-box; padding: 12px 16px; border-radius: 18px; background: rgba(12, 18, 52, .88); border: 2px solid #3d4a94; }
  .hd { height: 32px; display: flex; align-items: center; gap: 10px; }
  .lab { font-size: 18px; font-weight: 700; color: #ffd54f; }
  .chip { font-size: 17px; font-weight: 700; padding: 2px 12px; border-radius: 12px; background: #ff8a3c; color: #fff; }
  .rowlab { font-size: 16px; color: #aab5ea; margin-top: 4px; height: 22px; }
  .tiles { display: flex; gap: 4px; height: 50px; }
  .t { width: 44px; height: 48px; border-radius: 9px; font-size: 27px; font-weight: 700; display: flex; align-items: center; justify-content: center; box-sizing: border-box; }
  .t.c { background: #5a3fd0; color: #fff; border-bottom: 4px solid #36218f; }
  .t.p { background: #fff7dc; color: #2c2410; border-bottom: 4px solid #c9b77a; }
  .t.p.lit { background: #a8f5c4; border-bottom-color: #3fae6e; }
  .t.p.win { animation: hop .45s both; background: #7df0a6; border-bottom-color: #2f9a5b; }
  .t.flip { animation: flip .16s; }
  @keyframes flip { 0% { transform: scaleY(.3); } 100% { transform: scaleY(1); } }
  @keyframes hop { 0% { transform: translateY(0); } 40% { transform: translateY(-16px) rotate(-6deg); } 100% { transform: translateY(0); } }
  .tiles.s { height: 42px; }
  .tiles.s .t { width: 40px; height: 40px; font-size: 24px; }
  .arrow { font-size: 16px; color: #8fe9ff; height: 24px; margin-top: 6px; }
  .shake { animation: shake .35s; }
  @keyframes shake { 20% { transform: translateX(-8px); } 40% { transform: translateX(8px); } 60% { transform: translateX(-6px); } 80% { transform: translateX(6px); } }
  .foot { position: absolute; left: 16px; right: 16px; bottom: 12px; height: 52px; display: flex; align-items: center; gap: 10px; }
  #msg { flex: 1; font-size: 18px; font-weight: 700; color: #a8f5c4; line-height: 1.35; }
  #msg.bad { color: #ff9c9c; }
  #msg.note { font-size: 16px; font-weight: 400; color: #aab5ea; }
  .big { height: 52px; min-width: 150px; padding: 0 22px; font-size: 22px; font-weight: 700; border: 0; border-radius: 16px; background: #2fbf71; color: #fff; box-shadow: 0 5px 0 #1b7a45; }
  .big:active { transform: translateY(3px); box-shadow: 0 2px 0 #1b7a45; }
  .big.dim { background: #56608c; box-shadow: 0 5px 0 #353d63; }
  .bar { position: relative; height: 22px; border-radius: 11px; background: #1d2659; overflow: hidden; }
  .bar > i { position: absolute; left: 0; top: 0; bottom: 0; width: 100%; background: linear-gradient(90deg, #ffb13c, #ffe56a); border-radius: 11px; }
  .barrow { display: flex; align-items: center; gap: 10px; margin-top: 8px; font-size: 16px; color: #ffe9a8; }
  .barrow .bar { flex: 1; }
  .dots { display: flex; gap: 3px; margin-top: 8px; align-items: center; font-size: 16px; color: #aab5ea; }
  .dots i { width: 10px; height: 14px; border-radius: 3px; background: #2a3470; }
  .dots i.on { background: #5ee6ff; }
  .dots span { margin-right: 6px; }
  .choices { display: flex; flex-direction: column; gap: 12px; margin-top: 14px; }
  .choice { height: 62px; font-size: 26px; font-weight: 700; border: 0; border-radius: 16px; background: #fff7dc; color: #2c2410; box-shadow: 0 5px 0 #c9b77a; letter-spacing: 2px; }
  .choice small { font-size: 18px; letter-spacing: 0; color: #7a6a3a; margin-left: 10px; }
  .choice:hover { background: #ffe9a8; }

  /* ロボの総当たり */
  .roboL { position: absolute; left: 10px; top: 60px; width: 170px; height: 200px; }
  .roboL.happy { animation: hop .5s 2; }
  .roboL.dead { transition: transform 1s; transform: translateY(34px) rotate(-24deg); }
  .roboR { position: absolute; left: 188px; top: 12px; right: 16px; bottom: 12px; }
  .count { font-size: 46px; font-weight: 700; color: #ff7b8a; line-height: 54px; margin-top: 6px; }
  .count small { font-size: 18px; color: #c9d2ff; margin-left: 8px; }
  .lg { font-size: 18px; height: 27px; color: #9aa5d8; white-space: nowrap; }
  .lg b { letter-spacing: 2px; color: #dfe6ff; }
  .lg.hit { color: #ffe56a; font-weight: 700; } .lg.hit b { color: #ffe56a; }
  #rTry { font-size: 20px; height: 30px; white-space: nowrap; color: #dfe6ff; margin-top: 4px; }
  #rTry b { letter-spacing: 2px; color: #8fe9ff; }
  #rBig { font-size: 22px; font-weight: 700; height: 40px; white-space: nowrap; color: #ffe56a; margin-top: 6px; }
  #rBig.safe { color: #7df0a6; }
  .bat > i { background: linear-gradient(90deg, #ff5a6e, #ffb13c); }

  /* 合言葉 */
  .krow { display: flex; gap: 4px; height: 22px; }
  .krow span { width: 40px; text-align: center; font-size: 17px; font-weight: 700; color: #8fe9ff; }
  .slots .note { white-space: nowrap; }
  .slots { display: flex; gap: 6px; align-items: center; margin-top: 8px; height: 46px; }
  .slot { width: 40px; height: 44px; border-radius: 9px; background: #10173f; border: 2px dashed #5ee6ff; box-sizing: border-box; font-size: 26px; font-weight: 700; color: #8fe9ff; display: flex; align-items: center; justify-content: center; }
  .slot.f { border-style: solid; background: #123a55; }
  .slot.x { border-color: #3d4a94; }
  #combo { margin-left: 8px; font-size: 16px; line-height: 1.35; color: #ffe9a8; white-space: nowrap; }
  #combo b { font-size: 20px; }
  #combo.safe b { color: #7df0a6; }
  .kb { display: grid; grid-template-columns: repeat(13, 36px); gap: 3px 3px; margin-top: 8px; }
  .kb button { height: 34px; font-size: 18px; font-weight: 700; border: 0; border-radius: 7px; background: #dfe6ff; color: #1d2659; padding: 0; }
  .kb button:active { background: #ffd54f; }
  #btnDel { height: 44px; padding: 0 12px; white-space: nowrap; font-size: 16px; font-weight: 700; border: 0; border-radius: 9px; background: #56608c; color: #fff; }
  .note { font-size: 16px; color: #aab5ea; }

  /* かぶせる画面 */
  #banner { position: absolute; left: 0; top: 190px; width: 960px; height: 150px; display: none; flex-direction: column; align-items: center; justify-content: center; background: rgba(7, 11, 32, .93); border-top: 4px solid #ffd54f; border-bottom: 4px solid #ffd54f; z-index: 5; }
  #banner.on { display: flex; animation: slide 1.5s both; }
  #banner b { font-size: 22px; color: #ffd54f; }
  #banner span { font-size: 44px; font-weight: 700; margin-top: 4px; }
  @keyframes slide { 0% { opacity: 0; transform: translateX(-80px); } 15% { opacity: 1; transform: translateX(0); } 85% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(80px); } }
  #title, #result { position: absolute; inset: 0; z-index: 6; background: radial-gradient(circle at 50% 40%, #2a3a8c 0, #131a44 55%, #070b20 100%); }
  #title h1 { position: absolute; left: 0; top: 60px; width: 960px; margin: 0; text-align: center; font-size: 76px; color: #ffd54f; letter-spacing: 8px; text-shadow: 0 6px 0 #7a4b00; }
  #tSub { position: absolute; left: 0; top: 34px; width: 960px; text-align: center; font-size: 20px; color: #8fe9ff; font-weight: 700; letter-spacing: 4px; }
  #tCopy { position: absolute; left: 0; top: 172px; width: 960px; text-align: center; font-size: 24px; font-weight: 700; }
  #tTiles { position: absolute; left: 0; top: 226px; width: 960px; display: flex; justify-content: center; }
  #tMike { position: absolute; left: 96px; top: 200px; width: 170px; height: 170px; animation: bob 1.6s infinite; }
  #tRobo { position: absolute; left: 700px; top: 190px; width: 160px; height: 190px; animation: bob 1.3s infinite; }
  #btnStart { position: absolute; left: 360px; top: 306px; width: 240px; height: 76px; font-size: 34px; font-weight: 700; border: 0; border-radius: 22px; background: #ff8a3c; color: #fff; box-shadow: 0 7px 0 #b3531a; animation: bob 1s infinite; }
  #tNote { position: absolute; left: 0; top: 408px; width: 960px; text-align: center; font-size: 17px; line-height: 1.7; color: #dfe6ff; }
  #tNote b { color: #ffd54f; }
  #result { display: none; }
  #result h2 { position: absolute; left: 0; top: 14px; width: 960px; margin: 0; text-align: center; font-size: 38px; color: #ffd54f; }
  #stars { position: absolute; left: 0; top: 66px; width: 960px; height: 76px; display: flex; justify-content: center; gap: 14px; }
  #stars svg { width: 76px; height: 76px; animation: starIn .5s both; }
  @keyframes starIn { 0% { transform: scale(0) rotate(-90deg); } 70% { transform: scale(1.25); } 100% { transform: scale(1); } }
  #total { position: absolute; left: 0; top: 142px; width: 960px; text-align: center; font-size: 46px; font-weight: 700; }
  #total small { font-size: 22px; margin-left: 6px; }
  .col { position: absolute; top: 212px; box-sizing: border-box; padding: 12px 18px; border-radius: 16px; background: rgba(7, 11, 32, .7); border: 2px solid #3d4a94; font-size: 17px; line-height: 1.6; }
  #colL { left: 40px; width: 400px; height: 262px; }
  #colR { left: 460px; width: 460px; height: 216px; font-size: 16px; line-height: 1.55; }
  .col h3 { margin: 0 0 4px; font-size: 18px; color: #8fe9ff; }
  .br { display: flex; justify-content: space-between; }
  .br b { color: #ffe56a; }
  #colR div { margin-bottom: 2px; padding-left: 1em; text-indent: -1em; }
  #btnAgain { position: absolute; left: 680px; top: 440px; width: 240px; height: 56px; font-size: 22px; font-weight: 700; border: 0; border-radius: 16px; background: #ff8a3c; color: #fff; box-shadow: 0 5px 0 #b3531a; }
  #rNote { position: absolute; left: 464px; top: 442px; width: 210px; font-size: 16px; line-height: 1.5; color: #c9d2ff; }
  #fx { position: absolute; left: 0; top: 0; width: 960px; height: 540px; pointer-events: none; z-index: 8; }
  .float { position: absolute; z-index: 7; font-size: 30px; font-weight: 700; color: #ffe56a; text-shadow: 0 2px 0 #7a4b00; pointer-events: none; animation: floatUp 1.1s both; }
  .float.minus { color: #ff9c9c; text-shadow: 0 2px 0 #5a1010; }
  @keyframes floatUp { 0% { opacity: 0; transform: translateY(10px) scale(.7); } 20% { opacity: 1; transform: translateY(0) scale(1.15); } 100% { opacity: 0; transform: translateY(-50px); } }

  /* どの画面の大きさでも、960×540 のゲーム全体を縮めて真ん中に表示する */
  #fitbox { position: absolute; left: 0; top: 0; width: 960px; height: 540px; transform-origin: 0 0; }
</style>
</head>
<body>
<div id="fitbox">
<div id="game" data-scene="title" data-phase="title">
  <div id="grid"></div>
  <div id="top">
    <div id="logo">ひみつの手紙</div>
    <div class="pill" id="pill1">1 読む</div>
    <div class="pill" id="pill2">2 送る</div>
    <div class="pill" id="pill3">3 解く</div>
    <div class="pill" id="pill4">4 守る</div>
    <div id="score">0 点</div>
    <button id="mute" type="button">音:オン</button>
  </div>
  <div id="dialBox" class="off">
    <svg id="dial" viewBox="0 0 400 400" aria-label="暗号ダイヤル"></svg>
    <div id="dialBtns">
      <button id="btnMinus" type="button">◀ もどす</button>
      <button id="btnPlus" type="button">ずらす ▶</button>
    </div>
    <div id="legend"><span class="sw" style="background:#5a3fd0"></span>外の輪=暗号の文字 <span class="sw" style="background:#fff7dc"></span>内の輪=元の文字<br>マウスで回すか、左右のキーでも動きます</div>
  </div>
  <div id="talk">
    <div id="face"></div>
    <div id="bubble"><div id="line">…</div><button id="btnNext" type="button">次へ ▶</button></div>
  </div>
  <div id="work"></div>
  <div id="banner"><b id="bnA"></b><span id="bnB"></span></div>
  <div id="result"></div>
  <div id="title">
    <div id="tSub">暗号ゲーム</div>
    <h1>ひみつの手紙</h1>
    <div id="tCopy">解読ロボから、仲間への手紙を守ろう!</div>
    <div id="tTiles" class="tiles"></div>
    <div id="tMike"></div>
    <div id="tRobo"></div>
    <button id="btnStart" type="button">スタート</button>
    <div id="tNote">きみは見習いスパイ。暗号ダイヤルを回して、手紙を読んだり送ったりします。<br><b>ためしてよいのは、このゲームの中だけです。</b></div>
  </div>
  <canvas id="fx" width="960" height="540"></canvas>
</div>
</div>
<script>
(() => {
  // 画面の大きさ(480×360 など)に合わせて、960×540 のゲーム全体を縮めて真ん中に表示する
  const box = document.getElementById("fitbox");
  const fit = () => {
    const w = document.documentElement.clientWidth || window.innerWidth;
    const h = document.documentElement.clientHeight || window.innerHeight;
    const s = Math.min(w / 960, h / 540);
    box.style.transform = "translate(" + ((w - 960 * s) / 2) + "px, " + ((h - 540 * s) / 2) + "px) scale(" + s + ")";
  };
  window.addEventListener("resize", fit);
  fit();
})();
</script>
<script>
(() => {
  "use strict";

  // ===== かんたんに変えられるところ =====
  // 言葉は A〜Z の大文字だけ。10文字まで。[ローマ字, 意味]
  const WORDS = {
    read1: [["SAKANA", "魚"], ["MAGURO", "まぐろ"], ["KATSUO", "かつお"]],          // 場面1 ミケの好きな物
    read2: [["KOUEN", "公園"], ["GAKKOU", "学校"], ["EKIMAE", "駅前"], ["TOSHOKAN", "図書館"]], // 場面1 集合場所
    read3: [["ONIGIRI", "おにぎり"], ["SUSHI", "すし"], ["RINGO", "りんご"], ["BANANA", "バナナ"]], // 場面1 持ち物
    send: [["SHIMA", "島"], ["MIZUUMI", "湖"], ["URAYAMA", "裏山"]],                 // 場面2・4 宝のかくし場所
    spy1: [["ABURA", "油"], ["NEJI", "ねじ"], ["DENKYUU", "電球"]],                  // 場面3 ロボのほしい物
    spy2: [["OYATSU", "おやつ"], ["TAKARA", "宝"], ["OKASHI", "おかし"]],            // 場面3 ロボがねらう物
    spy3: [["DENCHIGIRE", "電池切れ"]]                                               // 場面3 ロボの弱点
  };
  const ROBO_BUDGET = 10000;   // 場面4でロボがためせる回数(電池)
  const STAR3 = 1900, STAR2 = 1400; // 星3つ・星2つに必要な点

  // ===== 小さな道具 =====
  const $ = (id) => document.getElementById(id);
  const ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const STEP = 360 / 26;
  const mod26 = (n) => ((n % 26) + 26) % 26;
  const shiftCh = (c, k) => ABC[mod26(ABC.indexOf(c) + k)];
  const caesar = (s, k) => s.split("").map((c) => shiftCh(c, k)).join("");
  const vig = (s, key, sign) => s.split("").map((c, i) => shiftCh(c, sign * ABC.indexOf(key[i % key.length]))).join("");
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
  const rnd = (a, b) => a + Math.floor(Math.random() * (b - a + 1));
  const fmt = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  const tilesHTML = (s, cls) => s.split("").map((c) => '<span class="t ' + cls + '">' + c + "</span>").join("");

  const game = $("game"), work = $("work"), dialBox = $("dialBox"), dialSvg = $("dial");
  const face = $("face"), bubble = $("bubble"), lineEl = $("line"), nextBtn = $("btnNext");
  const scoreEl = $("score"), fx = $("fx"), fxc = fx.getContext("2d");
  let started = false;
  const setPhase = (p) => { game.dataset.phase = p; };

  // ===== 音(Web Audio で合成。鳴らなくてもゲームは止まらない) =====
  let ac = null, master = null, muted = false;
  function audioInit() {
    if (ac) return;
    try {
      const C = window.AudioContext || window.webkitAudioContext;
      if (!C) return;
      ac = new C();
      master = ac.createGain();
      master.gain.value = 0.6;
      master.connect(ac.destination);
      const p = ac.resume && ac.resume();
      if (p && p.catch) p.catch(() => {});
    } catch (e) { ac = null; }
  }
  function tone(f, d, o) {
    if (!ac || muted) return;
    try {
      o = o || {};
      const t = ac.currentTime + (o.at || 0);
      const os = ac.createOscillator(), g = ac.createGain();
      os.type = o.type || "square";
      os.frequency.setValueAtTime(f, t);
      if (o.to) os.frequency.exponentialRampToValueAtTime(o.to, t + d);
      g.gain.setValueAtTime(0.0001, t);
      g.gain.exponentialRampToValueAtTime(o.vol || 0.1, t + 0.008);
      g.gain.exponentialRampToValueAtTime(0.0001, t + d);
      os.connect(g); g.connect(master);
      os.start(t); os.stop(t + d + 0.03);
    } catch (e) { /* 音が出なくても続ける */ }
  }
  function noise(d, vol) {
    if (!ac || muted) return;
    try {
      const n = Math.floor(ac.sampleRate * d), buf = ac.createBuffer(1, n, ac.sampleRate), ch = buf.getChannelData(0);
      for (let i = 0; i < n; i++) ch[i] = (Math.random() * 2 - 1) * (1 - i / n);
      const s = ac.createBufferSource(), g = ac.createGain(), f = ac.createBiquadFilter();
      f.type = "lowpass"; f.frequency.value = 900;
      g.gain.value = vol || 0.3;
      s.buffer = buf; s.connect(f); f.connect(g); g.connect(master); s.start();
    } catch (e) { /* 音が出なくても続ける */ }
  }
  const sfx = {
    tick: (k) => tone(520 + k * 22, 0.05, { type: "triangle", vol: 0.2 }),
    click: () => tone(880, 0.06, { vol: 0.08 }),
    type: (n) => { tone(440 * Math.pow(1.19, n), 0.09, { type: "triangle", vol: 0.2 }); },
    ok: () => { [523, 659, 784, 1047].forEach((f, i) => tone(f, 0.14, { at: i * 0.08, vol: 0.1 })); },
    bad: () => { tone(170, 0.28, { type: "sawtooth", to: 80, vol: 0.12 }); },
    blip: (n) => tone(300 + (n % 13) * 45, 0.04, { vol: 0.05 }),
    alarm: () => { [0, 1, 2].forEach((i) => { tone(880, 0.12, { at: i * 0.24, type: "sawtooth", vol: 0.09 }); tone(660, 0.12, { at: i * 0.24 + 0.12, type: "sawtooth", vol: 0.09 }); }); },
    send: () => tone(400, 0.3, { to: 1400, type: "sine", vol: 0.15 }),
    boom: () => { noise(0.9, 0.5); tone(120, 0.7, { to: 40, type: "sawtooth", vol: 0.15 }); },
    down: () => tone(500, 0.9, { to: 60, type: "square", vol: 0.08 }),
    win: () => { [523, 523, 523, 659, 784, 659, 784, 1047].forEach((f, i) => tone(f, i === 7 ? 0.5 : 0.13, { at: i * 0.13, vol: 0.1 })); },
    star: (i) => tone(784 * Math.pow(1.26, i), 0.25, { type: "triangle", vol: 0.2 })
  };
  $("mute").addEventListener("click", () => {
    muted = !muted;
    $("mute").textContent = muted ? "音:オフ" : "音:オン";
    if (!muted) { audioInit(); sfx.click(); }
  });

  // ===== キャラクターの絵(インライン SVG) =====
  function mikeSVG() {
    return '<svg viewBox="0 0 120 120" width="100%" height="100%">' +
      '<path d="M22 50 L26 14 L52 36 Z" fill="#f2a14a" stroke="#5b4636" stroke-width="3" stroke-linejoin="round"/>' +
      '<path d="M98 50 L94 14 L68 36 Z" fill="#7a5236" stroke="#5b4636" stroke-width="3" stroke-linejoin="round"/>' +
      '<ellipse cx="60" cy="72" rx="46" ry="38" fill="#fff7e8" stroke="#5b4636" stroke-width="3"/>' +
      '<path d="M18 62 Q22 40 46 38 Q44 58 18 62 Z" fill="#f2a14a"/>' +
      '<path d="M102 62 Q98 40 74 38 Q78 58 102 62 Z" fill="#7a5236"/>' +
      '<ellipse cx="60" cy="38" rx="50" ry="8" fill="#232a5c"/>' +
      '<path d="M32 36 Q34 8 60 8 Q86 8 88 36 Z" fill="#2f387a"/>' +
      '<rect x="33" y="27" width="54" height="7" fill="#ffd54f"/>' +
      '<ellipse cx="43" cy="68" rx="6" ry="8" fill="#23263a"/><ellipse cx="77" cy="68" rx="6" ry="8" fill="#23263a"/>' +
      '<circle cx="45" cy="65" r="2.2" fill="#fff"/><circle cx="79" cy="65" r="2.2" fill="#fff"/>' +
      '<path d="M56 79 L64 79 L60 84 Z" fill="#ff8fa3"/>' +
      '<path d="M50 88 Q55 94 60 86 Q65 94 70 88" fill="none" stroke="#5b4636" stroke-width="2.5" stroke-linecap="round"/>' +
      '<path d="M8 76 L30 80 M8 88 L30 86 M112 76 L90 80 M112 88 L90 86" stroke="#5b4636" stroke-width="2" stroke-linecap="round"/>' +
      "</svg>";
  }
  function roboSVG(st) {
    let eyes;
    if (st === "h") eyes = '<path d="M36 52 L45 42 L54 52 M66 52 L75 42 L84 52" fill="none" stroke="#ffe35a" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>';
    else if (st === "x") eyes = '<path d="M37 40 L53 56 M53 40 L37 56 M67 40 L83 56 M83 40 L67 56" stroke="#5a6480" stroke-width="5" stroke-linecap="round"/>';
    else eyes = '<circle cx="45" cy="48" r="10" fill="#ffe35a"/><circle cx="75" cy="48" r="10" fill="#ffe35a"/><circle cx="47" cy="49" r="4" fill="#23263a"/><circle cx="77" cy="49" r="4" fill="#23263a"/>';
    const lamp = st === "x" ? "#5a6480" : "#ff5a6e";
    return '<svg viewBox="0 0 120 140" width="100%" height="100%">' +
      '<line x1="60" y1="22" x2="60" y2="8" stroke="#44506b" stroke-width="4"/><circle cx="60" cy="8" r="6" fill="' + lamp + '"/>' +
      '<rect x="6" y="96" width="18" height="12" rx="6" fill="#7f8fb3"/><rect x="96" y="96" width="18" height="12" rx="6" fill="#7f8fb3"/>' +
      '<rect x="18" y="22" width="84" height="60" rx="14" fill="#c9d3e6" stroke="#44506b" stroke-width="3"/>' +
      '<rect x="28" y="32" width="64" height="32" rx="10" fill="#2b3350"/>' + eyes +
      '<rect x="44" y="68" width="32" height="9" rx="3" fill="#44506b"/><path d="M52 68 V77 M60 68 V77 M68 68 V77" stroke="#c9d3e6" stroke-width="2"/>' +
      '<rect x="26" y="86" width="68" height="42" rx="10" fill="#9fb0cf" stroke="#44506b" stroke-width="3"/>' +
      '<rect x="40" y="98" width="40" height="18" rx="4" fill="#2b3350"/><rect x="44" y="102" width="' + (st === "x" ? 3 : 22) + '" height="10" fill="' + lamp + '"/><rect x="80" y="103" width="4" height="8" fill="#2b3350"/>' +
      '<rect x="36" y="128" width="16" height="10" rx="3" fill="#44506b"/><rect x="68" y="128" width="16" height="10" rx="3" fill="#44506b"/>' +
      "</svg>";
  }
  function starSVG(on) {
    return '<svg viewBox="0 0 100 100"><path d="M50 6 L62 37 L95 39 L69 60 L78 93 L50 74 L22 93 L31 60 L5 39 L38 37 Z" fill="' + (on ? "#ffd54f" : "#2a3470") + '" stroke="' + (on ? "#b3801a" : "#3d4a94") + '" stroke-width="5" stroke-linejoin="round"/></svg>';
  }

  // ===== 暗号ダイヤル =====
  // 外の輪=暗号の文字(動かない)、内の輪=元の文字(回る)。内の輪の A が指す外の文字が「A がなる文字」。
  const dial = { k: 0, rot: 0, on: false, mode: "", text: "", cb: null };
  let innerG, numEl, pairEl;
  function buildDial() {
    let s = '<circle cx="200" cy="200" r="196" fill="#33218a" stroke="#9a86ff" stroke-width="4"/>';
    for (let i = 0; i < 26; i++) {
      s += '<g transform="rotate(' + (i * STEP) + ' 200 200)"><circle class="hl" id="ho' + i + '" cx="200" cy="29" r="18"/>' +
        '<text class="ot" id="ot' + i + '" x="200" y="37" text-anchor="middle">' + ABC[i] + "</text></g>" +
        '<line transform="rotate(' + ((i + 0.5) * STEP) + ' 200 200)" x1="200" y1="6" x2="200" y2="52" stroke="#5a48b8" stroke-width="2"/>';
    }
    s += '<g id="inner"><circle cx="200" cy="200" r="148" fill="#fff3cf" stroke="#b79a4a" stroke-width="4"/>';
    for (let i = 0; i < 26; i++) {
      s += '<g transform="rotate(' + (i * STEP) + ' 200 200)"><circle class="hl in" id="hi' + i + '" cx="200" cy="77" r="16"/>' +
        '<text class="it" x="200" y="84" text-anchor="middle">' + ABC[i] + "</text></g>" +
        '<line transform="rotate(' + ((i + 0.5) * STEP) + ' 200 200)" x1="200" y1="54" x2="200" y2="100" stroke="#dcc88a" stroke-width="2"/>';
    }
    s += '<path d="M200 40 L189 58 L211 58 Z" fill="#ff5a6e" stroke="#fff" stroke-width="2"/></g>';
    s += '<circle cx="200" cy="200" r="98" fill="#131a44" stroke="#ffd54f" stroke-width="5"/>' +
      '<text x="200" y="158" text-anchor="middle" font-size="19" font-weight="700" fill="#c9d2ff">ずらす数(かぎ)</text>' +
      '<text id="dNum" x="200" y="228" text-anchor="middle" font-size="68" font-weight="700" fill="#ffd54f">0</text>' +
      '<text id="dPair" x="200" y="264" text-anchor="middle" font-size="22" font-weight="700" fill="#8fe9ff">A → A</text>';
    dialSvg.innerHTML = s;
    innerG = $("inner"); numEl = $("dNum"); pairEl = $("dPair");
  }
  function dialRefresh(quiet) {
    innerG.style.transform = "rotate(" + dial.rot + "deg)";
    numEl.textContent = dial.k;
    pairEl.textContent = "A → " + ABC[dial.k];
    const outer = {}, inn = {};
    if (dial.mode) {
      for (const c of dial.text) {
        const i = ABC.indexOf(c);
        if (dial.mode === "dec") { outer[i] = 1; inn[mod26(i - dial.k)] = 1; }
        else { inn[i] = 1; outer[mod26(i + dial.k)] = 1; }
      }
    }
    for (let i = 0; i < 26; i++) {
      $("ho" + i).setAttribute("class", outer[i] ? "hl on" : "hl");
      $("ot" + i).setAttribute("class", outer[i] ? "ot on" : "ot");
      $("hi" + i).setAttribute("class", inn[i] ? "hl in on" : "hl in");
    }
    if (!quiet && dial.cb) dial.cb(dial.k);
  }
  function dialTurn(d) {
    if (!dial.on) return;
    dial.rot = Math.round(dial.rot / STEP) * STEP + d * STEP;
    dial.k = mod26(Math.round(dial.rot / STEP));
    sfx.tick(dial.k);
    dialRefresh();
  }
  function dialGo(k) { // 近いほうへ回して k にする
    let d = mod26(k - dial.k);
    if (d > 13) d -= 26;
    dial.rot = Math.round(dial.rot / STEP) * STEP + d * STEP;
    dial.k = mod26(k);
    dialRefresh(true);
  }
  function dialSet(o) { // {on, mode, text, cb, k}
    dial.on = !!o.on; dial.mode = o.mode || ""; dial.text = o.text || ""; dial.cb = o.cb || null;
    dialBox.className = dial.on ? "" : "off";
    dialGo(o.k || 0);
  }
  let drag = null;
  function dragEnd() {
    if (!drag) return;
    drag = null;
    innerG.setAttribute("class", "");
    dial.rot = Math.round(dial.rot / STEP) * STEP;
    dialRefresh(true);
  }
  dialSvg.addEventListener("pointerdown", (e) => {
    if (!dial.on || !started) return;
    const r = dialSvg.getBoundingClientRect();
    const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
    if (Math.hypot(e.clientX - cx, e.clientY - cy) > r.width / 2) return;
    drag = { cx: cx, cy: cy, a: Math.atan2(e.clientY - cy, e.clientX - cx) };
    innerG.setAttribute("class", "drag");
    e.preventDefault();
  });
  window.addEventListener("pointermove", (e) => {
    if (!drag) return;
    if (e.buttons === 0) { dragEnd(); return; }
    const a = Math.atan2(e.clientY - drag.cy, e.clientX - drag.cx);
    let d = (a - drag.a) * 180 / Math.PI;
    if (d > 180) d -= 360;
    if (d < -180) d += 360;
    drag.a = a;
    dial.rot += d;
    const k = mod26(Math.round(dial.rot / STEP));
    if (k !== dial.k) { dial.k = k; sfx.tick(k); dialRefresh(); }
    else innerG.style.transform = "rotate(" + dial.rot + "deg)";
  });
  window.addEventListener("pointerup", dragEnd);
  window.addEventListener("pointercancel", dragEnd);
  $("btnPlus").addEventListener("click", () => dialTurn(1));
  $("btnMinus").addEventListener("click", () => dialTurn(-1));

  let keyTyper = null; // 合言葉を入れる場面だけ使う
  document.addEventListener("keydown", (e) => {
    if (!started) return;
    if (e.key === "ArrowRight" || e.key === "ArrowUp") dialTurn(1);
    else if (e.key === "ArrowLeft" || e.key === "ArrowDown") dialTurn(-1);
    else if (keyTyper && e.key === "Backspace") keyTyper("");
    else if (keyTyper && e.key.length === 1 && /[a-zA-Z]/.test(e.key)) keyTyper(e.key.toUpperCase());
  });

  // ===== 点・かざり =====
  let pts = [0, 0, 0, 0], scene = 0;
  const total = () => pts[0] + pts[1] + pts[2] + pts[3];
  function addPts(n, x, y) {
    pts[scene - 1] = Math.max(0, pts[scene - 1] + n);
    scoreEl.textContent = fmt(total()) + " 点";
    const f = document.createElement("div");
    f.className = n < 0 ? "float minus" : "float";
    f.textContent = (n < 0 ? "−" : "+") + Math.abs(n);
    f.style.left = (x || 820) + "px"; f.style.top = (y || 430) + "px";
    game.appendChild(f);
    setTimeout(() => f.remove(), 1150);
  }
  const parts = [];
  function confetti(x, y, n) {
    const cols = ["#ffd54f", "#ff8a3c", "#5ee6ff", "#7df0a6", "#ff7b8a", "#fff"];
    for (let i = 0; i < n; i++) {
      const a = Math.random() * Math.PI * 2, v = 120 + Math.random() * 320;
      parts.push({ x: x, y: y, vx: Math.cos(a) * v, vy: Math.sin(a) * v - 180, g: 520, life: 1.2 + Math.random() * 0.8, t: 0, c: pick(cols), s: 5 + Math.random() * 6, r: Math.random() * 6 });
    }
  }
  function smoke(x, y, n) {
    for (let i = 0; i < n; i++) {
      parts.push({ x: x + (Math.random() - 0.5) * 50, y: y, vx: (Math.random() - 0.5) * 60, vy: -60 - Math.random() * 90, g: -20, life: 1 + Math.random() * 0.8, t: 0, c: "#aab2c8", s: 12 + Math.random() * 14, smoke: true });
    }
  }
  const hooks = new Set();
  let lastTs = 0, fxDirty = false;
  function frame(ts) {
    const dt = Math.min(0.05, lastTs ? (ts - lastTs) / 1000 : 0);
    lastTs = ts;
    hooks.forEach((h) => h(dt));
    if (parts.length || fxDirty) {
      fxc.clearRect(0, 0, 960, 540);
      fxDirty = parts.length > 0;
      for (let i = parts.length - 1; i >= 0; i--) {
        const p = parts[i];
        p.t += dt;
        if (p.t > p.life) { parts.splice(i, 1); continue; }
        p.vy += p.g * dt; p.x += p.vx * dt; p.y += p.vy * dt;
        fxc.globalAlpha = Math.max(0, 1 - p.t / p.life) * (p.smoke ? 0.6 : 1);
        fxc.fillStyle = p.c;
        if (p.smoke) { fxc.beginPath(); fxc.arc(p.x, p.y, p.s * (1 + p.t), 0, 7); fxc.fill(); }
        else { fxc.save(); fxc.translate(p.x, p.y); fxc.rotate(p.r + p.t * 6); fxc.fillRect(-p.s / 2, -p.s / 3, p.s, p.s * 0.66); fxc.restore(); }
      }
      fxc.globalAlpha = 1;
    }
    requestAnimationFrame(frame);
  }

  // ===== セリフ・場面の切りかえ =====
  let nextRes = null;
  function say(who, text, wait) {
    face.innerHTML = who === "robo" ? roboSVG("n") : who === "roboH" ? roboSVG("h") : who === "roboX" ? roboSVG("x") : mikeSVG();
    bubble.className = who === "mike" ? "" : "robo";
    lineEl.innerHTML = text.split("|").join("<br>");
    void bubble.offsetWidth;
    bubble.classList.add("pop");
    if (wait === false) { nextBtn.style.display = "none"; return Promise.resolve(); }
    nextBtn.style.display = "";
    return new Promise((res) => { nextRes = res; });
  }
  nextBtn.addEventListener("click", () => {
    if (!nextRes) return;
    const r = nextRes; nextRes = null;
    nextBtn.style.display = "none";
    sfx.click();
    r();
  });
  async function banner(n, a, b) {
    scene = n;
    game.dataset.scene = String(n);
    for (let i = 1; i <= 4; i++) $("pill" + i).className = "pill" + (i < n ? " done" : i === n ? " now" : "");
    setPhase("anim");
    work.innerHTML = "";
    $("bnA").textContent = a; $("bnB").textContent = b;
    const el = $("banner");
    el.className = ""; void el.offsetWidth; el.className = "on";
    tone(392, 0.12, { vol: 0.09 }); tone(587, 0.3, { at: 0.12, vol: 0.09 });
    await sleep(1500);
    el.className = "";
  }
  function setMsg(t, bad) { const m = $("msg"); if (m) { m.textContent = t; m.className = bad ? "bad" : ""; } }

  // ===== 読む(場面1・3 共通) =====
  // o: {label, chip, cipher, key, meaning, base, bonus, secs, penalty, assist, tries}
  function readTask(o) {
    return new Promise((res) => {
      setPhase("read");
      work.innerHTML = '<div class="card"><div class="hd"><span class="lab">' + o.label + '</span><span class="chip">' + o.chip + "</span></div>" +
        '<div class="rowlab">とどいた暗号文</div><div class="tiles" id="cRow">' + tilesHTML(o.cipher, "c") + "</div>" +
        '<div class="arrow">▼ ダイヤルを回すと、ずらした分だけもどして読めます</div>' +
        '<div class="tiles" id="pRow">' + tilesHTML(o.cipher, "p") + "</div>" +
        '<div class="barrow"><span>スピードボーナス</span><div class="bar"><i id="bonusBar"></i></div></div>' +
        (o.tries ? '<div class="dots" id="dots"><span>ためしたかぎ <b id="triesN">0</b>/25</span>' + new Array(26).join("<i></i>") + "</div>" : "") +
        '<div class="foot"><div id="msg"></div><button id="btnMain" class="big" type="button">読めた!</button></div></div>';
      const pRow = $("pRow"), bar = $("bonusBar"), main = $("btnMain");
      const tried = {};
      let nTried = 0, t = 0, done = false;
      const onK = (k) => {
        const txt = caesar(o.cipher, -k);
        for (let i = 0; i < txt.length; i++) {
          const el = pRow.children[i];
          el.textContent = txt[i];
          el.className = "t p" + (o.assist && k === o.key ? " lit" : "");
          void el.offsetWidth;
          el.classList.add("flip");
        }
        if (o.tries && k !== 0 && !tried[k]) {
          tried[k] = 1; nTried++;
          $("triesN").textContent = nTried;
          const dots = $("dots").getElementsByTagName("i");
          if (dots[k - 1]) dots[k - 1].className = "on";
        }
      };
      dialSet({ on: true, mode: "dec", text: o.cipher, cb: onK });
      const h = (dt) => { t += dt; bar.style.width = Math.max(0, 100 - t / o.secs * 100) + "%"; };
      hooks.add(h);
      main.addEventListener("click", () => {
        if (done) return;
        if (dial.k !== o.key) {
          sfx.bad();
          pRow.classList.remove("shake"); void pRow.offsetWidth; pRow.classList.add("shake");
          setMsg(dial.k === 0 ? "まずダイヤルを回しましょう" : "まだ暗号のままです…", true);
          if (o.penalty && dial.k !== 0) addPts(-o.penalty);
          return;
        }
        done = true;
        hooks.delete(h);
        dial.on = false;
        const bonus = Math.round(o.bonus * Math.max(0, 1 - t / o.secs) / 10) * 10;
        for (let i = 0; i < pRow.children.length; i++) {
          pRow.children[i].className = "t p win";
          pRow.children[i].style.animationDelay = (i * 0.05) + "s";
        }
        sfx.ok();
        confetti(680, 330, 40);
        setMsg(caesar(o.cipher, -o.key) + " = " + o.meaning + " かぎは " + o.key + " でした");
        addPts(o.base + bonus);
        setPhase("anim");
        setTimeout(res, 1700);
      });
    });
  }

  // ===== ロボの総当たり(ずらす暗号) =====
  function roboPanel(cipher, title) {
    work.innerHTML = '<div class="card"><div class="roboL" id="roboFig">' + roboSVG("n") + '</div><div class="roboR">' +
      '<div class="hd"><span class="lab">' + title + "</span></div>" +
      '<div class="tiles s">' + tilesHTML(cipher, "c") + "</div>" +
      '<div id="rBody"></div></div></div>';
  }
  function crackCaesar(cipher, key, desc) {
    return new Promise((res) => {
      setPhase("anim");
      roboPanel(cipher, "解読ロボの総当たり");
      $("rBody").innerHTML = '<div class="count"><span id="rCount">0</span><small>回ためした(全部で25通り)</small></div><div id="rLog"></div>';
      const log = $("rLog"), cnt = $("rCount");
      const iv = desc ? 0.13 : 0.17;
      let n = 0, t = -0.5;
      const h = (dt) => {
        t += dt;
        while (t >= iv) {
          t -= iv;
          n++;
          const k = desc ? 26 - n : n;
          const hit = k === key;
          const d = document.createElement("div");
          d.className = hit ? "lg hit" : "lg";
          d.innerHTML = "かぎ " + k + " → <b>" + caesar(cipher, -k) + "</b> " + (hit ? "○ 読めた!" : "✕");
          log.appendChild(d);
          if (log.children.length > 6) log.removeChild(log.firstChild);
          cnt.textContent = n;
          sfx.blip(n);
          if (hit || n >= 25) {
            hooks.delete(h);
            $("roboFig").innerHTML = roboSVG("h");
            $("roboFig").className = "roboL happy";
            sfx.alarm();
            setTimeout(() => res(n), 1100);
            return;
          }
        }
      };
      hooks.add(h);
    });
  }

  // ===== ロボの総当たり(合言葉) =====
  function crackPass(cipher, pw) {
    return new Promise((res) => {
      setPhase("anim");
      const L = pw.length, all = Math.pow(26, L);
      let idx = 0;
      for (const c of pw) idx = idx * 26 + ABC.indexOf(c);
      const cracked = idx < ROBO_BUDGET;
      const target = cracked ? idx + 1 : ROBO_BUDGET;
      const dur = cracked ? Math.min(6, Math.max(2, 6 * target / ROBO_BUDGET)) : 6;
      roboPanel(cipher, "解読ロボの総当たり");
      $("rBody").innerHTML = '<div class="count"><span id="rCount">0</span><small>/ ' + fmt(all) + " 通り</small></div>" +
        '<div id="rTry"></div>' +
        '<div class="barrow"><span>ロボの電池</span><div class="bar bat"><i id="rBat"></i></div></div>' +
        '<div class="note" style="margin-top:4px">電池は ' + fmt(ROBO_BUDGET) + ' 回ためすと切れます</div><div id="rBig"></div>';
      const cnt = $("rCount"), tr = $("rTry"), bat = $("rBat");
      const keyOf = (n) => { let s = "", v = n; for (let i = 0; i < L; i++) { s = ABC[v % 26] + s; v = Math.floor(v / 26); } return s; };
      let t = -0.5, bl = 0;
      const h = (dt) => {
        t += dt;
        if (t < 0) return;
        const f = Math.min(1, t / dur);
        const n = Math.max(1, Math.floor(target * f));
        const kk = keyOf(n - 1);
        cnt.textContent = fmt(n);
        tr.innerHTML = "合言葉 <b>" + kk + "</b> → " + vig(cipher, kk, -1) + (f >= 1 && cracked ? " ○" : " ✕");
        bat.style.width = Math.max(0, 100 - n / ROBO_BUDGET * 100) + "%";
        bl += dt;
        if (bl > 0.07) { bl = 0; sfx.blip(Math.floor(t * 14)); }
        if (f >= 1) {
          hooks.delete(h);
          const fig = $("roboFig");
          if (cracked) {
            fig.innerHTML = roboSVG("h"); fig.className = "roboL happy";
            $("rBig").textContent = fmt(n) + " 回目で読まれました…";
            sfx.alarm();
            setTimeout(() => res({ cracked: true, n: n, all: all }), 1300);
          } else {
            fig.innerHTML = roboSVG("x"); fig.className = "roboL dead";
            $("rBig").className = "safe";
            $("rBig").textContent = "電池切れ! 読まれませんでした";
            sfx.down(); sfx.boom();
            smoke(505, 330, 26);
            setTimeout(() => res({ cracked: false, n: n, all: all }), 1900);
          }
        }
      };
      hooks.add(h);
    });
  }

  // ===== 場面2:言葉を選ぶ → かぎを決めて送る =====
  function chooseWord() {
    return new Promise((res) => {
      setPhase("pick");
      dialSet({ on: false });
      work.innerHTML = '<div class="card"><div class="hd"><span class="lab">ミケに送る「宝のかくし場所」</span></div><div class="choices">' +
        WORDS.send.map((w, i) => '<button class="choice" type="button" data-i="' + i + '">' + w[0] + "<small>(" + w[1] + ")</small></button>").join("") + "</div></div>";
      const bs = work.querySelectorAll(".choice");
      bs.forEach((b) => b.addEventListener("click", () => { sfx.click(); res(WORDS.send[Number(b.dataset.i)]); }));
    });
  }
  function sendTask(word, ng) {
    return new Promise((res) => {
      setPhase("key");
      work.innerHTML = '<div class="card"><div class="hd"><span class="lab">送る手紙:宝は ' + word[1] + ' にある</span></div>' +
        '<div class="rowlab">元の文字</div><div class="tiles">' + tilesHTML(word[0], "p") + "</div>" +
        '<div class="arrow">▼ ダイヤルで、かぎの数だけずらす</div>' +
        '<div class="rowlab">暗号文(これを送る)</div><div class="tiles" id="cRow">' + tilesHTML(word[0], "c") + "</div>" +
        '<div class="foot"><div id="msg"></div><button id="btnMain" class="big dim" type="button">送る!</button></div></div>';
      const cRow = $("cRow"), main = $("btnMain");
      let done = false;
      dialSet({ on: true, mode: "enc", text: word[0], cb: (k) => {
        const txt = caesar(word[0], k);
        for (let i = 0; i < txt.length; i++) {
          const el = cRow.children[i];
          el.textContent = txt[i]; el.classList.remove("flip"); void el.offsetWidth; el.classList.add("flip");
        }
        main.className = k === 0 || k === ng ? "big dim" : "big";
        setMsg("");
      } });
      main.addEventListener("click", () => {
        if (done) return;
        if (dial.k === 0) { sfx.bad(); setMsg("かぎが 0 だと、そのまま読めてしまいます", true); return; }
        if (dial.k === ng) { sfx.bad(); setMsg("さっきと同じかぎです。別の数にしましょう", true); return; }
        done = true; dial.on = false;
        sfx.send();
        cRow.style.transition = "transform .6s, opacity .6s";
        cRow.style.transform = "translate(260px,-200px) scale(.3)"; cRow.style.opacity = "0";
        setPhase("anim");
        setTimeout(() => res(dial.k), 700);
      });
    });
  }

  // ===== 場面4:合言葉を決めて送る =====
  function passTask(word, min, max) {
    return new Promise((res) => {
      setPhase("pass");
      dialSet({ on: false });
      const P = word[0];
      let kb = "";
      for (const c of ABC) kb += '<button type="button" data-l="' + c + '">' + c + "</button>";
      let slots = "";
      for (let i = 0; i < max; i++) slots += '<div class="slot' + (i >= min ? " x" : "") + '"></div>';
      work.innerHTML = '<div class="card"><div class="hd"><span class="lab">送る手紙:宝は ' + word[1] + ' にある</span><span class="note">小さい字=その文字に使う合言葉</span></div>' +
        '<div class="krow" id="kRow">' + P.split("").map(() => "<span></span>").join("") + "</div>" +
        '<div class="tiles s">' + tilesHTML(P, "p") + "</div>" +
        '<div class="tiles s" id="cRow" style="margin-top:4px">' + tilesHTML(P, "c") + "</div>" +
        '<div class="slots"><span class="note">合言葉</span>' + slots + '<div id="combo"></div></div>' +
        '<div class="kb" id="kb">' + kb + "</div>" +
        '<div class="foot"><div id="msg" class="note">本物のパスワードは入れません</div><button id="btnDel" type="button">1字消す</button><button id="btnMain" class="big dim" type="button">送る!</button></div></div>';
      const cRow = $("cRow"), kRow = $("kRow"), main = $("btnMain"), combo = $("combo");
      const slotEls = work.querySelectorAll(".slot");
      let pw = "", done = false;
      const show = () => {
        for (let i = 0; i < max; i++) {
          slotEls[i].textContent = pw[i] || "";
          slotEls[i].className = "slot" + (pw[i] ? " f" : i >= min ? " x" : "");
        }
        const c = pw ? vig(P, pw, 1) : P;
        for (let i = 0; i < P.length; i++) {
          kRow.children[i].textContent = pw ? pw[i % pw.length] : "";
          if (cRow.children[i].textContent !== c[i]) {
            cRow.children[i].textContent = c[i];
            cRow.children[i].classList.remove("flip"); void cRow.children[i].offsetWidth; cRow.children[i].classList.add("flip");
          }
        }
        const all = Math.pow(26, pw.length);
        if (!pw) { combo.className = ""; combo.innerHTML = "かぎの数<br><b>?</b>"; }
        else {
          combo.className = all > ROBO_BUDGET ? "safe" : "";
          combo.innerHTML = "かぎの数 " + new Array(pw.length + 1).join("×26").slice(1) + "<br><b>= " + fmt(all) + " 通り</b>";
        }
        main.className = pw.length >= min ? "big" : "big dim";
      };
      const typer = (ch) => {
        if (done) return;
        if (ch === "") { if (pw) { pw = pw.slice(0, -1); sfx.click(); } }
        else if (pw.length < max) {
          pw += ch;
          sfx.type(pw.length);
          dialGo(ABC.indexOf(ch));
        } else { sfx.bad(); }
        setMsg("本物のパスワードは入れません");
        $("msg").className = "note";
        show();
      };
      keyTyper = typer;
      $("kb").addEventListener("click", (e) => { const l = e.target && e.target.dataset && e.target.dataset.l; if (l) typer(l); });
      $("btnDel").addEventListener("click", () => typer(""));
      main.addEventListener("click", () => {
        if (done) return;
        if (pw.length < min) { sfx.bad(); setMsg("合言葉は " + min + " 文字以上にします", true); return; }
        done = true; keyTyper = null;
        sfx.send();
        setPhase("anim");
        setTimeout(() => res(pw), 400);
      });
      show();
    });
  }

  // ===== お話の流れ =====
  async function play() {
    pts = [0, 0, 0, 0];
    scoreEl.textContent = "0 点";
    let crackedB = 0;

    // --- 場面1 読む
    await banner(1, "ミッション 1", "とどいた手紙を読む");
    await say("mike", "見習いスパイさん、ようこそですニャ。|仲間のミケです。ひみつの手紙を送ります。");
    await say("mike", "暗号は、文字をいくつかずらして作ります。|ダイヤルを回して、かぎに合わせますニャ。");
    const k2 = rnd(5, 9), k3 = rnd(10, 20);
    const r1 = pick(WORDS.read1), r2 = pick(WORDS.read2), r3 = pick(WORDS.read3);
    say("mike", "かぎは 3 です。ダイヤルを 3 に合わせて、|下の文字が読めたら「読めた!」ですニャ。", false);
    await readTask({ label: "ミケの手紙 1/3:好きな食べ物", chip: "かぎ 3", cipher: caesar(r1[0], 3), key: 3, meaning: r1[1], base: 100, bonus: 100, secs: 30, assist: true });
    say("mike", "次は集合場所ですニャ。|かぎは " + k2 + " です。", false);
    await readTask({ label: "ミケの手紙 2/3:集合場所", chip: "かぎ " + k2, cipher: caesar(r2[0], k2), key: k2, meaning: r2[1], base: 100, bonus: 100, secs: 30, assist: true });
    say("mike", "最後は持ち物ですニャ。かぎは、|「A が " + ABC[k3] + " になる」数です。", false);
    await readTask({ label: "ミケの手紙 3/3:持ち物", chip: "A → " + ABC[k3], cipher: caesar(r3[0], k3), key: k3, meaning: r3[1], base: 100, bonus: 100, secs: 30, assist: true });
    dialSet({ on: false });
    await say("mike", "全部読めましたニャ!|かぎを知っていれば、すぐ読めます。");

    // --- 場面2 送る
    await banner(2, "ミッション 2", "暗号にして送る");
    await say("mike", "こんどは、きみが手紙を送る番ですニャ。|宝のかくし場所を、暗号で教えてください。");
    say("mike", "送る言葉を選んでくださいニャ。", false);
    const word = await chooseWord();
    say("mike", "ダイヤルでかぎを決めて、|「送る!」を押してくださいニャ。", false);
    const ka = await sendTask(word, -1);
    work.innerHTML = "";
    sfx.alarm();
    await say("robo", "ピピッ! その手紙、とちゅうで|コピーさせてもらったゾ。");
    say("robo", "かぎを 1 から順に、全部ためすゾ…", false);
    const na = await crackCaesar(caesar(word[0], ka), ka, false);
    addPts(100);
    await say("roboH", "かぎ " + ka + " で読めたゾ! " + na + " 回ためしただけ。|宝は「" + word[1] + "」にあるんだナ。");
    await say("mike", "読まれてしまいましたニャ…。|別のかぎで、もう一度送ってみましょう。");
    say("mike", "さっきとちがうかぎを選んで、|「送る!」を押してくださいニャ。", false);
    const kb2 = await sendTask(word, ka);
    work.innerHTML = "";
    const desc = kb2 > 13;
    say("robo", desc ? "こんどは後ろから順にためすゾ…" : "また 1 から順にためすゾ…", false);
    await crackCaesar(caesar(word[0], kb2), kb2, desc);
    addPts(100);
    await say("roboH", "また読めたゾ! かぎは26通りだけ。|全部ためせば、必ず当たるゾ。");
    await say("mike", "これが「総当たり」ですニャ。|ずらすだけの暗号は、すぐ読まれます。");

    // --- 場面3 解く
    await banner(3, "ミッション 3", "かぎなしで読む");
    await say("mike", "ロボがボスに送る手紙を、こちらも|コピーしましたニャ。おたがいさまです。");
    await say("mike", "かぎは分かりません。こんどは、|きみが総当たりで読んでくださいニャ!");
    const s1 = pick(WORDS.spy1), s2 = pick(WORDS.spy2), s3 = pick(WORDS.spy3);
    const q1 = rnd(3, 7), q2 = rnd(9, 15), q3 = rnd(16, 23);
    say("mike", "ダイヤルを1つずつ回して、|読める言葉をさがしますニャ。", false);
    await readTask({ label: "ロボの手紙 1/3:ほしい物", chip: "かぎ ?", cipher: caesar(s1[0], q1), key: q1, meaning: s1[1], base: 150, bonus: 150, secs: 50, penalty: 30, tries: true });
    say("mike", "次の手紙ですニャ。|急ぐほど、点が高くなります。", false);
    await readTask({ label: "ロボの手紙 2/3:ねらっている物", chip: "かぎ ?", cipher: caesar(s2[0], q2), key: q2, meaning: s2[1], base: 150, bonus: 150, secs: 50, penalty: 30, tries: true });
    say("mike", "最後は、ロボの弱点が書いてある|手紙ですニャ。長いですよ!", false);
    await readTask({ label: "ロボの手紙 3/3:ロボの弱点", chip: "かぎ ?", cipher: caesar(s3[0], q3), key: q3, meaning: s3[1], base: 150, bonus: 150, secs: 50, penalty: 30, tries: true });
    dialSet({ on: false });
    await say("mike", "弱点は「" + s3[1] + "」ですニャ!|たくさんためさせれば、止まります。");

    // --- 場面4 守る
    await banner(4, "ミッション 4", "長いかぎで守る");
    await say("mike", "そこで、かぎを「合言葉」にしますニャ。|文字ごとに、ずらす数が変わります。");
    say("mike", "まずは 2文字でためしますニャ。|下の文字ボタンで入れてください。", false);
    const pa = await passTask(word, 2, 2);
    work.innerHTML = "";
    say("robo", "合言葉も、AA から順にためすゾ…", false);
    await crackPass(vig(word[0], pa, 1), pa);
    await say("roboH", "読めたゾ! 2文字は 676通りだけ。|電池は、まだたっぷりあるゾ。");
    await say("mike", "ロボの電池は " + fmt(ROBO_BUDGET) + "回ぶんですニャ。|合言葉を 3〜5文字にのばしましょう!");
    let lastPw = "";
    for (;;) {
      say("mike", "かぎの数が " + fmt(ROBO_BUDGET) + " をこえるように、|合言葉を決めてくださいニャ。", false);
      lastPw = await passTask(word, 3, 5);
      work.innerHTML = "";
      say("robo", "何文字でも、順にためすだけだゾ…", false);
      const r = await crackPass(vig(word[0], lastPw, 1), lastPw);
      if (!r.cracked) break;
      crackedB++;
      await say("roboH", "読めたゾ! その合言葉は、|早い順番でためしたゾ。");
      await say("mike", "おしいですニャ…。もっと長くするか、|後ろのほうの文字で始めましょう。");
    }
    addPts(Math.max(100, 400 + (lastPw.length - 3) * 100 - crackedB * 50), 640, 462);
    sfx.win();
    confetti(480, 200, 140);
    await say("roboX", "デ、電池が… もう…ダメ…だ…ゾ…");
    await say("mike", "やりましたニャ! 手紙は守られました。|長いかぎは、総当たりに強いのです。");
    showResult();
  }

  // ===== けっか =====
  function showResult() {
    setPhase("result");
    game.dataset.scene = "result";
    dialSet({ on: false });
    const sc = total();
    const stars = sc >= STAR3 ? 3 : sc >= STAR2 ? 2 : 1;
    const names = ["1 読む", "2 送る", "3 解く", "4 守る"];
    let br = "";
    for (let i = 0; i < 4; i++) br += '<div class="br"><span>ミッション ' + names[i] + "</span><b>" + fmt(pts[i]) + " 点</b></div>";
    const el = $("result");
    el.innerHTML = "<h2>ミッション成功!</h2>" +
      '<div id="stars">' + [0, 1, 2].map((i) => starSVG(i < stars).replace("<svg ", '<svg style="animation-delay:' + (0.3 + i * 0.35) + 's" ')).join("") + "</div>" +
      '<div id="total">' + fmt(sc) + "<small>点</small></div>" +
      '<div class="col" id="colL"><h3>点の内わけ</h3>' + br +
      '<div style="margin-top:10px;color:#aab5ea">速く、まちがえずに読むと点が上がります。</div>' + "</div>" +
      '<div class="col" id="colR"><h3>スパイのメモ</h3>' +
      "<div>・暗号は「ルール」と「かぎ」でできています。</div>" +
      "<div>・ずらす暗号のかぎは26通りだけ。総当たりですぐ読まれます。</div>" +
      "<div>・かぎが長いほど、ためす数が増えて強くなります。</div>" +
      "<div>・パスワードも同じです。長くして、使い回さないようにしましょう。</div></div>" +
      '<div id="rNote">ためしてよいのは、<br>このゲームの中だけです。</div>' +
      '<button id="btnAgain" type="button">もう一度あそぶ</button>';
    el.style.display = "block";
    for (let i = 0; i < stars; i++) setTimeout(() => { sfx.star(i); confetti(404 + i * 76, 104, 30); }, 300 + i * 350);
    $("btnAgain").addEventListener("click", () => {
      el.style.display = "none";
      el.innerHTML = "";
      sfx.click();
      play();
    });
  }

  // ===== はじまり =====
  buildDial();
  dialRefresh(true);
  $("tMike").innerHTML = mikeSVG();
  $("tRobo").innerHTML = roboSVG("n");
  face.innerHTML = mikeSVG();
  nextBtn.style.display = "none";
  const tTiles = $("tTiles");
  tTiles.innerHTML = tilesHTML("HIMITSU", "c");
  let tT = 0, tK = 5;
  const titleHook = (dt) => {
    tT += dt;
    if (tT < 0.45) return;
    tT = 0;
    tK = tK > 0 ? tK - 1 : 5;
    const s = caesar("HIMITSU", tK);
    for (let i = 0; i < s.length; i++) {
      tTiles.children[i].textContent = s[i];
      tTiles.children[i].className = tK === 0 ? "t p" : "t c";
    }
  };
  hooks.add(titleHook);
  $("btnStart").addEventListener("click", () => {
    if (started) return;
    started = true;
    audioInit();
    sfx.ok();
    hooks.delete(titleHook);
    $("title").style.display = "none";
    play();
  });
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>