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}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;color:#90aaa7;margin:20px 0 0;line-height:1.9}.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}}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. */27
const 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
})();176
if(typeof module!=='undefined'&&module.exports)module.exports=NightGarden;178
</script>179
<script>180
/* Original, locally synthesized ambient score. No downloads or network playback. */181
class 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){}}}261
}262
if(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>2
<html lang="zh-Hant">3
<head>4
<meta charset="utf-8">5
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">6
<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">7
<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">8
<meta name="theme-color" content="#0d202a">9
<meta name="description" content="一個關於拾光、歸途與陪伴的水墨小遊戲。序章之後,還有四十個夜晚等你種亮。">10
<title>借一粒星光 · 四十夜的歸途</title>11
<style>12
:root {13
color-scheme: dark;14
--gold: #dfcf98;15
--paper: #ece5d4;16
--muted: #a9bbb9;17
--bg: #0b1a24;18
--line: #8eaaa42e19
}21
* {22
box-sizing: border-box23
}25
html,26
body {27
margin: 0;28
min-height: 100%;29
background: var(--bg);30
color: var(--paper);31
font-family: 'Songti TC', 'Songti SC', 'STSong', 'Noto Serif CJK TC', 'Noto Serif CJK SC', 'Noto Serif TC', Georgia, serif32
}34
body {35
background: radial-gradient(ellipse at 60% 44%, #25404a66, transparent 65%), var(--bg)36
}38
button {39
font: inherit;40
cursor: pointer;41
touch-action: manipulation42
}44
button,45
input {46
accent-color: var(--gold)47
}49
button:disabled {50
cursor: default51
}53
button:focus-visible,54
canvas:focus-visible,55
input:focus-visible {56
outline: 2px solid var(--gold);57
outline-offset: 4px58
}60
[hidden] {61
display: none 62
}64
button {65
color: var(--paper)66
}68
.app {69
width: min(1440px, 100%);70
margin: auto;71
padding: 0 4.5%;72
min-height: 100svh;73
height: 100svh;74
max-height: 100svh;75
display: flex;76
flex-direction: column;77
overflow: hidden78
}80
.topbar {81
flex-shrink: 0;82
height: 84px;83
display: flex;84
align-items: center;85
justify-content: space-between;86
border-bottom: 1px solid var(--line);87
gap: 16px88
}90
.brand {91
font-size: 17px;92
letter-spacing: 4px93
}95
.brand small {96
display: block;97
margin-top: 7px;98
color: var(--muted);99
font: 9px/1.5 Arial, sans-serif;100
letter-spacing: 3px101
}103
.toolbar {104
display: flex;105
gap: 9px;106
align-items: center107
}109
.quiet {110
background: transparent;111
border: 1px solid var(--line);112
border-radius: 30px;113
padding: 10px 17px;114
font-size: 12px;115
min-height: 40px;116
letter-spacing: 1px;117
transition: background .2s118
}120
.quiet:hover {121
background: #c7dac412122
}124
.quiet:disabled {125
opacity: .4126
}128
.quiet[aria-pressed=true] {129
border-color: #dfcf9880;130
color: var(--gold)131
}133
.level-head {134
flex-shrink: 0;135
display: flex;136
justify-content: space-between;137
gap: 24px;138
align-items: center;139
padding: 26px 0 15px140
}142
.eyebrow {143
font: 10px/1.7 Arial, sans-serif;144
letter-spacing: 3px;145
color: var(--gold);146
text-transform: uppercase147
}149
h1 {150
font-weight: 400;151
font-size: clamp(25px, 3.4vw, 43px);152
letter-spacing: 5px;153
line-height: 1.35;154
margin: 8px 0155
}157
.intro-line {158
color: var(--muted);159
font-size: 12px;160
line-height: 1.8;161
max-width: 750px;162
letter-spacing: 1px;163
margin: 0164
}166
.progress {167
text-align: right;168
flex-shrink: 0169
}171
.progress .number {172
font: 34px/1.3 Georgia, serif;173
color: var(--gold)174
}176
.progress small {177
font: 11px Arial;178
letter-spacing: 2px;179
color: var(--muted)180
}182
.progress .caption {183
font-size: 10px;184
letter-spacing: 3px;185
color: var(--muted);186
margin-bottom: 5px187
}189
.progress-track {190
width: 145px;191
height: 2px;192
background: #9cb8b522;193
margin-top: 12px;194
overflow: hidden195
}197
.progress-track span {198
display: block;199
height: 100%;200
background: var(--gold);201
transition: width .35s202
}204
.stage {205
container-type: size;206
flex: 1 1 auto;207
min-height: 220px;208
position: relative;209
isolation: isolate;210
display: flex;211
align-items: center;212
justify-content: center;213
background: #07141c;214
border-bottom: 1px solid var(--line);215
border-top: 1px solid var(--line);216
overflow: hidden;217
height: auto218
}220
.stage-frame {221
position: relative;222
aspect-ratio: 1000/640;223
width: min(100cqw, calc(100cqh * 1000 / 640));224
height: auto;225
max-width: 100%;226
max-height: 100%227
}229
canvas {230
display: block;231
width: 100%;232
height: 100%;233
touch-action: none;234
border-radius: 2px235
}237
.stage-meta {238
position: absolute;239
top: 16px;240
left: 20px;241
right: 20px;242
display: flex;243
justify-content: space-between;244
gap: 15px;245
align-items: start;246
pointer-events: none247
}249
.objectives {250
display: flex;251
flex-wrap: wrap;252
gap: 8px253
}255
.objective {256
font-size: 11px;257
line-height: 1.5;258
letter-spacing: 1px;259
padding: 6px 10px;260
border-radius: 3px;261
background: #081923bd;262
color: #cbd5cd263
}265
.objective.done {266
color: var(--gold)267
}269
.weather {270
font-size: 11px;271
color: #c6d3cf;272
text-align: right;273
line-height: 1.9;274
white-space: nowrap275
}277
.stage-caption {278
position: absolute;279
bottom: 13px;280
left: 20px;281
font: 9px Arial, sans-serif;282
color: #bed0c070;283
letter-spacing: 3px;284
pointer-events: none285
}287
.understory {288
flex-shrink: 0;289
display: grid;290
grid-template-columns: 1fr auto;291
gap: 16px;292
align-items: center;293
padding: 18px 0 12px294
}296
.pocket-row {297
display: flex;298
align-items: center;299
gap: 12px300
}302
.pocket {303
display: flex;304
gap: 8px305
}307
.pocket i {308
width: 7px;309
height: 7px;310
border: 1px solid var(--gold);311
transform: rotate(45deg);312
transition: background .2s313
}315
.pocket i.on {316
background: var(--gold);317
box-shadow: 0 0 14px #dfcf9860318
}320
.pocket-label {321
font: 10px Arial;322
letter-spacing: 2px;323
color: var(--muted)324
}326
.message {327
font-size: 13px;328
line-height: 1.8;329
letter-spacing: 1px;330
margin-top: 9px;331
color: #d3ded3;332
min-height: 24px333
}335
.pulse {336
display: flex;337
gap: 12px;338
align-items: center;339
border: 1px solid #dcca9166;340
background: #dcca910b;341
border-radius: 40px;342
padding: 13px 21px;343
color: var(--gold);344
min-width: 132px;345
justify-content: center;346
min-height: 48px;347
font-size: 13px;348
letter-spacing: 2px349
}351
.pulse:disabled {352
color: var(--muted);353
border-color: var(--line)354
}356
.pulse small {357
font: 10px Arial;358
letter-spacing: 1px;359
color: var(--muted)360
}362
.footer {363
flex-shrink: 0;364
display: flex;365
justify-content: space-between;366
gap: 16px;367
padding: 7px 0 24px;368
color: #8da5a5;369
font-size: 10px;370
letter-spacing: 1px;371
line-height: 1.8372
}374
.save-status {375
white-space: nowrap376
}378
.overlay {379
position: fixed;380
inset: 0;381
z-index: 10;382
background: #06131cbf;383
backdrop-filter: blur(14px);384
display: flex;385
align-items: center;386
justify-content: center;387
padding: 24px;388
overflow: auto389
}391
.panel {392
position: relative;393
background: linear-gradient(145deg, #18303b, #101e2a);394
border: 1px solid #9db7ac30;395
max-width: 570px;396
width: 100%;397
padding: 46px 44px;398
border-radius: 5px;399
box-shadow: 0 35px 100px #0005;400
max-height: calc(100svh - 48px);401
overflow: auto402
}404
.center {405
text-align: center406
}408
.seal {409
color: var(--gold);410
font-size: 35px;411
margin-bottom: 20px412
}414
.panel h2 {415
font-size: 30px;416
font-weight: 400;417
letter-spacing: 4px;418
line-height: 1.6;419
margin: 8px 0 17px420
}422
.panel p {423
font-size: 14px;424
line-height: 2.1;425
letter-spacing: 1px;426
color: #bfcfc7;427
white-space: pre-line;428
margin: 14px 0 25px429
}431
.panel .tagline {432
font-size: 12px;433
color: var(--gold);434
margin-bottom: 28px435
}437
.primary {438
border: 1px solid #e0d2ab;439
background: #e0d2ab;440
color: #173138;441
padding: 14px 25px;442
min-height: 47px;443
letter-spacing: 2px;444
border-radius: 3px;445
font-size: 14px446
}448
.primary:hover {449
background: #f0e1bc450
}452
.actions {453
display: flex;454
align-items: center;455
justify-content: center;456
gap: 12px;457
flex-wrap: wrap458
}460
.text-button {461
border: 0;462
background: none;463
color: #acbfba;464
text-decoration: underline;465
text-underline-offset: 4px;466
font-size: 12px;467
padding: 12px468
}470
.meta-note {471
font-size: 11px ;472
color: #90aaa7 ;473
margin: 20px 0 0 ;474
line-height: 1.9 475
}477
.instructions {478
display: grid;479
grid-template-columns: repeat(3, 1fr);480
gap: 16px;481
margin: 25px 0 30px;482
font-size: 11px;483
color: #a9bdb7;484
line-height: 1.8485
}487
.instructions span {488
font-size: 20px;489
display: block;490
color: var(--gold);491
margin-bottom: 4px492
}494
.close {495
position: absolute;496
top: 16px;497
right: 17px;498
width: 40px;499
height: 40px;500
border: 0;501
background: transparent;502
font: 25px Arial;503
color: #adc1b8504
}506
.map-panel {507
max-width: 1020px;508
padding: 35px 40px509
}511
.map-heading {512
display: flex;513
justify-content: space-between;514
gap: 16px;515
align-items: end;516
margin: 0 0 18px517
}519
.map-heading h2 {520
margin-bottom: 3px521
}523
.map-heading p {524
font-size: 12px;525
margin: 0526
}528
.map-total {529
font: 28px Georgia;530
color: var(--gold);531
white-space: nowrap;532
margin-right: 20px533
}535
.map-total small {536
font: 11px Arial;537
color: var(--muted)538
}540
.map-zero {541
display: flex;542
justify-content: space-between;543
align-items: center;544
gap: 10px;545
padding: 10px 0 17px;546
border-bottom: 1px solid var(--line);547
font-size: 12px;548
color: var(--muted)549
}551
.map-chapter {552
margin-top: 24px553
}555
.chapter-title {556
display: flex;557
gap: 12px;558
align-items: center;559
margin-bottom: 12px560
}562
.chapter-mark {563
display: grid;564
place-items: center;565
width: 29px;566
height: 29px;567
border: 1px solid #b9b59a55;568
border-radius: 50%;569
font-size: 12px;570
color: var(--chapter)571
}573
.chapter-title h3 {574
font-size: 15px;575
font-weight: 400;576
letter-spacing: 3px;577
margin: 0578
}580
.chapter-title p {581
font-size: 11px;582
margin: 0 0 0 auto;583
color: #93aaa5;584
letter-spacing: 1px585
}587
.level-grid {588
display: grid;589
grid-template-columns: repeat(5, 1fr);590
gap: 9px591
}593
.level-tile {594
position: relative;595
text-align: left;596
border: 1px solid #99b3a92b;597
border-radius: 3px;598
background: #21353c5e;599
min-height: 89px;600
padding: 13px 12px;601
color: #d4dece;602
transition: background .2s603
}605
.level-tile:not(:disabled):hover {606
background: #45554c66;607
border-color: #d9ca9a80608
}610
.level-tile:disabled {611
background: #11232b;612
color: #90a1a0613
}615
.level-tile.current {616
border-color: var(--gold)617
}619
.level-tile .tile-no {620
font: 11px Georgia;621
color: var(--chapter);622
letter-spacing: 2px623
}625
.level-tile:disabled .tile-no {626
color: #78908d627
}629
.level-tile .tile-name {630
font-size: 12px;631
letter-spacing: 1px;632
display: block;633
margin: 8px 0;634
line-height: 1.6635
}637
.tile-stars {638
font: 11px Arial;639
color: var(--gold);640
letter-spacing: 3px641
}643
.tile-lock {644
font-size: 10px;645
color: #718b86646
}648
.rating {649
font-size: 24px;650
color: var(--gold);651
letter-spacing: 12px;652
margin: 20px 0 7px653
}655
.result-meta {656
font-size: 11px;657
line-height: 1.8;658
color: #9db5ac;659
margin-bottom: 26px660
}662
.setting {663
display: flex;664
align-items: center;665
justify-content: space-between;666
gap: 20px;667
text-align: left;668
padding: 16px 0;669
border-bottom: 1px solid var(--line);670
font-size: 13px671
}673
.setting small {674
display: block;675
font-size: 11px;676
line-height: 1.8;677
color: var(--muted);678
margin-top: 5px679
}681
.setting input {682
width: 19px;683
height: 19px;684
flex-shrink: 0685
}687
.keyboard-help {688
font-size: 12px;689
text-align: left;690
line-height: 2.1;691
color: var(--muted);692
margin: 24px 0693
}695
.keyboard-help strong {696
font-weight: 400;697
color: var(--paper)698
}700
.error {701
color: #ecc4ac702
}704
.sr-only {705
position: absolute;706
width: 1px;707
height: 1px;708
padding: 0;709
overflow: hidden;710
clip: rect(0, 0, 0, 0);711
white-space: nowrap;712
border: 0713
}715
@media(min-width:1600px) {716
.app {717
padding: 0 60px718
}719
}721
@media(max-width:700px) {722
.app {723
padding: 0 20px724
}726
.topbar {727
height: 75px728
}730
.brand {731
font-size: 14px;732
letter-spacing: 2px733
}735
.brand small {736
font-size: 8px;737
letter-spacing: 1px738
}740
.toolbar {741
gap: 5px742
}744
.quiet {745
padding: 9px 11px;746
font-size: 11px;747
min-height: 42px748
}750
.level-head {751
padding: 20px 0 14px;752
gap: 14px;753
align-items: start754
}756
h1 {757
font-size: 25px;758
letter-spacing: 2px759
}761
.intro-line {762
font-size: 11px;763
line-height: 1.7764
}766
.eyebrow {767
font-size: 9px;768
letter-spacing: 1px769
}771
.progress .number {772
font-size: 25px773
}775
.progress .caption {776
font-size: 9px;777
letter-spacing: 1px778
}780
.progress-track {781
width: 68px782
}784
.stage {785
height: auto;786
min-height: 0787
}789
.stage-meta {790
left: 10px;791
right: 10px;792
top: 12px;793
gap: 5px794
}796
.objectives {797
gap: 4px;798
max-width: 78%799
}801
.objective {802
font-size: 10px;803
padding: 5px 7px804
}806
.weather {807
font-size: 9px808
}810
.stage-caption {811
font-size: 8px;812
letter-spacing: 1px;813
left: 12px814
}816
.understory {817
gap: 10px;818
padding-top: 16px819
}821
.message {822
font-size: 11px;823
line-height: 1.9824
}826
.pulse {827
font-size: 16px;828
padding: 14px 22px;829
min-width: 128px;830
min-height: 56px;831
gap: 8px832
}834
.pulse small {835
display: none836
}838
.footer {839
flex-wrap: wrap;840
font-size: 9px;841
gap: 3px;842
padding-bottom: 17px843
}845
.panel {846
padding: 40px 25px847
}849
.panel h2 {850
font-size: 25px;851
letter-spacing: 2px852
}854
.panel p {855
font-size: 13px856
}858
.overlay {859
padding: 15px860
}862
.panel {863
max-height: calc(100svh - 30px)864
}866
.map-panel {867
padding: 38px 20px 25px868
}870
.map-heading {871
display: block872
}874
.map-total {875
font-size: 20px;876
margin-top: 12px877
}879
.chapter-title {880
gap: 8px881
}883
.chapter-title h3 {884
font-size: 14px;885
letter-spacing: 1px886
}888
.chapter-title p {889
display: none890
}892
.level-grid {893
grid-template-columns: repeat(3, 1fr);894
gap: 6px895
}897
.level-tile {898
padding: 10px 8px899
}901
.level-tile .tile-name {902
font-size: 11px903
}905
.map-zero {906
font-size: 11px907
}909
.map-zero .quiet {910
font-size: 10px911
}913
.instructions {914
gap: 9px;915
font-size: 10px916
}918
.actions .primary {919
font-size: 13px;920
padding: 13px 19px921
}922
}924
@media(max-width:370px) {925
.app {926
padding: 0 12px927
}929
.brand small {930
display: none931
}933
.toolbar .quiet {934
padding: 9px935
}937
.progress {938
min-width: 54px939
}941
.level-head {942
gap: 8px943
}945
h1 {946
font-size: 22px947
}949
.level-grid {950
grid-template-columns: repeat(2, 1fr)951
}952
}954
@media(prefers-reduced-motion:reduce) {955
* {956
transition: none 957
}958
}960
#result {961
background: #06131c7a;962
backdrop-filter: blur(2px)963
}965
.goal-hint {966
margin: 7px 0 0;967
font-size: 11px;968
letter-spacing: 1px;969
color: #c6d3cf;970
line-height: 1.65;971
text-shadow: 0 1px 8px #081923cc;972
white-space: nowrap973
}975
.objectives-col {976
display: flex;977
flex-direction: column;978
align-items: flex-start;979
gap: 0;980
pointer-events: none;981
max-width: 78%982
}984
.map-scroll-hint {985
position: sticky;986
bottom: 0;987
z-index: 1;988
margin: 8px 0 0;989
padding: 22px 0 4px;990
text-align: center;991
font-size: 12px;992
letter-spacing: 1px;993
color: var(--gold);994
background: linear-gradient(transparent, #101e2a 42%);995
}997
@media(max-width:700px) {998
.stage {999
flex: 0 0 auto;1000
height: auto;1001
min-height: 0;1002
container-type: normal1003
}1005
.stage-frame {1006
width: 100%;1007
height: auto;1008
aspect-ratio: 1000/6401009
}1011
.pulse {1012
font-size: 16px;1013
padding: 14px 22px;1014
min-width: 128px;1015
min-height: 56px;1016
gap: 8px1017
}1019
.goal-hint {1020
font-size: 10px;1021
max-width: 100%;1022
white-space: normal1023
}1024
}1026
</style>1027
</head>1028
<body>1029
<main class="app" id="app">1030
<header class="topbar">1031
<div class="brand">借一粒星光<small>四十夜的歸途</small></div>1032
<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>1033
</header>1034
<section class="level-head">1035
<div>1036
<div class="eyebrow" id="eyebrow">四十夜的歸途 · 第 01 / 40 夜</div>1037
<h1 id="level-title">露水的來處</h1>1038
<p class="intro-line" id="level-intro">先拾起三粒星光,再靠近樹根。</p>1039
</div>1040
<div class="progress">1041
<div class="caption">已送回星光</div><span class="number" id="delivered">0</span> <small id="required">/ 6</small>1042
<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>1043
</div>1044
</section>1045
<section class="stage" aria-label="夜色花園">1046
<div class="stage-frame"><canvas id="garden" tabindex="0" aria-label="遊戲區域。可用手指拖動、鼠標移動或方向鍵走動,點「屏息」或按空白鍵護光。每次攜帶三粒星光,送回樹根。">請用支持 Canvas 的瀏覽器打開遊戲。</canvas>1047
<div class="stage-meta">1048
<div class="objectives-col">1049
<div id="objectives" class="objectives"></div>1050
<p id="goal-hint" class="goal-hint"></p>1051
</div>1052
<div id="weather" class="weather"></div>1053
</div>1054
<div class="stage-caption">不必趕路。每一粒微光,都算數。</div>1055
</div>1056
</section>1057
<div class="understory">1058
<div>1059
<div class="pocket-row">1060
<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>1061
</div>1062
<div class="message" id="message" role="status" aria-live="polite">把散落的夜晚,種成一棵會發光的樹。</div>1063
</div><button class="pulse" id="pulse"><span id="pulse-label">屏息</span><small>空白鍵</small></button>1064
</div>1065
<footer class="footer"><span id="control-hint">滑鼠移動、方向鍵或 W A S D 移動 · 空白鍵護光 · Esc 暫停</span><span id="save-status" class="save-status">進度自動保存在當前瀏覽器</span></footer>1066
</main>1067
<div class="overlay" id="welcome" role="dialog" aria-modal="true" aria-labelledby="welcome-title">1068
<section class="panel center">1069
<div class="eyebrow">借一粒星光 · 第二卷</div>1070
<div class="seal" aria-hidden="true">✧</div>1071
<h2 id="welcome-title">四十夜的歸途</h2>1072
<p>那棵被你種亮的樹,寄來了一封信。<br>原來,森林的另一端,<br>還有四十個夜晚在等你。</p>1073
<div class="instructions">1074
<div><span>◇</span>拾起三粒光<br>帶回樹根</div>1075
<div><span>◎</span>繞過墨影<br>屏息護光</div>1076
<div><span>✺</span>點燈與同行<br>讓長夜開花</div>1077
</div>1078
<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>1079
<p class="meta-note">八個章節 · 四十個新關卡 · 自動存檔<br>入夜後播放輕柔背景音樂,可隨時關閉。<br>沒有倒計時。慢一點,也很好。</p>1080
</section>1081
</div>1082
<div class="overlay" id="map-dialog" role="dialog" aria-modal="true" aria-labelledby="map-title" hidden>1083
<section class="panel map-panel"><button class="close" id="map-close" aria-label="關閉夜行圖">×</button>1084
<div class="map-heading">1085
<div>1086
<div class="eyebrow">你的夜行圖</div>1087
<h2 id="map-title">夜行圖</h2>1088
<p>每走過一個夜晚,就為森林留下一朵花。</p>1089
</div>1090
<div class="map-total"><span id="map-count">0</span> <small>/ 40 夜已種亮</small></div>1091
</div>1092
<div class="map-zero"><span>序章 · 夜晚,借你一點光</span><button class="quiet" id="map-prologue">重溫序章</button></div>1093
<div id="chapters"></div>1094
<p class="meta-note">完成當前關卡,解鎖下一夜。已完成的關卡可以重玩。<br>花印:通關一枚;碰撞不超過三次兩枚;無碰撞三枚。沒有時間評分。<br>八個章節,頁面較長時請向下滑動,後面還有更多夜晚。</p>1095
<p class="map-scroll-hint" id="map-scroll-hint" hidden>向下滑動,後面還有更多章節。</p>1096
</section>1097
</div>1098
<div class="overlay" id="briefing" role="dialog" aria-modal="true" aria-labelledby="brief-title" hidden>1099
<section class="panel center">1100
<div class="eyebrow" id="brief-label"></div>1101
<div class="seal" id="brief-mark"></div>1102
<h2 id="brief-title"></h2>1103
<p id="brief-text"></p>1104
<div class="actions"><button class="primary" id="begin-level">走進這一夜</button><button class="quiet" id="brief-map">夜行圖</button></div>1105
<p class="meta-note">移動即可拾光,靠近就能互動。每次帶滿三粒再回樹根。<br>點「屏息」或按空白鍵,可短暫護光。<br>若這一夜有燈、月門或夥伴,都要完成,才算種亮。</p>1106
</section>1107
</div>1108
<div class="overlay" id="pause-dialog" role="dialog" aria-modal="true" aria-labelledby="pause-title" hidden>1109
<section class="panel">1110
<div class="eyebrow">先歇一口氣</div>1111
<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>1112
<div class="keyboard-help"><strong>方向鍵 / W A S D</strong> 移動 · <strong>空白鍵</strong> 屏息護光<br>也可以用滑鼠在畫面裡移動,或用手指拖動。<br>屏息持續 2.8 秒,8 秒後可再次使用。<br>墨影與荊棘會吹散一粒光,已經送回的光不會丟失。</div>1113
<div class="actions"><button class="primary" id="resume">繼續這一夜</button><button class="quiet" id="pause-map">夜行圖</button><button class="text-button" id="restart">重走本關</button></div>1114
<p class="meta-note" id="pause-save">離開、切換關卡或關閉頁面,都會保存當前進度。</p>1115
</section>1116
</div>1117
<div class="overlay" id="result" role="dialog" aria-modal="true" aria-labelledby="result-title" hidden>1118
<section class="panel center">1119
<div class="eyebrow" id="result-label"></div>1120
<div class="seal">✺</div>1121
<h2 id="result-title">這一夜,被你種亮了</h2>1122
<p id="poem"></p>1123
<div class="rating" id="rating" aria-label="本關花印"></div>1124
<div class="result-meta" id="result-meta"></div>1125
<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>1126
</section>1127
</div>1128
<script>1129
/* 借一粒星光 — deterministic campaign and simulation; no external dependencies. */1130
const NightGarden = (() => {1131
'use strict';1132
const WORLDS = [{1133
name: '苔原拾光',1134
subtitle: '在最初的微光裡,學會回家。',1135
color: '#dfcf98',1136
sky: ['#0a1923', '#23464b'],1137
flower: '#ebd3a4',1138
mark: '芽'1139
},1140
{1141
name: '風眠竹海',1142
subtitle: '風沒有方向,直到你決定出發。',1143
color: '#b9dac4',1144
sky: ['#0c2329', '#28564e'],1145
flower: '#cce6b5',1146
mark: '風'1147
},1148
{1149
name: '霧燈渡口',1150
subtitle: '看不見遠方的時候,先點亮身邊。',1151
color: '#bfcede',1152
sky: ['#151e30', '#38465e'],1153
flower: '#cbd8ef',1154
mark: '霧'1155
},1156
{1157
name: '荊棘書頁',1158
subtitle: '繞過刺,也是一種溫柔的勇敢。',1159
color: '#d7b6aa',1160
sky: ['#291e2c', '#57404a'],1161
flower: '#e8b6ba',1162
mark: '棘'1163
},1164
{1165
name: '鏡湖迴廊',1166
subtitle: '另一端的自己,也在等一場相逢。',1167
color: '#c9bde8',1168
sky: ['#191a34', '#3c4164'],1169
flower: '#d5c8f0',1170
mark: '鏡'1171
},1172
{1173
name: '潮聲群島',1174
subtitle: '有些重逢,需要等一等潮汐。',1175
color: '#a9d9df',1176
sky: ['#092532', '#265366'],1177
flower: '#b9e5e1',1178
mark: '潮'1179
},1180
{1181
name: '螢火來信',1182
subtitle: '這一次,回家的不只你一個。',1183
color: '#e6cb9c',1184
sky: ['#27232b', '#574d43'],1185
flower: '#f0d0a0',1186
mark: '信'1187
},1188
{1189
name: '黎明花園',1190
subtitle: '把走過的夜晚,交還給清晨。',1191
color: '#f0c7aa',1192
sky: ['#302638', '#765a60'],1193
flower: '#f8d0b5',1194
mark: '曉'1195
}1196
];1197
const root = (x, y, need = 3) => ({1198
x,1199
y,1200
need1201
});1202
const wall = (x1, y1, x2, y2) => ({1203
x1,1204
y1,1205
x2,1206
y21207
});1208
const pair = (ax, ay, bx, by) => [{1209
x: ax,1210
y: ay1211
}, {1212
x: bx,1213
y: by1214
}];1215
const P = [1216
[1, '露水的來處', '先拾起三粒星光,再靠近樹根。', [root(500, 540, 6)], {1217
shadows: 0,1218
pattern: 'ring'1219
}],1220
[2, '兩岸的芽', '兩棵樹,等你分別送去三粒光。', [root(240, 525), root(760, 525)], {1221
shadows: 1,1222
pattern: 'banks'1223
}],1224
[3, '微光小徑', '墨影會帶走一粒光;按空格可短暫護住自己。', [root(500, 540, 9)], {1225
shadows: 2,1226
pattern: 'trail'1227
}],1228
[4, '三封無字信', '沿三角形的歸途,把三棵樹都種亮。', [root(180, 480), root(500, 210), root(820, 480)], {1229
shadows: 2,1230
pattern: 'triangle'1231
}],1232
[5, '苔原的星座', '讓四個方向,都有一處可以歸來。', [root(170, 460), root(400, 550), root(650, 490), root(830, 300)], {1233
shadows: 2,1234
pattern: 'ring'1235
}],1236
[6, '風的第一行', '向東的風會推著你走。點「屏息」或按空白鍵,可暫時抵禦風。', [root(220, 510, 6)], {1237
shadows: 1,1238
wind: 'east',1239
pattern: 'banks'1240
}],1241
[7, '逆風的種子', '把光送往西邊,再走到竹海的另一側。', [root(160, 480), root(830, 450)], {1242
shadows: 2,1243
wind: 'west',1244
pattern: 'trail'1245
}],1246
[8, '竹葉的迴旋', '旋轉的風中,試著分段移動。', [root(500, 525, 9)], {1247
shadows: 2,1248
wind: 'swirl',1249
pattern: 'ring'1250
}],1251
[9, '風向改變之前', '風向會緩緩改變。每一段路,都可以重新選擇。', [root(200, 500), root(500, 290), root(800, 500)], {1252
shadows: 3,1253
wind: 'changing',1254
pattern: 'triangle'1255
}],1256
[10, '把風種下來', '沿著迴旋的風,完成四次歸途。', [root(260, 490, 6), root(760, 490, 6)], {1257
shadows: 2,1258
wind: 'swirl',1259
windPower: 1.1,1260
pattern: 'banks'1261
}],1262
[11, '第一盞霧燈', '靠近蓮花燈即可點亮;燈光會驅散周圍的霧。', [root(500, 525, 6)], {1263
shadows: 1,1264
fog: true,1265
lamps: [1266
[330, 330]1267
],1268
pattern: 'trail'1269
}],1270
[12, '隔霧相望', '點亮兩盞燈,也照亮彼此的樹。', [root(210, 515), root(790, 515)], {1271
shadows: 2,1272
fog: true,1273
lamps: [1274
[240, 285],1275
[760, 285]1276
],1277
pattern: 'banks'1278
}],1279
[13, '燈與風的約定', '霧會遮住遠處的星光,燈臺會一直留在原地。', [root(500, 525, 9)], {1280
shadows: 2,1281
fog: true,1282
lamps: [1283
[250, 300],1284
[700, 360]1285
],1286
wind: 'east',1287
pattern: 'ring'1288
}],1289
[14, '渡口不眠', '依次探索三個燈臺,再把光交給岸邊。', [root(200, 525), root(500, 480), root(800, 525)], {1290
shadows: 3,1291
fog: true,1292
lamps: [1293
[170, 290],1294
[500, 220],1295
[830, 290]1296
],1297
pattern: 'triangle'1298
}],1299
[15, '霧散時的名字', '霧燈、風與墨影,都成了你熟悉的路標。', [root(280, 520, 6), root(750, 500, 6)], {1300
shadows: 3,1301
fog: true,1302
lamps: [1303
[230, 280],1304
[500, 340],1305
[790, 230]1306
],1307
wind: 'changing',1308
pattern: 'banks'1309
}],1310
[16, '紙上的第一根刺', '荊棘不可穿越。繞過端點,就能找到另一條路。', [root(780, 510, 6)], {1311
shadows: 1,1312
thorns: [wall(490, 140, 490, 390)],1313
pattern: 'banks'1314
}],1315
[17, '留白的入口', '穿過兩段荊棘之間的留白。', [root(500, 520, 9)], {1316
shadows: 2,1317
thorns: [wall(150, 330, 420, 330), wall(580, 330, 850, 330)],1318
pattern: 'ring'1319
}],1320
[18, '摺頁花園', '每一處轉角,都藏著一條不必受傷的路。', [root(200, 500), root(800, 500)], {1321
shadows: 2,1322
thorns: [wall(370, 130, 370, 350), wall(630, 300, 630, 535)],1323
wind: 'west',1324
pattern: 'banks'1325
}],1326
[19, '刺間的燈', '在荊棘的缺口裡,點亮兩盞不熄的燈。', [root(500, 525, 9)], {1327
shadows: 2,1328
fog: true,1329
lamps: [1330
[250, 220],1331
[760, 220]1332
],1333
thorns: [wall(360, 270, 640, 270), wall(210, 380, 380, 380), wall(620, 380, 790, 380)],1334
pattern: 'triangle'1335
}],1336
[20, '溫柔的迷宮', '繞過三面書頁,把故事寫到最後。', [root(210, 520, 6), root(800, 510, 6)], {1337
shadows: 3,1338
thorns: [wall(330, 145, 330, 390), wall(670, 255, 670, 540), wall(425, 330, 580, 330)],1339
wind: 'changing',1340
pattern: 'trail'1341
}],1342
[21, '鏡子的另一面', '走進圓形月門,抵達同符號的另一端。穿過這對月門。', [root(800, 500, 6)], {1343
shadows: 1,1344
portals: [pair(230, 420, 770, 230)],1345
pattern: 'banks'1346
}],1347
[22, '兩次相逢', '兩對月門各穿過一次;符號標記了它們的連結。', [root(210, 500), root(800, 500)], {1348
shadows: 2,1349
portals: [pair(170, 240, 650, 460), pair(390, 460, 840, 240)],1350
pattern: 'ring'1351
}],1352
[23, '越過未寫的河', '借月門越過荊棘,或者繞行;記得留下穿越的足跡。', [root(800, 480, 9)], {1353
shadows: 2,1354
portals: [pair(230, 420, 770, 210)],1355
thorns: [wall(500, 100, 500, 470)],1356
pattern: 'banks'1357
}],1358
[24, '霧中的倒影', '先尋找燈,再看清鏡中的歸途。', [root(250, 510), root(760, 510)], {1359
shadows: 2,1360
fog: true,1361
lamps: [1362
[220, 270],1363
[790, 270]1364
],1365
portals: [pair(150, 420, 810, 180), pair(830, 420, 350, 180)],1366
pattern: 'triangle'1367
}],1368
[25, '迴廊盡頭是你', '在雙重鏡廊中,把兩岸的樹都種亮。', [root(210, 510, 6), root(800, 510, 6)], {1369
shadows: 3,1370
wind: 'swirl',1371
portals: [pair(160, 280, 760, 380), pair(840, 190, 300, 400)],1372
thorns: [wall(410, 180, 590, 180), wall(500, 330, 500, 490)],1373
pattern: 'banks'1374
}],1375
[26, '退潮的禮物', '帶波紋的星光只在退潮時出現;不必著急。', [root(500, 515, 6)], {1376
shadows: 1,1377
tide: 10,1378
pattern: 'tide'1379
}],1380
[27, '海把星星還回來', '水面升起時移動會慢一些,退潮後再去拾光。', [root(220, 510), root(790, 510)], {1381
shadows: 2,1382
tide: 11,1383
pattern: 'tide'1384
}],1385
[28, '風從海上來', '乘風走過淺灘,等待星光從潮水裡浮起。', [root(500, 510, 9)], {1386
shadows: 2,1387
tide: 10,1388
wind: 'east',1389
pattern: 'tide'1390
}],1391
[29, '潮間的月門', '門不會被海淹沒,它會把你送到另一片岸。', [root(220, 510), root(790, 510)], {1392
shadows: 2,1393
tide: 12,1394
portals: [pair(180, 300, 820, 200)],1395
pattern: 'tide'1396
}],1397
[30, '聽見海的呼吸', '點亮海邊的燈,穿過月門,等一場溫柔的退潮。', [root(260, 500, 6), root(740, 500, 6)], {1398
shadows: 3,1399
tide: 10,1400
fog: true,1401
lamps: [1402
[250, 220],1403
[750, 260]1404
],1405
portals: [pair(160, 390, 820, 190)],1406
pattern: 'tide'1407
}],1408
[31, '一封會飛的信', '靠近小螢火蟲,讓它跟著你回到樹根。', [root(500, 520, 6)], {1409
shadows: 1,1410
companions: [1411
[240, 240]1412
],1413
pattern: 'ring'1414
}],1415
[32, '我們一起回家', '兩隻螢火蟲在等你。慢一點,讓它們跟上。', [root(500, 530, 9)], {1416
shadows: 2,1417
companions: [1418
[180, 250],1419
[820, 230]1420
],1421
wind: 'west',1422
pattern: 'banks'1423
}],1424
[33, '燈下的三個人', '霧裡有三位夥伴,一次最多帶兩位回家。', [root(500, 520, 9)], {1425
shadows: 2,1426
fog: true,1427
lamps: [1428
[220, 300],1429
[780, 300]1430
],1431
companions: [1432
[160, 210],1433
[830, 200],1434
[500, 200]1435
],1436
pattern: 'triangle'1437
}],1438
[34, '寄往鏡湖的信', '同行的夥伴也能穿過月門。把三封信帶回樹根。', [root(500, 530, 9)], {1439
shadows: 2,1440
companions: [1441
[160, 220],1442
[840, 210],1443
[730, 350]1444
],1445
portals: [pair(220, 360, 790, 160)],1446
thorns: [wall(400, 270, 600, 270)],1447
pattern: 'banks'1448
}],1449
[35, '所有微光的姓名', '退潮時拾光,歸來時帶上等你的四位夥伴。', [root(500, 530, 12)], {1450
shadows: 3,1451
tide: 11,1452
wind: 'changing',1453
companions: [1454
[170, 180],1455
[830, 190],1456
[220, 350],1457
[780, 350]1458
],1459
pattern: 'tide'1460
}],1461
[36, '黎明的練習', '從霧燈開始,沿風的方向,讓花園慢慢醒來。', [root(250, 520, 6), root(760, 520, 6)], {1462
shadows: 2,1463
fog: true,1464
lamps: [1465
[200, 240],1466
[760, 220]1467
],1468
wind: 'changing',1469
thorns: [wall(430, 240, 570, 240)],1470
pattern: 'ring'1471
}],1472
[37, '夜晚的拼圖', '穿過兩對月門,把荊棘與燈光拼成歸途。月門即使能繞行,也需要走過一次。', [root(200, 510), root(500, 500), root(820, 510)], {1473
shadows: 2,1474
fog: true,1475
lamps: [1476
[260, 230],1477
[750, 300]1478
],1479
portals: [pair(150, 330, 680, 180), pair(840, 200, 330, 410)],1480
thorns: [wall(480, 170, 480, 355)],1481
pattern: 'banks'1482
}],1483
[38, '等一朵花醒來', '風、潮汐與遠方的夥伴,都會等到你。', [root(500, 535, 12)], {1484
shadows: 2,1485
tide: 10,1486
wind: 'swirl',1487
companions: [1488
[180, 210],1489
[830, 240],1490
[500, 160]1491
],1492
portals: [pair(200, 400, 770, 180)],1493
pattern: 'tide'1494
}],1495
[39, '把長夜折成信', '帶三位夥伴走出霧,跨過荊棘,把星光送回樹下。', [root(220, 520, 6), root(780, 520, 6)], {1496
shadows: 3,1497
fog: true,1498
lamps: [1499
[170, 240],1500
[520, 180],1501
[830, 270]1502
],1503
wind: 'changing',1504
companions: [1505
[230, 160],1506
[760, 170],1507
[500, 360]1508
],1509
thorns: [wall(360, 250, 360, 410), wall(650, 330, 650, 450)],1510
portals: [pair(150, 390, 790, 200)],1511
pattern: 'triangle'1512
}],1513
[40, '你就是那片星空', '點亮三盞燈,穿過兩對月門,帶四位夥伴回家。讓四棵樹開花。', [root(160, 530), root(380, 510), root(640, 520), root(850, 500)], {1514
shadows: 2,1515
fog: true,1516
lamps: [1517
[170, 240],1518
[490, 160],1519
[820, 240]1520
],1521
tide: 12,1522
wind: 'changing',1523
companions: [1524
[160, 160],1525
[830, 150],1526
[300, 260],1527
[700, 250]1528
],1529
portals: [pair(170, 390, 780, 190), pair(830, 390, 230, 190)],1530
thorns: [wall(380, 310, 570, 310), wall(680, 360, 680, 440)],1531
pattern: 'tide'1532
}]1533
];1534
const LEVELS = [{1535
id: 0,1536
world: 0,1537
title: '夜晚,借你一點光',1538
intro: '序章:先熟悉移動與拾光。每次拾起三粒星光,帶回樹根。送回六粒,讓荒蕪開花。',1539
roots: [root(500, 525, 6)],1540
shadows: 0,1541
pattern: 'ring'1542
}, ...P.map(([id, title, intro, roots, extra]) => ({1543
id,1544
world: Math.floor((id - 1) / 5),1545
title,1546
intro,1547
roots,1548
...extra1549
}))];1550
const poems = [1551
'你拾起的不是露水,\n是夜晚尚未說完的話。', '兩岸不再遙遠,\n因為你走過了中間的路。', '微光不需要很亮,\n只要照見下一步。', '那些未曾寄出的信,\n在枝頭長出了名字。', '你替荒原點了一盞燈,\n群星便有了回聲。',1552
'風從你的身邊經過,\n卻把春天留在這裡。', '你逆著風走來的樣子,\n是一粒種子最初的勇敢。', '兜兜轉轉的風,\n也終於找到了可以停留的枝。', '世界輕輕改變方向,\n你仍記得回家的路。', '沒有誰能留住風,\n但花園記得你來過。',1553
'一盞燈不必照亮整個夜晚,\n照亮身邊,就已經很好。', '隔著霧,你看不見我,\n但我們點著同樣的燈。', '風把霧推向遠處,\n你把光帶向歸途。', '有人在燈下等候,\n渡口就不會荒蕪。', '霧散之後,\n每一道腳印都有了名字。',1554
'不是每一條路都筆直,\n溫柔也可以抵達。', '留白不是空無,\n是世界為你留的一扇門。', '在生活折起的地方,\n你種下了一朵花。', '刺叢仍在,\n但你學會了讓燈先行。', '走出迷宮的時候,\n你沒有弄丟心裡的光。',1555
'你以為走向遠方,\n其實是與另一個自己相逢。', '每一次重逢,\n都讓夜晚少一分孤單。', '河流不說話,\n月亮替它搭了一座橋。', '倒影也有歸途,\n就像思念也會抵達。', '迴廊的盡頭沒有答案,\n只有一棵為你開花的樹。',1556
'海把珍藏的星光,\n輕輕放回你的手心。', '有些等待,\n會長成一片溫柔的海。', '風替海寫信,\n你替星光找到歸宿。', '月門的另一端,\n也有人在聽潮。', '當你願意慢下來,\n就能聽見海的呼吸。',1557
'一封信,終於等到收信的人。\n一粒光,終於不再獨行。', '回家的路沒有變短,\n只是從此有人同行。', '燈下多了三個影子,\n夜晚少了三份孤獨。', '你把很遠的思念,\n送到很近的樹下。', '每一粒小小的光,\n都有值得被記住的姓名。',1558
'黎明還沒有到來,\n你已經開始練習盛開。', '原來那些散落的夜晚,\n拼起來就是一座花園。', '一朵花醒來的時候,\n整個世界都輕了一點。', '長夜折成一封信,\n收信人是明天的你。', '你曾向夜晚借一粒星光。\n如今,你把一整片星空還給了它。'1559
];1560
const clamp = (n, a, b) => Math.max(a, Math.min(b, n));1561
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);1563
function segmentDistance(p, w) {1564
const dx = w.x2 - w.x1,1565
dy = w.y2 - w.y1,1566
u = clamp(((p.x - w.x1) * dx + (p.y - w.y1) * dy) / (dx * dx + dy * dy), 0, 1);1567
return Math.hypot(p.x - w.x1 - u * dx, p.y - w.y1 - u * dy)1568
}1569
class Game {1570
constructor(level, emit = () => {}, snapshot = null) {1571
this.level = level;1572
this.emit = emit;1573
this.seed = level.id * 811 + 2718;1574
this.time = 0;1575
this.carry = 0;1576
this.hits = 0;1577
this.complete = false;1578
this.player = {1579
x: 500,1580
y: 5851581
};1582
this.target = {1583
...this.player1584
};1585
this.shield = 0;1586
this.cooldown = 0;1587
this.invulnerable = 0;1588
this.portalCooldown = 0;1589
this.portalLatch = false;1590
this.depositWait = 0;1591
this.roots = level.roots.map(r => ({1592
...r,1593
received: 01594
}));1595
this.lamps = (level.lamps || []).map(([x, y]) => ({1596
x,1597
y,1598
lit: false1599
}));1600
this.portals = (level.portals || []).map(points => ({1601
points,1602
used: false1603
}));1604
this.companions = (level.companions || []).map(([x, y]) => ({1605
x,1606
y,1607
status: 'waiting'1608
}));1609
this.stars = [];1610
this.assist = false;1611
for (let i = 0; i < 12; i++) this.stars.push(this.spawnStar(i));1612
if (snapshot) {1613
this.restoreFailed = !this.restore(snapshot)1614
}1615
}1616
random() {1617
this.seed = (1664525 * this.seed + 1013904223) >>> 0;1618
return this.seed / 42949672961619
}1620
safe(p) {1621
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)1622
}1623
spawnStar(index) {1624
let p = {1625
x: 100,1626
y: 1801627
};1628
for (let attempt = 0; attempt < 250; attempt++) {1629
const u = this.random(),1630
v = this.random(),1631
n = index % 12;1632
switch (this.level.pattern) {1633
case 'banks':1634
p = {1635
x: (n % 2 ? 610 : 110) + u * 265,1636
y: 140 + v * 3101637
};1638
break;1639
case 'trail':1640
p = {1641
x: 110 + n / 11 * 770 + (u - .5) * 65,1642
y: 270 + Math.sin(n * .85 + this.level.id) * 125 + (v - .5) * 951643
};1644
break;1645
case 'triangle':1646
p = {1647
x: 135 + u * 730,1648
y: 140 + v * 3301649
};1650
break;1651
case 'tide':1652
p = {1653
x: 100 + u * 800,1654
y: 220 + v * 2351655
};1656
break;1657
default:1658
p = {1659
x: 500 + Math.cos(n / 12 * Math.PI * 2 + u * .4) * ((230 + v * 120)),1660
y: 320 + Math.sin(n / 12 * Math.PI * 2 + u * .4) * (130 + v * 45)1661
};1662
}1663
p.x = clamp(p.x, 80, 920);1664
p.y = clamp(p.y, 130, 475);1665
if (this.safe(p) && dist(p, this.player) > 105 && this.stars.every(s => dist(p, s) > 42)) break;1666
}1667
// A bounded fallback grid guarantees valid, non-overlapping positions.1668
if (!this.safe(p) || dist(p, this.player) <= 105 || this.stars.some(s => dist(p, s) < 35)) {1669
const choices = [];1670
for (let x = 85; x <= 915; x += 55)1671
for (let y = 140; y <= 470; y += 55) {1672
const q = {1673
x,1674
y1675
};1676
if (this.safe(q) && dist(q, this.player) > 105 && this.stars.every(s => dist(q, s) > 40)) choices.push(q)1677
}1678
if (choices.length) p = choices[Math.floor(this.random() * choices.length)];1679
}1680
return {1681
...p,1682
phase: this.random() * Math.PI * 2,1683
tidal: !!this.level.tide && index % 3 !== 01684
};1685
}1686
get required() {1687
return this.roots.reduce((n, r) => n + r.need, 0)1688
}1689
get delivered() {1690
return this.roots.reduce((n, r) => n + r.received, 0)1691
}1692
get ebb() {1693
return !this.level.tide || (this.time % this.level.tide) < this.level.tide * .61694
}1695
get tideSeconds() {1696
if (!this.level.tide) return 0;1697
const t = this.time % this.level.tide;1698
return Math.ceil((this.ebb ? this.level.tide * .6 : this.level.tide) - t)1699
}1700
starVisible(s) {1701
return !s.tidal || this.ebb1702
}1703
visibleAt(p) {1704
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)1705
}1706
shadows() {1707
return Array.from({1708
length: this.level.shadows || 01709
}, (_, i) => {1710
const t = this.time * (this.assist ? .64 : 1);1711
return {1712
x: 500 + Math.sin(t * (.22 + i * .025) + i * 2.31 + this.level.id * .24) * (290 + i % 2 * 75),1713
y: 315 + Math.cos(t * (.29 + i * .03) + i * 2.37) * 1221714
}1715
})1716
}1717
wind() {1718
const p = this.level.windPower || 1;1719
if (!this.level.wind || this.shield > 0) return {1720
x: 0,1721
y: 01722
};1723
switch (this.level.wind) {1724
case 'east':1725
return {1726
x: 49 * p, y: 8 * Math.sin(this.time)1727
};1728
case 'west':1729
return {1730
x: -49 * p, y: 8 * Math.cos(this.time)1731
};1732
case 'changing':1733
return {1734
x: Math.sin(this.time * .45) * 70 * p, y: Math.cos(this.time * .31) * 25 * p1735
};1736
default: {1737
const dx = this.player.x - 500,1738
dy = this.player.y - 330,1739
d = Math.max(60, Math.hypot(dx, dy));1740
return {1741
x: -dy / d * 65 * p,1742
y: dx / d * 47 * p1743
}1744
}1745
}1746
}1747
pulse() {1748
if (this.complete || this.cooldown > 0) return false;1749
this.shield = 2.8;1750
this.cooldown = 8;1751
this.emit('pulse', {1752
...this.player1753
});1754
return true1755
}1756
hurt(reason) {1757
if (this.invulnerable > 0 || this.shield > 0 || this.complete) return;1758
this.hits++;1759
const lost = this.carry > 0;1760
if (lost) this.carry--;1761
this.invulnerable = 2.5;1762
this.emit('hurt', {1763
reason,1764
lost,1765
...this.player1766
})1767
}1768
step(dt, input = {1769
x: 0,1770
y: 01771
}) {1772
if (this.complete) return;1773
dt = clamp(dt, 0, .05);1774
this.time += dt;1775
for (const k of ['shield', 'cooldown', 'invulnerable', 'portalCooldown', 'depositWait']) this[k] = Math.max(0, this[k] - dt);1776
let mx = 0,1777
my = 0;1778
const speed = (this.assist ? 260 : 225) * (this.level.tide && !this.ebb && this.player.y > 310 ? .76 : 1);1779
if (input.x || input.y) {1780
const n = Math.hypot(input.x, input.y);1781
mx = input.x / n * speed * dt;1782
my = input.y / n * speed * dt;1783
this.target = {1784
x: this.player.x + mx,1785
y: this.player.y + my1786
}1787
} else {1788
const dx = this.target.x - this.player.x,1789
dy = this.target.y - this.player.y,1790
d = Math.hypot(dx, dy),1791
f = Math.min(1, speed * dt / Math.max(1, d));1792
mx = dx * f;1793
my = dy * f1794
}1795
const wind = this.wind();1796
mx += wind.x * dt;1797
my += wind.y * dt;1798
// Axis-separated collision permits sliding along a thorn instead of getting stuck.1799
for (const [axis, delta] of [1800
['x', mx],1801
['y', my]1802
]) {1803
const p = {1804
...this.player,1805
[axis]: clamp(this.player[axis] + delta, axis === 'x' ? 35 : 100, axis === 'x' ? 965 : 607)1806
};1807
if ((this.level.thorns || []).some(w => segmentDistance(p, w) < 19)) {1808
this.hurt('thorns')1809
} else this.player = p1810
}1811
for (const l of this.lamps)1812
if (!l.lit && dist(l, this.player) < 37) {1813
l.lit = true;1814
this.emit('lamp', l)1815
}1816
if (this.portals.every(p => p.points.every(q => dist(q, this.player) > 48))) this.portalLatch = false;1817
if (!this.portalLatch && this.portalCooldown === 0) {1818
for (let i = 0; i < this.portals.length; i++) {1819
const p = this.portals[i],1820
end = p.points.findIndex(q => dist(q, this.player) < 28);1821
if (end >= 0) {1822
const dest = p.points[1 - end];1823
this.player = {1824
...dest1825
};1826
this.target = {1827
...dest1828
};1829
p.used = true;1830
this.portalLatch = true;1831
this.portalCooldown = 1.4;1832
this.invulnerable = Math.max(this.invulnerable, 1.2);1833
this.companions.filter(c => c.status === 'following').forEach((c, j) => {1834
c.x = dest.x + (j ? 18 : -18);1835
c.y = dest.y + 281836
});1837
this.emit('portal', {1838
...dest,1839
index: i1840
});1841
break1842
}1843
}1844
}1845
for (let i = 0; i < this.stars.length; i++) {1846
const s = this.stars[i];1847
if (this.carry < 3 && this.starVisible(s) && dist(s, this.player) < 25) {1848
this.carry++;1849
this.emit('collect', s);1850
this.stars.splice(i, 1);1851
this.stars.splice(i, 0, this.spawnStar(i));1852
}1853
}1854
let following = this.companions.filter(c => c.status === 'following').length;1855
for (const c of this.companions) {1856
if (c.status === 'waiting' && following < 2 && dist(c, this.player) < 38) {1857
c.status = 'following';1858
following++;1859
this.emit('friend', c)1860
}1861
if (c.status === 'following') {1862
const d = dist(c, this.player);1863
if (d > 20) {1864
const f = Math.min(1, (this.assist ? 225 : 193) * dt / Math.max(1, d));1865
const next = {1866
x: c.x + (this.player.x - c.x) * f,1867
y: c.y + (this.player.y - c.y) * f1868
};1869
// Companions are wisps: they can follow through foliage and never become trapped.1870
c.x = next.x;1871
c.y = next.y;1872
}1873
const home = this.roots.find(r => dist(r, this.player) < 58 && dist(r, c) < 62);1874
if (home) {1875
c.status = 'home';1876
c.x = home.x + ((this.companions.indexOf(c) % 3) - 1) * 22;1877
c.y = home.y - 25;1878
this.emit('home', c)1879
}1880
}1881
}1882
if (this.carry === 3 && this.depositWait === 0) {1883
const r = this.roots.find(r => r.received < r.need && dist(r, this.player) < 42);1884
if (r) {1885
r.received += 3;1886
this.carry = 0;1887
this.depositWait = .8;1888
this.emit('deposit', r)1889
}1890
}1891
for (const s of this.shadows())1892
if (dist(s, this.player) < 29) this.hurt('shadow');1893
if (this.delivered === this.required && this.lamps.every(l => l.lit) && this.portals.every(p => p.used) && this.companions.every(c => c.status === 'home')) {1894
this.complete = true;1895
this.emit('complete', {1896
rating: this.hits === 0 ? 3 : this.hits <= 3 ? 2 : 11897
})1898
}1899
}1900
snapshot() {1901
const keys = ['time', 'seed', 'carry', 'hits', 'player', 'target', 'roots', 'lamps', 'portals', 'companions', 'stars', 'shield', 'cooldown', 'invulnerable', 'portalCooldown', 'portalLatch', 'depositWait'];1902
return JSON.parse(JSON.stringify(Object.fromEntries([1903
['levelId', this.level.id], ...keys.map(k => [k, this[k]])1904
])))1905
}1906
restore(s) {1907
if (!s || s.levelId !== this.level.id) return false;1908
const position = p => p && Number.isFinite(p.x) && Number.isFinite(p.y) && p.x >= 0 && p.x <= 1000 && p.y >= 0 && p.y <= 640;1909
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;1910
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;1911
if (!Array.isArray(s.lamps) || s.lamps.length !== this.lamps.length || !s.lamps.every(l => typeof l.lit === 'boolean')) return false;1912
if (!Array.isArray(s.portals) || s.portals.length !== this.portals.length || !s.portals.every(p => typeof p.used === 'boolean')) return false;1913
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;1914
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;1915
const timers = ['shield', 'cooldown', 'invulnerable', 'portalCooldown', 'depositWait'];1916
if (!timers.every(k => Number.isFinite(s[k]) && s[k] >= 0 && s[k] <= 8) || typeof s.portalLatch !== 'boolean') return false;1917
for (const k of ['time', 'seed', 'carry', 'hits', ...timers, 'portalLatch']) this[k] = s[k];1918
this.player = {1919
...s.player1920
};1921
this.target = {1922
...s.target1923
};1924
this.roots.forEach((r, i) => r.received = s.roots[i].received);1925
this.lamps.forEach((l, i) => l.lit = s.lamps[i].lit);1926
this.portals.forEach((p, i) => p.used = s.portals[i].used);1927
this.companions = s.companions.map(c => ({1928
...c1929
}));1930
this.stars = s.stars.map(p => ({1931
...p1932
}));1933
return true;1934
}1935
}1936
return {1937
WORLDS,1938
LEVELS,1939
poems,1940
Game,1941
dist,1942
segmentDistance,1943
clamp1944
};1945
})();1946
if (typeof module !== 'undefined' && module.exports) module.exports = NightGarden;1948
</script>1949
<script>1950
/* Original, locally synthesized ambient score. No downloads or network playback. */1951
class NightMusic {1952
constructor(context) {1953
this.context = context;1954
this.playing = false;1955
this.timer = null;1956
this.step = 0;1957
this.nextTime = 0;1958
this.world = 0;1959
this.volume = .42;1960
this.voices = new Set();1961
this.ending = false;1962
this.breeze = null;1963
this.windBuffer = null;1964
const a = context;1965
this.master = a.createGain();1966
this.master.gain.value = 0;1967
this.master.connect(a.destination);1968
this.score = a.createGain();1969
this.score.gain.value = 1;1970
this.score.connect(this.master);1971
this.dry = a.createGain();1972
this.dry.gain.value = .8;1973
this.dry.connect(this.score);1974
this.reverb = a.createConvolver();1975
this.wet = a.createGain();1976
this.wet.gain.value = .28;1977
this.reverb.connect(this.wet);1978
this.wet.connect(this.score);1979
const length = Math.ceil(a.sampleRate * 2.8),1980
impulse = a.createBuffer(2, length, a.sampleRate);1981
let seed = 7321;1982
for (let c = 0; c < 2; c++) {1983
const channel = impulse.getChannelData(c);1984
for (let i = 0; i < length; i++) {1985
seed = (1664525 * seed + 1013904223) >>> 0;1986
channel[i] = (seed / 4294967296 * 2 - 1) * Math.pow(1 - i / length, 3.1) * .51987
}1988
}1989
this.reverb.buffer = impulse;1990
}1991
setVolume(value) {1992
this.volume = Math.max(0, Math.min(1, value));1993
if (this.playing) this.master.gain.setTargetAtTime(this.volume, this.context.currentTime, .12)1994
}1995
setWorld(world) {1996
this.world = Math.max(0, Math.min(7, world))1997
}1998
setEnding(enabled) {1999
enabled = !!enabled;2000
if (this.ending === enabled) return;2001
this.ending = enabled;2002
const now = this.context.currentTime;2003
this.score.gain.cancelScheduledValues(now);2004
this.score.gain.setTargetAtTime(enabled ? 0 : 1, now, .55);2005
if (enabled && this.playing) this.startWind();2006
else if (!enabled) this.stopWind();2007
}2008
startWind() {2009
if (this.breeze) return;2010
const a = this.context,2011
now = a.currentTime;2012
if (!this.windBuffer) {2013
const length = Math.ceil(a.sampleRate * 16);2014
// Two gentle smoothing stages soften the noise before the wind filters.2015
const smoothing = 1 - Math.exp(-2 * Math.PI * 900 / a.sampleRate);2016
this.windBuffer = a.createBuffer(2, length, a.sampleRate);2017
let seed = 19073;2018
for (let c = 0; c < 2; c++) {2019
const channel = this.windBuffer.getChannelData(c);2020
let smooth = 0,2021
soft = 0;2022
for (let i = 0; i < length; i++) {2023
seed = (1664525 * seed + 1013904223) >>> 0;2024
channel[i] = seed / 4294967296 * 2 - 1;2025
}2026
// Warm up on the same noise cycle so the loop has no gap or gain dip.2027
for (let pass = 0; pass < 2; pass++)2028
for (let i = 0; i < length; i++) {2029
smooth += smoothing * (channel[i] - smooth);2030
soft += smoothing * (smooth - soft);2031
if (pass === 1) channel[i] = soft * 1.8;2032
}2033
}2034
}2035
const source = a.createBufferSource(),2036
highpass = a.createBiquadFilter(),2037
lowpass = a.createBiquadFilter();2038
const gust = a.createGain(),2039
fade = a.createGain(),2040
lfo = a.createOscillator(),2041
depth = a.createGain(),2042
cutoffDepth = a.createGain();2043
source.buffer = this.windBuffer;2044
source.loop = true;2045
highpass.type = 'highpass';2046
highpass.frequency.value = 180;2047
highpass.Q.value = .35;2048
lowpass.type = 'lowpass';2049
lowpass.frequency.value = 650;2050
lowpass.Q.value = .35;2051
gust.gain.value = .075;2052
depth.gain.value = .008;2053
cutoffDepth.gain.value = 40;2054
lfo.type = 'sine';2055
lfo.frequency.value = .035;2056
source.connect(highpass);2057
highpass.connect(lowpass);2058
lowpass.connect(gust);2059
gust.connect(fade);2060
fade.connect(this.master);2061
lfo.connect(depth);2062
depth.connect(gust.gain);2063
lfo.connect(cutoffDepth);2064
cutoffDepth.connect(lowpass.frequency);2065
fade.gain.setValueAtTime(0, now);2066
fade.gain.setTargetAtTime(1, now, 1.2);2067
const nodes = {2068
source,2069
highpass,2070
lowpass,2071
gust,2072
fade,2073
lfo,2074
depth,2075
cutoffDepth2076
};2077
this.breeze = nodes;2078
source.onended = () => {2079
for (const node of Object.values(nodes)) node.disconnect()2080
};2081
source.start(now);2082
lfo.start(now);2083
}2084
stopWind() {2085
const nodes = this.breeze;2086
if (!nodes) return;2087
this.breeze = null;2088
const now = this.context.currentTime;2089
nodes.fade.gain.cancelScheduledValues(now);2090
nodes.fade.gain.setTargetAtTime(0, now, .035);2091
nodes.source.stop(now + .18);2092
nodes.lfo.stop(now + .18);2093
}2094
tone(midi, time, duration, gain, kind = 'bell') {2095
const a = this.context,2096
o = a.createOscillator(),2097
g = a.createGain(),2098
filter = a.createBiquadFilter();2099
o.type = kind === 'pad' ? 'triangle' : 'sine';2100
o.frequency.value = 440 * Math.pow(2, (midi - 69) / 12);2101
filter.type = 'lowpass';2102
filter.frequency.value = kind === 'pad' ? 650 : 2600;2103
filter.Q.value = .35;2104
const attack = kind === 'pad' ? .9 : .018;2105
g.gain.setValueAtTime(0, time);2106
g.gain.linearRampToValueAtTime(gain, time + attack);2107
g.gain.exponentialRampToValueAtTime(.0001, time + duration);2108
o.connect(filter);2109
filter.connect(g);2110
g.connect(this.dry);2111
g.connect(this.reverb);2112
this.voices.add(o);2113
o.onended = () => {2114
this.voices.delete(o);2115
o.disconnect();2116
filter.disconnect();2117
g.disconnect()2118
};2119
o.start(time);2120
o.stop(time + duration + .05);2121
}2122
schedule() {2123
if (!this.playing || this.ending || this.context.state !== 'running') return;2124
const a = this.context;2125
if (this.nextTime < a.currentTime - .15) this.nextTime = a.currentTime + .05;2126
const chords = [2127
[48, 55, 59, 64],2128
[45, 52, 55, 60],2129
[41, 48, 55, 57],2130
[43, 50, 55, 60],2131
[38, 45, 53, 57],2132
[40, 47, 55, 59],2133
[41, 48, 52, 57],2134
[43, 50, 55, 62]2135
];2136
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];2137
const transpose = [0, 2, -2, -3, 4, 0, 2, 5][this.world],2138
eighth = 60 / 64 / 2;2139
while (this.nextTime < a.currentTime + .24) {2140
const slot = this.step % 64,2141
bar = Math.floor(slot / 8),2142
chord = chords[bar],2143
at = this.nextTime;2144
if (slot % 8 === 0) {2145
chord.forEach((n, i) => this.tone(n + transpose, at + i * .025, 5.1, i === 0 ? .029 : .016, 'pad'));2146
this.tone(chord[0] - 12 + transpose, at, 3.1, .027)2147
}2148
if (slot % 2 === 0) this.tone(chord[(slot / 2) % 4] + 12 + transpose, at, 1.9, .029);2149
if (melody[slot] !== null) this.tone(melody[slot] + transpose, at + .025, 2.6, slot % 8 === 0 ? .051 : .039);2150
this.step++;2151
this.nextTime += eighth;2152
}2153
}2154
start() {2155
if (this.playing) return;2156
this.playing = true;2157
this.nextTime = this.context.currentTime + .045;2158
this.master.gain.cancelScheduledValues(this.context.currentTime);2159
this.master.gain.setTargetAtTime(this.volume, this.context.currentTime, .3);2160
if (this.ending) this.startWind();2161
this.schedule();2162
this.timer = setInterval(() => this.schedule(), 100)2163
}2164
stop() {2165
if (this.timer !== null) {2166
clearInterval(this.timer);2167
this.timer = null2168
}2169
this.playing = false;2170
this.stopWind();2171
const now = this.context.currentTime;2172
this.master.gain.cancelScheduledValues(now);2173
this.master.gain.setTargetAtTime(0, now, .035);2174
for (const voice of this.voices) {2175
try {2176
voice.stop(now + .17)2177
} catch (e) {}2178
}2179
}2180
}2181
if (typeof module !== 'undefined' && module.exports) module.exports = NightMusic;2183
(() => {2184
'use strict';2185
const {2186
Game,2187
LEVELS,2188
WORLDS,2189
poems,2190
clamp2191
} = NightGarden;2192
const $ = id => document.getElementById(id),2193
canvas = $('garden'),2194
ctx = canvas.getContext('2d');2195
const fogCanvas = document.createElement('canvas'),2196
fogCtx = fogCanvas.getContext('2d');2197
const SAVE_KEY = 'borrowed-light-campaign-v2';2198
let save = {2199
version: 2,2200
active: 1,2201
completed: {},2202
snapshots: {},2203
settings: {2204
sound: false,2205
music: true,2206
musicVolume: .42,2207
assist: false,2208
motion: matchMedia('(prefers-reduced-motion: reduce)').matches2209
}2210
};2211
let storageOK = true,2212
saveNotice = '',2213
running = false,2214
game, activeDialog = 'welcome',2215
mapReturn = 'welcome',2216
W = 1000,2217
H = 640,2218
dpr = 1,2219
sx = 1,2220
sy = 1,2221
visualScale = 1,2222
last = 0,2223
clock = 0,2224
endDelay = 0,2225
saveTimer = 0,2226
dirty = false,2227
particles = [],2228
trail = [],2229
petals = [],2230
petalTime = 0,2231
petalSpawn = 0,2232
audio = null,2233
music = null,2234
audioReady = false,2235
audioPending = false,2236
trees = [],2237
lastUI = '',2238
lastPulse = '',2239
keys = new Set();2240
try {2241
const raw = localStorage.getItem(SAVE_KEY);2242
if (raw) {2243
const data = JSON.parse(raw);2244
if (data.version === 2 && data.completed && typeof data.completed === 'object') {2245
for (let i = 0; i <= 40; i++) {2246
const r = data.completed[i];2247
if (r && Number.isInteger(r.rating) && r.rating >= 1 && r.rating <= 3 && Number.isInteger(r.hits) && r.hits >= 0) save.completed[i] = {2248
rating: r.rating,2249
hits: r.hits2250
};2251
}2252
if (data.settings)2253
for (const key of ['sound', 'music', 'assist', 'motion'])2254
if (typeof data.settings[key] === 'boolean') save.settings[key] = data.settings[key];2255
if (Number.isFinite(data.settings?.musicVolume)) save.settings.musicVolume = clamp(data.settings.musicVolume, 0, 1);2256
if (data.snapshots && typeof data.snapshots === 'object')2257
for (let i = 0; i <= 40; i++)2258
if (data.snapshots[i]) {2259
const trial = new Game(LEVELS[i]);2260
if (trial.restore(data.snapshots[i])) save.snapshots[i] = trial.snapshot()2261
}2262
if (Number.isInteger(data.active) && data.active >= 0 && data.active <= unlocked()) save.active = data.active;2263
} else saveNotice = '舊存檔格式不適用,已開始新的旅程。';2264
}2265
} catch (e) {2266
storageOK = false;2267
saveNotice = '本機存檔暫不可用;請保持頁面打開。'2268
}2270
function unlocked() {2271
let n = 1;2272
while (n < 40 && save.completed[n]) n++;2273
return n2274
}2276
function persist() {2277
if (!game) return;2278
if (!game.complete && running) save.snapshots[game.level.id] = game.snapshot();2279
save.active = game.level.id;2280
try {2281
localStorage.setItem(SAVE_KEY, JSON.stringify(save));2282
storageOK = true;2283
$('save-status').textContent = '已保存 · 當前瀏覽器';2284
$('pause-save').textContent = '進度已保存在當前瀏覽器;下次打開可繼續。'2285
} catch (e) {2286
storageOK = false;2287
$('save-status').textContent = '存檔不可用 · 請保持頁面打開';2288
$('pause-save').textContent = '當前瀏覽器無法保存;關閉頁面會丟失進度。'2289
}2290
dirty = false;2291
saveTimer = 02292
}2294
function stash() {2295
if (game && !game.complete) save.snapshots[game.level.id] = game.snapshot();2296
persist()2297
}2299
function getAudio() {2300
audio = audio || new(window.AudioContext || window.webkitAudioContext)();2301
return audio2302
}2304
function audioFailure() {2305
audioReady = false;2306
audioPending = false;2307
if (music) music.stop();2308
$('sound').textContent = '音樂 · 重試';2309
$('sound').setAttribute('aria-pressed', 'false');2310
message('聲音暫未啟動,點擊「音樂 · 重試」再試一次。')2311
}2313
function syncMusic() {2314
if (!music) return;2315
music.setWorld(game?.level.world || 0);2316
music.setEnding(!!game?.complete);2317
music.setVolume(save.settings.musicVolume);2318
if (audioReady && save.settings.music && (running || (game?.complete && activeDialog === 'result')) && !document.hidden) music.start();2319
else music.stop()2320
}2322
function unlockAudio() {2323
if (!save.settings.music && !save.settings.sound) return;2324
try {2325
const a = getAudio();2326
if (!music) music = new NightMusic(a);2327
if (a.state === 'running') {2328
audioReady = true;2329
syncMusic();2330
return2331
}2332
if (audioPending) return;2333
audioPending = true;2334
a.resume().then(() => {2335
audioPending = false;2336
audioReady = a.state === 'running';2337
if (audioReady) syncMusic();2338
else audioFailure()2339
}).catch(audioFailure)2340
} catch (e) {2341
audioFailure()2342
}2343
}2345
function note(n, long = false) {2346
if (!save.settings.sound || document.hidden) return;2347
try {2348
const a = getAudio();2349
if (a.state !== 'running') return;2350
const now = a.currentTime,2351
o = a.createOscillator(),2352
g = a.createGain();2353
o.type = 'sine';2354
o.frequency.value = [261.63, 293.66, 329.63, 392, 440, 523.25, 587.33, 659.25][n % 8];2355
g.gain.setValueAtTime(0, now);2356
g.gain.linearRampToValueAtTime(.055, now + .025);2357
g.gain.exponentialRampToValueAtTime(.0001, now + (long ? 2.7 : 1.25));2358
o.connect(g);2359
g.connect(a.destination);2360
o.onended = () => {2361
o.disconnect();2362
g.disconnect()2363
};2364
o.start();2365
o.stop(now + (long ? 2.8 : 1.3))2366
} catch (e) {2367
audioFailure()2368
}2369
}2371
function message(text) {2372
$('message').textContent = text2373
}2375
function burst(p, color, n = 16) {2376
if (save.settings.motion) return;2377
for (let i = 0; i < n; i++) particles.push({2378
x: p.x,2379
y: p.y,2380
vx: (Math.random() - .5) * 110,2381
vy: -Math.random() * 80,2382
life: 1 + Math.random(),2383
color2384
});2385
if (particles.length > 220) particles.splice(0, particles.length - 220)2386
}2388
function spawnPetal() {2389
if (petals.length >= 84 || !trees.length) return;2390
const index = Math.floor(Math.random() * trees.length),2391
tree = trees[index],2392
root = game.roots[index];2393
const leaf = tree.leaves[Math.floor(Math.random() * tree.leaves.length)],2394
unit = fringeTreeUnit();2395
petals.push({2396
x: root.x + leaf.x * unit / sx + (Math.random() - .5) * 9,2397
y: root.y + leaf.y * unit / sy,2398
size: 4.5 + Math.random() * 3.2,2399
angle: Math.random() * Math.PI * 2,2400
spin: (Math.random() - .5) * 1.7,2401
phase: Math.random() * Math.PI * 2,2402
speed: 12 + Math.random() * 13,2403
age: 0,2404
life: 22 + Math.random() * 10,2405
color: Math.random() < .5 ? '#f8f8ee' : '#e8eede'2406
});2407
}2409
function startPetals() {2410
petals = [];2411
petalTime = 0;2412
petalSpawn = 0;2413
if (save.settings.motion) return;2414
for (let i = 0; i < Math.min(36, 18 + game.roots.length * 5); i++) spawnPetal();2415
}2417
function updatePetals(dt) {2418
petalTime += dt;2419
const direction = game.level.wind === 'west' ? -1 : 1;2420
const breeze = direction * (14 + Math.sin(petalTime * .24) * 10);2421
for (const p of petals) {2422
p.age += dt;2423
p.x += (breeze + Math.sin(petalTime * .75 + p.phase) * 10) * dt;2424
p.y += p.speed * (.85 + Math.sin(petalTime * 1.15 + p.phase) * .15) * dt;2425
p.angle += (p.spin + Math.sin(petalTime * .6 + p.phase) * .25) * dt;2426
}2427
petals = petals.filter(p => p.age < p.life && p.y < 660 && p.x > -35 && p.x < 1035);2428
petalSpawn += dt * (game.level.id === 40 ? 7 : 5);2429
while (petalSpawn >= 1) {2430
spawnPetal();2431
petalSpawn--2432
}2433
}2435
function drawPetals() {2436
if (!game.complete || save.settings.motion) return;2437
for (const p of petals) {2438
const fadeIn = Math.min(1, p.age / .65),2439
fadeOut = Math.min(1, (p.life - p.age) / 3);2440
const r = clamp(p.size * sx * visualScale, 2.4, 7.5);2441
ctx.save();2442
ctx.translate(p.x, p.y);2443
ctx.scale(1 / sx, 1 / sy);2444
ctx.rotate(p.angle);2445
ctx.scale(.3 + Math.abs(Math.cos(p.angle * .8)) * .7, 1);2446
ctx.globalAlpha = fadeIn * fadeOut * .82;2447
ctx.fillStyle = p.color;2448
ctx.beginPath();2449
ctx.moveTo(0, -r);2450
ctx.bezierCurveTo(r * .2, -r * .45, r * .32, r * .65, r * .12, r);2451
ctx.bezierCurveTo(-r * .12, r * .55, -r * .15, -r * .65, 0, -r);2452
ctx.fill();2453
ctx.strokeStyle = '#ffffff66';2454
ctx.lineWidth = .35;2455
ctx.beginPath();2456
ctx.moveTo(0, -r * .65);2457
ctx.quadraticCurveTo(r * .18, 0, 0, r * .6);2458
ctx.stroke();2459
ctx.restore();2460
}2461
}2463
function onEvent(type, p) {2464
dirty = true;2465
const color = '#f2f3e5';2466
if (type === 'collect') {2467
burst(p, '#ead29c', 10);2468
note(game.carry + game.delivered);2469
message(game.carry === 3 ? '懷裡裝滿了星光,回到還沒種亮的樹根吧。' : `拾起了 ${game.carry} 粒光,帶滿三粒就可以回家。`)2470
}2471
if (type === 'hurt') {2472
burst(p, '#acc5d5', 14);2473
message(p.lost ? '風吹散了一粒光。沒關係,已經種下的光還在。' : '輕輕繞過' + (p.reason === 'thorns' ? '荊棘,留白處可以通行。' : '墨影;空格可以短暫護住自己。'))2474
}2475
if (type === 'pulse') {2476
burst(p, '#d8e4cf', 22);2477
note(4);2478
message('屏住呼吸,讓風與墨影從身邊經過。荊棘仍需繞行。')2479
}2480
if (type === 'deposit') {2481
burst(p, color, 40);2482
note(2 + game.delivered / 3, true);2483
message(game.delivered === game.required ? '樹已經種亮了,再看看本關還有哪些約定沒有完成。' : '一段樹枝醒來了。下一粒光,會在哪裡?')2484
}2485
if (type === 'lamp') {2486
burst(p, '#ead3a0', 22);2487
note(5);2488
message('燈亮了。它會替你記住這條路。')2489
}2490
if (type === 'portal') {2491
burst(p, '#c8bde7', 27);2492
note(6);2493
message('月亮替你摺疊了距離。同行的夥伴也到了。')2494
}2495
if (type === 'friend') {2496
burst(p, '#dce5b0', 15);2497
note(4);2498
message('一位夥伴跟上了你,帶它回到任意樹根。一次最多同行兩位。')2499
}2500
if (type === 'home') {2501
burst(p, '#e8cf95', 25);2502
note(5, true);2503
message('夥伴到家了。這個夜晚,少了一份孤單。')2504
}2505
if (type === 'complete') {2506
const id = game.level.id,2507
old = save.completed[id];2508
if (!old || p.rating > old.rating || (p.rating === old.rating && game.hits < old.hits)) save.completed[id] = {2509
rating: p.rating,2510
hits: game.hits2511
};2512
delete save.snapshots[id];2513
persist();2514
endDelay = 3.6;2515
startPetals();2516
syncSettings();2517
syncMusic();2518
burst({2519
x: 500,2520
y: 3002521
}, color, 85);2522
note(7, true);2523
message(id === 40 ? '你向夜晚借來的光,已經長成了一整片星空。' : '這一夜,被你種亮了。');2524
}2525
}2527
function fringeTreeUnit() {2528
return clamp(sx * 1.1, .5, 1.05)2529
}2531
function makeTree(seed) {2532
const out = [],2533
leaves = [];2534
let rng = seed + 41;2535
const rand = () => {2536
rng = (rng * 1664525 + 1013904223) >>> 0;2537
return rng / 42949672962538
};2540
function branch(x, y, len, angle, depth) {2541
const ex = x + Math.cos(angle) * len,2542
ey = y + Math.sin(angle) * len;2543
out.push({2544
x,2545
y,2546
ex,2547
ey,2548
depth,2549
bend: (rand() - .5) * 92550
});2551
if (depth === 4) {2552
const leaf = {2553
x: ex,2554
y: ey,2555
phase: rand() * 6.28,2556
order: rand(),2557
foliage: [],2558
flowers: [],2559
art: {}2560
};2561
for (let j = 0; j < 4; j++) leaf.foliage.push({2562
x: (rand() - .5) * 25,2563
y: (rand() - .5) * 15 + 5,2564
angle: (rand() - .5) * 2.8,2565
size: 7 + rand() * 52566
});2567
for (let j = 0; j < 5; j++) leaf.flowers.push({2568
x: (rand() - .5) * 28,2569
y: (rand() - .5) * 21,2570
angle: (rand() - .5) * 1.2,2571
length: 8 + rand() * 6,2572
bend: (rand() - .5) * 42573
});2574
leaves.push(leaf);2575
return;2576
}2577
if (depth === 0) {2578
for (const delta of [-.64, .05, .69]) branch(ex, ey, 34 + rand() * 6, angle + delta, 1)2579
} else {2580
const spread = .42 + rand() * .17;2581
branch(ex, ey, len * .7, angle - spread, depth + 1);2582
branch(ex, ey, len * .7, angle + spread, depth + 1)2583
}2584
}2585
branch(0, 0, 46, -Math.PI / 2 + (rand() - .5) * .08, 0);2586
const inner = out.filter(b => b.depth === 3);2587
inner.forEach((b, i) => leaves.unshift({2588
...leaves[leaves.length - 1 - i],2589
x: b.ex,2590
y: b.ey - 42591
}));2592
return {2593
out,2594
leaves2595
};2596
}2598
function loadLevel(id, resume = true) {2599
if (id < 0 || id > 40 || id > unlocked()) return;2600
game = new Game(LEVELS[id], onEvent, resume ? save.snapshots[id] : null);2601
game.assist = save.settings.assist;2602
if (game.restoreFailed) {2603
delete save.snapshots[id];2604
const note = '先前的進度與此版本略有不同,這一夜將重新開始。已完成的夜晚仍會保留。';2605
saveNotice = saveNotice || note;2606
try {2607
localStorage.setItem(SAVE_KEY, JSON.stringify(save))2608
} catch (e) {}2609
}2610
save.active = id;2611
particles = [];2612
trail = [];2613
petals = [];2614
petalTime = 0;2615
petalSpawn = 0;2616
endDelay = 0;2617
keys.clear();2618
lastUI = '';2619
trees = game.roots.map((_, i) => makeTree(id * 53 + i * 31));2620
document.documentElement.style.setProperty('--gold', WORLDS[game.level.world].color);2621
$('level-title').textContent = game.level.title;2622
$('level-intro').textContent = game.level.intro;2623
$('eyebrow').textContent = id ? `${WORLDS[game.level.world].name} · 第 ${String(id).padStart(2,'0')} / 40 夜` : '序章 · 夜的植物誌';2624
$('required').textContent = '/ ' + game.required;2625
$('progress').setAttribute('aria-valuemax', String(game.required));2626
message(game.restoreFailed ? (saveNotice || game.level.intro) : (save.snapshots[id]?.time > 0.5 && resume ? '你離開時的光還在。沿著上次的腳步繼續吧。' : game.level.intro));2627
updateUI();2628
}2629
const dialogs = ['welcome', 'map-dialog', 'briefing', 'pause-dialog', 'result'];2631
function showDialog(id) {2632
running = false;2633
keys.clear();2634
dialogs.forEach(d => $(d).hidden = d !== id);2635
activeDialog = id;2636
$('app').inert = !!id;2637
if (id) {2638
const focus = $(id).querySelector('button:not(:disabled)');2639
if (focus) focus.focus()2640
} else {2641
running = true;2642
canvas.focus();2643
unlockAudio()2644
}2645
syncMusic()2646
}2648
function chooseLevel(id) {2649
if (id > unlocked()) return;2650
stash();2651
loadLevel(id);2652
$('brief-label').textContent = id ? `第 ${id} 夜 · ${WORLDS[game.level.world].name}` : '序章 · 原來的故事';2653
$('brief-mark').textContent = WORLDS[game.level.world].mark;2654
$('brief-title').textContent = game.level.title;2655
$('brief-text').textContent = game.level.intro;2656
showDialog('briefing');2657
persist()2658
}2660
function renderMap() {2661
const completed = Object.keys(save.completed).filter(k => Number(k) > 0).length;2662
$('map-count').textContent = completed;2663
const container = $('chapters');2664
container.replaceChildren();2665
WORLDS.forEach((world, wi) => {2666
const section = document.createElement('section');2667
section.className = 'map-chapter';2668
section.style.setProperty('--chapter', world.color);2669
const heading = document.createElement('div');2670
heading.className = 'chapter-title';2671
const mark = document.createElement('span');2672
mark.className = 'chapter-mark';2673
mark.textContent = world.mark;2674
const h = document.createElement('h3');2675
h.textContent = `${['一','二','三','四','五','六','七','八'][wi]} · ${world.name}`;2676
const desc = document.createElement('p');2677
desc.textContent = world.subtitle;2678
heading.append(mark, h, desc);2679
section.append(heading);2680
const grid = document.createElement('div');2681
grid.className = 'level-grid';2682
LEVELS.slice(wi * 5 + 1, wi * 5 + 6).forEach(level => {2683
const b = document.createElement('button'),2684
record = save.completed[level.id],2685
locked = level.id > unlocked();2686
b.className = 'level-tile' + (game.level.id === level.id ? ' current' : '');2687
b.disabled = locked;2688
b.setAttribute('aria-label', `第 ${level.id} 夜 ${level.title},${locked?'未解鎖':record?`已完成,${record.rating} 枚花印`:save.snapshots[level.id]?'繼續旅程':'可以開始'}`);2689
const num = document.createElement('span');2690
num.className = 'tile-no';2691
num.textContent = String(level.id).padStart(2, '0');2692
const name = document.createElement('span');2693
name.className = 'tile-name';2694
name.textContent = level.title;2695
const state = document.createElement('span');2696
state.className = record ? 'tile-stars' : 'tile-lock';2697
state.textContent = record ? '✦'.repeat(record.rating) + '·'.repeat(3 - record.rating) : locked ? '待前夜開花' : save.snapshots[level.id] ? '繼續 →' : '出發 →';2698
b.append(num, name, state);2699
b.onclick = () => chooseLevel(level.id);2700
grid.append(b)2701
});2702
section.append(grid);2703
container.append(section)2704
})2705
}2707
function openMap() {2708
stash();2709
mapReturn = activeDialog;2710
renderMap();2711
showDialog('map-dialog');2712
requestAnimationFrame(updateMapHint)2713
}2715
function showResult() {2716
const id = game.level.id,2717
record = save.completed[id];2718
$('result-label').textContent = id === 40 ? '四十夜 · 屬於你的花園' : id ? `第 ${id} 夜 · ${WORLDS[game.level.world].name}` : '序章完成 · 四十夜的旅途即將開始';2719
$('result-title').textContent = id === 40 ? '你就是那片星空' : '這一夜,被你種亮了';2720
$('poem').textContent = id ? poems[id - 1] : '那些被你拾起的微光,\n終於有了可以停留的枝頭。';2721
const rating = game.hits === 0 ? 3 : game.hits <= 3 ? 2 : 1;2722
$('rating').textContent = '✦'.repeat(rating) + '·'.repeat(3 - rating);2723
$('rating').setAttribute('aria-label', `${rating} 枚花印`);2724
$('result-meta').textContent = `送回 ${game.required} 粒光 · ${game.hits} 次碰撞 · 最佳 ${record.rating} 枚花印`;2725
$('next-level').textContent = id === 40 ? '回望四十夜' : '走向第 ' + (id + 1) + ' 夜';2726
showDialog('result')2727
}2729
function updateUI() {2730
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]);2731
if (signature !== lastUI) {2732
lastUI = signature;2733
$('delivered').textContent = game.delivered;2734
$('progress-fill').style.width = (game.delivered / game.required * 100) + '%';2735
$('progress').setAttribute('aria-valuenow', String(game.delivered));2736
[...$('pocket').children].forEach((n, i) => n.classList.toggle('on', i < game.carry));2737
$('pocket').setAttribute('aria-label', `攜帶星光 ${game.carry} / 3`);2738
$('pocket-label').textContent = `${game.carry} / 3 · 攜帶中`;2739
const goals = [2740
['星光', game.delivered, game.required],2741
['樹', game.roots.filter(r => r.received === r.need).length, game.roots.length]2742
];2743
if (game.lamps.length) goals.push(['燈', game.lamps.filter(l => l.lit).length, game.lamps.length]);2744
if (game.portals.length) goals.push(['月門', game.portals.filter(p => p.used).length, game.portals.length]);2745
if (game.companions.length) goals.push(['夥伴', game.companions.filter(c => c.status === 'home').length, game.companions.length]);2746
$('objectives').replaceChildren(...goals.map(([label, n, all]) => {2747
const el = document.createElement('span');2748
el.className = 'objective' + (n === all ? ' done' : '');2749
el.textContent = `${n===all?'✓ ':''}${label} ${n} / ${all}`;2750
if (label === '月門') el.title = '月門需要走過一次,才算完成';2751
return el2752
}));2753
const hint = $('goal-hint');2754
if (hint) {2755
const extras = [];2756
if (game.lamps.length) extras.push('燈');2757
if (game.portals.length) extras.push('月門');2758
if (game.companions.length) extras.push('夥伴');2759
hint.textContent = game.complete ? '這一夜的目標都完成了。' : (extras.length ? `還要完成:${extras.join('、')}。全部完成,這一夜才算種亮。` : '送滿星光,讓樹開花。');2760
hint.hidden = false2761
}2762
}2763
const pulseState = game.complete ? '花已開' : game.shield > 0 ? '護光中' : game.cooldown > 0 ? `${Math.ceil(game.cooldown)} 秒` : '屏息';2764
if (lastPulse !== pulseState) {2765
lastPulse = pulseState;2766
updateSoundLabel();2767
$('pulse-label').textContent = pulseState;2768
$('pulse').disabled = game.cooldown > 0 || game.complete2769
}2770
const weather = [];2771
if (game.level.tide) weather.push(`${game.ebb?'退潮 · 拾光':'漲潮 · 等候'} ${game.tideSeconds}s`);2772
if (game.level.wind) weather.push({2773
east: '風向 →',2774
west: '風向 ←',2775
swirl: '迴旋的風',2776
changing: '風向漸變'2777
} [game.level.wind]);2778
if (!weather.length) weather.push('無須趕路');2779
const text = weather.join(' · ');2780
if ($('weather').textContent !== text) $('weather').textContent = text;2781
}2783
function isTouchLayout() {2784
return matchMedia('(max-width:700px), (pointer:coarse)').matches2785
}2787
function updateControlHint() {2788
const el = $('control-hint');2789
if (!el) return;2790
el.textContent = isTouchLayout() ? '用手指在夜色裡拖動來移動。點「屏息」可短暫護光。' : '滑鼠移動、方向鍵或 W A S D 移動 · 空白鍵護光 · Esc 暫停'2791
}2793
function updateMapHint() {2794
const hint = $('map-scroll-hint'),2795
panel = document.querySelector('#map-dialog .map-panel');2796
if (!hint || !panel) return;2797
const more = panel.scrollHeight > panel.clientHeight + 16;2798
hint.hidden = !more2799
}2801
function resize() {2802
W = canvas.clientWidth;2803
H = canvas.clientHeight;2804
dpr = Math.min(devicePixelRatio || 1, 2);2805
sx = W / 1000;2806
sy = H / 640;2807
visualScale = clamp(1 / Math.min(sx, sy), .85, 2.2);2808
canvas.width = Math.round(W * dpr);2809
canvas.height = Math.round(H * dpr);2810
fogCanvas.width = canvas.width;2811
fogCanvas.height = canvas.height;2812
updateControlHint();2813
updateMapHint()2814
}2815
new ResizeObserver(resize).observe(canvas);2816
resize();2817
const circle = (x, y, r) => {2818
ctx.beginPath();2819
ctx.ellipse(x, y, r, r * sx / sy, 0, 0, Math.PI * 2)2820
};2822
function glow(x, y, r, color) {2823
ctx.save();2824
ctx.translate(x, y);2825
ctx.scale(1, sx / sy);2826
const g = ctx.createRadialGradient(0, 0, 0, 0, 0, r);2827
g.addColorStop(0, color);2828
g.addColorStop(1, 'transparent');2829
ctx.fillStyle = g;2830
ctx.fillRect(-r, -r, r * 2, r * 2);2831
ctx.restore()2832
}2834
function label(text, x, y, color = '#bfcdbb', size = 11) {2835
ctx.save();2836
ctx.translate(x, y);2837
ctx.scale(1 / sx, 1 / sy);2838
ctx.font = `${size}px 'Songti TC','Songti SC','Noto Serif CJK TC','Noto Serif CJK SC',Georgia,serif`;2839
ctx.textAlign = 'center';2840
ctx.fillStyle = color;2841
ctx.fillText(text, 0, 0);2842
ctx.restore()2843
}2845
function drawBackground(world, t) {2846
const bg = ctx.createLinearGradient(0, 0, 0, 640);2847
bg.addColorStop(0, world.sky[0]);2848
bg.addColorStop(.68, world.sky[1]);2849
bg.addColorStop(1, '#0d242b');2850
ctx.fillStyle = bg;2851
ctx.fillRect(0, 0, 1000, 640);2852
for (let i = 0; i < 90; i++) {2853
const x = ((i * 137.508) % 997),2854
y = (i * i * 37 % 503) * .78;2855
ctx.globalAlpha = .18 + (save.settings.motion ? .2 : (Math.sin(t * .35 + i) + 1) * .16);2856
ctx.fillStyle = '#dce6d6';2857
circle(x, y, (i % 5 === 0 ? 1.4 : .65) * visualScale);2858
ctx.fill()2859
}2860
ctx.globalAlpha = 1;2861
let moonX = 810,2862
moonY = 118;2863
glow(moonX, moonY, 95, world.color + '19');2864
ctx.fillStyle = '#e5dec0';2865
circle(moonX, moonY, 26);2866
ctx.fill();2867
ctx.save();2868
ctx.clip();2869
ctx.fillStyle = world.sky[0];2870
circle(moonX - 10 - game.level.world * 1.6, moonY - 6, 23);2871
ctx.fill();2872
ctx.restore();2873
for (let layer = 0; layer < 4; layer++) {2874
ctx.beginPath();2875
ctx.moveTo(0, 640);2876
for (let x = 0; x <= 1010; x += 10) {2877
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;2878
ctx.lineTo(x, y)2879
}2880
ctx.lineTo(1000, 640);2881
ctx.closePath();2882
ctx.fillStyle = ['#789a9030', '#41656045', '#16383e77', '#0c252ac9'][layer];2883
ctx.fill()2884
}2885
if (game.level.world === 1 || game.level.wind) {2886
ctx.strokeStyle = '#7baf9d15';2887
ctx.lineWidth = 3;2888
for (let i = 0; i < 12; i++) {2889
const x = i * 97 + 30;2890
ctx.beginPath();2891
ctx.moveTo(x, 530);2892
ctx.quadraticCurveTo(x - 15, 260, x + 8, 95);2893
ctx.stroke();2894
for (let j = 0; j < 5; j++) {2895
const y = 180 + j * 57;2896
ctx.beginPath();2897
ctx.moveTo(x, y);2898
ctx.quadraticCurveTo(x + 22, y - 16, x + 37, y - 5);2899
ctx.stroke()2900
}2901
}2902
}2903
if (game.level.tide) {2904
const y = game.ebb ? 459 : 365;2905
const water = ctx.createLinearGradient(0, y, 0, 600);2906
water.addColorStop(0, '#7ba6b42a');2907
water.addColorStop(1, '#20546605');2908
ctx.fillStyle = water;2909
ctx.fillRect(0, y, 1000, 600 - y);2910
ctx.strokeStyle = '#b5d8d52b';2911
ctx.lineWidth = .8;2912
for (let j = 0; j < 8; j++) {2913
ctx.beginPath();2914
for (let x = 0; x <= 1000; x += 10) ctx.lineTo(x, y + j * 18 + Math.sin(x * .014 + t * .6 + j) * 3);2915
ctx.stroke()2916
}2917
}2918
ctx.strokeStyle = '#97bbb127';2919
ctx.lineWidth = .9;2920
for (let i = 0; i < 60; i++) {2921
const x = i * 83.17 % 1000,2922
y = 604 + i % 4 * 5;2923
ctx.beginPath();2924
ctx.moveTo(x, y);2925
ctx.quadraticCurveTo(x - 6, y - 15, x + Math.sin(i) * 10, y - 16 - i % 6 * 5);2926
ctx.stroke()2927
}2928
}2930
function paintFringeCluster(ctx, cluster, bloom) {2931
ctx.save();2932
for (const leaf of cluster.foliage) {2933
ctx.save();2934
ctx.translate(leaf.x, leaf.y);2935
ctx.rotate(leaf.angle);2936
const shade = ctx.createLinearGradient(-4, 0, 5, 0);2937
shade.addColorStop(0, '#304e3f');2938
shade.addColorStop(.55, '#78947a');2939
shade.addColorStop(1, '#496b51');2940
ctx.fillStyle = shade;2941
ctx.beginPath();2942
ctx.moveTo(0, -leaf.size);2943
ctx.bezierCurveTo(8, -leaf.size * .7, 7, leaf.size * .65, 0, leaf.size);2944
ctx.bezierCurveTo(-6, leaf.size * .5, -7, -leaf.size * .65, 0, -leaf.size);2945
ctx.fill();2946
ctx.strokeStyle = '#b0bf8d55';2947
ctx.lineWidth = .55;2948
ctx.beginPath();2949
ctx.moveTo(0, -leaf.size * .75);2950
ctx.quadraticCurveTo(1, 0, 0, leaf.size * .8);2951
ctx.stroke();2952
ctx.restore();2953
}2954
if (bloom > 0) {2955
ctx.globalAlpha = bloom;2956
for (const flower of cluster.flowers) {2957
ctx.strokeStyle = '#b9bf9980';2958
ctx.lineWidth = .6;2959
ctx.beginPath();2960
ctx.moveTo(0, 8);2961
ctx.quadraticCurveTo(flower.x * .4, 2, flower.x, flower.y);2962
ctx.stroke();2963
ctx.save();2964
ctx.translate(flower.x, flower.y);2965
ctx.rotate(flower.angle);2966
for (let k = 0; k < 4; k++) {2967
ctx.save();2968
ctx.rotate((k - 1.5) * .55);2969
const length = flower.length * (.86 + k * .07),2970
bend = flower.bend;2971
ctx.fillStyle = k % 2 ? '#e8eddf' : '#faf9eb';2972
ctx.beginPath();2973
ctx.moveTo(-.7, 0);2974
ctx.bezierCurveTo(-1.5, length * .35, bend - 1, length * .8, bend, length);2975
ctx.bezierCurveTo(bend + 1.1, length * .75, 1.3, length * .3, .7, 0);2976
ctx.closePath();2977
ctx.fill();2978
ctx.restore();2979
}2980
ctx.fillStyle = '#d5d7a2';2981
ctx.beginPath();2982
ctx.arc(0, 0, 1, 0, Math.PI * 2);2983
ctx.fill();2984
ctx.restore();2985
}2986
ctx.globalAlpha = 1;2987
}2988
ctx.restore();2989
}2991
function drawFringeCluster(cluster, bloom, t) {2992
const key = bloom > 0 ? 'flowers' : 'leaves';2993
if (!cluster.art[key]) {2994
const art = document.createElement('canvas');2995
art.width = 160;2996
art.height = 160;2997
const paint = art.getContext('2d');2998
paint.scale(2, 2);2999
paint.translate(40, 40);3000
paintFringeCluster(paint, cluster, bloom);3001
cluster.art[key] = art;3002
}3003
ctx.save();3004
ctx.translate(cluster.x, cluster.y);3005
if (!save.settings.motion) ctx.rotate(Math.sin(t * .55 + cluster.phase) * .035);3006
ctx.drawImage(cluster.art[key], -40, -40, 80, 80);3007
ctx.restore();3008
}3010
function drawTree(r, index, world, t) {3011
const tree = trees[index],3012
ratio = r.received / r.need,3013
growth = ratio * 4,3014
unit = fringeTreeUnit();3015
ctx.save();3016
ctx.translate(r.x, r.y);3017
glow(0, -15, 75 + ratio * 50, '#e9efd415');3018
ctx.strokeStyle = game.carry === 3 && r.received < r.need ? world.color : '#9bbcaf77';3019
ctx.lineWidth = game.carry === 3 ? 1.7 : 1;3020
ctx.beginPath();3021
ctx.ellipse(0, 0, 41, 12, 0, 0, Math.PI * 2);3022
ctx.stroke();3023
ctx.setLineDash([2, 6]);3024
ctx.beginPath();3025
ctx.ellipse(0, 0, 50, 17, 0, 0, Math.PI * 2);3026
ctx.stroke();3027
ctx.setLineDash([]);3028
ctx.save();3029
ctx.scale(unit / sx, unit / sy);3030
for (const b of tree.out) {3031
const visible = clamp(growth - b.depth + 1, 0, 1);3032
if (!visible) continue;3033
ctx.beginPath();3034
ctx.moveTo(b.x, b.y);3035
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);3036
ctx.lineCap = 'round';3037
ctx.lineWidth = Math.max(.9, 7 - b.depth * 1.5);3038
ctx.strokeStyle = ratio ? '#746e58' : '#6e7e6b';3039
ctx.stroke();3040
ctx.save();3041
ctx.translate(-.7, 0);3042
ctx.lineWidth = Math.max(.45, (7 - b.depth * 1.5) * .25);3043
ctx.strokeStyle = '#c4bd9380';3044
ctx.stroke();3045
ctx.restore();3046
}3047
if (ratio === 1) {3048
for (const cluster of tree.leaves) drawFringeCluster(cluster, 1, t)3049
} else if (ratio >= .5) {3050
const tips = tree.out.filter(b => b.depth === Math.floor(growth));3051
tips.forEach((b, i) => drawFringeCluster({3052
...tree.leaves[i % tree.leaves.length],3053
x: b.ex,3054
y: b.ey3055
}, 0, t));3056
}3057
ctx.restore();3058
label(r.received === r.need ? '流蘇花開' : r.received + ' / ' + r.need, 0, 36, r.received === r.need ? '#eef1de' : '#c0d0bf', 10);3059
ctx.restore();3060
}3062
function drawThorns(t) {3063
const unit = Math.max(.2, Math.min(sx, sy));3064
const stem = Math.max(3.5 * visualScale, 7 / unit);3065
const tick = Math.max(1.4 * visualScale, 2.4 / unit);3066
const tickLen = Math.max(10, 16 / unit);3067
for (const w of game.level.thorns || []) {3068
ctx.strokeStyle = '#e2b6b0a8';3069
ctx.lineWidth = stem;3070
ctx.lineCap = 'round';3071
ctx.beginPath();3072
ctx.moveTo(w.x1, w.y1);3073
ctx.lineTo(w.x2, w.y2);3074
ctx.stroke();3075
const dx = w.x2 - w.x1,3076
dy = w.y2 - w.y1,3077
len = Math.hypot(dx, dy),3078
nx = -dy / len,3079
ny = dx / len;3080
for (let d = 0; d < len; d += 20) {3081
const x = w.x1 + dx * d / len,3082
y = w.y1 + dy * d / len;3083
ctx.strokeStyle = '#f0c6c0b0';3084
ctx.lineWidth = tick;3085
ctx.beginPath();3086
ctx.moveTo(x - nx * tickLen, y - ny * tickLen);3087
ctx.lineTo(x + nx * tickLen + dx / len * 5, y + ny * tickLen + dy / len * 5);3088
ctx.stroke()3089
}3090
}3091
ctx.lineCap = 'butt'3092
}3094
function drawPortals(t) {3095
for (let i = 0; i < game.portals.length; i++) {3096
const p = game.portals[i],3097
color = i % 2 ? '#a2d6d8' : '#c5b6e9';3098
for (const q of p.points) {3099
glow(q.x, q.y, 43, color + '28');3100
ctx.save();3101
ctx.translate(q.x, q.y);3102
ctx.strokeStyle = color;3103
ctx.lineWidth = 1.5;3104
ctx.beginPath();3105
ctx.ellipse(0, 0, 20, 26 * sx / sy, 0, 0, 7);3106
ctx.stroke();3107
ctx.strokeStyle = color + '55';3108
ctx.setLineDash([5, 8]);3109
circle(0, 0, 32);3110
ctx.stroke();3111
ctx.setLineDash([]);3112
label(i ? 'Ⅱ' : 'Ⅰ', 0, 5, color, 11);3113
ctx.restore();3114
if (p.used) {3115
label('✓', q.x, q.y + 43, color, 9)3116
}3117
}3118
}3119
}3120
// Render-only lighting state: game mechanics and saved lamp objects are untouched.3121
const lampRenderState = new WeakMap();3123
function lampGradient(x0, y0, x1, y1, stops) {3124
const g = ctx.createLinearGradient(x0, y0, x1, y1);3125
for (const [at, color] of stops) g.addColorStop(at, color);3126
return g3127
}3129
function lampHalo(x, y, r, strength) {3130
if (strength <= 0) return;3131
const g = ctx.createRadialGradient(x, y, 0, x, y, r);3132
g.addColorStop(0, `rgba(255,216,145,${strength})`);3133
g.addColorStop(.35, `rgba(241,189,109,${strength*.38})`);3134
g.addColorStop(1, 'rgba(241,189,109,0)');3135
ctx.fillStyle = g;3136
ctx.fillRect(x - r, y - r, r * 2, r * 2)3137
}3139
function lampOval(x, y, rx, ry, fill) {3140
ctx.beginPath();3141
ctx.ellipse(x, y, rx, ry, 0, 0, Math.PI * 2);3142
ctx.fillStyle = fill;3143
ctx.fill()3144
}3146
function lampFlame(bright, y = 0) {3147
lampHalo(0, y, 19, .28 * bright);3148
ctx.fillStyle = '#b5a47c';3149
ctx.fillRect(-1.4, y + 4, 2.8, 7);3150
ctx.save();3151
ctx.globalAlpha = .16 + .84 * bright;3152
const flame = lampGradient(0, y - 10, 0, y + 8, [3153
[0, '#fff5d7'],3154
[.4, '#ffe2a0'],3155
[1, '#bb7b3d']3156
]);3157
ctx.fillStyle = flame;3158
ctx.beginPath();3159
ctx.moveTo(0, y - 11);3160
ctx.bezierCurveTo(-2, y - 3, -6, y, -4, y + 5);3161
ctx.bezierCurveTo(-2, y + 10, 5, y + 9, 5, y + 4);3162
ctx.bezierCurveTo(5, y, 1, y - 4, 0, y - 11);3163
ctx.fill();3164
ctx.fillStyle = '#fff7d9';3165
lampOval(0, y + 4, 1.6, 3, '#fff7d9');3166
ctx.restore();3167
}3169
function lampLotus(bright) {3170
const bronze = lampGradient(-24, -22, 24, 24, [3171
[0, '#253f3b'],3172
[.26, '#688578'],3173
[.48, '#b3a57c'],3174
[.62, '#6f8068'],3175
[1, '#273f38']3176
]);3177
// The rear petal and solid cup enclose the wick even before the lamp is lit.3178
ctx.fillStyle = bronze;3179
ctx.beginPath();3180
ctx.moveTo(0, 16);3181
ctx.bezierCurveTo(-14, 1, -10, -24, 0, -35);3182
ctx.bezierCurveTo(11, -24, 15, 1, 0, 16);3183
ctx.fill();3184
ctx.fillStyle = lampGradient(0, -30, 0, 13, [3185
[0, '#bec4a061'],3186
[.5, '#607e6980'],3187
[1, '#344f3f']3188
]);3189
ctx.beginPath();3190
ctx.moveTo(0, -29);3191
ctx.quadraticCurveTo(-7, -10, 0, 8);3192
ctx.quadraticCurveTo(8, -10, 0, -29);3193
ctx.fill();3194
lampFlame(bright, -4);3195
for (const side of [-1, 1]) {3196
ctx.save();3197
ctx.translate(side * 4, 12);3198
ctx.scale(side, 1);3199
ctx.rotate(bright * .72);3200
ctx.fillStyle = bronze;3201
ctx.beginPath();3202
ctx.moveTo(0, 0);3203
ctx.bezierCurveTo(17, -5, 23, -22, 13, -35);3204
ctx.bezierCurveTo(1, -30, -6, -12, 0, 0);3205
ctx.fill();3206
ctx.fillStyle = lampGradient(0, -23, 17, 0, [3207
[0, '#9baa8566'],3208
[.4, '#cfb77d80'],3209
[1, '#344d3b']3210
]);3211
ctx.beginPath();3212
ctx.moveTo(2, -3);3213
ctx.bezierCurveTo(14, -10, 18, -23, 13, -30);3214
ctx.bezierCurveTo(7, -22, 3, -11, 2, -3);3215
ctx.fill();3216
ctx.save();3217
ctx.globalAlpha = bright * .58;3218
ctx.fillStyle = lampGradient(0, -23, 16, 2, [3219
[0, '#f8dc9a'],3220
[1, '#b8995340']3221
]);3222
ctx.beginPath();3223
ctx.moveTo(2, -3);3224
ctx.quadraticCurveTo(10, -7, 13, -27);3225
ctx.quadraticCurveTo(1, -15, 2, -3);3226
ctx.fill();3227
ctx.restore();3228
ctx.strokeStyle = '#d4c49155';3229
ctx.lineWidth = .8;3230
ctx.beginPath();3231
ctx.moveTo(3, -3);3232
ctx.quadraticCurveTo(14, -15, 13, -30);3233
ctx.stroke();3234
lampOval(0, 0, 2.1, 2.1, '#cab480');3235
lampOval(.5, .5, .8, .8, '#526451');3236
ctx.restore();3237
}3238
ctx.fillStyle = bronze;3239
ctx.beginPath();3240
ctx.moveTo(-17, 12);3241
ctx.quadraticCurveTo(0, 19, 17, 12);3242
ctx.bezierCurveTo(15, 26, -15, 26, -17, 12);3243
ctx.fill();3244
lampOval(0, 13, 17, 4, '#c4b786');3245
lampOval(0, 13, 13, 2.3, '#596549');3246
ctx.fillStyle = lampGradient(-4, 18, 5, 28, [3247
[0, '#30473e'],3248
[.5, '#ad9f75'],3249
[1, '#475642']3250
]);3251
ctx.fillRect(-4, 20, 8, 9);3252
lampOval(0, 30, 18, 5, '#30433a');3253
lampOval(0, 28, 17, 4, '#7e8969');3254
lampOval(0, 27, 11, 2, '#a6a382');3255
}3257
function drawLamps(t) {3258
const unit = clamp(sx * visualScale, .72, 1.12);3259
for (let i = 0; i < game.lamps.length; i++) {3260
const l = game.lamps[i],3261
target = l.lit ? 1 : 0;3262
let state = lampRenderState.get(l);3263
if (!state) {3264
state = {3265
brightness: target,3266
time: t3267
};3268
lampRenderState.set(l, state)3269
}3270
const elapsed = clamp(t - state.time, 0, .08);3271
state.time = t;3272
state.brightness = save.settings.motion ? target : state.brightness + (target - state.brightness) * (1 - Math.exp(-elapsed * 3.2));3273
const bright = state.brightness;3274
// Undo the game world's unequal x/y scales: each object remains solid and upright on phones.3275
ctx.save();3276
ctx.translate(l.x, l.y);3277
ctx.scale(unit / sx, unit / sy);3278
ctx.lineCap = 'round';3279
ctx.lineJoin = 'round';3280
lampHalo(0, -3, 78, .105 * bright);3281
lampOval(2, 34, 30, 7, '#06181266');3282
lampLotus(bright);3283
ctx.restore();3284
label(l.lit ? '已點亮' : '燈', l.x, l.y + 48 * unit / sy, l.lit ? '#d9c794' : '#a5b4a6', 9);3285
}3286
}3288
function drawStars(t) {3289
if (game.complete) return;3290
for (const s of game.stars) {3291
const visible = game.starVisible(s);3292
if (!visible) {3293
ctx.strokeStyle = '#afcbcf44';3294
ctx.lineWidth = 1;3295
ctx.beginPath();3296
ctx.ellipse(s.x, s.y, 9 * visualScale, 3.5, 0, 0, 7);3297
ctx.stroke();3298
continue3299
}3300
const pulse = save.settings.motion ? 1 : 1 + Math.sin(t * 2 + s.phase) * .12,3301
r = 7 * visualScale * pulse;3302
glow(s.x, s.y, 25 * visualScale, '#f0dc9c25');3303
ctx.fillStyle = '#f4dda1';3304
ctx.beginPath();3305
ctx.moveTo(s.x, s.y - r * sx / sy);3306
ctx.lineTo(s.x + r * .55, s.y);3307
ctx.lineTo(s.x, s.y + r * sx / sy);3308
ctx.lineTo(s.x - r * .55, s.y);3309
ctx.closePath();3310
ctx.fill();3311
if (s.tidal) {3312
ctx.strokeStyle = '#bddedc55';3313
ctx.beginPath();3314
ctx.ellipse(s.x, s.y + 12 * visualScale, 9 * visualScale, 3, 0, 0, 7);3315
ctx.stroke()3316
}3317
}3318
}3320
function drawShadows(t) {3321
if (game.complete) return;3322
for (const s of game.shadows()) {3323
glow(s.x, s.y, 36, '#040b17ba');3324
ctx.fillStyle = '#0c1a28';3325
circle(s.x, s.y, 12 * visualScale);3326
ctx.fill();3327
ctx.strokeStyle = '#a6bec47a';3328
ctx.lineWidth = 1;3329
ctx.beginPath();3330
ctx.ellipse(s.x, s.y, 17 * visualScale, 20 * visualScale * sx / sy, 0, 0, Math.PI * 1.6);3331
ctx.stroke()3332
}3333
}3335
function drawFog() {3336
if (!game.level.fog || game.complete) return;3337
fogCtx.setTransform(dpr * sx, 0, 0, dpr * sy, 0, 0);3338
fogCtx.globalCompositeOperation = 'source-over';3339
fogCtx.clearRect(0, 0, 1000, 640);3340
fogCtx.fillStyle = '#091724ed';3341
fogCtx.fillRect(0, 0, 1000, 640);3342
fogCtx.globalCompositeOperation = 'destination-out';3343
const holes = [{3344
...game.player,3345
r: 1753346
}, ...game.lamps.filter(l => l.lit).map(l => ({3347
...l,3348
r: 2353349
})), ...game.roots.map(r => ({3350
...r,3351
r: 1053352
}))];3353
for (const p of holes) {3354
const g = fogCtx.createRadialGradient(p.x, p.y, 25, p.x, p.y, p.r);3355
g.addColorStop(0, '#000');3356
g.addColorStop(.5, '#000');3357
g.addColorStop(1, 'transparent');3358
fogCtx.fillStyle = g;3359
fogCtx.fillRect(p.x - p.r, p.y - p.r, p.r * 2, p.r * 2)3360
}3361
fogCtx.globalCompositeOperation = 'source-over';3362
ctx.drawImage(fogCanvas, 0, 0, 1000, 640)3363
}3365
function drawFriends(t) {3366
for (let i = 0; i < game.companions.length; i++) {3367
const c = game.companions[i];3368
if (c.status === 'waiting' && !game.visibleAt(c)) continue;3369
glow(c.x, c.y, 21, '#e3ebb633');3370
ctx.strokeStyle = '#d1e5b5';3371
ctx.lineWidth = 1;3372
const wing = save.settings.motion ? 1 : Math.sin(t * 4 + i) * .2 + 1;3373
ctx.beginPath();3374
ctx.ellipse(c.x - 7, c.y - 2, 6, 3 * wing, -.5, 0, 7);3375
ctx.ellipse(c.x + 7, c.y - 2, 6, 3 * wing, .5, 0, 7);3376
ctx.stroke();3377
ctx.fillStyle = '#e6e8b4';3378
circle(c.x, c.y, 3.4 * visualScale);3379
ctx.fill();3380
if (c.status === 'waiting') label('等你', c.x, c.y + 25, '#c1cfa8', 9)3381
}3382
}3384
function drawPlayer(t) {3385
const p = game.player;3386
if (game.shield > 0) {3387
glow(p.x, p.y, 60, '#dce9c52c');3388
ctx.strokeStyle = '#dce9c5b0';3389
ctx.lineWidth = 1.2;3390
circle(p.x, p.y, 28 * visualScale);3391
ctx.stroke()3392
}3393
for (const point of trail) {3394
ctx.globalAlpha = point.life * .38;3395
ctx.fillStyle = '#f1daa1';3396
circle(point.x, point.y, 2 * visualScale * point.life);3397
ctx.fill()3398
}3399
ctx.globalAlpha = 1;3400
glow(p.x, p.y, 30 * visualScale, game.invulnerable > 0 ? '#cadfe755' : '#f3dba353');3401
ctx.fillStyle = game.invulnerable > 0 ? '#cadfe7' : '#fff1cb';3402
circle(p.x, p.y, 4.5 * visualScale);3403
ctx.fill();3404
for (let i = 0; i < game.carry; i++) {3405
const a = (save.settings.motion ? 0 : t) + i * Math.PI * 2 / game.carry;3406
circle(p.x + Math.cos(a) * 17 * visualScale, p.y + Math.sin(a) * 17 * visualScale, 2.1 * visualScale);3407
ctx.fill()3408
}3409
}3411
function draw() {3412
if (!game || !W || !H) return;3413
ctx.setTransform(dpr * sx, 0, 0, dpr * sy, 0, 0);3414
ctx.globalAlpha = 1;3415
const world = WORLDS[game.level.world],3416
t = save.settings.motion ? 0 : clock;3417
drawBackground(world, t);3418
drawThorns(t);3419
game.roots.forEach((r, i) => drawTree(r, i, world, t));3420
drawStars(t);3421
drawShadows(t);3422
drawFog();3423
drawPortals(t);3424
drawLamps(t);3425
drawFriends(t);3426
drawPlayer(t);3427
if (game.level.wind && !save.settings.motion && !game.complete) {3428
const wind = game.wind();3429
ctx.strokeStyle = '#a5cec524';3430
ctx.lineWidth = .8;3431
for (let i = 0; i < 17; i++) {3432
const x = (i * 131 + clock * wind.x * .55 + 100000) % 1000,3433
y = 150 + (i * 97 % 380);3434
ctx.beginPath();3435
ctx.moveTo(x, y);3436
ctx.lineTo(x + wind.x * .4, y + wind.y * .4);3437
ctx.stroke()3438
}3439
}3440
for (const p of particles) {3441
ctx.globalAlpha = Math.min(1, p.life * .6);3442
ctx.fillStyle = p.color;3443
circle(p.x, p.y, 2 * visualScale);3444
ctx.fill()3445
}3446
ctx.globalAlpha = 1;3447
drawPetals();3448
}3450
function frame(now) {3451
const dt = Math.min((now - last) / 1000 || 0, .04);3452
last = now;3453
if (!document.hidden) {3454
if (running) {3455
clock += dt;3456
if (!game.complete) {3457
const input = {3458
x: (keys.has('arrowright') || keys.has('d') ? 1 : 0) - (keys.has('arrowleft') || keys.has('a') ? 1 : 0),3459
y: (keys.has('arrowdown') || keys.has('s') ? 1 : 0) - (keys.has('arrowup') || keys.has('w') ? 1 : 0)3460
};3461
game.step(dt, input);3462
if (!save.settings.motion) {3463
trail.push({3464
...game.player,3465
life: 13466
});3467
if (trail.length > 38) trail.shift()3468
}3469
saveTimer += dt;3470
if (dirty || saveTimer > 2.5) persist()3471
} else if (endDelay > 0) {3472
endDelay -= dt;3473
if (endDelay <= 0) showResult()3474
}3475
trail.forEach(p => p.life -= dt * 1.6);3476
trail = trail.filter(p => p.life > 0);3477
particles.forEach(p => {3478
p.x += p.vx * dt;3479
p.y += p.vy * dt;3480
p.vy += dt * 18;3481
p.life -= dt3482
});3483
particles = particles.filter(p => p.life > 0)3484
}3485
if (game.complete && (running || activeDialog === 'result') && !save.settings.motion) updatePetals(dt);3486
updateUI();3487
draw()3488
}3489
requestAnimationFrame(frame)3490
}3492
function point(e) {3493
if (!running || game.complete) return;3494
const rect = canvas.getBoundingClientRect();3495
game.target = {3496
x: clamp((e.clientX - rect.left) / rect.width * 1000, 35, 965),3497
y: clamp((e.clientY - rect.top) / rect.height * 640, 100, 607)3498
}3499
}3500
canvas.addEventListener('pointermove', e => {3501
if (e.pointerType !== 'touch' || e.buttons) point(e)3502
});3503
canvas.addEventListener('pointerdown', e => {3504
if (!running) return;3505
canvas.focus();3506
canvas.setPointerCapture(e.pointerId);3507
point(e)3508
});3509
canvas.addEventListener('keydown', e => {3510
const key = e.key.toLowerCase();3511
if (['arrowup', 'arrowdown', 'arrowleft', 'arrowright', 'w', 'a', 's', 'd'].includes(key)) {3512
e.preventDefault();3513
keys.add(key)3514
}3515
if (e.code === 'Space') {3516
e.preventDefault();3517
if (running) game.pulse()3518
}3519
});3520
window.addEventListener('keyup', e => keys.delete(e.key.toLowerCase()));3521
canvas.addEventListener('blur', () => keys.clear());3522
document.addEventListener('keydown', e => {3523
if (e.key === 'Escape') {3524
e.preventDefault();3525
if (activeDialog === 'map-dialog') showDialog(mapReturn);3526
else if (activeDialog === 'pause-dialog') showDialog(null);3527
else if (!activeDialog) {3528
stash();3529
showDialog('pause-dialog')3530
}3531
}3532
if (e.key === 'Tab' && activeDialog) {3533
const nodes = [...$(activeDialog).querySelectorAll('button:not(:disabled),input:not(:disabled)')].filter(n => !n.hidden);3534
const first = nodes[0],3535
last = nodes[nodes.length - 1];3536
if (e.shiftKey && document.activeElement === first) {3537
e.preventDefault();3538
last.focus()3539
} else if (!e.shiftKey && document.activeElement === last) {3540
e.preventDefault();3541
first.focus()3542
}3543
}3544
});3545
window.addEventListener('blur', () => {3546
keys.clear();3547
if (running && !game.complete) {3548
stash();3549
showDialog('pause-dialog')3550
}3551
});3552
document.addEventListener('visibilitychange', () => {3553
if (document.hidden && game) {3554
if (music) music.stop();3555
stash();3556
if (running && !game.complete) showDialog('pause-dialog')3557
} else if (game) {3558
syncMusic()3559
}3560
});3561
window.addEventListener('pagehide', () => {3562
if (music) music.stop();3563
if (game) stash()3564
});3565
$('sound').onclick = () => {3566
if ($('sound').textContent.includes('重試')) save.settings.music = true;3567
else save.settings.music = !save.settings.music;3568
syncSettings();3569
unlockAudio();3570
syncMusic();3571
stash()3572
};3574
function updateSoundLabel() {3575
if ($('sound').textContent.includes('重試')) return;3576
$('sound').textContent = (game?.complete ? '風聲' : '音樂') + ' · ' + (save.settings.music ? '開' : '關');3577
$('sound').setAttribute('aria-pressed', String(save.settings.music))3578
}3580
function syncSettings() {3581
$('sound').textContent = '';3582
updateSoundLabel();3583
$('music-enabled').checked = save.settings.music;3584
$('effects').checked = save.settings.sound;3585
$('music-volume').value = Math.round(save.settings.musicVolume * 100);3586
$('volume-label').textContent = Math.round(save.settings.musicVolume * 100) + '%';3587
$('assist').checked = save.settings.assist;3588
$('motion').checked = save.settings.motion;3589
if (game) game.assist = save.settings.assist3590
}3591
$('music-enabled').onchange = () => {3592
save.settings.music = $('music-enabled').checked;3593
syncSettings();3594
unlockAudio();3595
syncMusic();3596
stash()3597
};3598
$('music-volume').oninput = () => {3599
save.settings.musicVolume = Number($('music-volume').value) / 100;3600
$('volume-label').textContent = Math.round(save.settings.musicVolume * 100) + '%';3601
if (music) music.setVolume(save.settings.musicVolume)3602
};3603
$('music-volume').onchange = () => stash();3604
$('effects').onchange = () => {3605
save.settings.sound = $('effects').checked;3606
unlockAudio();3607
if (save.settings.sound) note(3);3608
stash()3609
};3610
$('assist').onchange = () => {3611
save.settings.assist = $('assist').checked;3612
syncSettings();3613
stash()3614
};3615
$('motion').onchange = () => {3616
save.settings.motion = $('motion').checked;3617
particles = [];3618
trail = [];3619
petals = [];3620
if (game.complete && !save.settings.motion) startPetals();3621
stash()3622
};3623
$('map-button').onclick = openMap;3624
$('welcome-map').onclick = openMap;3625
$('brief-map').onclick = openMap;3626
$('pause-map').onclick = openMap;3627
$('result-map').onclick = openMap;3628
$('map-close').onclick = () => showDialog(mapReturn);3629
$('pause-button').onclick = () => {3630
stash();3631
showDialog('pause-dialog')3632
};3633
$('resume').onclick = () => showDialog(null);3634
$('pulse').onclick = () => {3635
if (running) game.pulse();3636
canvas.focus()3637
};3638
$('continue').onclick = () => chooseLevel(save.active);3639
$('prologue').onclick = () => chooseLevel(0);3640
$('map-prologue').onclick = () => chooseLevel(0);3641
$('begin-level').onclick = () => {3642
showDialog(null);3643
persist();3644
note(0)3645
};3646
$('restart').onclick = () => {3647
delete save.snapshots[game.level.id];3648
loadLevel(game.level.id, false);3649
showDialog(null);3650
persist()3651
};3652
$('next-level').onclick = () => {3653
if (game.level.id === 40) openMap();3654
else chooseLevel(game.level.id + 1)3655
};3656
$('stay').onclick = () => {3657
endDelay = 0;3658
showDialog(null);3659
message('聽風吹過花瓣。點擊夜行圖,繼續下一段旅程。')3660
};3661
// Resume an unfinished night; otherwise suggest the next unlocked chapter.3662
if (save.completed[save.active] && !save.snapshots[save.active]) save.active = unlocked();3663
loadLevel(save.active);3664
syncSettings();3665
$('continue').textContent = save.snapshots[save.active] ? (save.active === 0 ? '繼續序章' : `繼續第 ${save.active} 夜`) : (save.active === 0 ? '走進序章' : `開始第 ${save.active} 夜`);3666
if (saveNotice) {3667
message(saveNotice);3668
$('save-status').textContent = saveNotice3669
}3670
showDialog('welcome');3671
requestAnimationFrame(frame);3672
})();3674
</script>3675
</body>3676
</html>