CTF:答えはコードの中にある ソースコード
遊ぶ一覧にもどる

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

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>CTF:答えはコードの中にある</title>
<style>
/* ========== 共通の見た目 ========== */
body { margin: 0; font-family: sans-serif; font-size: 13px; color: #2b2f2c; background: #f2f5f3; word-break: auto-phrase; line-break: strict; }
header { height: 34px; display: flex; align-items: center; gap: 8px; padding: 0 10px; background: #1e5a3e; color: #fff; }
header b { flex: 1; font-size: 16px; }
#myTime { font-size: 12px; }
#myScore { font-weight: bold; }
button { font: inherit; border: 0; border-radius: 8px; background: #3a7e52; color: #fff; padding: 4px 10px; cursor: pointer; }
button.sub { background: #e2e9e4; color: #2b2f2c; }
.screen { display: none; position: absolute; left: 0; top: 34px; width: 480px; height: 326px; box-sizing: border-box; padding: 6px 10px; }
.screen.on { display: block; }
p { margin: 3px 0; line-height: 1.55; }
.small { font-size: 11px; color: #767b78; line-height: 1.5; }
/* 「Q1」などの番号の色=むずかしさ */
.lv0 { color: #767b78; } /* れんしゅう */
.lv1 { color: #2f8a52; } /* やさしい */
.lv2 { color: #c46a10; } /* ふつう */
.lv3 { color: #c0392b; } /* むずかしい */
.lv4 { color: #7d3c98; } /* ボス */

/* ========== ホーム(問題の一覧) ========== */
#list { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 6px; margin-top: 4px; }
.row { position: relative; height: 40px; padding: 3px 8px; box-sizing: border-box; background: #fff; border-radius: 8px; cursor: pointer; }
.row:hover { background: #e8f3ec; }
.row.done { background: #d5efdf; }
.row.done::after { content: "✔"; position: absolute; top: 3px; right: 8px; font-weight: bold; color: #2f7048; } /* 正解した問題は、右上にチェック */
.row.done .name { padding-right: 16px; }
.row .name { font-weight: bold; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row .info { font-size: 11px; color: #767b78; white-space: nowrap; }

/* ========== 問題の画面(共通) ========== */
#pTop { display: flex; align-items: center; gap: 6px; height: 28px; }
#pTop b { flex: 1; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#pPoint { font-size: 12px; }
#pBody { height: 200px; margin-top: 4px; padding: 6px 10px; background: #fff; border-radius: 10px; overflow: auto; box-sizing: border-box; }
#pBody section { display: none; }
#pBody section.on { display: block; }
#answer { display: flex; gap: 6px; margin-top: 6px; }
#ans { flex: 1; font: inherit; font-size: 15px; padding: 3px 8px; border: 2px solid #8bba93; border-radius: 8px; }
#msg { height: 38px; margin-top: 3px; font-size: 12px; line-height: 1.5; }
#msg.ok { color: #2f7048; font-weight: bold; }
#msg.ng { color: #b0500f; }
#hintBox { display: none; margin-top: 6px; padding: 5px 8px; background: #fdecdc; border-radius: 8px; font-size: 12px; }
#startBox { display: none; text-align: center; padding-top: 36px; }
#startBox button { font-size: 18px; padding: 7px 28px; margin-top: 10px; }
#answer.off { opacity: .4; pointer-events: none; }
#codeBox { display: none; margin: 0; font: 11px/1.5 monospace; white-space: pre-wrap; word-break: break-all; color: #e3ece6; }
#editBox { display: none; }
#codeEdit { width: 100%; height: 150px; box-sizing: border-box; font: 11px/1.5 monospace; color: #e3ece6; background: #132a20; border: 1px solid #3d5a4a; border-radius: 6px; }
#btnRun { margin-top: 4px; background: #b0500f; }
#pBody.code { background: #1b3328; }
#pBody.code section, #pBody.code #hintBox { display: none !important; }
.cipher { margin: 6px 0; font-size: 22px; font-weight: bold; letter-spacing: 6px; text-align: center; }
.table { display: flex; flex-wrap: wrap; gap: 3px 10px; justify-content: center; font-size: 12px; }

/* ========== ランキング ========== */
.rk { display: flex; height: 22px; padding: 0 8px; background: #fff; border-radius: 6px; margin-bottom: 3px; align-items: center; }
.rk.me { background: #fdecdc; font-weight: bold; }
.rk span:nth-child(2) { flex: 1; margin-left: 8px; overflow: hidden; white-space: nowrap; }

/* ========== Q1 ニセモノ URL ========== */
#q1out { margin: 4px 0; padding: 2px 8px; background: #e8f3ec; border-radius: 6px; font-size: 12px; }
#q1urls button { margin: 2px; padding: 2px 8px; font-size: 12px; }

/* ========== Q2 見えない文字 ========== */
#q2box { font-size: 28px; font-weight: bold; letter-spacing: 4px; text-align: center; background: #fff8e1; border-radius: 8px; padding: 4px 0; }
#q2box .v { color: #374151; }
#q2box .a { color: #fff8e1; }
#q2box .b { opacity: 0; }
#q2box .c { font-size: 0; }

/* ========== Q6 モールス信号 ========== */
#q6lamp { width: 44px; height: 44px; margin: 6px auto; border-radius: 50%; background: #374151; border: 3px solid #9ca3af; }

/* ========== Q8 光るランプ ========== */
#q8lamps { margin: 2px auto 0; border-collapse: collapse; font-size: 17px; line-height: 1.1; color: #f59e0b; }
#q8lamps td { width: 28px; text-align: center; }
#q8lamps .num td { font-size: 11px; color: #6b7280; }

/* ========== Q10 見えない絵 ========== */
#q10cv { display: block; margin: 6px auto 0; border-radius: 8px; }

/* ========== おわり ========== */
</style>
</head>
<body>

<!-- ========== 上のバー ========== -->
<header>
  <b>CTF:答えはコードの中にある</b>
  <span id="myTime">⏱ 0:00</span>
  <span id="myScore">0 点</span>
  <button id="btnRank" type="button" class="sub">ランキング</button>
</header>

<!-- ========== ホーム(問題の一覧) ========== -->
<div id="home" class="screen on">
  <p class="small">かくされた「答え」を見つけて、点をあつめよう。答えはローマ字(例:NEKO)。<br>ためしてよいのは、この作品の中だけです。</p>
  <div id="list"></div>
</div>

<!-- ========== 問題の画面(共通) ========== -->
<div id="prob" class="screen">
  <div id="pTop">
    <button id="btnBack" type="button" class="sub">◀ もどる</button>
    <b id="pTitle"></b>
    <span id="pPoint"></span>
    <button id="btnCode" type="button">コードを見る</button>
  </div>
  <div id="pBody">

    <!-- スタート画面(まだ解いていない問題を開いたときに出る) -->
    <div id="startBox">
      <p id="startText"></p>
      <button id="btnStart" type="button">スタート</button>
    </div>

    <!-- ===== Q0 れんしゅう ===== -->
    <section id="q0">
      <p>この問題のコード(中身)のどこかに、答えがかくれています。</p>
      <p>右上の「コードを見る」を押すと、<br>この問題のコードが見られます。</p>
      <p class="small">見つけた答えは、下のらんに入れて「提出」を押します。<br>作品全体のコードは、この作品をコピーすると見られます。</p>
      <!-- Q0 の答え:次の文字を、後ろから読もう → O K E N -->
    </section>

    <!-- ===== Q1 ニセモノ URL ===== -->
    <section id="q1">
      <p>モグモグ銀行から「ログインしてください」とメールが来ました。<br>本物の URL は <b>mogmog-bank.jp</b> です。<br>本物のサイトに書いてある言葉が答えです。</p>
      <p id="q1out">URL を押すと、ここにそのサイトが出ます。</p>
      <div id="q1urls"></div>
    </section>

    <!-- ===== Q2 見えない文字 ===== -->
    <section id="q2">
      <p>下の箱には、見えない文字が6つかくれています。<br>見えない文字だけを、左から順につなげると答えです。</p>
      <p id="q2box"><span class="v">T</span><span class="a">S</span><span class="v">O</span><span class="b">A</span><span class="v">M</span><span class="c">K</span><span class="v">A</span><span class="a">U</span><span class="v">T</span><span class="b">R</span><span class="v">O</span><span class="c">A</span></p>
    </section>

    <!-- ===== Q3 ふせんの下 ===== -->
    <section id="q3">
      <p>答えを書いた紙の上に、ふせんがはってあります。<br>ふせんは、はがせません…。</p>
      <svg width="220" height="90" viewBox="0 0 220 90" style="display:block;margin:6px auto 0">
        <rect x="5" y="5" width="210" height="80" rx="6" fill="#ffffff" stroke="#d1d5db"/>
        <text x="110" y="57" font-size="30" font-weight="bold" text-anchor="middle" fill="#374151">IRUKA</text>
        <rect x="20" y="15" width="180" height="60" rx="4" fill="#fde68a"/>
      </svg>
    </section>

    <!-- ===== Q4 記号の暗号 ===== -->
    <section id="q4">
      <p>記号でできた暗号です。下の表を見て、アルファベットにもどそう。<br>でも、表がとちゅうまでしかありません…。</p>
      <p class="cipher">◆ ● ▲ ■ ▲</p>
      <p class="table" id="q4table"></p>
    </section>

    <!-- ===== Q5 シーザー暗号 ===== -->
    <section id="q5">
      <p>ロボが送った暗号です。<br>アルファベットを、いくつかずらして作りました。<br>ずらす数は、この問題のコードの中に書いてあります。</p>
      <p class="cipher">W D Q X N L</p>
      <p id="q5abc" class="small" style="text-align:center"></p>
    </section>

    <!-- ===== Q6 モールス信号 ===== -->
    <section id="q6">
      <p>ランプが光って、合図を送っています。<br>短く光るのが「・」、長く光るのが「ー」です。<br>表を見て、アルファベットにもどそう。</p>
      <div id="q6lamp"></div>
      <p class="table"><span>A ・ー</span><span>D ー・・</span><span>E ・</span><span>I ・・</span><span>K ー・ー</span><span>M ーー</span><span>N ー・</span><span>R ・ー・</span><span>S ・・・</span><span>T ー</span><span>U ・・ー</span></p>
      <p class="small" style="text-align:center">光るのが速くて読めないときは、コードを見てみよう。</p>
    </section>

    <!-- ===== Q7 2つのかぎ ===== -->
    <section id="q7">
      <p>こんどは、かぎが2つあります。<br>1・3・5…番目の文字は「かぎ1」、2・4・6…番目の文字は「かぎ2」で<br>ずらしてあります。かぎ2 はコードの中に。かぎ1 は分かりません。</p>
      <p class="cipher" id="q7text">VQEAFVP</p>
      <p style="text-align:center">かぎ1 <button id="q7minus1" type="button">◀</button> <b id="q7k1">0</b> <button id="q7plus1" type="button">▶</button>  かぎ2 <button id="q7minus2" type="button">◀</button> <b id="q7k2">0</b> <button id="q7plus2" type="button">▶</button></p>
    </section>

    <!-- ===== Q8 光るランプ ===== -->
    <section id="q8">
      <p>1つの行が1文字です。<br>●のランプの上の数を足すと、その番目のアルファベットになります。</p>
      <p class="small" style="text-align:center">(A が 1、B が 2、C が 3…)</p>
      <table id="q8lamps">
        <tr class="num"><td>16</td><td>8</td><td>4</td><td>2</td><td>1</td></tr>
        <tr><td>●</td><td>●</td><td>○</td><td>●</td><td>○</td></tr>
        <tr><td>○</td><td>○</td><td>●</td><td>○</td><td>●</td></tr>
        <tr><td>○</td><td>○</td><td>○</td><td>●</td><td>○</td></tr>
        <tr><td>●</td><td>○</td><td>○</td><td>●</td><td>○</td></tr>
        <tr><td>○</td><td>○</td><td>○</td><td>○</td><td>●</td></tr>
      </table>
    </section>

    <!-- ===== Q9 金庫 ===== -->
    <section id="q9">
      <p>3けたの番号で開く金庫です。<br>番号は、コードの中で計算して決めています。<br>3回まちがえると、ロックされます。</p>
      <p>番号 <input id="q9in" maxlength="3" size="4"> <button id="q9open" type="button">開ける</button></p>
      <p id="q9out"></p>
    </section>

    <!-- ===== Q10 見えない絵 ===== -->
    <section id="q10">
      <p>答えは下に描いてあります。でも、絵の色が背景と同じで見えません。</p>
      <p class="small">この問題は「コードを見る」で、コードを書きかえて動かせます。</p>
      <canvas id="q10cv" width="432" height="72"></canvas>
    </section>

    <!-- ===== Q11 ボス ===== -->
    <section id="q11">
      <p><b>ボス問題(テキスト言語に自信がある人向け)</b><br>あいことばは、アルファベット大文字の4文字です。<br>金庫は、あいことばを「指紋(ハッシュ)」にしてくらべます。</p>
      <p class="cipher" style="font-size:18px;letter-spacing:2px">指紋:<span id="q11target"></span></p>
      <p>あいことば <input id="q11in" maxlength="4" size="5"> <button id="q11try" type="button">ためす</button> <span id="q11out"></span></p>
      <p class="small">手でためせるのは3回まで。作品をコピーして、総当たりのプログラムを書こう。</p>
    </section>

    <!-- ヒントとコード(どの問題でも、ここに出る) -->
    <p id="hintBox"></p>
    <pre id="codeBox"></pre>
    <div id="editBox">
      <textarea id="codeEdit" spellcheck="false"></textarea>
      <button id="btnRun" type="button">このコードで動かす</button>
    </div>
  </div>
  <div id="answer">
    <input id="ans" placeholder="答え(ローマ字)">
    <button id="btnSend" type="button">提出</button>
    <button id="btnHint" type="button" class="sub">ヒント</button>
  </div>
  <div id="msg"></div>
</div>

<!-- ========== ランキング ========== -->
<div id="rank" class="screen">
  <div style="display:flex;align-items:center;gap:8px;height:28px">
    <button id="btnBack2" type="button" class="sub">◀ もどる</button>
    <b style="flex:1;font-size:15px">ランキング(上位10人)</b>
  </div>
  <p id="myClear"></p>
  <div id="rankList" style="margin-top:4px"></div>
  <p class="small">ランキングは、作品を開いたときと、自分が答えを提出したときに新しくなります。</p>
</div>

<script>
// ========== 共通の道具 ==========
const $ = (id) => document.getElementById(id);
// 「コードを見る」で書きかえて動かせる問題は、ここに「動かし方」を入れる(例:RUN[10])
const RUN = {};
// 書きかえたコードから「const 名前 = 値;」の値を読む(スタジオでは eval が使えないため、値だけを読む)
const readValue = (code, name) => {
  const m = code.match(new RegExp("const\\s+" + name + "\\s*=\\s*([^;\\n]+)"));
  try { return m ? JSON.parse(m[1].trim().replace(/'/g, '"')) : undefined; } catch (e) { return undefined; }
};

// ========== 本部(問題の一覧・提出・ヒント・ランキング) ==========
(() => {
  // 音タブの音:sound-1 = 正解(コイン)、sound-2 = まちがい(キャンセル)
  const oto = (no) => { if (typeof playSound === "function") playSound("sounds/sound-" + no + ".sound"); };
  const show = (id) => {
    for (const s of document.querySelectorAll(".screen")) s.classList.toggle("on", s.id === id);
  };

  // ----- 問題の一覧 -----
  // 答えは「ハッシュ」(答えの指紋)にしてあるので、ここを見ても答えは分かりません。
  // ヒントは文字を1つずつずらしてあります(見ると点が半分になるため)。
  const QUESTIONS = [
    { title: "Q0 れんしゅう:中を見る", point: 0, ans: "d84f3df0", hint: "」ゴヽナん覌れ『ん抽じで。ゴモヴド)=\"..!ど!..?!はぃぅち*んざきじみず〃斈存ん徍ゎがり誮むみず〃" },
    { title: "Q1 ニセモノ URL", point: 100, ans: "7795f472", hint: "VSM!ん2斈存せづ覌ぐりぺみず〃ポダヴん抽じだどぎぬ击れ訁葊ば。ヘヮケリメは訉箘と汻みるみず〃" },
    { title: "Q2 見えない文字", point: 100, ans: "eeaf8812", hint: "斈存は艳ゅ覌ぉ斺ば。tuzmf!は丮と汻もでぅみず〃胍晰ど名す艳は斈存。覌ぉにぐじでぃれ斈存んざきじみず〃" },
    { title: "Q3 ふせんの下", point: 100, ans: "f6db7253", hint: "」ゴヽナん覌れ『と。絶)twh*は丮ん覌みず〃囜觓)sfdu*は丌ぬ。斈存)ufyu*きがぐろでぅみず〃" },
    { title: "Q4 記号の暗号", point: 100, ans: "aa705669", hint: "甼靣は衩ぬにぅ訙司ば。ごは啐額はゴヽナは丮は衩)izpv*ぬはつでぅみず〃" },
    { title: "Q5 シーザー暗号", point: 150, ans: "a69596c5", hint: "せりず敱ば。ゴヽナは丮は!{vsbtv!とず〃暘司は斈存ん。ぞは敱ちげィレブアペツドは剎ぬゃなじみず〃" },
    { title: "Q6 モールス信号", point: 150, ans: "98282b1d", hint: "ゴヽナは!tijohpv!ば。2!き」ー『。4!き」ヽ『。1!き斈存は医刈るとず〃衩ど覌ぐりぺで誮むみず〃" },
    { title: "Q7 2つのかぎ", point: 200, ans: "885f7164", hint: "がく3!ば。ゴヽナは丮は!lbhj3!とず〃がく3!んぞは敱ぬじでがり。がく2!ん!2!がり頇ぬだもじみず)緐彔だる*〃" },
    { title: "Q8 光るランプ", point: 200, ans: "640c69c5", hint: "◐はリヴヘは下は敱ん趴じみず〃だどぉぱ!◌◌◐◌◐!ば!5!,!2!>!6!と。6畫盯は斈存ば!F!とず〃" },
    { title: "Q9 金庫", point: 250, ans: "770213b1", hint: "釒庬は畫司ば。gps!はぐるがぉじと訉箘じでぅみず〃2囟せづ級ぬ曹ぅで訉箘じでむみじよぇ〃" },
    { title: "Q10 見えない絵", point: 300, ans: "aaba6ecc", hint: "」ゴヽナん覌れ『ん抽じで。jsp!ん百)#$gggggg#*ぬ曹ぎがぉ。」ごはゴヽナと勖がず『ん抽じみず〃" },
    { title: "Q11 ボス:指紋をやぶれ", point: 500, ans: "1b9769b9", hint: "佝哂んゴフヽじで。R22!はゴヽナぬ!B〝[!は!gps!ん5づ野ので曹ぎ。tijnpo)5斈存*!き!nplvizpv!ど名すぬにれ訁葊ん!dpotpmf/mph!と击じみず〃" }
  ];

  // ----- 正解した人数(カウンター) -----
  // カウンターは1作品10個までなので、1つのカウンターに5問分の人数をまとめて入れる。
  // count1 に Q0〜Q4、count2 に Q5〜Q9、count3 に Q10〜Q11(セーブデータ タブで3つ作っておく)。
  // 1問ごとに3けたずつ使う(Q0 は1の位から3けた、Q1 は1000の位から3けた…)。
  const counterName = (no) => "count" + (Math.floor(no / 5) + 1);
  const counterStep = (no) => Math.pow(1000, no % 5);
  const solvedCount = (no) => typeof loadCounter === "function" ? Math.floor(loadCounter(counterName(no)) / counterStep(no)) % 1000 : 0;

  // ----- セーブデータと点数 -----
  const loaded = typeof loadMyData === "function" ? loadMyData() : {};
  const data = loaded.version === 2 ? loaded : { version: 2, solved: [], hints: [], times: [] };
  QUESTIONS.forEach((q, no) => { data.times[no] = data.times[no] || 0; }); // 問題ごとに、開いていた時間(秒)
  const pointOf = (no) => data.hints.includes(no) ? QUESTIONS[no].point / 2 : QUESTIONS[no].point;
  const myScore = () => data.solved.reduce((sum, no) => sum + pointOf(no), 0);
  const save = () => { if (typeof saveMyData === "function") saveMyData(data); };
  const timeText = (sec) => Math.floor(sec / 60) + "分" + (sec % 60) + "秒";
  const clock = (sec) => Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
  const totalSec = () => data.times.reduce((sum, t) => sum + t, 0);

  // 問題の名前を「Q1」(むずかしさの色)と「ニセモノ URL」に分けて出す
  const putTitle = (el, no) => {
    const q = QUESTIONS[no], sp = q.title.indexOf(" ");
    const lv = q.point === 0 ? 0 : q.point <= 100 ? 1 : q.point <= 200 ? 2 : q.point < 500 ? 3 : 4;
    el.innerHTML = '<span class="lv' + lv + '"></span>';
    el.firstChild.textContent = q.title.slice(0, sp);
    el.append(q.title.slice(sp));
  };

  // ----- ホーム -----
  const drawHome = () => {
    $("myScore").textContent = myScore() + " 点";
    $("myTime").textContent = "⏱ 合計 " + clock(totalSec());
    $("list").textContent = "";
    QUESTIONS.forEach((q, no) => {
      const done = data.solved.includes(no);
      const row = document.createElement("div");
      row.className = "row" + (done ? " done" : "");
      row.innerHTML = '<div class="name"></div><div class="info"></div>';
      putTitle(row.children[0], no);
      row.children[1].textContent = pointOf(no) + "点 " + solvedCount(no) + "人が正解" + (done ? " ⏱ " + clock(data.times[no]) : "");
      row.addEventListener("click", () => openQ(no));
      $("list").appendChild(row);
    });
  };

  // ----- 問題を開く -----
  let now = 0, hintAsked = false, started = false;
  const openQ = (no) => {
    now = no;
    putTitle($("pTitle"), no);
    $("pPoint").textContent = pointOf(no) + "点";
    $("myTime").textContent = "⏱ " + clock(data.times[no]);
    showCode(false);
    $("hintBox").style.display = "none";
    $("ans").value = "";
    hintAsked = false;
    // まだ解いていない問題は、スタートを押すまで問いを出さない
    started = data.solved.includes(no);
    $("startText").textContent = data.times[no] > 0
      ? "つづきから始めます(いままでの時間 " + clock(data.times[no]) + ")"
      : "スタートを押すと問いが出て、この問題の時間を測り始めます。";
    $("btnStart").textContent = data.times[no] > 0 ? "つづける" : "スタート";
    showQuestion(started);
    setMsg(data.solved.includes(no) ? "この問題は、もう正解しています(" + timeText(data.times[no]) + ")。" : "", "");
    show("prob");
  };
  const showQuestion = (on) => {
    for (const s of document.querySelectorAll("#pBody section")) s.classList.toggle("on", on && s.id === "q" + now);
    $("startBox").style.display = on ? "none" : "block";
    $("answer").classList.toggle("off", !on);
    $("btnCode").style.visibility = on ? "" : "hidden";
  };
  $("btnStart").addEventListener("click", () => { started = true; showQuestion(true); });
  const setMsg = (text, kind) => { $("msg").textContent = text; $("msg").className = kind; };
  $("btnBack").addEventListener("click", () => { started = false; save(); drawHome(); show("home"); });

  // ----- コードを見る -----
  // この作品の本物のコードから、いま開いている問題の部分だけを切り出して見せる
  const firstHTML = {}; // プログラムが書きかえる前の、問題の HTML
  for (const s of document.querySelectorAll("#pBody section")) firstHTML[s.id] = s.outerHTML;
  const cssOf = (no) => {
    const all = [...document.querySelectorAll("style")].map((s) => s.textContent).join("\n");
    const start = all.indexOf("/* ========== Q" + no + " ");
    return start < 0 ? "" : all.slice(start, all.indexOf("/* ==========", start + 10)).trim();
  };
  const jsOf = (no) => {
    const mark = "// ========== Q" + no + " ";
    const s = [...document.scripts].find((el) => el.textContent.includes(mark));
    if (!s) return "";
    const t = s.textContent;
    // スタジオが自動で足したもの(くりかえしの見張りなど)は消して見せる
    return t.slice(t.indexOf(mark)).replace(/__tentoGuard\w*\([^)]*\);?/g, "").replace(/\/\/# sourceURL=.*/g, "").trim();
  };
  const edited = {}; // 書きかえたコード(問題ごと)
  let codeOn = false;
  const showCode = (on) => {
    codeOn = on;
    const canRun = !!RUN[now]; // 書きかえて動かせる問題か
    $("pBody").classList.toggle("code", on);
    $("codeBox").style.display = on && !canRun ? "block" : "none";
    $("editBox").style.display = on && canRun ? "block" : "none";
    $("btnCode").textContent = on ? "問題にもどる" : "コードを見る";
    $("btnBack").style.visibility = on ? "hidden" : ""; // コードを見ている間は、まちがえてホームにもどらないよう消す
    if (!on) return;
    const html = firstHTML["q" + now].replace(/\n {4}/g, "\n");
    const css = cssOf(now), js = jsOf(now);
    const text = "【HTML】\n" + html + (css ? "\n\n【CSS】\n" + css : "") + (js ? "\n\n【JavaScript】\n" + js : "");
    if (canRun) $("codeEdit").value = edited[now] || text; else $("codeBox").textContent = text;
    $("pBody").scrollTop = 0;
    if (canRun) setMsg("この問題は、コードを書きかえて動かせます(書きかえられるのは、数や色などの値だけ)。", "");
  };
  $("btnCode").addEventListener("click", () => showCode(!codeOn));
  $("btnRun").addEventListener("click", () => {
    edited[now] = $("codeEdit").value;
    const ok = RUN[now](edited[now]);
    showCode(false);
    setMsg(ok ? "書きかえたコードで動かしました。" : "書きかえたコードを読めませんでした。色は \"#ffffff\" のように書きます。", ok ? "ok" : "ng");
  });

  // ----- 答えの提出 -----
  // 答えを「指紋」にする(同じ答えなら、いつも同じ指紋になる)
  const hash = (text) => {
    let h = 2166136261;
    for (const ch of "tento-ctf:" + text) { h ^= ch.codePointAt(0); h = Math.imul(h, 16777619) >>> 0; }
    return h.toString(16);
  };
  let miss = 0, lockUntil = 0;
  const send = () => {
    if (Date.now() < lockUntil) return;
    const text = $("ans").value.normalize("NFKC").toUpperCase().replace(/\s/g, "").replace(/^FLAG\{|\}$/g, "");
    if (!text) return;
    if (/[ぁ-んァ-ン]/.test(text)) { setMsg("答えはローマ字(半角)で入れます。", "ng"); return; }
    if (hash(text) !== QUESTIONS[now].ans) {
      miss++;
      oto(2);
      if (miss >= 3) { miss = 0; lockUntil = Date.now() + 30000; }
      else setMsg("ちがうようです…(" + text + ")", "ng");
      return;
    }
    miss = 0;
    oto(1);
    if (data.solved.includes(now)) { setMsg("正解! この問題は、もう点をもらっています。", "ok"); return; }
    data.solved.push(now);
    save();
    try {
      if (typeof addCounter === "function") addCounter(counterName(now), counterStep(now));
      if (typeof saveRankingScore === "function" && myScore() > 0) saveRankingScore(myScore()); // 0点はランキングにのせない
    } catch (e) { console.warn(e); }
    const tokuten = QUESTIONS[now].point > 0 ? "+" + pointOf(now) + "点" : "れんしゅうなので点はつきません";
    setMsg("正解! " + tokuten + "(かかった時間 " + timeText(data.times[now]) + ")", "ok");
    $("myScore").textContent = myScore() + " 点";
    if (data.solved.length === QUESTIONS.length) {
      setMsg("全問クリア! 合計の時間は " + timeText(totalSec()) + " でした。", "ok");
    }
  };
  $("btnSend").addEventListener("click", send);
  $("ans").addEventListener("keydown", (e) => { if (e.key === "Enter") send(); });
  // ロック中は、あと何秒か出す(「何回もためさせない」守り方)
  setInterval(() => {
    const left = Math.ceil((lockUntil - Date.now()) / 1000);
    $("btnSend").disabled = left > 0;
    if (left > 0) setMsg("3回続けてまちがえたので、ロック中です。あと " + left + " 秒…", "ng");
  }, 250);

  // ----- タイマー -----
  // スタートした問題を開いている間だけ、その問題の時間が1秒ずつ進む(正解したら止まる)
  setInterval(() => {
    if (!started || data.solved.includes(now) || !$("prob").classList.contains("on") || document.visibilityState !== "visible") return;
    data.times[now]++;
    $("myTime").textContent = "⏱ " + clock(data.times[now]);
    if (data.times[now] % 15 === 0) save(); // 15秒ごとに保存
  }, 1000);

  // ----- ヒント -----
  const unshift = (t) => [...t].map((c) => String.fromCodePoint(c.codePointAt(0) - 1)).join("");
  $("btnHint").addEventListener("click", () => {
    const seen = data.hints.includes(now) || data.solved.includes(now) || QUESTIONS[now].point === 0; // 0点の問題は、すぐ見られる
    if (!seen && !hintAsked) {
      hintAsked = true;
      setMsg("ヒントを見ると、この問題の点が半分になります。もう一度押すと見られます。", "");
      return;
    }
    if (!data.hints.includes(now) && !data.solved.includes(now)) { data.hints.push(now); save(); }
    showCode(false);
    $("pPoint").textContent = pointOf(now) + "点";
    $("hintBox").textContent = "ヒント:" + unshift(QUESTIONS[now].hint);
    $("hintBox").style.display = "block";
    $("pBody").scrollTop = $("pBody").scrollHeight;
    setMsg("ヒントを、問題の下に出しました。", "");
  });

  // ----- ランキング -----
  const drawRank = () => {
    const box = $("rankList");
    box.textContent = "";
    $("myClear").textContent = "きみ:" + data.solved.length + "問正解、時間の合計 " + timeText(totalSec()) +
      (data.solved.length === QUESTIONS.length ? "(全問クリア!)" : "");
    const rows = typeof loadRanking === "function" ? loadRanking() : [];
    const unit = typeof loadRankingInfo === "function" ? (loadRankingInfo().unit || "点") : "点";
    if (!rows.length) box.textContent = "まだだれも記録がありません。";
    rows.forEach((r, i) => {
      const d = document.createElement("div");
      d.className = "rk" + (r.me ? " me" : "");
      d.innerHTML = "<span></span><span></span><span></span>";
      d.children[0].textContent = (i + 1) + "位";
      d.children[1].textContent = r.name + (r.me ? "(きみ)" : "");
      d.children[2].textContent = r.value + unit;
      box.appendChild(d);
    });
  };
  $("btnRank").addEventListener("click", () => { drawRank(); show("rank"); });
  $("btnBack2").addEventListener("click", () => { drawHome(); show("home"); });

  drawHome();
})();
</script>

<script>
// ========== Q1 ニセモノ URL ==========
{
  const urls = ["mogmog-bank.jp.login-check.com", "m0gmog-bank.jp", "mogmog-bamk.jp", "mogmog-bank.jp", "mogmogbank.jp", "mogmog-bank.net"];
  const words = ["KAERU", "USAGI", "RISU", "KUMA", "SARU", "MOGURA"];
  urls.forEach((url, i) => {
    const b = document.createElement("button");
    b.type = "button";
    b.className = "sub";
    b.textContent = "https://" + url + "/";
    // 押した URL のサイトに書いてある言葉(どの言葉になるかは、この計算で決まる)
    b.addEventListener("click", () => {
      $("q1out").textContent = url + " のサイト:「" + words[(i * 5 + 2) % 6] + "」";
      for (const x of $("q1urls").children) x.className = x === b ? "" : "sub"; // 押した URL の色を変える
    });
    $("q1urls").appendChild(b);
  });
}
</script>

<script>
// ========== Q4 記号の暗号 ==========
{
  // 暗号の表(画面には、とちゅうまでしか出していない)
  const hyou = { "★": "S", "◆": "K", "♥": "E", "●": "O", "♠": "T", "▲": "A", "♣": "N", "■": "R" };
  for (const kigou of Object.keys(hyou).slice(0, 5)) {
    const span = document.createElement("span");
    span.textContent = kigou + " = " + hyou[kigou];
    $("q4table").appendChild(span);
  }
}
</script>

<script>
// ========== Q5 シーザー暗号 ==========
{
  const zurasu = 9 - 6; // この暗号の「ずらす数」
  let abc = "";
  for (let i = 0; i < 26; i++) abc += String.fromCharCode(65 + i) + " ";
  $("q5abc").textContent = abc;
}
</script>

<script>
// ========== Q6 モールス信号 ==========
{
  // 合図:1 は短く光る(・)、3 は長く光る(ー)、0 は文字の区切り
  const shingou = [1, 3, 1, 0, 1, 3, 0, 3, 1, 3, 0, 1, 1, 3, 0, 3, 1, 1, 0, 1, 3];
  let i = 0;
  const hikaru = () => {
    if (i === shingou.length) { i = 0; setTimeout(hikaru, 2500); return; } // 最後まで送ったら、少し休んで最初から
    const s = shingou[i];
    i++;
    if (s === 0) { setTimeout(hikaru, 900); return; }
    $("q6lamp").style.background = "#facc15";
    setTimeout(() => { $("q6lamp").style.background = "#374151"; setTimeout(hikaru, 350); }, s * 250);
  };
  hikaru();
}
</script>

<script>
// ========== Q7 2つのかぎ ==========
{
  const ango = "VQEAFVP";
  const kagi2 = 4 * 2; // 2・4・6…番目の文字の「ずらす数」
  let k1 = 0, k2 = 0;
  const modosu = (c, k) => String.fromCharCode((c.charCodeAt(0) - 65 - k + 26) % 26 + 65); // k だけ前にもどす
  const draw = () => {
    $("q7k1").textContent = k1;
    $("q7k2").textContent = k2;
    $("q7text").textContent = [...ango].map((c, i) => modosu(c, i % 2 === 0 ? k1 : k2)).join("");
  };
  $("q7plus1").addEventListener("click", () => { k1 = (k1 + 1) % 26; draw(); });
  $("q7minus1").addEventListener("click", () => { k1 = (k1 + 25) % 26; draw(); });
  $("q7plus2").addEventListener("click", () => { k2 = (k2 + 1) % 26; draw(); });
  $("q7minus2").addEventListener("click", () => { k2 = (k2 + 25) % 26; draw(); });
}
</script>

<script>
// ========== Q9 金庫 ==========
{
  // 金庫の番号は、この計算で決まる
  let bango = 5;
  for (let i = 0; i < 4; i++) {
    bango = bango * 2 + 3;
  }
  const takara = "QBOEB"; // 金庫の中の言葉(文字を1つずつずらしてある)
  let miss = 0;
  $("q9open").addEventListener("click", () => {
    if (miss >= 3) return;
    if (Number($("q9in").value) === bango) {
      $("q9out").textContent = "開いた! 中の言葉:" + [...takara].map((c) => String.fromCharCode(c.charCodeAt(0) - 1)).join("");
      return;
    }
    miss++;
    $("q9out").textContent = miss >= 3 ? "ロックされました。作品をスタートし直すと、またためせます。" : "開きません…(あと " + (3 - miss) + " 回)";
  });
}
</script>

<script>
// ========== Q10 見えない絵 ==========
{
  const iro = "#1e293b";    // 絵の色
  const haikei = "#1e293b"; // 背景の色
  const dots = [
    ["10001", "11011", "10101", "10001", "10001"],
    ["01110", "10001", "11111", "10001", "10001"],
    ["01110", "10001", "10001", "10001", "01110"],
    ["11110", "10001", "11110", "10010", "10001"],
    ["10001", "10001", "10001", "10001", "01110"]
  ];
  const narabi = [0, 1, 0, 2, 3, 4]; // どの絵を、どの順に描くか
  const draw = (iro, haikei) => {
    const cv = $("q10cv").getContext("2d");
    cv.fillStyle = haikei;
    cv.fillRect(0, 0, 432, 72);
    cv.fillStyle = iro;
    narabi.forEach((n, k) => {
      dots[n].forEach((line, y) => {
        [...line].forEach((v, x) => { if (v === "1") cv.fillRect(6 + k * 72 + x * 12, 6 + y * 12, 11, 11); });
      });
    });
  };
  draw(iro, haikei);
  // 「コードを見る」で書きかえたら:書きかえたコードの iro と haikei を読んで、描き直す
  RUN[10] = (code) => {
    const newIro = readValue(code, "iro"), newHaikei = readValue(code, "haikei");
    if (typeof newIro !== "string" || typeof newHaikei !== "string") return false;
    draw(newIro, newHaikei);
    return true;
  };
}
</script>
<script>
// ========== Q11 ボス ==========
{
  // 指紋(ハッシュ)を作る関数。同じ言葉からは、いつも同じ指紋ができる
  const shimon = (text) => {
    let h = 2166136261;
    for (const ch of "tento-ctf:" + text) { h ^= ch.codePointAt(0); h = Math.imul(h, 16777619) >>> 0; }
    return h.toString(16);
  };
  const mokuhyou = "1b9769b9"; // あいことばの指紋
  $("q11target").textContent = mokuhyou;
  let miss = 0;
  $("q11try").addEventListener("click", () => {
    if (miss >= 3) return;
    if (shimon($("q11in").value.toUpperCase()) === mokuhyou) {
      $("q11out").textContent = "開いた! これが答えです";
      return;
    }
    miss++;
    $("q11out").textContent = miss >= 3 ? "ロックされました" : "ちがいます(あと " + (3 - miss) + " 回)";
  });
  // ↓ コピーした作品で、ここに総当たりのプログラムを書いてみよう(答えは console.log で、コンソールに出せる)

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