借一粒星光 · 遊戲原碼 單檔 HTML 原始碼,可在瀏覽器閱讀,不必下載
開啟遊戲 返回官網
檔案 play/game.html 原文 533 行 · 85.4 KB 整齊排版後 3676 行(只為方便閱讀,內容相同)
1<!doctype html>
2<html lang="zh-Hant">
3<head>
4<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='6' fill='%230b1a24'/%3E%3Cpath fill='%23dfcf98' d='M16 4l1.7 8.3L26 16l-8.3 1.7L16 26l-1.7-8.3L6 16l8.3-1.7z'/%3E%3C/svg%3E"><link rel="apple-touch-icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='6' fill='%230b1a24'/%3E%3Cpath fill='%23dfcf98' d='M16 4l1.7 8.3L26 16l-8.3 1.7L16 26l-1.7-8.3L6 16l8.3-1.7z'/%3E%3C/svg%3E">
5<meta name="theme-color" content="#0d202a"><meta name="description" content="一個關於拾光、歸途與陪伴的水墨小遊戲。序章之後,還有四十個夜晚等你種亮。">
6<title>借一粒星光 · 四十夜的歸途</title>
7<style>
8:root{color-scheme:dark;--gold:#dfcf98;--paper:#ece5d4;--muted:#a9bbb9;--bg:#0b1a24;--line:#8eaaa42e}*{box-sizing:border-box}html,body{margin:0;min-height:100%;background:var(--bg);color:var(--paper);font-family:'Songti TC','Songti SC','STSong','Noto Serif CJK TC','Noto Serif CJK SC','Noto Serif TC',Georgia,serif}body{background:radial-gradient(ellipse at 60% 44%,#25404a66,transparent 65%),var(--bg)}button{font:inherit;cursor:pointer;touch-action:manipulation}button,input{accent-color:var(--gold)}button:disabled{cursor:default}button:focus-visible,canvas:focus-visible,input:focus-visible{outline:2px solid var(--gold);outline-offset:4px}[hidden]{display:none!important}button{color:var(--paper)}.app{width:min(1440px,100%);margin:auto;padding:0 4.5%;min-height:100svh;height:100svh;max-height:100svh;display:flex;flex-direction:column;overflow:hidden}.topbar{flex-shrink:0;height:84px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:16px}.brand{font-size:17px;letter-spacing:4px}.brand small{display:block;margin-top:7px;color:var(--muted);font:9px/1.5 Arial,sans-serif;letter-spacing:3px}.toolbar{display:flex;gap:9px;align-items:center}.quiet{background:transparent;border:1px solid var(--line);border-radius:30px;padding:10px 17px;font-size:12px;min-height:40px;letter-spacing:1px;transition:background .2s}.quiet:hover{background:#c7dac412}.quiet:disabled{opacity:.4}.quiet[aria-pressed=true]{border-color:#dfcf9880;color:var(--gold)}.level-head{flex-shrink:0;display:flex;justify-content:space-between;gap:24px;align-items:center;padding:26px 0 15px}.eyebrow{font:10px/1.7 Arial,sans-serif;letter-spacing:3px;color:var(--gold);text-transform:uppercase}h1{font-weight:400;font-size:clamp(25px,3.4vw,43px);letter-spacing:5px;line-height:1.35;margin:8px 0}.intro-line{color:var(--muted);font-size:12px;line-height:1.8;max-width:750px;letter-spacing:1px;margin:0}.progress{text-align:right;flex-shrink:0}.progress .number{font:34px/1.3 Georgia,serif;color:var(--gold)}.progress small{font:11px Arial;letter-spacing:2px;color:var(--muted)}.progress .caption{font-size:10px;letter-spacing:3px;color:var(--muted);margin-bottom:5px}.progress-track{width:145px;height:2px;background:#9cb8b522;margin-top:12px;overflow:hidden}.progress-track span{display:block;height:100%;background:var(--gold);transition:width .35s}.stage{container-type:size;flex:1 1 auto;min-height:220px;position:relative;isolation:isolate;display:flex;align-items:center;justify-content:center;background:#07141c;border-bottom:1px solid var(--line);border-top:1px solid var(--line);overflow:hidden;height:auto}.stage-frame{position:relative;aspect-ratio:1000/640;width:min(100cqw,calc(100cqh * 1000 / 640));height:auto;max-width:100%;max-height:100%}canvas{display:block;width:100%;height:100%;touch-action:none;border-radius:2px}.stage-meta{position:absolute;top:16px;left:20px;right:20px;display:flex;justify-content:space-between;gap:15px;align-items:start;pointer-events:none}.objectives{display:flex;flex-wrap:wrap;gap:8px}.objective{font-size:11px;line-height:1.5;letter-spacing:1px;padding:6px 10px;border-radius:3px;background:#081923bd;color:#cbd5cd}.objective.done{color:var(--gold)}.weather{font-size:11px;color:#c6d3cf;text-align:right;line-height:1.9;white-space:nowrap}.stage-caption{position:absolute;bottom:13px;left:20px;font:9px Arial,sans-serif;color:#bed0c070;letter-spacing:3px;pointer-events:none}.understory{flex-shrink:0;display:grid;grid-template-columns:1fr auto;gap:16px;align-items:center;padding:18px 0 12px}.pocket-row{display:flex;align-items:center;gap:12px}.pocket{display:flex;gap:8px}.pocket i{width:7px;height:7px;border:1px solid var(--gold);transform:rotate(45deg);transition:background .2s}.pocket i.on{background:var(--gold);box-shadow:0 0 14px #dfcf9860}.pocket-label{font:10px Arial;letter-spacing:2px;color:var(--muted)}.message{font-size:13px;line-height:1.8;letter-spacing:1px;margin-top:9px;color:#d3ded3;min-height:24px}.pulse{display:flex;gap:12px;align-items:center;border:1px solid #dcca9166;background:#dcca910b;border-radius:40px;padding:13px 21px;color:var(--gold);min-width:132px;justify-content:center;min-height:48px;font-size:13px;letter-spacing:2px}.pulse:disabled{color:var(--muted);border-color:var(--line)}.pulse small{font:10px Arial;letter-spacing:1px;color:var(--muted)}.footer{flex-shrink:0;display:flex;justify-content:space-between;gap:16px;padding:7px 0 24px;color:#8da5a5;font-size:10px;letter-spacing:1px;line-height:1.8}.save-status{white-space:nowrap}.overlay{position:fixed;inset:0;z-index:10;background:#06131cbf;backdrop-filter:blur(14px);display:flex;align-items:center;justify-content:center;padding:24px;overflow:auto}.panel{position:relative;background:linear-gradient(145deg,#18303b,#101e2a);border:1px solid #9db7ac30;max-width:570px;width:100%;padding:46px 44px;border-radius:5px;box-shadow:0 35px 100px #0005;max-height:calc(100svh - 48px);overflow:auto}.center{text-align:center}.seal{color:var(--gold);font-size:35px;margin-bottom:20px}.panel h2{font-size:30px;font-weight:400;letter-spacing:4px;line-height:1.6;margin:8px 0 17px}.panel p{font-size:14px;line-height:2.1;letter-spacing:1px;color:#bfcfc7;white-space:pre-line;margin:14px 0 25px}.panel .tagline{font-size:12px;color:var(--gold);margin-bottom:28px}.primary{border:1px solid #e0d2ab;background:#e0d2ab;color:#173138;padding:14px 25px;min-height:47px;letter-spacing:2px;border-radius:3px;font-size:14px}.primary:hover{background:#f0e1bc}.actions{display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap}.text-button{border:0;background:none;color:#acbfba;text-decoration:underline;text-underline-offset:4px;font-size:12px;padding:12px}.meta-note{font-size:11px!important;color:#90aaa7!important;margin:20px 0 0!important;line-height:1.9!important}.instructions{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin:25px 0 30px;font-size:11px;color:#a9bdb7;line-height:1.8}.instructions span{font-size:20px;display:block;color:var(--gold);margin-bottom:4px}.close{position:absolute;top:16px;right:17px;width:40px;height:40px;border:0;background:transparent;font:25px Arial;color:#adc1b8}.map-panel{max-width:1020px;padding:35px 40px}.map-heading{display:flex;justify-content:space-between;gap:16px;align-items:end;margin:0 0 18px}.map-heading h2{margin-bottom:3px}.map-heading p{font-size:12px;margin:0}.map-total{font:28px Georgia;color:var(--gold);white-space:nowrap;margin-right:20px}.map-total small{font:11px Arial;color:var(--muted)}.map-zero{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:10px 0 17px;border-bottom:1px solid var(--line);font-size:12px;color:var(--muted)}.map-chapter{margin-top:24px}.chapter-title{display:flex;gap:12px;align-items:center;margin-bottom:12px}.chapter-mark{display:grid;place-items:center;width:29px;height:29px;border:1px solid #b9b59a55;border-radius:50%;font-size:12px;color:var(--chapter)}.chapter-title h3{font-size:15px;font-weight:400;letter-spacing:3px;margin:0}.chapter-title p{font-size:11px;margin:0 0 0 auto;color:#93aaa5;letter-spacing:1px}.level-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:9px}.level-tile{position:relative;text-align:left;border:1px solid #99b3a92b;border-radius:3px;background:#21353c5e;min-height:89px;padding:13px 12px;color:#d4dece;transition:background .2s}.level-tile:not(:disabled):hover{background:#45554c66;border-color:#d9ca9a80}.level-tile:disabled{background:#11232b;color:#90a1a0}.level-tile.current{border-color:var(--gold)}.level-tile .tile-no{font:11px Georgia;color:var(--chapter);letter-spacing:2px}.level-tile:disabled .tile-no{color:#78908d}.level-tile .tile-name{font-size:12px;letter-spacing:1px;display:block;margin:8px 0;line-height:1.6}.tile-stars{font:11px Arial;color:var(--gold);letter-spacing:3px}.tile-lock{font-size:10px;color:#718b86}.rating{font-size:24px;color:var(--gold);letter-spacing:12px;margin:20px 0 7px}.result-meta{font-size:11px;line-height:1.8;color:#9db5ac;margin-bottom:26px}.setting{display:flex;align-items:center;justify-content:space-between;gap:20px;text-align:left;padding:16px 0;border-bottom:1px solid var(--line);font-size:13px}.setting small{display:block;font-size:11px;line-height:1.8;color:var(--muted);margin-top:5px}.setting input{width:19px;height:19px;flex-shrink:0}.keyboard-help{font-size:12px;text-align:left;line-height:2.1;color:var(--muted);margin:24px 0}.keyboard-help strong{font-weight:400;color:var(--paper)}.error{color:#ecc4ac}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(min-width:1600px){.app{padding:0 60px}}@media(max-width:700px){.app{padding:0 20px}.topbar{height:75px}.brand{font-size:14px;letter-spacing:2px}.brand small{font-size:8px;letter-spacing:1px}.toolbar{gap:5px}.quiet{padding:9px 11px;font-size:11px;min-height:42px}.level-head{padding:20px 0 14px;gap:14px;align-items:start}h1{font-size:25px;letter-spacing:2px}.intro-line{font-size:11px;line-height:1.7}.eyebrow{font-size:9px;letter-spacing:1px}.progress .number{font-size:25px}.progress .caption{font-size:9px;letter-spacing:1px}.progress-track{width:68px}.stage{height:auto;min-height:0}.stage-meta{left:10px;right:10px;top:12px;gap:5px}.objectives{gap:4px;max-width:78%}.objective{font-size:10px;padding:5px 7px}.weather{font-size:9px}.stage-caption{font-size:8px;letter-spacing:1px;left:12px}.understory{gap:10px;padding-top:16px}.message{font-size:11px;line-height:1.9}.pulse{font-size:16px;padding:14px 22px;min-width:128px;min-height:56px;gap:8px}.pulse small{display:none}.footer{flex-wrap:wrap;font-size:9px;gap:3px;padding-bottom:17px}.panel{padding:40px 25px}.panel h2{font-size:25px;letter-spacing:2px}.panel p{font-size:13px}.overlay{padding:15px}.panel{max-height:calc(100svh - 30px)}.map-panel{padding:38px 20px 25px}.map-heading{display:block}.map-total{font-size:20px;margin-top:12px}.chapter-title{gap:8px}.chapter-title h3{font-size:14px;letter-spacing:1px}.chapter-title p{display:none}.level-grid{grid-template-columns:repeat(3,1fr);gap:6px}.level-tile{padding:10px 8px}.level-tile .tile-name{font-size:11px}.map-zero{font-size:11px}.map-zero .quiet{font-size:10px}.instructions{gap:9px;font-size:10px}.actions .primary{font-size:13px;padding:13px 19px}}@media(max-width:370px){.app{padding:0 12px}.brand small{display:none}.toolbar .quiet{padding:9px}.progress{min-width:54px}.level-head{gap:8px}h1{font-size:22px}.level-grid{grid-template-columns:repeat(2,1fr)}}@media(prefers-reduced-motion:reduce){*{transition:none!important}}
9#result{background:#06131c7a;backdrop-filter:blur(2px)}
10.goal-hint{margin:7px 0 0;font-size:11px;letter-spacing:1px;color:#c6d3cf;line-height:1.65;text-shadow:0 1px 8px #081923cc;white-space:nowrap}.objectives-col{display:flex;flex-direction:column;align-items:flex-start;gap:0;pointer-events:none;max-width:78%}.map-scroll-hint{position:sticky;bottom:0;z-index:1;margin:8px 0 0;padding:22px 0 4px;text-align:center;font-size:12px;letter-spacing:1px;color:var(--gold);background:linear-gradient(transparent,#101e2a 42%);}@media(max-width:700px){.stage{flex:0 0 auto;height:auto;min-height:0;container-type:normal}.stage-frame{width:100%;height:auto;aspect-ratio:1000/640}.pulse{font-size:16px;padding:14px 22px;min-width:128px;min-height:56px;gap:8px}.goal-hint{font-size:10px;max-width:100%;white-space:normal}}</style>
11</head>
12<body>
13<main class="app" id="app">
14<header class="topbar"><div class="brand">借一粒星光<small>四十夜的歸途</small></div><nav class="toolbar" aria-label="遊戲菜單"><button class="quiet" id="sound" aria-pressed="true">音樂 · 開</button><button class="quiet" id="map-button">夜行圖</button><button class="quiet" id="pause-button">暫停</button></nav></header>
15<section class="level-head"><div><div class="eyebrow" id="eyebrow">四十夜的歸途 · 第 01 / 40 夜</div><h1 id="level-title">露水的來處</h1><p class="intro-line" id="level-intro">先拾起三粒星光,再靠近樹根。</p></div><div class="progress"><div class="caption">已送回星光</div><span class="number" id="delivered">0</span> <small id="required">/ 6</small><div class="progress-track" role="progressbar" aria-label="送回星光進度" aria-valuemin="0" aria-valuemax="6" aria-valuenow="0" id="progress"><span id="progress-fill" style="width:0%"></span></div></div></section>
16<section class="stage" aria-label="夜色花園"><div class="stage-frame"><canvas id="garden" tabindex="0" aria-label="遊戲區域。可用手指拖動、鼠標移動或方向鍵走動,點「屏息」或按空白鍵護光。每次攜帶三粒星光,送回樹根。">請用支持 Canvas 的瀏覽器打開遊戲。</canvas><div class="stage-meta"><div class="objectives-col"><div id="objectives" class="objectives"></div><p id="goal-hint" class="goal-hint"></p></div><div id="weather" class="weather"></div></div><div class="stage-caption">不必趕路。每一粒微光,都算數。</div></div></section>
17<div class="understory"><div><div class="pocket-row"><div id="pocket" class="pocket" aria-label="攜帶星光 0 / 3"><i></i><i></i><i></i></div><span class="pocket-label" id="pocket-label">0 / 3 · 攜帶中</span></div><div class="message" id="message" role="status" aria-live="polite">把散落的夜晚,種成一棵會發光的樹。</div></div><button class="pulse" id="pulse"><span id="pulse-label">屏息</span><small>空白鍵</small></button></div>
18<footer class="footer"><span id="control-hint">滑鼠移動、方向鍵或 W A S D 移動 · 空白鍵護光 · Esc 暫停</span><span id="save-status" class="save-status">進度自動保存在當前瀏覽器</span></footer>
19</main>
20<div class="overlay" id="welcome" role="dialog" aria-modal="true" aria-labelledby="welcome-title"><section class="panel center"><div class="eyebrow">借一粒星光 · 第二卷</div><div class="seal" aria-hidden="true">✧</div><h2 id="welcome-title">四十夜的歸途</h2><p>那棵被你種亮的樹,寄來了一封信。<br>原來,森林的另一端,<br>還有四十個夜晚在等你。</p><div class="instructions"><div><span>◇</span>拾起三粒光<br>帶回樹根</div><div><span>◎</span>繞過墨影<br>屏息護光</div><div><span>✺</span>點燈與同行<br>讓長夜開花</div></div><div class="actions"><button class="primary" id="continue">開始第 1 夜</button><button class="quiet" id="welcome-map">展開夜行圖</button></div><button class="text-button" id="prologue">重溫原來的序章</button><p class="meta-note">八個章節 · 四十個新關卡 · 自動存檔<br>入夜後播放輕柔背景音樂,可隨時關閉。<br>沒有倒計時。慢一點,也很好。</p></section></div>
21<div class="overlay" id="map-dialog" role="dialog" aria-modal="true" aria-labelledby="map-title" hidden><section class="panel map-panel"><button class="close" id="map-close" aria-label="關閉夜行圖">×</button><div class="map-heading"><div><div class="eyebrow">你的夜行圖</div><h2 id="map-title">夜行圖</h2><p>每走過一個夜晚,就為森林留下一朵花。</p></div><div class="map-total"><span id="map-count">0</span> <small>/ 40 夜已種亮</small></div></div><div class="map-zero"><span>序章 · 夜晚,借你一點光</span><button class="quiet" id="map-prologue">重溫序章</button></div><div id="chapters"></div><p class="meta-note">完成當前關卡,解鎖下一夜。已完成的關卡可以重玩。<br>花印:通關一枚;碰撞不超過三次兩枚;無碰撞三枚。沒有時間評分。<br>八個章節,頁面較長時請向下滑動,後面還有更多夜晚。</p><p class="map-scroll-hint" id="map-scroll-hint" hidden>向下滑動,後面還有更多章節。</p></section></div>
22<div class="overlay" id="briefing" role="dialog" aria-modal="true" aria-labelledby="brief-title" hidden><section class="panel center"><div class="eyebrow" id="brief-label"></div><div class="seal" id="brief-mark"></div><h2 id="brief-title"></h2><p id="brief-text"></p><div class="actions"><button class="primary" id="begin-level">走進這一夜</button><button class="quiet" id="brief-map">夜行圖</button></div><p class="meta-note">移動即可拾光,靠近就能互動。每次帶滿三粒再回樹根。<br>點「屏息」或按空白鍵,可短暫護光。<br>若這一夜有燈、月門或夥伴,都要完成,才算種亮。</p></section></div>
23<div class="overlay" id="pause-dialog" role="dialog" aria-modal="true" aria-labelledby="pause-title" hidden><section class="panel"><div class="eyebrow">先歇一口氣</div><h2 id="pause-title">讓夜晚,等你一會兒</h2><label class="setting"><span>背景音樂<small>遊戲中播放輕柔旋律;通關飄花時切換為風聲。</small></span><input type="checkbox" id="music-enabled" checked></label><label class="setting"><span>背景音量 <output id="volume-label">42%</output><small>調節旋律與通關後的風聲。</small></span><input type="range" id="music-volume" min="0" max="100" value="42" aria-label="背景聲音量" style="width:115px;height:28px"></label><label class="setting"><span>互動音效<small>拾光、點燈與開花時的聲音。</small></span><input type="checkbox" id="effects"></label><label class="setting"><span>慢行模式<small>墨影放慢,移動更輕快;不影響解鎖。</small></span><input type="checkbox" id="assist"></label><label class="setting"><span>減少裝飾動畫<small>減少尾跡、閃爍、粒子與落花,保留必要的遊戲移動。</small></span><input type="checkbox" id="motion"></label><div class="keyboard-help"><strong>方向鍵 / W A S D</strong> 移動 · <strong>空白鍵</strong> 屏息護光<br>也可以用滑鼠在畫面裡移動,或用手指拖動。<br>屏息持續 2.8 秒,8 秒後可再次使用。<br>墨影與荊棘會吹散一粒光,已經送回的光不會丟失。</div><div class="actions"><button class="primary" id="resume">繼續這一夜</button><button class="quiet" id="pause-map">夜行圖</button><button class="text-button" id="restart">重走本關</button></div><p class="meta-note" id="pause-save">離開、切換關卡或關閉頁面,都會保存當前進度。</p></section></div>
24<div class="overlay" id="result" role="dialog" aria-modal="true" aria-labelledby="result-title" hidden><section class="panel center"><div class="eyebrow" id="result-label"></div><div class="seal">✺</div><h2 id="result-title">這一夜,被你種亮了</h2><p id="poem"></p><div class="rating" id="rating" aria-label="本關花印"></div><div class="result-meta" id="result-meta"></div><div class="actions"><button class="primary" id="next-level">走向下一夜</button><button class="quiet" id="result-map">夜行圖</button></div><button class="text-button" id="stay">留下來,看看花</button></section></div>
25<script>
26/* 借一粒星光 — deterministic campaign and simulation; no external dependencies. */
27const NightGarden = (() => {
28 'use strict';
29 const WORLDS = [
30 {name:'苔原拾光',subtitle:'在最初的微光裡,學會回家。',color:'#dfcf98',sky:['#0a1923','#23464b'],flower:'#ebd3a4',mark:'芽'},
31 {name:'風眠竹海',subtitle:'風沒有方向,直到你決定出發。',color:'#b9dac4',sky:['#0c2329','#28564e'],flower:'#cce6b5',mark:'風'},
32 {name:'霧燈渡口',subtitle:'看不見遠方的時候,先點亮身邊。',color:'#bfcede',sky:['#151e30','#38465e'],flower:'#cbd8ef',mark:'霧'},
33 {name:'荊棘書頁',subtitle:'繞過刺,也是一種溫柔的勇敢。',color:'#d7b6aa',sky:['#291e2c','#57404a'],flower:'#e8b6ba',mark:'棘'},
34 {name:'鏡湖迴廊',subtitle:'另一端的自己,也在等一場相逢。',color:'#c9bde8',sky:['#191a34','#3c4164'],flower:'#d5c8f0',mark:'鏡'},
35 {name:'潮聲群島',subtitle:'有些重逢,需要等一等潮汐。',color:'#a9d9df',sky:['#092532','#265366'],flower:'#b9e5e1',mark:'潮'},
36 {name:'螢火來信',subtitle:'這一次,回家的不只你一個。',color:'#e6cb9c',sky:['#27232b','#574d43'],flower:'#f0d0a0',mark:'信'},
37 {name:'黎明花園',subtitle:'把走過的夜晚,交還給清晨。',color:'#f0c7aa',sky:['#302638','#765a60'],flower:'#f8d0b5',mark:'曉'}
38 ];
39 const root=(x,y,need=3)=>({x,y,need});
40 const wall=(x1,y1,x2,y2)=>({x1,y1,x2,y2});
41 const pair=(ax,ay,bx,by)=>[{x:ax,y:ay},{x:bx,y:by}];
42 const P=[
43 [1,'露水的來處','先拾起三粒星光,再靠近樹根。', [root(500,540,6)], {shadows:0,pattern:'ring'}],
44 [2,'兩岸的芽','兩棵樹,等你分別送去三粒光。',[root(240,525),root(760,525)],{shadows:1,pattern:'banks'}],
45 [3,'微光小徑','墨影會帶走一粒光;按空格可短暫護住自己。',[root(500,540,9)],{shadows:2,pattern:'trail'}],
46 [4,'三封無字信','沿三角形的歸途,把三棵樹都種亮。',[root(180,480),root(500,210),root(820,480)],{shadows:2,pattern:'triangle'}],
47 [5,'苔原的星座','讓四個方向,都有一處可以歸來。',[root(170,460),root(400,550),root(650,490),root(830,300)],{shadows:2,pattern:'ring'}],
48 [6,'風的第一行','向東的風會推著你走。點「屏息」或按空白鍵,可暫時抵禦風。',[root(220,510,6)],{shadows:1,wind:'east',pattern:'banks'}],
49 [7,'逆風的種子','把光送往西邊,再走到竹海的另一側。',[root(160,480),root(830,450)],{shadows:2,wind:'west',pattern:'trail'}],
50 [8,'竹葉的迴旋','旋轉的風中,試著分段移動。',[root(500,525,9)],{shadows:2,wind:'swirl',pattern:'ring'}],
51 [9,'風向改變之前','風向會緩緩改變。每一段路,都可以重新選擇。',[root(200,500),root(500,290),root(800,500)],{shadows:3,wind:'changing',pattern:'triangle'}],
52 [10,'把風種下來','沿著迴旋的風,完成四次歸途。',[root(260,490,6),root(760,490,6)],{shadows:2,wind:'swirl',windPower:1.1,pattern:'banks'}],
53 [11,'第一盞霧燈','靠近蓮花燈即可點亮;燈光會驅散周圍的霧。',[root(500,525,6)],{shadows:1,fog:true,lamps:[[330,330]],pattern:'trail'}],
54 [12,'隔霧相望','點亮兩盞燈,也照亮彼此的樹。',[root(210,515),root(790,515)],{shadows:2,fog:true,lamps:[[240,285],[760,285]],pattern:'banks'}],
55 [13,'燈與風的約定','霧會遮住遠處的星光,燈臺會一直留在原地。',[root(500,525,9)],{shadows:2,fog:true,lamps:[[250,300],[700,360]],wind:'east',pattern:'ring'}],
56 [14,'渡口不眠','依次探索三個燈臺,再把光交給岸邊。',[root(200,525),root(500,480),root(800,525)],{shadows:3,fog:true,lamps:[[170,290],[500,220],[830,290]],pattern:'triangle'}],
57 [15,'霧散時的名字','霧燈、風與墨影,都成了你熟悉的路標。',[root(280,520,6),root(750,500,6)],{shadows:3,fog:true,lamps:[[230,280],[500,340],[790,230]],wind:'changing',pattern:'banks'}],
58 [16,'紙上的第一根刺','荊棘不可穿越。繞過端點,就能找到另一條路。',[root(780,510,6)],{shadows:1,thorns:[wall(490,140,490,390)],pattern:'banks'}],
59 [17,'留白的入口','穿過兩段荊棘之間的留白。',[root(500,520,9)],{shadows:2,thorns:[wall(150,330,420,330),wall(580,330,850,330)],pattern:'ring'}],
60 [18,'摺頁花園','每一處轉角,都藏著一條不必受傷的路。',[root(200,500),root(800,500)],{shadows:2,thorns:[wall(370,130,370,350),wall(630,300,630,535)],wind:'west',pattern:'banks'}],
61 [19,'刺間的燈','在荊棘的缺口裡,點亮兩盞不熄的燈。',[root(500,525,9)],{shadows:2,fog:true,lamps:[[250,220],[760,220]],thorns:[wall(360,270,640,270),wall(210,380,380,380),wall(620,380,790,380)],pattern:'triangle'}],
62 [20,'溫柔的迷宮','繞過三面書頁,把故事寫到最後。',[root(210,520,6),root(800,510,6)],{shadows:3,thorns:[wall(330,145,330,390),wall(670,255,670,540),wall(425,330,580,330)],wind:'changing',pattern:'trail'}],
63 [21,'鏡子的另一面','走進圓形月門,抵達同符號的另一端。穿過這對月門。',[root(800,500,6)],{shadows:1,portals:[pair(230,420,770,230)],pattern:'banks'}],
64 [22,'兩次相逢','兩對月門各穿過一次;符號標記了它們的連結。',[root(210,500),root(800,500)],{shadows:2,portals:[pair(170,240,650,460),pair(390,460,840,240)],pattern:'ring'}],
65 [23,'越過未寫的河','借月門越過荊棘,或者繞行;記得留下穿越的足跡。',[root(800,480,9)],{shadows:2,portals:[pair(230,420,770,210)],thorns:[wall(500,100,500,470)],pattern:'banks'}],
66 [24,'霧中的倒影','先尋找燈,再看清鏡中的歸途。',[root(250,510),root(760,510)],{shadows:2,fog:true,lamps:[[220,270],[790,270]],portals:[pair(150,420,810,180),pair(830,420,350,180)],pattern:'triangle'}],
67 [25,'迴廊盡頭是你','在雙重鏡廊中,把兩岸的樹都種亮。',[root(210,510,6),root(800,510,6)],{shadows:3,wind:'swirl',portals:[pair(160,280,760,380),pair(840,190,300,400)],thorns:[wall(410,180,590,180),wall(500,330,500,490)],pattern:'banks'}],
68 [26,'退潮的禮物','帶波紋的星光只在退潮時出現;不必著急。',[root(500,515,6)],{shadows:1,tide:10,pattern:'tide'}],
69 [27,'海把星星還回來','水面升起時移動會慢一些,退潮後再去拾光。',[root(220,510),root(790,510)],{shadows:2,tide:11,pattern:'tide'}],
70 [28,'風從海上來','乘風走過淺灘,等待星光從潮水裡浮起。',[root(500,510,9)],{shadows:2,tide:10,wind:'east',pattern:'tide'}],
71 [29,'潮間的月門','門不會被海淹沒,它會把你送到另一片岸。',[root(220,510),root(790,510)],{shadows:2,tide:12,portals:[pair(180,300,820,200)],pattern:'tide'}],
72 [30,'聽見海的呼吸','點亮海邊的燈,穿過月門,等一場溫柔的退潮。',[root(260,500,6),root(740,500,6)],{shadows:3,tide:10,fog:true,lamps:[[250,220],[750,260]],portals:[pair(160,390,820,190)],pattern:'tide'}],
73 [31,'一封會飛的信','靠近小螢火蟲,讓它跟著你回到樹根。',[root(500,520,6)],{shadows:1,companions:[[240,240]],pattern:'ring'}],
74 [32,'我們一起回家','兩隻螢火蟲在等你。慢一點,讓它們跟上。',[root(500,530,9)],{shadows:2,companions:[[180,250],[820,230]],wind:'west',pattern:'banks'}],
75 [33,'燈下的三個人','霧裡有三位夥伴,一次最多帶兩位回家。',[root(500,520,9)],{shadows:2,fog:true,lamps:[[220,300],[780,300]],companions:[[160,210],[830,200],[500,200]],pattern:'triangle'}],
76 [34,'寄往鏡湖的信','同行的夥伴也能穿過月門。把三封信帶回樹根。',[root(500,530,9)],{shadows:2,companions:[[160,220],[840,210],[730,350]],portals:[pair(220,360,790,160)],thorns:[wall(400,270,600,270)],pattern:'banks'}],
77 [35,'所有微光的姓名','退潮時拾光,歸來時帶上等你的四位夥伴。',[root(500,530,12)],{shadows:3,tide:11,wind:'changing',companions:[[170,180],[830,190],[220,350],[780,350]],pattern:'tide'}],
78 [36,'黎明的練習','從霧燈開始,沿風的方向,讓花園慢慢醒來。',[root(250,520,6),root(760,520,6)],{shadows:2,fog:true,lamps:[[200,240],[760,220]],wind:'changing',thorns:[wall(430,240,570,240)],pattern:'ring'}],
79 [37,'夜晚的拼圖','穿過兩對月門,把荊棘與燈光拼成歸途。月門即使能繞行,也需要走過一次。',[root(200,510),root(500,500),root(820,510)],{shadows:2,fog:true,lamps:[[260,230],[750,300]],portals:[pair(150,330,680,180),pair(840,200,330,410)],thorns:[wall(480,170,480,355)],pattern:'banks'}],
80 [38,'等一朵花醒來','風、潮汐與遠方的夥伴,都會等到你。',[root(500,535,12)],{shadows:2,tide:10,wind:'swirl',companions:[[180,210],[830,240],[500,160]],portals:[pair(200,400,770,180)],pattern:'tide'}],
81 [39,'把長夜折成信','帶三位夥伴走出霧,跨過荊棘,把星光送回樹下。',[root(220,520,6),root(780,520,6)],{shadows:3,fog:true,lamps:[[170,240],[520,180],[830,270]],wind:'changing',companions:[[230,160],[760,170],[500,360]],thorns:[wall(360,250,360,410),wall(650,330,650,450)],portals:[pair(150,390,790,200)],pattern:'triangle'}],
82 [40,'你就是那片星空','點亮三盞燈,穿過兩對月門,帶四位夥伴回家。讓四棵樹開花。',[root(160,530),root(380,510),root(640,520),root(850,500)],{shadows:2,fog:true,lamps:[[170,240],[490,160],[820,240]],tide:12,wind:'changing',companions:[[160,160],[830,150],[300,260],[700,250]],portals:[pair(170,390,780,190),pair(830,390,230,190)],thorns:[wall(380,310,570,310),wall(680,360,680,440)],pattern:'tide'}]
83 ];
84 const LEVELS=[{id:0,world:0,title:'夜晚,借你一點光',intro:'序章:先熟悉移動與拾光。每次拾起三粒星光,帶回樹根。送回六粒,讓荒蕪開花。',roots:[root(500,525,6)],shadows:0,pattern:'ring'},...P.map(([id,title,intro,roots,extra])=>({id,world:Math.floor((id-1)/5),title,intro,roots,...extra}))];
85 const poems=[
86 '你拾起的不是露水,\n是夜晚尚未說完的話。','兩岸不再遙遠,\n因為你走過了中間的路。','微光不需要很亮,\n只要照見下一步。','那些未曾寄出的信,\n在枝頭長出了名字。','你替荒原點了一盞燈,\n群星便有了回聲。',
87 '風從你的身邊經過,\n卻把春天留在這裡。','你逆著風走來的樣子,\n是一粒種子最初的勇敢。','兜兜轉轉的風,\n也終於找到了可以停留的枝。','世界輕輕改變方向,\n你仍記得回家的路。','沒有誰能留住風,\n但花園記得你來過。',
88 '一盞燈不必照亮整個夜晚,\n照亮身邊,就已經很好。','隔著霧,你看不見我,\n但我們點著同樣的燈。','風把霧推向遠處,\n你把光帶向歸途。','有人在燈下等候,\n渡口就不會荒蕪。','霧散之後,\n每一道腳印都有了名字。',
89 '不是每一條路都筆直,\n溫柔也可以抵達。','留白不是空無,\n是世界為你留的一扇門。','在生活折起的地方,\n你種下了一朵花。','刺叢仍在,\n但你學會了讓燈先行。','走出迷宮的時候,\n你沒有弄丟心裡的光。',
90 '你以為走向遠方,\n其實是與另一個自己相逢。','每一次重逢,\n都讓夜晚少一分孤單。','河流不說話,\n月亮替它搭了一座橋。','倒影也有歸途,\n就像思念也會抵達。','迴廊的盡頭沒有答案,\n只有一棵為你開花的樹。',
91 '海把珍藏的星光,\n輕輕放回你的手心。','有些等待,\n會長成一片溫柔的海。','風替海寫信,\n你替星光找到歸宿。','月門的另一端,\n也有人在聽潮。','當你願意慢下來,\n就能聽見海的呼吸。',
92 '一封信,終於等到收信的人。\n一粒光,終於不再獨行。','回家的路沒有變短,\n只是從此有人同行。','燈下多了三個影子,\n夜晚少了三份孤獨。','你把很遠的思念,\n送到很近的樹下。','每一粒小小的光,\n都有值得被記住的姓名。',
93 '黎明還沒有到來,\n你已經開始練習盛開。','原來那些散落的夜晚,\n拼起來就是一座花園。','一朵花醒來的時候,\n整個世界都輕了一點。','長夜折成一封信,\n收信人是明天的你。','你曾向夜晚借一粒星光。\n如今,你把一整片星空還給了它。'
94 ];
95 const clamp=(n,a,b)=>Math.max(a,Math.min(b,n));
96 const dist=(a,b)=>Math.hypot(a.x-b.x,a.y-b.y);
97 function segmentDistance(p,w){const dx=w.x2-w.x1,dy=w.y2-w.y1,u=clamp(((p.x-w.x1)*dx+(p.y-w.y1)*dy)/(dx*dx+dy*dy),0,1);return Math.hypot(p.x-w.x1-u*dx,p.y-w.y1-u*dy)}
98 class Game {
99 constructor(level,emit=()=>{},snapshot=null){
100 this.level=level;this.emit=emit;this.seed=level.id*811+2718;this.time=0;this.carry=0;this.hits=0;this.complete=false;this.player={x:500,y:585};this.target={...this.player};this.shield=0;this.cooldown=0;this.invulnerable=0;this.portalCooldown=0;this.portalLatch=false;this.depositWait=0;this.roots=level.roots.map(r=>({...r,received:0}));this.lamps=(level.lamps||[]).map(([x,y])=>({x,y,lit:false}));this.portals=(level.portals||[]).map(points=>({points,used:false}));this.companions=(level.companions||[]).map(([x,y])=>({x,y,status:'waiting'}));this.stars=[];this.assist=false;
101 for(let i=0;i<12;i++)this.stars.push(this.spawnStar(i));
102 if(snapshot){this.restoreFailed=!this.restore(snapshot)}
103 }
104 random(){this.seed=(1664525*this.seed+1013904223)>>>0;return this.seed/4294967296}
105 safe(p){return this.roots.every(r=>dist(p,r)>78)&&(this.level.thorns||[]).every(w=>segmentDistance(p,w)>42)&&this.portals.every(pair=>pair.points.every(q=>dist(p,q)>57))&&this.lamps.every(l=>dist(p,l)>40)}
106 spawnStar(index){
107 let p={x:100,y:180};for(let attempt=0;attempt<250;attempt++){
108 const u=this.random(),v=this.random(),n=index%12;
109 switch(this.level.pattern){
110 case 'banks':p={x:(n%2?610:110)+u*265,y:140+v*310};break;
111 case 'trail':p={x:110+n/11*770+(u-.5)*65,y:270+Math.sin(n*.85+this.level.id)*125+(v-.5)*95};break;
112 case 'triangle':p={x:135+u*730,y:140+v*330};break;
113 case 'tide':p={x:100+u*800,y:220+v*235};break;
114 default:p={x:500+Math.cos(n/12*Math.PI*2+u*.4)*((230+v*120)),y:320+Math.sin(n/12*Math.PI*2+u*.4)*(130+v*45)};
115 }
116 p.x=clamp(p.x,80,920);p.y=clamp(p.y,130,475);
117 if(this.safe(p)&&dist(p,this.player)>105&&this.stars.every(s=>dist(p,s)>42))break;
118 }
119 // A bounded fallback grid guarantees valid, non-overlapping positions.
120 if(!this.safe(p)||dist(p,this.player)<=105||this.stars.some(s=>dist(p,s)<35)){
121 const choices=[];for(let x=85;x<=915;x+=55)for(let y=140;y<=470;y+=55){const q={x,y};if(this.safe(q)&&dist(q,this.player)>105&&this.stars.every(s=>dist(q,s)>40))choices.push(q)}
122 if(choices.length)p=choices[Math.floor(this.random()*choices.length)];
123 }
124 return {...p,phase:this.random()*Math.PI*2,tidal:!!this.level.tide&&index%3!==0};
125 }
126 get required(){return this.roots.reduce((n,r)=>n+r.need,0)}
127 get delivered(){return this.roots.reduce((n,r)=>n+r.received,0)}
128 get ebb(){return !this.level.tide||(this.time%this.level.tide)<this.level.tide*.6}
129 get tideSeconds(){if(!this.level.tide)return 0;const t=this.time%this.level.tide;return Math.ceil((this.ebb?this.level.tide*.6:this.level.tide)-t)}
130 starVisible(s){return !s.tidal||this.ebb}
131 visibleAt(p){return !this.level.fog||dist(p,this.player)<150||this.lamps.some(l=>l.lit&&dist(p,l)<220)||this.roots.some(r=>dist(p,r)<100)}
132 shadows(){return Array.from({length:this.level.shadows||0},(_,i)=>{const t=this.time*(this.assist?.64:1);return {x:500+Math.sin(t*(.22+i*.025)+i*2.31+this.level.id*.24)*(290+i%2*75),y:315+Math.cos(t*(.29+i*.03)+i*2.37)*122}})}
133 wind(){const p=this.level.windPower||1;if(!this.level.wind||this.shield>0)return {x:0,y:0};switch(this.level.wind){case 'east':return{x:49*p,y:8*Math.sin(this.time)};case 'west':return{x:-49*p,y:8*Math.cos(this.time)};case 'changing':return{x:Math.sin(this.time*.45)*70*p,y:Math.cos(this.time*.31)*25*p};default:{const dx=this.player.x-500,dy=this.player.y-330,d=Math.max(60,Math.hypot(dx,dy));return{x:-dy/d*65*p,y:dx/d*47*p}}}}
134 pulse(){if(this.complete||this.cooldown>0)return false;this.shield=2.8;this.cooldown=8;this.emit('pulse',{...this.player});return true}
135 hurt(reason){if(this.invulnerable>0||this.shield>0||this.complete)return;this.hits++;const lost=this.carry>0;if(lost)this.carry--;this.invulnerable=2.5;this.emit('hurt',{reason,lost,...this.player})}
136 step(dt,input={x:0,y:0}){
137 if(this.complete)return;dt=clamp(dt,0,.05);this.time+=dt;
138 for(const k of ['shield','cooldown','invulnerable','portalCooldown','depositWait'])this[k]=Math.max(0,this[k]-dt);
139 let mx=0,my=0;const speed=(this.assist?260:225)*(this.level.tide&&!this.ebb&&this.player.y>310?.76:1);
140 if(input.x||input.y){const n=Math.hypot(input.x,input.y);mx=input.x/n*speed*dt;my=input.y/n*speed*dt;this.target={x:this.player.x+mx,y:this.player.y+my}}
141 else{const dx=this.target.x-this.player.x,dy=this.target.y-this.player.y,d=Math.hypot(dx,dy),f=Math.min(1,speed*dt/Math.max(1,d));mx=dx*f;my=dy*f}
142 const wind=this.wind();mx+=wind.x*dt;my+=wind.y*dt;
143 // Axis-separated collision permits sliding along a thorn instead of getting stuck.
144 for(const [axis,delta] of [['x',mx],['y',my]]){const p={...this.player,[axis]:clamp(this.player[axis]+delta,axis==='x'?35:100,axis==='x'?965:607)};if((this.level.thorns||[]).some(w=>segmentDistance(p,w)<19)){this.hurt('thorns')}else this.player=p}
145 for(const l of this.lamps)if(!l.lit&&dist(l,this.player)<37){l.lit=true;this.emit('lamp',l)}
146 if(this.portals.every(p=>p.points.every(q=>dist(q,this.player)>48)))this.portalLatch=false;
147 if(!this.portalLatch&&this.portalCooldown===0){for(let i=0;i<this.portals.length;i++){const p=this.portals[i],end=p.points.findIndex(q=>dist(q,this.player)<28);if(end>=0){const dest=p.points[1-end];this.player={...dest};this.target={...dest};p.used=true;this.portalLatch=true;this.portalCooldown=1.4;this.invulnerable=Math.max(this.invulnerable,1.2);this.companions.filter(c=>c.status==='following').forEach((c,j)=>{c.x=dest.x+(j?18:-18);c.y=dest.y+28});this.emit('portal',{...dest,index:i});break}}}
148 for(let i=0;i<this.stars.length;i++){const s=this.stars[i];if(this.carry<3&&this.starVisible(s)&&dist(s,this.player)<25){this.carry++;this.emit('collect',s);this.stars.splice(i,1);this.stars.splice(i,0,this.spawnStar(i));}}
149 let following=this.companions.filter(c=>c.status==='following').length;
150 for(const c of this.companions){if(c.status==='waiting'&&following<2&&dist(c,this.player)<38){c.status='following';following++;this.emit('friend',c)}if(c.status==='following'){
151 const d=dist(c,this.player);if(d>20){const f=Math.min(1,(this.assist?225:193)*dt/Math.max(1,d));const next={x:c.x+(this.player.x-c.x)*f,y:c.y+(this.player.y-c.y)*f};
152 // Companions are wisps: they can follow through foliage and never become trapped.
153 c.x=next.x;c.y=next.y;}
154 const home=this.roots.find(r=>dist(r,this.player)<58&&dist(r,c)<62);if(home){c.status='home';c.x=home.x+((this.companions.indexOf(c)%3)-1)*22;c.y=home.y-25;this.emit('home',c)}
155 }}
156 if(this.carry===3&&this.depositWait===0){const r=this.roots.find(r=>r.received<r.need&&dist(r,this.player)<42);if(r){r.received+=3;this.carry=0;this.depositWait=.8;this.emit('deposit',r)}}
157 for(const s of this.shadows())if(dist(s,this.player)<29)this.hurt('shadow');
158 if(this.delivered===this.required&&this.lamps.every(l=>l.lit)&&this.portals.every(p=>p.used)&&this.companions.every(c=>c.status==='home')){this.complete=true;this.emit('complete',{rating:this.hits===0?3:this.hits<=3?2:1})}
159 }
160 snapshot(){const keys=['time','seed','carry','hits','player','target','roots','lamps','portals','companions','stars','shield','cooldown','invulnerable','portalCooldown','portalLatch','depositWait'];return JSON.parse(JSON.stringify(Object.fromEntries([['levelId',this.level.id],...keys.map(k=>[k,this[k]])])))}
161 restore(s){
162 if(!s||s.levelId!==this.level.id)return false;
163 const position=p=>p&&Number.isFinite(p.x)&&Number.isFinite(p.y)&&p.x>=0&&p.x<=1000&&p.y>=0&&p.y<=640;
164 if(!position(s.player)||!position(s.target)||!Number.isInteger(s.carry)||s.carry<0||s.carry>3||!Number.isInteger(s.hits)||s.hits<0||!Number.isFinite(s.time)||s.time<0||!Number.isInteger(s.seed)||s.seed<0)return false;
165 if(!Array.isArray(s.roots)||s.roots.length!==this.roots.length||!s.roots.every((r,i)=>Number.isInteger(r.received)&&r.received>=0&&r.received<=this.roots[i].need&&r.received%3===0))return false;
166 if(!Array.isArray(s.lamps)||s.lamps.length!==this.lamps.length||!s.lamps.every(l=>typeof l.lit==='boolean'))return false;
167 if(!Array.isArray(s.portals)||s.portals.length!==this.portals.length||!s.portals.every(p=>typeof p.used==='boolean'))return false;
168 if(!Array.isArray(s.companions)||s.companions.length!==this.companions.length||!s.companions.every(c=>position(c)&&['waiting','following','home'].includes(c.status)))return false;
169 if(!Array.isArray(s.stars)||s.stars.length!==12||!s.stars.every(p=>position(p)&&Number.isFinite(p.phase)&&typeof p.tidal==='boolean'&&this.safe(p)))return false;
170 const timers=['shield','cooldown','invulnerable','portalCooldown','depositWait'];if(!timers.every(k=>Number.isFinite(s[k])&&s[k]>=0&&s[k]<=8)||typeof s.portalLatch!=='boolean')return false;
171 for(const k of ['time','seed','carry','hits',...timers,'portalLatch'])this[k]=s[k];this.player={...s.player};this.target={...s.target};this.roots.forEach((r,i)=>r.received=s.roots[i].received);this.lamps.forEach((l,i)=>l.lit=s.lamps[i].lit);this.portals.forEach((p,i)=>p.used=s.portals[i].used);this.companions=s.companions.map(c=>({...c}));this.stars=s.stars.map(p=>({...p}));return true;
172 }
173 }
174 return {WORLDS,LEVELS,poems,Game,dist,segmentDistance,clamp};
175})();
176if(typeof module!=='undefined'&&module.exports)module.exports=NightGarden;
178</script>
179<script>
180/* Original, locally synthesized ambient score. No downloads or network playback. */
181class NightMusic {
182 constructor(context){
183 this.context=context;this.playing=false;this.timer=null;this.step=0;this.nextTime=0;this.world=0;this.volume=.42;this.voices=new Set();this.ending=false;this.breeze=null;this.windBuffer=null;
184 const a=context;this.master=a.createGain();this.master.gain.value=0;this.master.connect(a.destination);
185 this.score=a.createGain();this.score.gain.value=1;this.score.connect(this.master);
186 this.dry=a.createGain();this.dry.gain.value=.8;this.dry.connect(this.score);
187 this.reverb=a.createConvolver();this.wet=a.createGain();this.wet.gain.value=.28;this.reverb.connect(this.wet);this.wet.connect(this.score);
188 const length=Math.ceil(a.sampleRate*2.8),impulse=a.createBuffer(2,length,a.sampleRate);let seed=7321;
189 for(let c=0;c<2;c++){const channel=impulse.getChannelData(c);for(let i=0;i<length;i++){seed=(1664525*seed+1013904223)>>>0;channel[i]=(seed/4294967296*2-1)*Math.pow(1-i/length,3.1)*.5}}
190 this.reverb.buffer=impulse;
191 }
192 setVolume(value){this.volume=Math.max(0,Math.min(1,value));if(this.playing)this.master.gain.setTargetAtTime(this.volume,this.context.currentTime,.12)}
193 setWorld(world){this.world=Math.max(0,Math.min(7,world))}
194 setEnding(enabled){
195 enabled=!!enabled;if(this.ending===enabled)return;
196 this.ending=enabled;const now=this.context.currentTime;
197 this.score.gain.cancelScheduledValues(now);this.score.gain.setTargetAtTime(enabled?0:1,now,.55);
198 if(enabled&&this.playing)this.startWind();else if(!enabled)this.stopWind();
199 }
200 startWind(){
201 if(this.breeze)return;
202 const a=this.context,now=a.currentTime;
203 if(!this.windBuffer){
204 const length=Math.ceil(a.sampleRate*16);
205 // Two gentle smoothing stages soften the noise before the wind filters.
206 const smoothing=1-Math.exp(-2*Math.PI*900/a.sampleRate);
207 this.windBuffer=a.createBuffer(2,length,a.sampleRate);let seed=19073;
208 for(let c=0;c<2;c++){
209 const channel=this.windBuffer.getChannelData(c);let smooth=0,soft=0;
210 for(let i=0;i<length;i++){
211 seed=(1664525*seed+1013904223)>>>0;
212 channel[i]=seed/4294967296*2-1;
213 }
214 // Warm up on the same noise cycle so the loop has no gap or gain dip.
215 for(let pass=0;pass<2;pass++)for(let i=0;i<length;i++){
216 smooth+=smoothing*(channel[i]-smooth);
217 soft+=smoothing*(smooth-soft);
218 if(pass===1)channel[i]=soft*1.8;
219 }
220 }
221 }
222 const source=a.createBufferSource(),highpass=a.createBiquadFilter(),lowpass=a.createBiquadFilter();
223 const gust=a.createGain(),fade=a.createGain(),lfo=a.createOscillator(),depth=a.createGain(),cutoffDepth=a.createGain();
224 source.buffer=this.windBuffer;source.loop=true;
225 highpass.type='highpass';highpass.frequency.value=180;highpass.Q.value=.35;
226 lowpass.type='lowpass';lowpass.frequency.value=650;lowpass.Q.value=.35;
227 gust.gain.value=.075;depth.gain.value=.008;cutoffDepth.gain.value=40;
228 lfo.type='sine';lfo.frequency.value=.035;
229 source.connect(highpass);highpass.connect(lowpass);lowpass.connect(gust);gust.connect(fade);fade.connect(this.master);
230 lfo.connect(depth);depth.connect(gust.gain);lfo.connect(cutoffDepth);cutoffDepth.connect(lowpass.frequency);
231 fade.gain.setValueAtTime(0,now);fade.gain.setTargetAtTime(1,now,1.2);
232 const nodes={source,highpass,lowpass,gust,fade,lfo,depth,cutoffDepth};this.breeze=nodes;
233 source.onended=()=>{for(const node of Object.values(nodes))node.disconnect()};
234 source.start(now);lfo.start(now);
235 }
236 stopWind(){
237 const nodes=this.breeze;if(!nodes)return;this.breeze=null;
238 const now=this.context.currentTime;nodes.fade.gain.cancelScheduledValues(now);nodes.fade.gain.setTargetAtTime(0,now,.035);
239 nodes.source.stop(now+.18);nodes.lfo.stop(now+.18);
240 }
241 tone(midi,time,duration,gain,kind='bell'){
242 const a=this.context,o=a.createOscillator(),g=a.createGain(),filter=a.createBiquadFilter();o.type=kind==='pad'?'triangle':'sine';o.frequency.value=440*Math.pow(2,(midi-69)/12);filter.type='lowpass';filter.frequency.value=kind==='pad'?650:2600;filter.Q.value=.35;
243 const attack=kind==='pad'?.9:.018;g.gain.setValueAtTime(0,time);g.gain.linearRampToValueAtTime(gain,time+attack);g.gain.exponentialRampToValueAtTime(.0001,time+duration);
244 o.connect(filter);filter.connect(g);g.connect(this.dry);g.connect(this.reverb);this.voices.add(o);o.onended=()=>{this.voices.delete(o);o.disconnect();filter.disconnect();g.disconnect()};o.start(time);o.stop(time+duration+.05);
245 }
246 schedule(){
247 if(!this.playing||this.ending||this.context.state!=='running')return;
248 const a=this.context;if(this.nextTime<a.currentTime-.15)this.nextTime=a.currentTime+.05;
249 const chords=[[48,55,59,64],[45,52,55,60],[41,48,55,57],[43,50,55,60],[38,45,53,57],[40,47,55,59],[41,48,52,57],[43,50,55,62]];
250 const melody=[72,null,76,null,79,76,null,74,72,null,69,null,67,null,null,null,69,null,72,null,76,74,72,null,74,null,79,null,77,74,null,null,74,null,77,null,81,77,76,null,76,null,79,null,83,null,79,null,81,null,79,76,77,null,76,null,74,null,71,null,67,null,null,null];
251 const transpose=[0,2,-2,-3,4,0,2,5][this.world],eighth=60/64/2;
252 while(this.nextTime<a.currentTime+.24){const slot=this.step%64,bar=Math.floor(slot/8),chord=chords[bar],at=this.nextTime;
253 if(slot%8===0){chord.forEach((n,i)=>this.tone(n+transpose,at+i*.025,5.1,i===0?.029:.016,'pad'));this.tone(chord[0]-12+transpose,at,3.1,.027)}
254 if(slot%2===0)this.tone(chord[(slot/2)%4]+12+transpose,at,1.9,.029);
255 if(melody[slot]!==null)this.tone(melody[slot]+transpose,at+.025,2.6,slot%8===0?.051:.039);
256 this.step++;this.nextTime+=eighth;
257 }
258 }
259 start(){if(this.playing)return;this.playing=true;this.nextTime=this.context.currentTime+.045;this.master.gain.cancelScheduledValues(this.context.currentTime);this.master.gain.setTargetAtTime(this.volume,this.context.currentTime,.3);if(this.ending)this.startWind();this.schedule();this.timer=setInterval(()=>this.schedule(),100)}
260 stop(){if(this.timer!==null){clearInterval(this.timer);this.timer=null}this.playing=false;this.stopWind();const now=this.context.currentTime;this.master.gain.cancelScheduledValues(now);this.master.gain.setTargetAtTime(0,now,.035);for(const voice of this.voices){try{voice.stop(now+.17)}catch(e){}}}
262if(typeof module!=='undefined'&&module.exports)module.exports=NightMusic;
264(() => {
265 'use strict';
266 const {Game,LEVELS,WORLDS,poems,clamp}=NightGarden;
267 const $=id=>document.getElementById(id),canvas=$('garden'),ctx=canvas.getContext('2d');
268 const fogCanvas=document.createElement('canvas'),fogCtx=fogCanvas.getContext('2d');
269 const SAVE_KEY='borrowed-light-campaign-v2';
270 let save={version:2,active:1,completed:{},snapshots:{},settings:{sound:false,music:true,musicVolume:.42,assist:false,motion:matchMedia('(prefers-reduced-motion: reduce)').matches}};
271 let storageOK=true,saveNotice='',running=false,game,activeDialog='welcome',mapReturn='welcome',W=1000,H=640,dpr=1,sx=1,sy=1,visualScale=1,last=0,clock=0,endDelay=0,saveTimer=0,dirty=false,particles=[],trail=[],petals=[],petalTime=0,petalSpawn=0,audio=null,music=null,audioReady=false,audioPending=false,trees=[],lastUI='',lastPulse='',keys=new Set();
272 try{
273 const raw=localStorage.getItem(SAVE_KEY);if(raw){const data=JSON.parse(raw);
274 if(data.version===2&&data.completed&&typeof data.completed==='object'){
275 for(let i=0;i<=40;i++){const r=data.completed[i];if(r&&Number.isInteger(r.rating)&&r.rating>=1&&r.rating<=3&&Number.isInteger(r.hits)&&r.hits>=0)save.completed[i]={rating:r.rating,hits:r.hits};}
276 if(data.settings)for(const key of ['sound','music','assist','motion'])if(typeof data.settings[key]==='boolean')save.settings[key]=data.settings[key];
277 if(Number.isFinite(data.settings?.musicVolume))save.settings.musicVolume=clamp(data.settings.musicVolume,0,1);
278 if(data.snapshots&&typeof data.snapshots==='object')for(let i=0;i<=40;i++)if(data.snapshots[i]){const trial=new Game(LEVELS[i]);if(trial.restore(data.snapshots[i]))save.snapshots[i]=trial.snapshot()}
279 if(Number.isInteger(data.active)&&data.active>=0&&data.active<=unlocked())save.active=data.active;
280 }else saveNotice='舊存檔格式不適用,已開始新的旅程。';
281 }
282 }catch(e){storageOK=false;saveNotice='本機存檔暫不可用;請保持頁面打開。'}
283 function unlocked(){let n=1;while(n<40&&save.completed[n])n++;return n}
284 function persist(){if(!game)return;if(!game.complete&&running)save.snapshots[game.level.id]=game.snapshot();save.active=game.level.id;try{localStorage.setItem(SAVE_KEY,JSON.stringify(save));storageOK=true;$('save-status').textContent='已保存 · 當前瀏覽器';$('pause-save').textContent='進度已保存在當前瀏覽器;下次打開可繼續。'}catch(e){storageOK=false;$('save-status').textContent='存檔不可用 · 請保持頁面打開';$('pause-save').textContent='當前瀏覽器無法保存;關閉頁面會丟失進度。'}dirty=false;saveTimer=0}
285 function stash(){if(game&&!game.complete)save.snapshots[game.level.id]=game.snapshot();persist()}
286 function getAudio(){audio=audio||new(window.AudioContext||window.webkitAudioContext)();return audio}
287 function audioFailure(){audioReady=false;audioPending=false;if(music)music.stop();$('sound').textContent='音樂 · 重試';$('sound').setAttribute('aria-pressed','false');message('聲音暫未啟動,點擊「音樂 · 重試」再試一次。')}
288 function syncMusic(){if(!music)return;music.setWorld(game?.level.world||0);music.setEnding(!!game?.complete);music.setVolume(save.settings.musicVolume);if(audioReady&&save.settings.music&&(running||(game?.complete&&activeDialog==='result'))&&!document.hidden)music.start();else music.stop()}
289 function unlockAudio(){if(!save.settings.music&&!save.settings.sound)return;try{const a=getAudio();if(!music)music=new NightMusic(a);if(a.state==='running'){audioReady=true;syncMusic();return}if(audioPending)return;audioPending=true;a.resume().then(()=>{audioPending=false;audioReady=a.state==='running';if(audioReady)syncMusic();else audioFailure()}).catch(audioFailure)}catch(e){audioFailure()}}
290 function note(n,long=false){if(!save.settings.sound||document.hidden)return;try{const a=getAudio();if(a.state!=='running')return;const now=a.currentTime,o=a.createOscillator(),g=a.createGain();o.type='sine';o.frequency.value=[261.63,293.66,329.63,392,440,523.25,587.33,659.25][n%8];g.gain.setValueAtTime(0,now);g.gain.linearRampToValueAtTime(.055,now+.025);g.gain.exponentialRampToValueAtTime(.0001,now+(long?2.7:1.25));o.connect(g);g.connect(a.destination);o.onended=()=>{o.disconnect();g.disconnect()};o.start();o.stop(now+(long?2.8:1.3))}catch(e){audioFailure()}}
291 function message(text){$('message').textContent=text}
292 function burst(p,color,n=16){if(save.settings.motion)return;for(let i=0;i<n;i++)particles.push({x:p.x,y:p.y,vx:(Math.random()-.5)*110,vy:-Math.random()*80,life:1+Math.random(),color});if(particles.length>220)particles.splice(0,particles.length-220)}
293 function spawnPetal(){
294 if(petals.length>=84||!trees.length)return;
295 const index=Math.floor(Math.random()*trees.length),tree=trees[index],root=game.roots[index];
296 const leaf=tree.leaves[Math.floor(Math.random()*tree.leaves.length)],unit=fringeTreeUnit();
297 petals.push({x:root.x+leaf.x*unit/sx+(Math.random()-.5)*9,y:root.y+leaf.y*unit/sy,
298 size:4.5+Math.random()*3.2,angle:Math.random()*Math.PI*2,spin:(Math.random()-.5)*1.7,
299 phase:Math.random()*Math.PI*2,speed:12+Math.random()*13,age:0,life:22+Math.random()*10,
300 color:Math.random()<.5?'#f8f8ee':'#e8eede'});
301 }
302 function startPetals(){
303 petals=[];petalTime=0;petalSpawn=0;
304 if(save.settings.motion)return;
305 for(let i=0;i<Math.min(36,18+game.roots.length*5);i++)spawnPetal();
306 }
307 function updatePetals(dt){
308 petalTime+=dt;
309 const direction=game.level.wind==='west'?-1:1;
310 const breeze=direction*(14+Math.sin(petalTime*.24)*10);
311 for(const p of petals){
312 p.age+=dt;p.x+=(breeze+Math.sin(petalTime*.75+p.phase)*10)*dt;
313 p.y+=p.speed*(.85+Math.sin(petalTime*1.15+p.phase)*.15)*dt;
314 p.angle+=(p.spin+Math.sin(petalTime*.6+p.phase)*.25)*dt;
315 }
316 petals=petals.filter(p=>p.age<p.life&&p.y<660&&p.x>-35&&p.x<1035);
317 petalSpawn+=dt*(game.level.id===40?7:5);
318 while(petalSpawn>=1){spawnPetal();petalSpawn--}
319 }
320 function drawPetals(){
321 if(!game.complete||save.settings.motion)return;
322 for(const p of petals){
323 const fadeIn=Math.min(1,p.age/.65),fadeOut=Math.min(1,(p.life-p.age)/3);
324 const r=clamp(p.size*sx*visualScale,2.4,7.5);
325 ctx.save();ctx.translate(p.x,p.y);ctx.scale(1/sx,1/sy);ctx.rotate(p.angle);
326 ctx.scale(.3+Math.abs(Math.cos(p.angle*.8))*.7,1);
327 ctx.globalAlpha=fadeIn*fadeOut*.82;ctx.fillStyle=p.color;
328 ctx.beginPath();ctx.moveTo(0,-r);
329 ctx.bezierCurveTo(r*.2,-r*.45,r*.32,r*.65,r*.12,r);
330 ctx.bezierCurveTo(-r*.12,r*.55,-r*.15,-r*.65,0,-r);
331 ctx.fill();ctx.strokeStyle='#ffffff66';ctx.lineWidth=.35;
332 ctx.beginPath();ctx.moveTo(0,-r*.65);ctx.quadraticCurveTo(r*.18,0,0,r*.6);ctx.stroke();ctx.restore();
333 }
334 }
335 function onEvent(type,p){dirty=true;const color='#f2f3e5';
336 if(type==='collect'){burst(p,'#ead29c',10);note(game.carry+game.delivered);message(game.carry===3?'懷裡裝滿了星光,回到還沒種亮的樹根吧。':`拾起了 ${game.carry} 粒光,帶滿三粒就可以回家。`)}
337 if(type==='hurt'){burst(p,'#acc5d5',14);message(p.lost?'風吹散了一粒光。沒關係,已經種下的光還在。':'輕輕繞過'+(p.reason==='thorns'?'荊棘,留白處可以通行。':'墨影;空格可以短暫護住自己。'))}
338 if(type==='pulse'){burst(p,'#d8e4cf',22);note(4);message('屏住呼吸,讓風與墨影從身邊經過。荊棘仍需繞行。')}
339 if(type==='deposit'){burst(p,color,40);note(2+game.delivered/3,true);message(game.delivered===game.required?'樹已經種亮了,再看看本關還有哪些約定沒有完成。':'一段樹枝醒來了。下一粒光,會在哪裡?')}
340 if(type==='lamp'){burst(p,'#ead3a0',22);note(5);message('燈亮了。它會替你記住這條路。')}
341 if(type==='portal'){burst(p,'#c8bde7',27);note(6);message('月亮替你摺疊了距離。同行的夥伴也到了。')}
342 if(type==='friend'){burst(p,'#dce5b0',15);note(4);message('一位夥伴跟上了你,帶它回到任意樹根。一次最多同行兩位。')}
343 if(type==='home'){burst(p,'#e8cf95',25);note(5,true);message('夥伴到家了。這個夜晚,少了一份孤單。')}
344 if(type==='complete'){
345 const id=game.level.id,old=save.completed[id];if(!old||p.rating>old.rating||(p.rating===old.rating&&game.hits<old.hits))save.completed[id]={rating:p.rating,hits:game.hits};delete save.snapshots[id];persist();endDelay=3.6;startPetals();syncSettings();syncMusic();burst({x:500,y:300},color,85);note(7,true);message(id===40?'你向夜晚借來的光,已經長成了一整片星空。':'這一夜,被你種亮了。');
346 }
347 }
348 function fringeTreeUnit(){return clamp(sx*1.1,.5,1.05)}
349 function makeTree(seed){
350 const out=[],leaves=[];let rng=seed+41;
351 const rand=()=>{rng=(rng*1664525+1013904223)>>>0;return rng/4294967296};
352 function branch(x,y,len,angle,depth){
353 const ex=x+Math.cos(angle)*len,ey=y+Math.sin(angle)*len;
354 out.push({x,y,ex,ey,depth,bend:(rand()-.5)*9});
355 if(depth===4){
356 const leaf={x:ex,y:ey,phase:rand()*6.28,order:rand(),foliage:[],flowers:[],art:{}};
357 for(let j=0;j<4;j++)leaf.foliage.push({x:(rand()-.5)*25,y:(rand()-.5)*15+5,angle:(rand()-.5)*2.8,size:7+rand()*5});
358 for(let j=0;j<5;j++)leaf.flowers.push({x:(rand()-.5)*28,y:(rand()-.5)*21,angle:(rand()-.5)*1.2,length:8+rand()*6,bend:(rand()-.5)*4});
359 leaves.push(leaf);return;
360 }
361 if(depth===0){for(const delta of [-.64,.05,.69])branch(ex,ey,34+rand()*6,angle+delta,1)}
362 else{const spread=.42+rand()*.17;branch(ex,ey,len*.7,angle-spread,depth+1);branch(ex,ey,len*.7,angle+spread,depth+1)}
363 }
364 branch(0,0,46,-Math.PI/2+(rand()-.5)*.08,0);
365 const inner=out.filter(b=>b.depth===3);
366 inner.forEach((b,i)=>leaves.unshift({...leaves[leaves.length-1-i],x:b.ex,y:b.ey-4}));
367 return {out,leaves};
368 }
369 function loadLevel(id,resume=true){if(id<0||id>40||id>unlocked())return;game=new Game(LEVELS[id],onEvent,resume?save.snapshots[id]:null);game.assist=save.settings.assist;if(game.restoreFailed){delete save.snapshots[id];const note='先前的進度與此版本略有不同,這一夜將重新開始。已完成的夜晚仍會保留。';saveNotice=saveNotice||note;try{localStorage.setItem(SAVE_KEY,JSON.stringify(save))}catch(e){}}save.active=id;particles=[];trail=[];petals=[];petalTime=0;petalSpawn=0;endDelay=0;keys.clear();lastUI='';trees=game.roots.map((_,i)=>makeTree(id*53+i*31));document.documentElement.style.setProperty('--gold',WORLDS[game.level.world].color);$('level-title').textContent=game.level.title;$('level-intro').textContent=game.level.intro;$('eyebrow').textContent=id?`${WORLDS[game.level.world].name} · 第 ${String(id).padStart(2,'0')} / 40 夜`:'序章 · 夜的植物誌';$('required').textContent='/ '+game.required;$('progress').setAttribute('aria-valuemax',String(game.required));message(game.restoreFailed?(saveNotice||game.level.intro):(save.snapshots[id]?.time>0.5&&resume?'你離開時的光還在。沿著上次的腳步繼續吧。':game.level.intro));updateUI();}
370 const dialogs=['welcome','map-dialog','briefing','pause-dialog','result'];
371 function showDialog(id){running=false;keys.clear();dialogs.forEach(d=>$(d).hidden=d!==id);activeDialog=id;$('app').inert=!!id;if(id){const focus=$(id).querySelector('button:not(:disabled)');if(focus)focus.focus()}else{running=true;canvas.focus();unlockAudio()}syncMusic()}
372 function chooseLevel(id){if(id>unlocked())return;stash();loadLevel(id);$('brief-label').textContent=id?`第 ${id} 夜 · ${WORLDS[game.level.world].name}`:'序章 · 原來的故事';$('brief-mark').textContent=WORLDS[game.level.world].mark;$('brief-title').textContent=game.level.title;$('brief-text').textContent=game.level.intro;showDialog('briefing');persist()}
373 function renderMap(){const completed=Object.keys(save.completed).filter(k=>Number(k)>0).length;$('map-count').textContent=completed;const container=$('chapters');container.replaceChildren();WORLDS.forEach((world,wi)=>{const section=document.createElement('section');section.className='map-chapter';section.style.setProperty('--chapter',world.color);const heading=document.createElement('div');heading.className='chapter-title';const mark=document.createElement('span');mark.className='chapter-mark';mark.textContent=world.mark;const h=document.createElement('h3');h.textContent=`${['一','二','三','四','五','六','七','八'][wi]} · ${world.name}`;const desc=document.createElement('p');desc.textContent=world.subtitle;heading.append(mark,h,desc);section.append(heading);const grid=document.createElement('div');grid.className='level-grid';LEVELS.slice(wi*5+1,wi*5+6).forEach(level=>{const b=document.createElement('button'),record=save.completed[level.id],locked=level.id>unlocked();b.className='level-tile'+(game.level.id===level.id?' current':'');b.disabled=locked;b.setAttribute('aria-label',`第 ${level.id} 夜 ${level.title},${locked?'未解鎖':record?`已完成,${record.rating} 枚花印`:save.snapshots[level.id]?'繼續旅程':'可以開始'}`);const num=document.createElement('span');num.className='tile-no';num.textContent=String(level.id).padStart(2,'0');const name=document.createElement('span');name.className='tile-name';name.textContent=level.title;const state=document.createElement('span');state.className=record?'tile-stars':'tile-lock';state.textContent=record?'✦'.repeat(record.rating)+'·'.repeat(3-record.rating):locked?'待前夜開花':save.snapshots[level.id]?'繼續 →':'出發 →';b.append(num,name,state);b.onclick=()=>chooseLevel(level.id);grid.append(b)});section.append(grid);container.append(section)})}
374 function openMap(){stash();mapReturn=activeDialog;renderMap();showDialog('map-dialog');requestAnimationFrame(updateMapHint)}
375 function showResult(){const id=game.level.id,record=save.completed[id];$('result-label').textContent=id===40?'四十夜 · 屬於你的花園':id?`第 ${id} 夜 · ${WORLDS[game.level.world].name}`:'序章完成 · 四十夜的旅途即將開始';$('result-title').textContent=id===40?'你就是那片星空':'這一夜,被你種亮了';$('poem').textContent=id?poems[id-1]:'那些被你拾起的微光,\n終於有了可以停留的枝頭。';const rating=game.hits===0?3:game.hits<=3?2:1;$('rating').textContent='✦'.repeat(rating)+'·'.repeat(3-rating);$('rating').setAttribute('aria-label',`${rating} 枚花印`);$('result-meta').textContent=`送回 ${game.required} 粒光 · ${game.hits} 次碰撞 · 最佳 ${record.rating} 枚花印`;$('next-level').textContent=id===40?'回望四十夜':'走向第 '+(id+1)+' 夜';showDialog('result')}
376 function updateUI(){const signature=JSON.stringify([game.delivered,game.carry,game.lamps.map(l=>l.lit),game.portals.map(p=>p.used),game.companions.map(c=>c.status),game.complete]);if(signature!==lastUI){lastUI=signature;$('delivered').textContent=game.delivered;$('progress-fill').style.width=(game.delivered/game.required*100)+'%';$('progress').setAttribute('aria-valuenow',String(game.delivered));[...$('pocket').children].forEach((n,i)=>n.classList.toggle('on',i<game.carry));$('pocket').setAttribute('aria-label',`攜帶星光 ${game.carry} / 3`);$('pocket-label').textContent=`${game.carry} / 3 · 攜帶中`;const goals=[['星光',game.delivered,game.required],['樹',game.roots.filter(r=>r.received===r.need).length,game.roots.length]];if(game.lamps.length)goals.push(['燈',game.lamps.filter(l=>l.lit).length,game.lamps.length]);if(game.portals.length)goals.push(['月門',game.portals.filter(p=>p.used).length,game.portals.length]);if(game.companions.length)goals.push(['夥伴',game.companions.filter(c=>c.status==='home').length,game.companions.length]);$('objectives').replaceChildren(...goals.map(([label,n,all])=>{const el=document.createElement('span');el.className='objective'+(n===all?' done':'');el.textContent=`${n===all?'✓ ':''}${label} ${n} / ${all}`;if(label==='月門')el.title='月門需要走過一次,才算完成';return el}));const hint=$('goal-hint');if(hint){const extras=[];if(game.lamps.length)extras.push('燈');if(game.portals.length)extras.push('月門');if(game.companions.length)extras.push('夥伴');hint.textContent=game.complete?'這一夜的目標都完成了。':(extras.length?`還要完成:${extras.join('、')}。全部完成,這一夜才算種亮。`:'送滿星光,讓樹開花。');hint.hidden=false}}
377 const pulseState=game.complete?'花已開':game.shield>0?'護光中':game.cooldown>0?`${Math.ceil(game.cooldown)} 秒`:'屏息';if(lastPulse!==pulseState){lastPulse=pulseState;updateSoundLabel();$('pulse-label').textContent=pulseState;$('pulse').disabled=game.cooldown>0||game.complete}
378 const weather=[];if(game.level.tide)weather.push(`${game.ebb?'退潮 · 拾光':'漲潮 · 等候'} ${game.tideSeconds}s`);if(game.level.wind)weather.push({east:'風向 →',west:'風向 ←',swirl:'迴旋的風',changing:'風向漸變'}[game.level.wind]);if(!weather.length)weather.push('無須趕路');const text=weather.join(' · ');if($('weather').textContent!==text)$('weather').textContent=text;
379 }
380 function isTouchLayout(){return matchMedia('(max-width:700px), (pointer:coarse)').matches}function updateControlHint(){const el=$('control-hint');if(!el)return;el.textContent=isTouchLayout()?'用手指在夜色裡拖動來移動。點「屏息」可短暫護光。':'滑鼠移動、方向鍵或 W A S D 移動 · 空白鍵護光 · Esc 暫停'}function updateMapHint(){const hint=$('map-scroll-hint'),panel=document.querySelector('#map-dialog .map-panel');if(!hint||!panel)return;const more=panel.scrollHeight>panel.clientHeight+16;hint.hidden=!more}function resize(){W=canvas.clientWidth;H=canvas.clientHeight;dpr=Math.min(devicePixelRatio||1,2);sx=W/1000;sy=H/640;visualScale=clamp(1/Math.min(sx,sy),.85,2.2);canvas.width=Math.round(W*dpr);canvas.height=Math.round(H*dpr);fogCanvas.width=canvas.width;fogCanvas.height=canvas.height;updateControlHint();updateMapHint()}
381 new ResizeObserver(resize).observe(canvas);resize();
382 const circle=(x,y,r)=>{ctx.beginPath();ctx.ellipse(x,y,r,r*sx/sy,0,0,Math.PI*2)};
383 function glow(x,y,r,color){ctx.save();ctx.translate(x,y);ctx.scale(1,sx/sy);const g=ctx.createRadialGradient(0,0,0,0,0,r);g.addColorStop(0,color);g.addColorStop(1,'transparent');ctx.fillStyle=g;ctx.fillRect(-r,-r,r*2,r*2);ctx.restore()}
384 function label(text,x,y,color='#bfcdbb',size=11){ctx.save();ctx.translate(x,y);ctx.scale(1/sx,1/sy);ctx.font=`${size}px 'Songti TC','Songti SC','Noto Serif CJK TC','Noto Serif CJK SC',Georgia,serif`;ctx.textAlign='center';ctx.fillStyle=color;ctx.fillText(text,0,0);ctx.restore()}
385 function drawBackground(world,t){const bg=ctx.createLinearGradient(0,0,0,640);bg.addColorStop(0,world.sky[0]);bg.addColorStop(.68,world.sky[1]);bg.addColorStop(1,'#0d242b');ctx.fillStyle=bg;ctx.fillRect(0,0,1000,640);
386 for(let i=0;i<90;i++){const x=((i*137.508)%997),y=(i*i*37%503)*.78;ctx.globalAlpha=.18+(save.settings.motion?.2:(Math.sin(t*.35+i)+1)*.16);ctx.fillStyle='#dce6d6';circle(x,y,(i%5===0?1.4:.65)*visualScale);ctx.fill()}ctx.globalAlpha=1;
387 let moonX=810,moonY=118;glow(moonX,moonY,95,world.color+'19');ctx.fillStyle='#e5dec0';circle(moonX,moonY,26);ctx.fill();ctx.save();ctx.clip();ctx.fillStyle=world.sky[0];circle(moonX-10-game.level.world*1.6,moonY-6,23);ctx.fill();ctx.restore();
388 for(let layer=0;layer<4;layer++){ctx.beginPath();ctx.moveTo(0,640);for(let x=0;x<=1010;x+=10){const y=365+layer*54+Math.sin(x/1000*7+layer*2.2+game.level.world*.5)*38+Math.sin(x/1000*15+layer)*14;ctx.lineTo(x,y)}ctx.lineTo(1000,640);ctx.closePath();ctx.fillStyle=['#789a9030','#41656045','#16383e77','#0c252ac9'][layer];ctx.fill()}
389 if(game.level.world===1||game.level.wind){ctx.strokeStyle='#7baf9d15';ctx.lineWidth=3;for(let i=0;i<12;i++){const x=i*97+30;ctx.beginPath();ctx.moveTo(x,530);ctx.quadraticCurveTo(x-15,260,x+8,95);ctx.stroke();for(let j=0;j<5;j++){const y=180+j*57;ctx.beginPath();ctx.moveTo(x,y);ctx.quadraticCurveTo(x+22,y-16,x+37,y-5);ctx.stroke()}}}
390 if(game.level.tide){const y=game.ebb?459:365;const water=ctx.createLinearGradient(0,y,0,600);water.addColorStop(0,'#7ba6b42a');water.addColorStop(1,'#20546605');ctx.fillStyle=water;ctx.fillRect(0,y,1000,600-y);ctx.strokeStyle='#b5d8d52b';ctx.lineWidth=.8;for(let j=0;j<8;j++){ctx.beginPath();for(let x=0;x<=1000;x+=10)ctx.lineTo(x,y+j*18+Math.sin(x*.014+t*.6+j)*3);ctx.stroke()}}
391 ctx.strokeStyle='#97bbb127';ctx.lineWidth=.9;for(let i=0;i<60;i++){const x=i*83.17%1000,y=604+i%4*5;ctx.beginPath();ctx.moveTo(x,y);ctx.quadraticCurveTo(x-6,y-15,x+Math.sin(i)*10,y-16-i%6*5);ctx.stroke()}
392 }
393 function paintFringeCluster(ctx,cluster,bloom){
394 ctx.save();
395 for(const leaf of cluster.foliage){
396 ctx.save();ctx.translate(leaf.x,leaf.y);ctx.rotate(leaf.angle);
397 const shade=ctx.createLinearGradient(-4,0,5,0);shade.addColorStop(0,'#304e3f');shade.addColorStop(.55,'#78947a');shade.addColorStop(1,'#496b51');
398 ctx.fillStyle=shade;ctx.beginPath();ctx.moveTo(0,-leaf.size);ctx.bezierCurveTo(8,-leaf.size*.7,7,leaf.size*.65,0,leaf.size);ctx.bezierCurveTo(-6,leaf.size*.5,-7,-leaf.size*.65,0,-leaf.size);ctx.fill();
399 ctx.strokeStyle='#b0bf8d55';ctx.lineWidth=.55;ctx.beginPath();ctx.moveTo(0,-leaf.size*.75);ctx.quadraticCurveTo(1,0,0,leaf.size*.8);ctx.stroke();ctx.restore();
400 }
401 if(bloom>0){
402 ctx.globalAlpha=bloom;
403 for(const flower of cluster.flowers){
404 ctx.strokeStyle='#b9bf9980';ctx.lineWidth=.6;ctx.beginPath();ctx.moveTo(0,8);ctx.quadraticCurveTo(flower.x*.4,2,flower.x,flower.y);ctx.stroke();
405 ctx.save();ctx.translate(flower.x,flower.y);ctx.rotate(flower.angle);
406 for(let k=0;k<4;k++){
407 ctx.save();ctx.rotate((k-1.5)*.55);const length=flower.length*(.86+k*.07),bend=flower.bend;
408 ctx.fillStyle=k%2?'#e8eddf':'#faf9eb';ctx.beginPath();ctx.moveTo(-.7,0);ctx.bezierCurveTo(-1.5,length*.35,bend-1,length*.8,bend,length);ctx.bezierCurveTo(bend+1.1,length*.75,1.3,length*.3,.7,0);ctx.closePath();ctx.fill();ctx.restore();
409 }
410 ctx.fillStyle='#d5d7a2';ctx.beginPath();ctx.arc(0,0,1,0,Math.PI*2);ctx.fill();ctx.restore();
411 }
412 ctx.globalAlpha=1;
413 }
414 ctx.restore();
415 }
416 function drawFringeCluster(cluster,bloom,t){
417 const key=bloom>0?'flowers':'leaves';
418 if(!cluster.art[key]){
419 const art=document.createElement('canvas');art.width=160;art.height=160;
420 const paint=art.getContext('2d');paint.scale(2,2);paint.translate(40,40);
421 paintFringeCluster(paint,cluster,bloom);cluster.art[key]=art;
422 }
423 ctx.save();ctx.translate(cluster.x,cluster.y);
424 if(!save.settings.motion)ctx.rotate(Math.sin(t*.55+cluster.phase)*.035);
425 ctx.drawImage(cluster.art[key],-40,-40,80,80);ctx.restore();
426 }
427 function drawTree(r,index,world,t){
428 const tree=trees[index],ratio=r.received/r.need,growth=ratio*4,unit=fringeTreeUnit();
429 ctx.save();ctx.translate(r.x,r.y);
430 glow(0,-15,75+ratio*50,'#e9efd415');
431 ctx.strokeStyle=game.carry===3&&r.received<r.need?world.color:'#9bbcaf77';ctx.lineWidth=game.carry===3?1.7:1;
432 ctx.beginPath();ctx.ellipse(0,0,41,12,0,0,Math.PI*2);ctx.stroke();ctx.setLineDash([2,6]);ctx.beginPath();ctx.ellipse(0,0,50,17,0,0,Math.PI*2);ctx.stroke();ctx.setLineDash([]);
433 ctx.save();ctx.scale(unit/sx,unit/sy);
434 for(const b of tree.out){
435 const visible=clamp(growth-b.depth+1,0,1);if(!visible)continue;
436 ctx.beginPath();ctx.moveTo(b.x,b.y);ctx.quadraticCurveTo(b.x+(b.ex-b.x)*.4+b.bend,b.y+(b.ey-b.y)*.6,b.x+(b.ex-b.x)*visible,b.y+(b.ey-b.y)*visible);
437 ctx.lineCap='round';ctx.lineWidth=Math.max(.9,7-b.depth*1.5);ctx.strokeStyle=ratio?'#746e58':'#6e7e6b';ctx.stroke();
438 ctx.save();ctx.translate(-.7,0);ctx.lineWidth=Math.max(.45,(7-b.depth*1.5)*.25);ctx.strokeStyle='#c4bd9380';ctx.stroke();ctx.restore();
439 }
440 if(ratio===1){for(const cluster of tree.leaves)drawFringeCluster(cluster,1,t)}
441 else if(ratio>=.5){
442 const tips=tree.out.filter(b=>b.depth===Math.floor(growth));
443 tips.forEach((b,i)=>drawFringeCluster({...tree.leaves[i%tree.leaves.length],x:b.ex,y:b.ey},0,t));
444 }
445 ctx.restore();
446 label(r.received===r.need?'流蘇花開':r.received+' / '+r.need,0,36,r.received===r.need?'#eef1de':'#c0d0bf',10);ctx.restore();
447 }
448 function drawThorns(t){const unit=Math.max(.2,Math.min(sx,sy));const stem=Math.max(3.5*visualScale,7/unit);const tick=Math.max(1.4*visualScale,2.4/unit);const tickLen=Math.max(10,16/unit);for(const w of game.level.thorns||[]){ctx.strokeStyle='#e2b6b0a8';ctx.lineWidth=stem;ctx.lineCap='round';ctx.beginPath();ctx.moveTo(w.x1,w.y1);ctx.lineTo(w.x2,w.y2);ctx.stroke();const dx=w.x2-w.x1,dy=w.y2-w.y1,len=Math.hypot(dx,dy),nx=-dy/len,ny=dx/len;for(let d=0;d<len;d+=20){const x=w.x1+dx*d/len,y=w.y1+dy*d/len;ctx.strokeStyle='#f0c6c0b0';ctx.lineWidth=tick;ctx.beginPath();ctx.moveTo(x-nx*tickLen,y-ny*tickLen);ctx.lineTo(x+nx*tickLen+dx/len*5,y+ny*tickLen+dy/len*5);ctx.stroke()}}ctx.lineCap='butt'}
449 function drawPortals(t){for(let i=0;i<game.portals.length;i++){const p=game.portals[i],color=i%2?'#a2d6d8':'#c5b6e9';for(const q of p.points){glow(q.x,q.y,43,color+'28');ctx.save();ctx.translate(q.x,q.y);ctx.strokeStyle=color;ctx.lineWidth=1.5;ctx.beginPath();ctx.ellipse(0,0,20,26*sx/sy,0,0,7);ctx.stroke();ctx.strokeStyle=color+'55';ctx.setLineDash([5,8]);circle(0,0,32);ctx.stroke();ctx.setLineDash([]);label(i?'Ⅱ':'Ⅰ',0,5,color,11);ctx.restore();if(p.used){label('✓',q.x,q.y+43,color,9)}}}}
450 // Render-only lighting state: game mechanics and saved lamp objects are untouched.
451 const lampRenderState = new WeakMap();
452 function lampGradient(x0,y0,x1,y1,stops){const g=ctx.createLinearGradient(x0,y0,x1,y1);for(const [at,color] of stops)g.addColorStop(at,color);return g}
453 function lampHalo(x,y,r,strength){if(strength<=0)return;const g=ctx.createRadialGradient(x,y,0,x,y,r);g.addColorStop(0,`rgba(255,216,145,${strength})`);g.addColorStop(.35,`rgba(241,189,109,${strength*.38})`);g.addColorStop(1,'rgba(241,189,109,0)');ctx.fillStyle=g;ctx.fillRect(x-r,y-r,r*2,r*2)}
454 function lampOval(x,y,rx,ry,fill){ctx.beginPath();ctx.ellipse(x,y,rx,ry,0,0,Math.PI*2);ctx.fillStyle=fill;ctx.fill()}
455 function lampFlame(bright,y=0){
456 lampHalo(0,y,19,.28*bright);
457 ctx.fillStyle='#b5a47c';ctx.fillRect(-1.4,y+4,2.8,7);
458 ctx.save();ctx.globalAlpha=.16+.84*bright;
459 const flame=lampGradient(0,y-10,0,y+8,[[0,'#fff5d7'],[.4,'#ffe2a0'],[1,'#bb7b3d']]);
460 ctx.fillStyle=flame;ctx.beginPath();ctx.moveTo(0,y-11);ctx.bezierCurveTo(-2,y-3,-6,y, -4,y+5);ctx.bezierCurveTo(-2,y+10,5,y+9,5,y+4);ctx.bezierCurveTo(5,y,1,y-4,0,y-11);ctx.fill();
461 ctx.fillStyle='#fff7d9';lampOval(0,y+4,1.6,3,'#fff7d9');ctx.restore();
462 }
463 function lampLotus(bright){
464 const bronze=lampGradient(-24,-22,24,24,[[0,'#253f3b'],[.26,'#688578'],[.48,'#b3a57c'],[.62,'#6f8068'],[1,'#273f38']]);
465 // The rear petal and solid cup enclose the wick even before the lamp is lit.
466 ctx.fillStyle=bronze;ctx.beginPath();ctx.moveTo(0,16);ctx.bezierCurveTo(-14,1,-10,-24,0,-35);ctx.bezierCurveTo(11,-24,15,1,0,16);ctx.fill();
467 ctx.fillStyle=lampGradient(0,-30,0,13,[[0,'#bec4a061'],[.5,'#607e6980'],[1,'#344f3f']]);ctx.beginPath();ctx.moveTo(0,-29);ctx.quadraticCurveTo(-7,-10,0,8);ctx.quadraticCurveTo(8,-10,0,-29);ctx.fill();
468 lampFlame(bright,-4);
469 for(const side of [-1,1]){
470 ctx.save();ctx.translate(side*4,12);ctx.scale(side,1);ctx.rotate(bright*.72);
471 ctx.fillStyle=bronze;ctx.beginPath();ctx.moveTo(0,0);ctx.bezierCurveTo(17,-5,23,-22,13,-35);ctx.bezierCurveTo(1,-30,-6,-12,0,0);ctx.fill();
472 ctx.fillStyle=lampGradient(0,-23,17,0,[[0,'#9baa8566'],[.4,'#cfb77d80'],[1,'#344d3b']]);ctx.beginPath();ctx.moveTo(2,-3);ctx.bezierCurveTo(14,-10,18,-23,13,-30);ctx.bezierCurveTo(7,-22,3,-11,2,-3);ctx.fill();
473 ctx.save();ctx.globalAlpha=bright*.58;ctx.fillStyle=lampGradient(0,-23,16,2,[[0,'#f8dc9a'],[1,'#b8995340']]);ctx.beginPath();ctx.moveTo(2,-3);ctx.quadraticCurveTo(10,-7,13,-27);ctx.quadraticCurveTo(1,-15,2,-3);ctx.fill();ctx.restore();
474 ctx.strokeStyle='#d4c49155';ctx.lineWidth=.8;ctx.beginPath();ctx.moveTo(3,-3);ctx.quadraticCurveTo(14,-15,13,-30);ctx.stroke();
475 lampOval(0,0,2.1,2.1,'#cab480');lampOval(.5,.5,.8,.8,'#526451');ctx.restore();
476 }
477 ctx.fillStyle=bronze;ctx.beginPath();ctx.moveTo(-17,12);ctx.quadraticCurveTo(0,19,17,12);ctx.bezierCurveTo(15,26,-15,26,-17,12);ctx.fill();
478 lampOval(0,13,17,4,'#c4b786');lampOval(0,13,13,2.3,'#596549');
479 ctx.fillStyle=lampGradient(-4,18,5,28,[[0,'#30473e'],[.5,'#ad9f75'],[1,'#475642']]);ctx.fillRect(-4,20,8,9);
480 lampOval(0,30,18,5,'#30433a');lampOval(0,28,17,4,'#7e8969');lampOval(0,27,11,2,'#a6a382');
481 }
482 function drawLamps(t){
483 const unit=clamp(sx*visualScale,.72,1.12);
484 for(let i=0;i<game.lamps.length;i++){
485 const l=game.lamps[i],target=l.lit?1:0;
486 let state=lampRenderState.get(l);
487 if(!state){state={brightness:target,time:t};lampRenderState.set(l,state)}
488 const elapsed=clamp(t-state.time,0,.08);state.time=t;
489 state.brightness=save.settings.motion?target:state.brightness+(target-state.brightness)*(1-Math.exp(-elapsed*3.2));
490 const bright=state.brightness;
491 // Undo the game world's unequal x/y scales: each object remains solid and upright on phones.
492 ctx.save();ctx.translate(l.x,l.y);ctx.scale(unit/sx,unit/sy);ctx.lineCap='round';ctx.lineJoin='round';
493 lampHalo(0,-3,78,.105*bright);lampOval(2,34,30,7,'#06181266');
494 lampLotus(bright);
495 ctx.restore();
496 label(l.lit?'已點亮':'燈',l.x,l.y+48*unit/sy,l.lit?'#d9c794':'#a5b4a6',9);
497 }
498 }
500 function drawStars(t){if(game.complete)return;for(const s of game.stars){const visible=game.starVisible(s);if(!visible){ctx.strokeStyle='#afcbcf44';ctx.lineWidth=1;ctx.beginPath();ctx.ellipse(s.x,s.y,9*visualScale,3.5,0,0,7);ctx.stroke();continue}const pulse=save.settings.motion?1:1+Math.sin(t*2+s.phase)*.12,r=7*visualScale*pulse;glow(s.x,s.y,25*visualScale,'#f0dc9c25');ctx.fillStyle='#f4dda1';ctx.beginPath();ctx.moveTo(s.x,s.y-r*sx/sy);ctx.lineTo(s.x+r*.55,s.y);ctx.lineTo(s.x,s.y+r*sx/sy);ctx.lineTo(s.x-r*.55,s.y);ctx.closePath();ctx.fill();if(s.tidal){ctx.strokeStyle='#bddedc55';ctx.beginPath();ctx.ellipse(s.x,s.y+12*visualScale,9*visualScale,3,0,0,7);ctx.stroke()}}}
501 function drawShadows(t){if(game.complete)return;for(const s of game.shadows()){glow(s.x,s.y,36,'#040b17ba');ctx.fillStyle='#0c1a28';circle(s.x,s.y,12*visualScale);ctx.fill();ctx.strokeStyle='#a6bec47a';ctx.lineWidth=1;ctx.beginPath();ctx.ellipse(s.x,s.y,17*visualScale,20*visualScale*sx/sy,0,0,Math.PI*1.6);ctx.stroke()}}
502 function drawFog(){if(!game.level.fog||game.complete)return;fogCtx.setTransform(dpr*sx,0,0,dpr*sy,0,0);fogCtx.globalCompositeOperation='source-over';fogCtx.clearRect(0,0,1000,640);fogCtx.fillStyle='#091724ed';fogCtx.fillRect(0,0,1000,640);fogCtx.globalCompositeOperation='destination-out';const holes=[{...game.player,r:175},...game.lamps.filter(l=>l.lit).map(l=>({...l,r:235})),...game.roots.map(r=>({...r,r:105}))];for(const p of holes){const g=fogCtx.createRadialGradient(p.x,p.y,25,p.x,p.y,p.r);g.addColorStop(0,'#000');g.addColorStop(.5,'#000');g.addColorStop(1,'transparent');fogCtx.fillStyle=g;fogCtx.fillRect(p.x-p.r,p.y-p.r,p.r*2,p.r*2)}fogCtx.globalCompositeOperation='source-over';ctx.drawImage(fogCanvas,0,0,1000,640)}
503 function drawFriends(t){for(let i=0;i<game.companions.length;i++){const c=game.companions[i];if(c.status==='waiting'&&!game.visibleAt(c))continue;glow(c.x,c.y,21,'#e3ebb633');ctx.strokeStyle='#d1e5b5';ctx.lineWidth=1;const wing=save.settings.motion?1:Math.sin(t*4+i)*.2+1;ctx.beginPath();ctx.ellipse(c.x-7,c.y-2,6,3*wing,-.5,0,7);ctx.ellipse(c.x+7,c.y-2,6,3*wing,.5,0,7);ctx.stroke();ctx.fillStyle='#e6e8b4';circle(c.x,c.y,3.4*visualScale);ctx.fill();if(c.status==='waiting')label('等你',c.x,c.y+25,'#c1cfa8',9)}}
504 function drawPlayer(t){const p=game.player;if(game.shield>0){glow(p.x,p.y,60,'#dce9c52c');ctx.strokeStyle='#dce9c5b0';ctx.lineWidth=1.2;circle(p.x,p.y,28*visualScale);ctx.stroke()}for(const point of trail){ctx.globalAlpha=point.life*.38;ctx.fillStyle='#f1daa1';circle(point.x,point.y,2*visualScale*point.life);ctx.fill()}ctx.globalAlpha=1;glow(p.x,p.y,30*visualScale,game.invulnerable>0?'#cadfe755':'#f3dba353');ctx.fillStyle=game.invulnerable>0?'#cadfe7':'#fff1cb';circle(p.x,p.y,4.5*visualScale);ctx.fill();for(let i=0;i<game.carry;i++){const a=(save.settings.motion?0:t)+i*Math.PI*2/game.carry;circle(p.x+Math.cos(a)*17*visualScale,p.y+Math.sin(a)*17*visualScale,2.1*visualScale);ctx.fill()}}
505 function draw(){if(!game||!W||!H)return;ctx.setTransform(dpr*sx,0,0,dpr*sy,0,0);ctx.globalAlpha=1;const world=WORLDS[game.level.world],t=save.settings.motion?0:clock;drawBackground(world,t);drawThorns(t);game.roots.forEach((r,i)=>drawTree(r,i,world,t));drawStars(t);drawShadows(t);drawFog();drawPortals(t);drawLamps(t);drawFriends(t);drawPlayer(t);if(game.level.wind&&!save.settings.motion&&!game.complete){const wind=game.wind();ctx.strokeStyle='#a5cec524';ctx.lineWidth=.8;for(let i=0;i<17;i++){const x=(i*131+clock*wind.x*.55+100000)%1000,y=150+(i*97%380);ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+wind.x*.4,y+wind.y*.4);ctx.stroke()}}
506 for(const p of particles){ctx.globalAlpha=Math.min(1,p.life*.6);ctx.fillStyle=p.color;circle(p.x,p.y,2*visualScale);ctx.fill()}ctx.globalAlpha=1;drawPetals();
507 }
508 function frame(now){const dt=Math.min((now-last)/1000||0,.04);last=now;if(!document.hidden){if(running){clock+=dt;if(!game.complete){const input={x:(keys.has('arrowright')||keys.has('d')?1:0)-(keys.has('arrowleft')||keys.has('a')?1:0),y:(keys.has('arrowdown')||keys.has('s')?1:0)-(keys.has('arrowup')||keys.has('w')?1:0)};game.step(dt,input);if(!save.settings.motion){trail.push({...game.player,life:1});if(trail.length>38)trail.shift()}saveTimer+=dt;if(dirty||saveTimer>2.5)persist()}else if(endDelay>0){endDelay-=dt;if(endDelay<=0)showResult()}trail.forEach(p=>p.life-=dt*1.6);trail=trail.filter(p=>p.life>0);particles.forEach(p=>{p.x+=p.vx*dt;p.y+=p.vy*dt;p.vy+=dt*18;p.life-=dt});particles=particles.filter(p=>p.life>0)}if(game.complete&&(running||activeDialog==='result')&&!save.settings.motion)updatePetals(dt);updateUI();draw()}requestAnimationFrame(frame)}
509 function point(e){if(!running||game.complete)return;const rect=canvas.getBoundingClientRect();game.target={x:clamp((e.clientX-rect.left)/rect.width*1000,35,965),y:clamp((e.clientY-rect.top)/rect.height*640,100,607)}}
510 canvas.addEventListener('pointermove',e=>{if(e.pointerType!=='touch'||e.buttons)point(e)});canvas.addEventListener('pointerdown',e=>{if(!running)return;canvas.focus();canvas.setPointerCapture(e.pointerId);point(e)});
511 canvas.addEventListener('keydown',e=>{const key=e.key.toLowerCase();if(['arrowup','arrowdown','arrowleft','arrowright','w','a','s','d'].includes(key)){e.preventDefault();keys.add(key)}if(e.code==='Space'){e.preventDefault();if(running)game.pulse()}});
512 window.addEventListener('keyup',e=>keys.delete(e.key.toLowerCase()));canvas.addEventListener('blur',()=>keys.clear());
513 document.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();if(activeDialog==='map-dialog')showDialog(mapReturn);else if(activeDialog==='pause-dialog')showDialog(null);else if(!activeDialog){stash();showDialog('pause-dialog')}}if(e.key==='Tab'&&activeDialog){const nodes=[...$(activeDialog).querySelectorAll('button:not(:disabled),input:not(:disabled)')].filter(n=>!n.hidden);const first=nodes[0],last=nodes[nodes.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus()}}});
514 window.addEventListener('blur',()=>{keys.clear();if(running&&!game.complete){stash();showDialog('pause-dialog')}});document.addEventListener('visibilitychange',()=>{if(document.hidden&&game){if(music)music.stop();stash();if(running&&!game.complete)showDialog('pause-dialog')}else if(game){syncMusic()}});window.addEventListener('pagehide',()=>{if(music)music.stop();if(game)stash()});
515 $('sound').onclick=()=>{if($('sound').textContent.includes('重試'))save.settings.music=true;else save.settings.music=!save.settings.music;syncSettings();unlockAudio();syncMusic();stash()};
516 function updateSoundLabel(){if($('sound').textContent.includes('重試'))return;$('sound').textContent=(game?.complete?'風聲':'音樂')+' · '+(save.settings.music?'開':'關');$('sound').setAttribute('aria-pressed',String(save.settings.music))}
517 function syncSettings(){$('sound').textContent='';updateSoundLabel();$('music-enabled').checked=save.settings.music;$('effects').checked=save.settings.sound;$('music-volume').value=Math.round(save.settings.musicVolume*100);$('volume-label').textContent=Math.round(save.settings.musicVolume*100)+'%';$('assist').checked=save.settings.assist;$('motion').checked=save.settings.motion;if(game)game.assist=save.settings.assist}
518 $('music-enabled').onchange=()=>{save.settings.music=$('music-enabled').checked;syncSettings();unlockAudio();syncMusic();stash()};
519 $('music-volume').oninput=()=>{save.settings.musicVolume=Number($('music-volume').value)/100;$('volume-label').textContent=Math.round(save.settings.musicVolume*100)+'%';if(music)music.setVolume(save.settings.musicVolume)};$('music-volume').onchange=()=>stash();
520 $('effects').onchange=()=>{save.settings.sound=$('effects').checked;unlockAudio();if(save.settings.sound)note(3);stash()};
521 $('assist').onchange=()=>{save.settings.assist=$('assist').checked;syncSettings();stash()};$('motion').onchange=()=>{save.settings.motion=$('motion').checked;particles=[];trail=[];petals=[];if(game.complete&&!save.settings.motion)startPetals();stash()};
522 $('map-button').onclick=openMap;$('welcome-map').onclick=openMap;$('brief-map').onclick=openMap;$('pause-map').onclick=openMap;$('result-map').onclick=openMap;$('map-close').onclick=()=>showDialog(mapReturn);
523 $('pause-button').onclick=()=>{stash();showDialog('pause-dialog')};$('resume').onclick=()=>showDialog(null);$('pulse').onclick=()=>{if(running)game.pulse();canvas.focus()};
524 $('continue').onclick=()=>chooseLevel(save.active);$('prologue').onclick=()=>chooseLevel(0);$('map-prologue').onclick=()=>chooseLevel(0);
525 $('begin-level').onclick=()=>{showDialog(null);persist();note(0)};$('restart').onclick=()=>{delete save.snapshots[game.level.id];loadLevel(game.level.id,false);showDialog(null);persist()};
526 $('next-level').onclick=()=>{if(game.level.id===40)openMap();else chooseLevel(game.level.id+1)};$('stay').onclick=()=>{endDelay=0;showDialog(null);message('聽風吹過花瓣。點擊夜行圖,繼續下一段旅程。')};
527 // Resume an unfinished night; otherwise suggest the next unlocked chapter.
528 if(save.completed[save.active]&&!save.snapshots[save.active])save.active=unlocked();
529 loadLevel(save.active);syncSettings();$('continue').textContent=save.snapshots[save.active]?(save.active===0?'繼續序章':`繼續第 ${save.active} 夜`):(save.active===0?'走進序章':`開始第 ${save.active} 夜`);if(saveNotice){message(saveNotice);$('save-status').textContent=saveNotice}showDialog('welcome');requestAnimationFrame(frame);
530})();
532</script>
533</body></html>