Files
mfyheart/game.js
T

1174 lines
141 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
const canvas = document.querySelector('#game');
const ctx = canvas.getContext('2d');
const titleScreen = document.querySelector('#titleScreen');
const controlsScreen = document.querySelector('#controlsScreen');
const settingsScreen = document.querySelector('#settingsScreen');
const pauseScreen = document.querySelector('#pauseScreen');
const endingScreen = document.querySelector('#endingScreen');
const introScreen = document.querySelector('#introScreen');
const introChapter = document.querySelector('#introChapter');
const introSpeaker = document.querySelector('#introSpeaker');
const introText = document.querySelector('#introText');
const introProgress = document.querySelector('#introProgress');
const introCg = document.querySelector('#introCg');
const endingCg = document.querySelector('#endingCg');
const mapScreen = document.querySelector('#mapScreen');
const mapRooms = document.querySelector('#mapRooms');
const mapSummary = document.querySelector('#mapSummary');
const journalScreen = document.querySelector('#journalScreen');
const journalObjective = document.querySelector('#journalObjective');
const journalRoute = document.querySelector('#journalRoute');
const journalAbilities = document.querySelector('#journalAbilities');
const journalQuests = document.querySelector('#journalQuests');
const journalCompletion = document.querySelector('#journalCompletion');
const journalPlaytime = document.querySelector('#journalPlaytime');
const continueButton = document.querySelector('#continueButton');
const saveSummary = document.querySelector('#saveSummary');
const musicVolumeInput = document.querySelector('#musicVolume');
const sfxVolumeInput = document.querySelector('#sfxVolume');
const musicVolumeValue = document.querySelector('#musicVolumeValue');
const sfxVolumeValue = document.querySelector('#sfxVolumeValue');
const audioStatus = document.querySelector('#audioStatus');
const controlModeSelect = document.querySelector('#controlMode');
const controlModeStatus = document.querySelector('#controlModeStatus');
const fullscreenButton = document.querySelector('#fullscreenButton');
const fullscreenStatus = document.querySelector('#fullscreenStatus');
const settingsContext = document.querySelector('#settingsContext');
const mobileControls = document.querySelector('#mobileControls');
const touchJoystick = document.querySelector('#touchJoystick');
const joystickKnob = document.querySelector('#joystickKnob');
const toast = document.querySelector('#toast');
const nightcord = document.querySelector('#nightcord');
const nightcordMessages = document.querySelector('#nightcordMessages');
const characterPortrait = document.querySelector('#characterPortrait');
const portraitSprite = document.querySelector('#portraitSprite');
const tutorialGuide = document.querySelector('#tutorialGuide');
const tutorialIndex = document.querySelector('#tutorialIndex');
const tutorialTitle = document.querySelector('#tutorialTitle');
const tutorialInput = document.querySelector('#tutorialInput');
const tutorialProgress = document.querySelector('#tutorialProgress');
const areaTitle = document.querySelector('#areaTitle');
const W = canvas.width, H = canvas.height, ROOM_W = 2400, ROOM_COUNT = 20, WORLD_W = ROOM_W * ROOM_COUNT;
const JUMP_SPEED = 650, GRAVITY = 1850, RUN_SPEED = 285;
const GROUND_ACCEL = 3000, TURN_ACCEL = 4400, AIR_ACCEL = 1700, GROUND_DECEL = 4100, AIR_DECEL = 520;
const COYOTE_TIME = .14, JUMP_BUFFER_TIME = .15, ATTACK_BUFFER_TIME = .13, ACTION_BUFFER_TIME = .16;
const CHARGE_FULL_TIME = .82, CHARGE_RELEASE_DURATION = .58, FREEZE_CHANCE = .34;
const APEX_GRAVITY_SCALE = .62, FALL_GRAVITY_SCALE = 1.24, JUMP_CUT_GRAVITY_SCALE = 1.9;
const MAX_SAFE_RISE = 92, MAX_SAFE_GAP = 170;
const MAX_PARTICLES = 360, MAX_PROJECTILES = 96, MAX_RESONANCE_SHOTS = 24;
const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
const keys = new Set(), pressed = new Set(), released = new Set(), touchHeld = new Set();
const bg = new Image(); bg.src = 'assets/silent-stage.png';
const loadSprite = src => { const image=new Image(); image.src=src; return image; };
['assets/cg-prologue-nightcord.png','assets/cg-prologue-arrival.png','assets/cg-prologue-aquarium.png','assets/cg-ending-true.png','assets/cg-ending-return.png'].forEach(src=>loadSprite(src));
const interactionSprite = loadSprite('assets/mafuyu-interactions-normalized.png');
const benchFrontSprite = loadSprite('assets/mafuyu-bench-front-normalized.png');
const interactableSprite = loadSprite('assets/sekai-interactables-16.png');
const iceBowSprite = loadSprite('assets/mafuyu-ice-bow.png');
const iceChargeSprite = loadSprite('assets/mafuyu-ice-charge.png');
const iceReleaseSprite = loadSprite('assets/mafuyu-ice-release.png');
const normalizedFrames = row => Array.from({length:4},(_,column)=>({sx:column*256,sy:row*256,sw:256,sh:256,ax:128}));
const benchFrames = row => Array.from({length:4},(_,column)=>({sx:column*256,sy:row*256,sw:256,sh:256,ax:128}));
const gridFrames16 = (cell=320) => Array.from({length:16},(_,index)=>({sx:(index%4)*cell,sy:Math.floor(index/4)*cell,sw:cell,sh:cell,ax:cell/2}));
const spriteSets = {
idle:{image:loadSprite('assets/mafuyu-idle.png'),frames:[
{sx:140,sy:62,sw:235,sh:776},{sx:542,sy:62,sw:238,sh:775},
{sx:937,sy:64,sw:229,sh:773},{sx:1320,sy:64,sw:233,sh:774}
]},
run:{image:loadSprite('assets/mafuyu-run.png'),frames:[
{sx:122,sy:36,sw:307,sh:396},{sx:486,sy:33,sw:268,sh:400},
{sx:928,sy:54,sw:359,sh:380},{sx:1287,sy:38,sw:238,sh:390},
{sx:115,sy:471,sw:299,sh:371},{sx:459,sy:467,sw:298,sh:384},
{sx:933,sy:475,sw:206,sh:384},{sx:1287,sy:464,sw:241,sh:393}
]},
jump:{image:loadSprite('assets/mafuyu-jump.png'),frames:[
{sx:82,sy:334,sw:312,sh:488},{sx:510,sy:166,sw:286,sh:486},
{sx:893,sy:67,sw:301,sh:580},{sx:1293,sy:176,sw:372,sh:624}
]},
attack:{image:loadSprite('assets/mafuyu-attack-16.png'),frames:gridFrames16()},
iceBow:{image:iceBowSprite,frames:gridFrames16()},
iceCharge:{image:iceChargeSprite,frames:gridFrames16()},
iceRelease:{image:iceReleaseSprite,frames:gridFrames16()},
interact:{image:interactionSprite,frames:normalizedFrames(0)},
sit:{image:benchFrontSprite,frames:benchFrames(0)},
rest:{image:benchFrontSprite,frames:[...benchFrames(1),...benchFrames(2)]}
};
const bossSprite = loadSprite('assets/mafuyu-boss.png');
const enemySprite = loadSprite('assets/sekai-enemies-16.png');
const expansionEnemySprite = loadSprite('assets/sekai-expansion-enemies-16.png');
const expansionPropSprite = loadSprite('assets/sekai-expansion-interactables-16.png');
const finalBossSprite = loadSprite('assets/mafuyu-final-boss-16.png');
const BOSS_FRAMES = [
[{sx:181,sy:14,sw:233,sh:215},{sx:564,sy:14,sw:223,sh:215},{sx:946,sy:14,sw:219,sh:215},{sx:1316,sy:14,sw:214,sh:215}],
[{sx:150,sy:229,sw:262,sh:229},{sx:496,sy:229,sw:265,sh:229},{sx:896,sy:229,sw:391,sh:229},{sx:1287,sy:229,sw:304,sh:229}],
[{sx:143,sy:479,sw:272,sh:186},{sx:511,sy:474,sw:309,sh:191},{sx:886,sy:476,sw:372,sh:211},{sx:1287,sy:478,sw:312,sh:187}],
[{sx:153,sy:687,sw:229,sh:197},{sx:523,sy:694,sw:236,sh:192},{sx:924,sy:687,sw:258,sh:204},{sx:1314,sy:687,sw:266,sh:206}]
];
const ENEMY_FRAMES = Array.from({length:4},(_,row)=>Array.from({length:16},(_,column)=>({sx:column*192,sy:row*144,sw:192,sh:144})));
const INTERACTABLE_FRAMES = Array.from({length:4},(_,row)=>Array.from({length:16},(_,column)=>({sx:column*192,sy:row*192,sw:192,sh:192})));
const EXPANSION_ENEMY_FRAMES = Array.from({length:4},(_,row)=>Array.from({length:16},(_,column)=>({sx:column*192,sy:row*160,sw:192,sh:160})));
const EXPANSION_PROP_FRAMES = Array.from({length:4},(_,row)=>Array.from({length:16},(_,column)=>({sx:column*224,sy:row*224,sw:224,sh:224})));
const FINAL_BOSS_FRAMES = Array.from({length:4},(_,row)=>Array.from({length:16},(_,column)=>({sx:column*256,sy:row*256,sw:256,sh:256})));
const storageGet=key=>{try{return localStorage.getItem(key);}catch{return null;}};
const storageSet=(key,value)=>{try{localStorage.setItem(key,value);return true;}catch{return false;}};
const storageRemove=key=>{try{localStorage.removeItem(key);}catch{}}
const storedVolume=(key,fallback)=>{const raw=storageGet(key);if(raw===null||raw==='')return fallback;const value=Number(raw);return Number.isFinite(value)&&value>=0&&value<=1?value:fallback;};
const MUSIC_TRACKS={empty:'assets/audio/bgm-empty.mp3',aquarium:'assets/audio/bgm-aquarium.mp3',corridor:'assets/audio/bgm-corridor.mp3',stage:'assets/audio/bgm-stage.mp3',ending:'assets/audio/bgm-ending.mp3'};
const SFX_TRACKS={hover:'assets/audio/sfx-menu-hover.ogg',confirm:'assets/audio/sfx-menu-confirm.ogg',back:'assets/audio/sfx-menu-back.ogg',transition:'assets/audio/sfx-transition.ogg',checkpoint:'assets/audio/sfx-checkpoint.ogg',death:'assets/audio/sfx-death.ogg',attack:'assets/audio/sfx-attack.ogg',iceBowCharge:'assets/audio/sfx-ice-bow-charge.ogg',iceArrow:'assets/audio/sfx-ice-arrow.ogg',iceCharge:'assets/audio/sfx-ice-charge.ogg',iceHeavy:'assets/audio/sfx-ice-heavy.ogg',freeze:'assets/audio/sfx-freeze.ogg',hit:'assets/audio/sfx-hit.ogg',hurt:'assets/audio/sfx-hurt.ogg',jump:'assets/audio/sfx-jump.ogg',dash:'assets/audio/sfx-dash.ogg',collect:'assets/audio/sfx-collect.ogg',enemyShot:'assets/audio/sfx-enemy-shot.ogg',bossCast:'assets/audio/sfx-boss-cast.ogg',footstep1:'assets/audio/sfx-footstep-1.ogg',footstep2:'assets/audio/sfx-footstep-2.ogg',victory:'assets/audio/sfx-victory.mp3'};
const sfxTemplates=Object.fromEntries(Object.entries(SFX_TRACKS).map(([key,src])=>{const audio=new Audio(src);audio.preload='auto';return[key,audio];}));
const musicChannels=[new Audio(),new Audio()];musicChannels.forEach(audio=>{audio.loop=true;audio.preload='auto';audio.playsInline=true;});
let running = false, paused = false, introActive = false, mapOpen = false, journalOpen = false, last = 0, time = 0, shake = 0, flash = 0, hitStop = 0;
let muted = storageGet('silent-sekai-muted') === 'true';
let musicVolume=storedVolume('silent-sekai-music-volume',.55),sfxVolume=storedVolume('silent-sekai-sfx-volume',.7);
let controlMode=['auto','keyboard','touch'].includes(storageGet('silent-sekai-control-mode'))?storageGet('silent-sekai-control-mode'):'auto';
let settingsReturn='title',touchAxis=0,joystickPointerId=null;
let audioUnlocked=false,musicKey='',pendingMusic='empty',activeMusic=0,musicFade=null,musicGain=.45,footstepClock=0,musicRequestId=0;
let camera = {x:0, y:0}, cameraLookahead = 0;
let particles = [], enemies = [], slashes = [], projectiles = [], resonanceShots = [], hasDash = false, hasDoubleJump = false, ending = false;
let checkpoint = {x:140,y:505};
let combo = 0, bestCombo = 0, score = 0, judgement = '', judgeTimer = 0, beatIndex = -1;
let currentArea = 0, currentRoom = 0, storyFlags = new Set(), discoveredRooms = new Set([0]), fragmentsFound = 0, memoryArenaActive = false, memoryArenaCleared = false, arenaActive = false, midBossDefeated = false, rainArenaActive = false, rainArenaCleared = false, finalArenaActive = false, bossDefeated = false, relayCooldown = 0, doorPhaseGrace = 0, playTime = 0;
let roomTransition = {active:false,t:0,duration:1.15,from:0,to:0,direction:1,revealed:false};
const BEAT = .6;
const areas = [
{start:0,end:7200,name:'空白 SEKAI',sub:'EMPTY SEKAI · 无机质的微光',tone:'#d7eff4'},
{start:7200,end:14400,name:'沉水的记忆',sub:'AQUARIUM MEMORY · 说不出口的喜欢',tone:'#72d9ed'},
{start:14400,end:21600,name:'25时回廊',sub:'NIGHTCORD 25:00 · 被切断的讯息',tone:'#ba91ff'},
{start:21600,end:28800,name:'无声剧场',sub:'SILENT STAGE · 假面背后的心音',tone:'#ef9cda'},
{start:28800,end:38400,name:'雨幕校舍',sub:'RAIN CAMPUS · 没有写进日程的放学后',tone:'#78b9e8'},
{start:38400,end:48000,name:'未完成乐章',sub:'UNWRITTEN SCORE · 由自己写下的第一行',tone:'#f0b5ff'}
];
const backgroundGradients=[['#d8dce4','#8e97a8','#17192a'],['#06182c','#123b52','#07121f'],['#110a25','#281442','#080916'],['#210b22','#38142f','#090713'],['#101d32','#273f59','#070d18'],['#1a0d2d','#39214b','#080712']].map(colors=>{const gradient=ctx.createLinearGradient(0,0,0,H);gradient.addColorStop(0,colors[0]);gradient.addColorStop(.55,colors[1]);gradient.addColorStop(1,colors[2]);return gradient;});
const INTRO_SCENES = [
{chapter:'25:00 · NIGHTCORD',speaker:'SYSTEM',text:'语音连接中断。检测到未知的 SEKAI 信号。',image:'assets/cg-prologue-nightcord.png'},
{chapter:'25:00 · SIGNAL LOST',speaker:'K',text:'「まふゆ,能听见吗?不要一个人切断连接。」',image:'assets/cg-prologue-nightcord.png'},
{chapter:'UNKNOWN SEKAI · NO RESPONSE',speaker:'朝比奈 まふゆ',text:'「……这里没有任何声音。可为什么,我会觉得有人在叫我?」',image:'assets/cg-prologue-arrival.png'},
{chapter:'AQUARIUM MEMORY · ECHO',speaker:'朝比奈 まふゆ',text:'「这个蓝色……我以前,真的说过喜欢吗?」',image:'assets/cg-prologue-aquarium.png'},
{chapter:'VOICE FRAGMENTS · 0 / 10',speaker:'SYSTEM',text:'散落的歌词正在回应。踩准节拍,以自己的声音照亮前路。',image:'assets/cg-prologue-arrival.png'}
];
const ROOMS = [
{start:0,end:2400,name:'空白入口',x:3,y:40,w:10,h:20,area:0},
{start:2400,end:4800,name:'无机质长廊',x:14,y:31,w:10,h:20,area:0},
{start:4800,end:7200,name:'断讯阶梯',x:25,y:40,w:10,h:20,area:0},
{start:7200,end:9600,name:'水族馆入口',x:36,y:46,w:9,h:18,area:1},
{start:9600,end:12000,name:'沉水展厅',x:46,y:32,w:11,h:22,area:1},
{start:12000,end:14400,name:'记忆核心',x:58,y:43,w:11,h:20,area:1},
{start:14400,end:16800,name:'封音门',x:70,y:53,w:9,h:18,area:2},
{start:16800,end:19200,name:'断线缓存区',x:62,y:65,w:10,h:18,area:2},
{start:19200,end:21600,name:'25时中枢',x:50,y:73,w:11,h:18,area:2},
{start:21600,end:24000,name:'无声后台',x:37,y:65,w:11,h:19,area:3},
{start:24000,end:26400,name:'幕间走廊',x:25,y:73,w:10,h:18,area:3},
{start:26400,end:28800,name:'假面舞台',x:13,y:65,w:11,h:22,area:3},
{start:28800,end:31200,name:'雨幕天台',x:25,y:54,w:10,h:18,area:4},
{start:31200,end:33600,name:'积雨回廊',x:37,y:43,w:10,h:18,area:4},
{start:33600,end:36000,name:'镜像教室',x:49,y:34,w:11,h:20,area:4},
{start:36000,end:38400,name:'无人放学路',x:62,y:42,w:11,h:20,area:4},
{start:38400,end:40800,name:'断裂谱库',x:73,y:54,w:10,h:18,area:5},
{start:40800,end:43200,name:'失声礼堂',x:64,y:67,w:11,h:19,area:5},
{start:43200,end:45600,name:'无名化妆间',x:49,y:75,w:11,h:18,area:5},
{start:45600,end:48000,name:'未写下的舞台',x:32,y:70,w:12,h:22,area:5}
];
const fragments = [
{x:1390,y:305,text:'「我」',taken:false},{x:4160,y:305,text:'「喜欢」',taken:false},
{x:6090,y:305,text:'「水族馆」',taken:false},{x:8600,y:305,text:'「声音」',taken:false},
{x:11280,y:390,text:'「并不是」',taken:false},{x:13280,y:305,text:'「好孩子」',taken:false},
{x:15310,y:390,text:'「想要」',taken:false},{x:18180,y:305,text:'「被找到」',taken:false},
{x:23020,y:305,text:'「真正的我」',taken:false},{x:26150,y:305,text:'「活下去」',taken:false},
{x:29820,y:390,text:'「下雨以后」',taken:false},{x:32360,y:305,text:'「绕一点路」',taken:false},
{x:34600,y:401,text:'「也没有关系」',taken:false},{x:37420,y:305,text:'「我不想再」',taken:false},
{x:39760,y:316,text:'「只回答正确答案」',taken:false},{x:42140,y:305,text:'「请听我说」',taken:false},
{x:44480,y:486,text:'「这是我的」',taken:false},{x:46950,y:316,text:'「第一首歌」',taken:false}
];
const ROOM_LAYOUTS = [
{ground:[[0,2400]],ledges:[[420,525,320],[820,440,300],[1230,355,340],[1660,440,300],[2050,525,250]]},
{ground:[[0,760],[900,720],[1770,630]],ledges:[[540,525,280],[920,525,320],[1280,440,300],[1640,355,320],[2050,440,270]]},
{ground:[[0,620],[770,780],[1700,700]],ledges:[[390,525,300],[790,440,300],[1130,355,340],[1530,440,310],[1910,525,330]]},
{ground:[[0,2400]],ledges:[[500,525,300],[880,440,300],[1260,355,320],[1650,440,300],[2020,525,270]]},
{ground:[[0,700],[850,760],[1760,640]],ledges:[[480,525,280],[860,440,300],[1240,525,300],[1610,440,300],[2000,355,330]]},
{ground:[[0,2400]],ledges:[[360,525,300],[750,440,300],[1130,355,340],[1540,440,300],[1940,525,330]]},
{ground:[[0,1040],[1190,1210]],ledges:[[420,525,300],[790,440,300],[1190,440,300],[1550,355,340],[1990,440,300]]},
{ground:[[0,680],[830,780],[1760,640]],ledges:[[440,525,300],[850,440,300],[1230,355,340],[1630,440,300],[2020,525,280]]},
{ground:[[0,620],[770,700],[1630,770]],ledges:[[390,525,300],[790,440,300],[1150,355,340],[1540,440,300],[1940,355,330]]},
{ground:[[0,2400]],ledges:[[500,525,300],[880,440,300],[1260,355,330],[1660,440,300],[2040,525,270]]},
{ground:[[0,720],[870,760],[1780,620]],ledges:[[450,525,300],[890,440,300],[1280,525,300],[1650,440,300],[2010,355,330]]},
{ground:[[0,2400]],ledges:[[460,525,320],[900,440,320],[1390,355,360],[1880,440,320]]},
{ground:[[0,690],[840,720],[1710,690]],ledges:[[430,525,300],[860,440,300],[1240,355,340],[1640,440,300],[2040,525,280]]},
{ground:[[0,600],[750,780],[1680,720]],ledges:[[350,525,300],[770,440,320],[1160,355,330],[1560,440,310],[1960,355,330]]},
{ground:[[0,2400]],ledges:[[420,525,310],[830,440,310],[1240,355,340],[1660,440,310],[2050,525,250]]},
{ground:[[0,720],[870,720],[1740,660]],ledges:[[450,525,300],[890,440,300],[1270,355,340],[1670,440,300],[2020,525,300]]},
{ground:[[0,640],[790,730],[1670,730]],ledges:[[390,525,300],[810,440,300],[1190,355,340],[1600,440,300],[1990,355,330]]},
{ground:[[0,2400]],ledges:[[470,525,300],[870,440,300],[1260,355,350],[1690,440,300],[2060,525,260]]},
{ground:[[0,700],[850,740],[1740,660]],ledges:[[430,525,300],[870,440,300],[1260,525,300],[1640,440,300],[2020,355,330]]},
{ground:[[0,2400]],ledges:[[430,525,320],[850,440,320],[1290,355,360],[1780,440,330]]}
];
const platforms=ROOM_LAYOUTS.flatMap((layout,index)=>{const start=index*ROOM_W;return[...layout.ground.map(([x,w])=>({x:start+x,y:610,w,h:130})),...layout.ledges.map(([x,y,w])=>({x:start+x,y,w,h:24}))];});
const spikes = [{x:3850,y:592,w:100},{x:5310,y:592,w:100},{x:11100,y:592,w:110},{x:13300,y:592,w:110},{x:18300,y:592,w:100},{x:19700,y:592,w:110},{x:20850,y:592,w:100},{x:25400,y:592,w:110},{x:29660,y:592,w:100},{x:31640,y:592,w:110},{x:36940,y:592,w:110},{x:39320,y:592,w:110},{x:43780,y:592,w:100}];
const door = {x:15720,y:380,w:48,h:230};
const shrine = {x:10020,y:490,w:92,h:120,taken:false,kind:'shrine'};
const airShrine = {x:34620,y:490,w:92,h:120,taken:false,kind:'airShrine'};
const mobilityGate = {x:39240,y:350,w:44,h:260};
const benches = [
{x:7500,y:510,w:180,h:100,kind:'bench'},
{x:21900,y:510,w:180,h:100,kind:'bench'},
{x:29040,y:510,w:180,h:100,kind:'bench'},
{x:36240,y:510,w:180,h:100,kind:'bench'},
{x:41040,y:510,w:180,h:100,kind:'bench'},
{x:45840,y:510,w:180,h:100,kind:'bench'}
];
const relays = [{x:10500,y:552,w:36,h:58,pair:'aquarium'},{x:13980,y:467,w:36,h:58,pair:'aquarium'},{x:31980,y:552,w:36,h:58,pair:'rain'},{x:41880,y:382,w:36,h:58,pair:'rain'}];
const terminals = [
{x:260,y:500,w:108,h:110,id:'entry',kind:'terminal',title:'未发送的登录记录',speaker:'SYSTEM',text:'25:00。账号「雪」仍在线,但语音轨道没有输入。'},
{x:7850,y:500,w:108,h:110,id:'aquarium',kind:'terminal',title:'水族馆记忆:蓝色',speaker:'K',text:'你说喜欢水族馆的时候,声音没有在说谎。'},
{x:17060,y:500,w:108,h:110,id:'nightcord',kind:'terminal',title:'Nightcord 断线缓存',speaker:'Enanan',text:'连接断掉也没关系。想说的时候,再把真正的话发给我们。'},
{x:24260,y:500,w:108,h:110,id:'backstage',kind:'terminal',title:'无声舞台:演出指令',speaker:'まふゆ',text:'这次,我不想按照别人写好的台词笑。'},
{x:28890,y:500,w:108,h:110,id:'rooftop',kind:'terminal',title:'雨幕天台:未发送语音',speaker:'Amia',text:'偶尔绕路也可以呀。没有人规定你必须马上到达正确答案。'},
{x:34080,y:500,w:108,h:110,id:'classroom',kind:'terminal',title:'镜像教室:值日日志',speaker:'Enanan',text:'镜子里的笑不是假的,只是你不必永远维持它。'},
{x:40520,y:500,w:108,h:110,id:'hall',kind:'terminal',title:'失声礼堂:空白谱面',speaker:'K',text:'第一小节不用完整。只要是你写下的,就足够开始。'},
{x:43480,y:500,w:108,h:110,id:'dressing',kind:'terminal',title:'无名化妆间:卸下的面具',speaker:'まふゆ',text:'我还不知道真正的自己是什么。但我想继续寻找。'}
];
const memoryLamps = [
{x:30240,y:470,w:86,h:140,kind:'lamp',id:'roof',lit:false},{x:32640,y:470,w:86,h:140,kind:'lamp',id:'rain',lit:false},
{x:37140,y:470,w:86,h:140,kind:'lamp',id:'walk',lit:false},{x:40260,y:470,w:86,h:140,kind:'lamp',id:'score',lit:false},
{x:42640,y:470,w:86,h:140,kind:'lamp',id:'hall',lit:false},{x:44940,y:470,w:86,h:140,kind:'lamp',id:'mirror',lit:false}
];
const safeZones = [
{x:0,y:430,w:2400,h:180,label:'入门静默区'},{x:7320,y:430,w:900,h:180,label:'水族馆休息站'},
{x:9780,y:430,w:980,h:180,label:'共鸣静室'},{x:16920,y:430,w:700,h:180,label:'断线静默区'},
{x:21720,y:430,w:760,h:180,label:'后台休息站'},{x:24120,y:430,w:700,h:180,label:'幕间静默区'},
{x:28800,y:430,w:520,h:180,label:'天台雨棚'},{x:33600,y:430,w:760,h:180,label:'镜像教室静区'},
{x:36000,y:430,w:620,h:180,label:'放学路候车亭'},{x:40320,y:430,w:480,h:180,label:'谱库静读区'},{x:40800,y:430,w:720,h:180,label:'礼堂前厅'},{x:43200,y:430,w:920,h:180,label:'化妆间静区'},
{x:45600,y:430,w:560,h:180,label:'最终幕准备区'}
];
const safeZoneGlow=ctx.createLinearGradient(0,430,0,610);safeZoneGlow.addColorStop(0,'rgba(143,241,245,0)');safeZoneGlow.addColorStop(1,'rgba(143,241,245,.12)');
const memoryGates = [{x:12120,y:350,w:30,h:260},{x:14280,y:350,w:30,h:260}];
const arenaGates = [{x:26520,y:350,w:34,h:260},{x:28680,y:350,w:34,h:260}];
const rainGates = [{x:33720,y:350,w:34,h:260},{x:35880,y:350,w:34,h:260}];
const finalGates = [{x:45720,y:350,w:34,h:260},{x:47880,y:350,w:34,h:260}];
const exit = {x:47750,y:490,w:80,h:120};
const groupByRoom = items => Array.from({length:ROOM_COUNT},(_,index)=>items.filter(item=>roomIndexAt(item.x+(item.w||0)*.5)===index));
const platformsByRoom=groupByRoom(platforms),spikesByRoom=groupByRoom(spikes),benchesByRoom=groupByRoom(benches),relaysByRoom=groupByRoom(relays),terminalsByRoom=groupByRoom(terminals),safeZonesByRoom=groupByRoom(safeZones),fragmentsByRoom=groupByRoom(fragments),lampsByRoom=groupByRoom(memoryLamps);
const trainingDummy={x:930,y:312,w:82,h:128,flash:0,hits:0};
const TUTORIAL_LESSONS=[
{title:'让真冬向前移动',keyboard:'A / D',touch:'左侧摇杆'},
{title:'跳上第一层音轨',keyboard:'SPACE',touch:'跳跃'},
{title:'用音刃击中练习水晶',keyboard:'J / X',touch:'音刃'},
{title:'在判定框重合时获得 PERFECT',keyboard:'J / X',touch:'音刃'},
{title:'消耗共鸣能量发射音律',keyboard:'L / C',touch:'投射'},
{title:'打开记忆地图确认前路',keyboard:'M / TAB',touch:'MAP'}
];
let tutorial={step:0,flags:{moved:false,jumped:false,dummyHit:false,perfect:false,ranged:false,map:false},complete:false,hideTimer:0};
let playerSafeZoneActive=false,portraitVisibleUntil=0,portraitSpeakingUntil=0,portraitFrame=-1;
function validatePlatformReachability(){
const reachable=new Set([0]),queue=[0];
const gap=(a,b)=>Math.max(0,Math.max(a.x,b.x)-Math.min(a.x+a.w,b.x+b.w));
const jumpReach=rise=>{const discriminant=JUMP_SPEED*JUMP_SPEED-2*GRAVITY*Math.max(0,rise);if(discriminant<0)return 0;const airTime=(JUMP_SPEED+Math.sqrt(discriminant))/GRAVITY;return 260*airTime+38;};
while(queue.length){
const from=platforms[queue.shift()];
platforms.forEach((to,index)=>{
if(reachable.has(index))return;
const rise=from.y-to.y,horizontal=gap(from,to);
if(rise<=MAX_SAFE_RISE&&horizontal<=MAX_SAFE_GAP&&horizontal<=jumpReach(rise)){reachable.add(index);queue.push(index);}
});
}
const missing=platforms.map((_,index)=>index).filter(index=>!reachable.has(index));
if(missing.length)console.warn('[Level] Unreachable platform indices:',missing);
else console.info(`[Level] ${platforms.length} platforms pass reachability check (rise ≤ ${MAX_SAFE_RISE}px, gap ≤ ${MAX_SAFE_GAP}px).`);
}
validatePlatformReachability();
const player = {
x:180,y:505,w:38,h:78,vx:0,vy:0,dir:1,onGround:false,coyote:0,jumpBuffer:0,dropTimer:0,
hp:5,maxHp:5,invuln:0,hurtControlTimer:0,attackTimer:0,attackCooldown:0,attackBuffer:0,attackInputTime:0,dashTimer:0,dashCooldown:0,dashBuffer:0,
energy:0,maxEnergy:100,rangedTimer:0,rangedCooldown:0,rangedBuffer:0,rangedFired:false,chargeActive:false,chargeTimer:0,chargeReady:false,chargeSoundPlayed:false,chargeInputTime:0,chargeReleaseTimer:0,chargeHitDone:false,
respawnTimer:0,anim:0,landSquash:0,turnFxCooldown:0,airJumps:0,action:'',actionTimer:0,actionDuration:0,actionTarget:null,actionApplied:false
};
function resetGame(full=true){
if(full){ hasDash=false;hasDoubleJump=false;player.maxHp=5;player.maxEnergy=100;checkpoint={x:140,y:505};shrine.taken=false;airShrine.taken=false;combo=0;bestCombo=0;score=0;playTime=0;fragmentsFound=0;storyFlags.clear();discoveredRooms=new Set([0]);fragments.forEach(f=>f.taken=false);memoryLamps.forEach(lamp=>lamp.lit=false);currentArea=0;currentRoom=0;memoryArenaActive=false;memoryArenaCleared=false;arenaActive=false;midBossDefeated=false;rainArenaActive=false;rainArenaCleared=false;finalArenaActive=false;bossDefeated=false;relayCooldown=0;doorPhaseGrace=0; }
currentRoom=roomIndexAt(checkpoint.x);currentArea=ROOMS[currentRoom].area;
Object.assign(player,{x:checkpoint.x,y:checkpoint.y,vx:0,vy:0,hp:player.maxHp,invuln:1,hurtControlTimer:0,coyote:0,jumpBuffer:0,dropTimer:0,attackTimer:0,attackCooldown:0,attackBuffer:0,attackInputTime:0,dashTimer:0,dashCooldown:0,dashBuffer:0,energy:full?0:player.energy,rangedTimer:0,rangedCooldown:0,rangedBuffer:0,rangedFired:false,chargeActive:false,chargeTimer:0,chargeReady:false,chargeSoundPlayed:false,chargeInputTime:0,chargeReleaseTimer:0,chargeHitDone:false,respawnTimer:0,landSquash:0,turnFxCooldown:0,airJumps:0,action:'',actionTimer:0,actionDuration:0,actionTarget:null,actionApplied:false});
tutorial={step:0,flags:{moved:false,jumped:false,dummyHit:false,perfect:false,ranged:false,map:false},complete:currentRoom>0,hideTimer:0};trainingDummy.flash=0;trainingDummy.hits=0;updateTutorialGuide();
enemies = [
makeEnemy(3450,555,'shade'),makeEnemy(3900,576,'crawler'),makeEnemy(4500,360,'wisp'),
makeEnemy(5750,576,'crawler'),makeEnemy(6250,555,'shade'),makeEnemy(6900,360,'sentinel'),
makeEnemy(8400,555,'shade'),makeEnemy(9100,360,'wisp'),
makeEnemy(11000,576,'crawler'),makeEnemy(11600,360,'wisp'),
makeEnemy(12500,555,'shade'),makeEnemy(13200,576,'crawler'),makeEnemy(13800,360,'sentinel'),
makeEnemy(14900,555,'shade'),makeEnemy(16000,576,'crawler'),makeEnemy(16400,360,'wisp'),
makeEnemy(18000,555,'shade'),makeEnemy(18600,360,'sentinel'),
makeEnemy(19600,576,'crawler'),makeEnemy(20300,555,'shade'),makeEnemy(21100,360,'wisp'),
makeEnemy(22800,360,'sentinel'),makeEnemy(23600,555,'shade'),
makeEnemy(25200,576,'crawler'),makeEnemy(26000,360,'wisp'),
makeEnemy(27800,482,'conductor'),
makeEnemy(29700,390,'maskling'),makeEnemy(30400,548,'metronome'),makeEnemy(31040,345,'rainChoir'),
makeEnemy(31650,548,'mirrorHound'),makeEnemy(32500,390,'maskling'),makeEnemy(33200,548,'metronome'),
makeEnemy(34140,360,'rainChoir'),makeEnemy(34950,548,'mirrorHound'),makeEnemy(35540,390,'maskling'),
makeEnemy(36720,548,'metronome'),makeEnemy(37500,360,'rainChoir'),makeEnemy(38200,548,'mirrorHound'),
makeEnemy(38940,390,'maskling'),makeEnemy(39920,548,'metronome'),makeEnemy(40500,360,'rainChoir'),
makeEnemy(41400,548,'mirrorHound'),makeEnemy(42300,390,'maskling'),makeEnemy(43020,548,'metronome'),
makeEnemy(43740,360,'rainChoir'),makeEnemy(44620,548,'mirrorHound'),makeEnemy(45200,390,'maskling'),
makeEnemy(46920,466,'mirror')
];
if(midBossDefeated){const boss=enemies.find(e=>e.type==='conductor');if(boss)boss.dead=true;}if(bossDefeated){const boss=enemies.find(e=>e.type==='mirror');if(boss)boss.dead=true;}
particles=[]; slashes=[]; projectiles=[];resonanceShots=[];roomTransition.active=false; ending=false; mapOpen=false;journalOpen=false;hitStop=0;cameraLookahead=0;mapScreen.classList.add('hidden');journalScreen.classList.add('hidden');endingScreen.classList.add('hidden');camera.x=roomCameraTarget(player.x,currentRoom);
}
function readSave(){
try{
const save=JSON.parse(storageGet('silent-sekai-save'));
return save?.version===7&&save?.checkpoint&&Number.isFinite(save.checkpoint.x)&&Number.isFinite(save.checkpoint.y)?save:null;
}catch{return null;}
}
function saveGame(){
storageSet('silent-sekai-save',JSON.stringify({
version:7,checkpoint,hasDash,hasDoubleJump,memoryArenaCleared,midBossDefeated,rainArenaCleared,bossDefeated,energy:player.energy,maxEnergy:player.maxEnergy,maxHp:player.maxHp,lamps:memoryLamps.map(lamp=>lamp.lit),fragments:fragments.map(f=>f.taken),discoveredRooms:[...discoveredRooms],storyFlags:[...storyFlags],score,bestCombo,playTime,savedAt:Date.now()
}));
updateContinueUI();
}
function updateContinueUI(){
const save=readSave();continueButton.disabled=!save;
if(!save){saveSummary.textContent='尚无 SEKAI 记忆';return;}
const count=Array.isArray(save.fragments)?save.fragments.filter(Boolean).length:0;
const area=areas.find(a=>save.checkpoint.x>=a.start&&save.checkpoint.x<a.end)?.name||'空白 SEKAI';
const minutes=Math.floor((save.playTime||0)/60);saveSummary.textContent=`记忆:${area} · ${minutes} 分钟 · 歌词 ${count}/${fragments.length} · ${String(save.score||0).padStart(7,'0')}`;
}
function hasCoarsePointer(){const coarse=window.matchMedia&&window.matchMedia('(pointer: coarse)').matches,compactTouch=navigator.maxTouchPoints>0&&Math.min(window.innerWidth,window.innerHeight)<900;return Boolean(coarse||compactTouch);}
function resolvedControlMode(){return controlMode==='auto'?(hasCoarsePointer()?'touch':'keyboard'):controlMode;}
function resetJoystick(){touchAxis=0;joystickPointerId=null;if(joystickKnob)joystickKnob.style.transform='translate(-50%,-50%)';}
function held(code){return keys.has(code)||touchHeld.has(code);}
function syncMobileControls(){
const resolved=resolvedControlMode(),visible=resolved==='touch'&&running&&!paused&&!introActive&&!mapOpen&&!journalOpen&&!ending&&settingsScreen.classList.contains('hidden');
document.body.classList.toggle('touch-controls-active',visible);mobileControls.setAttribute('aria-hidden',String(!visible));controlModeSelect.value=controlMode;
controlModeStatus.textContent=controlMode==='auto'?`自动识别:当前使用${resolved==='touch'?'触控摇杆':'键鼠'}模式`:controlMode==='touch'?'强制显示移动端摇杆与动作按钮':'隐藏虚拟按键,仅使用键盘输入';
if(!visible){touchHeld.clear();resetJoystick();}if(typeof tutorial!=='undefined')updateTutorialGuide();
}
function setControlMode(mode){
if(!['auto','keyboard','touch'].includes(mode))return;controlMode=mode;storageSet('silent-sekai-control-mode',mode);syncMobileControls();
}
function openSettings(source='title'){
settingsReturn=source;clearInput();settingsContext.textContent=source==='pause'?'PAUSED GAME':'MAIN MENU';titleScreen.classList.add('hidden');pauseScreen.classList.add('hidden');controlsScreen.classList.add('hidden');settingsScreen.classList.remove('hidden');syncAudioUI();updateFullscreenUI();syncMobileControls();playSfx('confirm',.55);
}
function closeSettings(){
settingsScreen.classList.add('hidden');if(settingsReturn==='pause'&&running){pauseScreen.classList.remove('hidden');}else titleScreen.classList.remove('hidden');last=performance.now();syncMobileControls();playSfx('back',.5);
}
function fullscreenElement(){return document.fullscreenElement||document.webkitFullscreenElement||null;}
function updateFullscreenUI(){const active=Boolean(fullscreenElement());fullscreenButton.textContent=active?'退出全屏':'进入全屏';fullscreenStatus.textContent=active?'当前为全屏模式':'当前为窗口模式';}
async function toggleFullscreen(){
try{
if(fullscreenElement()){const exit=document.exitFullscreen||document.webkitExitFullscreen;if(!exit)throw new Error('unsupported');await exit.call(document);}
else{const root=document.documentElement,request=root.requestFullscreen||root.webkitRequestFullscreen;if(!request)throw new Error('unsupported');await request.call(root);}
updateFullscreenUI();
}catch{fullscreenStatus.textContent='当前浏览器不支持或阻止了全屏请求';}
}
function clearInput(){keys.clear();pressed.clear();released.clear();touchHeld.clear();player.jumpBuffer=0;player.attackBuffer=0;player.attackInputTime=0;player.dashBuffer=0;player.rangedBuffer=0;player.chargeActive=false;player.chargeTimer=0;player.chargeReady=false;player.chargeReleaseTimer=0;resetJoystick();mobileControls.querySelectorAll('.is-active').forEach(button=>button.classList.remove('is-active'));}
function setPaused(value,silent=false){
if(!running)return;paused=value;clearInput();pauseScreen.classList.toggle('hidden',!paused);
setMusicGain(paused ? 0.26 : (arenaActive ? 1.1 : 1));
if(!silent)playSfx(paused?'back':'confirm',.55);
if(!paused)last=performance.now();syncMobileControls();updateTutorialGuide();
}
function beginPlay(){
running=true;paused=false;introActive=false;ending=false;clearInput();setMusicGain(1);ensureMusicPlaying();titleScreen.classList.add('hidden');introScreen.classList.add('hidden');controlsScreen.classList.add('hidden');settingsScreen.classList.add('hidden');pauseScreen.classList.add('hidden');endingScreen.classList.add('hidden');last=performance.now();syncMobileControls();updateTutorialGuide();
}
function startNewGame(){
unlockAudio();playMusic('empty',1.4,true);setMusicGain(.38);playSfx('confirm',.8);storageRemove('silent-sekai-save');resetGame(true);camera.x=0;updateContinueUI();startIntro();tone(220,.2,'sine',.025);
}
function continueGame(){
const save=readSave();if(!save)return;
resetGame(true);checkpoint={x:save.checkpoint.x,y:save.checkpoint.y};hasDash=Boolean(save.hasDash);hasDoubleJump=Boolean(save.hasDoubleJump);shrine.taken=hasDash;airShrine.taken=hasDoubleJump;memoryArenaCleared=Boolean(save.memoryArenaCleared)||roomIndexAt(checkpoint.x)>5;midBossDefeated=Boolean(save.midBossDefeated)||roomIndexAt(checkpoint.x)>11;rainArenaCleared=Boolean(save.rainArenaCleared)||roomIndexAt(checkpoint.x)>14;bossDefeated=Boolean(save.bossDefeated);player.maxEnergy=Math.max(100,Number(save.maxEnergy)||100);player.maxHp=Math.max(5,Number(save.maxHp)||5);player.energy=Math.max(0,Math.min(player.maxEnergy,Number(save.energy)||0));
if(Array.isArray(save.lamps))memoryLamps.forEach((lamp,index)=>lamp.lit=Boolean(save.lamps[index]));playTime=Math.max(0,Number(save.playTime)||0);
if(Array.isArray(save.fragments))fragments.forEach((fragment,index)=>fragment.taken=Boolean(save.fragments[index]));
fragmentsFound=fragments.filter(fragment=>fragment.taken).length;discoveredRooms=new Set(Array.isArray(save.discoveredRooms)?save.discoveredRooms:[0]);storyFlags=new Set(Array.isArray(save.storyFlags)?save.storyFlags:[]);score=Number(save.score)||0;bestCombo=Number(save.bestCombo)||0;
resetGame(false);camera.x=roomCameraTarget(checkpoint.x,currentRoom);unlockAudio();playMusic(['empty','aquarium','corridor','stage','aquarium','stage'][currentArea]||'empty',.55,true);playSfx('confirm',.8);beginPlay();showToast('已载入 SEKAI 记忆');tone(360,.18,'sine',.025);
}
function returnToMainMenu(){
running=false;paused=false;introActive=false;mapOpen=false;journalOpen=false;ending=false;clearInput();setMusicGain(.45);playMusic('empty',1);playSfx('back',.75);introScreen.classList.add('hidden');mapScreen.classList.add('hidden');journalScreen.classList.add('hidden');pauseScreen.classList.add('hidden');endingScreen.classList.add('hidden');controlsScreen.classList.add('hidden');settingsScreen.classList.add('hidden');nightcord.classList.add('hidden');characterPortrait.classList.add('hidden');tutorialGuide.classList.add('hidden');areaTitle.classList.add('hidden');toast.classList.add('hidden');titleScreen.classList.remove('hidden');updateContinueUI();syncMobileControls();tone(180,.1,'sine',.018);
}
let introIndex=0;
function startIntro(){
running=false;introActive=true;introIndex=0;titleScreen.classList.add('hidden');introScreen.classList.remove('hidden');syncMobileControls();renderIntroScene();
}
function renderIntroScene(){
const scene=INTRO_SCENES[introIndex];introChapter.textContent=scene.chapter;introSpeaker.textContent=scene.speaker;introText.textContent=scene.text;introText.classList.remove('changing');introCg.classList.remove('changing');if(introCg.getAttribute('src')!==scene.image)introCg.src=scene.image;introProgress.innerHTML=INTRO_SCENES.map((_,index)=>`<i class="${index<=introIndex?'active':''}"></i>`).join('');
document.querySelector('#introNextButton').childNodes[0].nodeValue=introIndex===INTRO_SCENES.length-1?'进入 SEKAI ':'继续 ';
}
function advanceIntro(){
if(!introActive)return;playSfx('confirm',.45,1+.04*introIndex,0);if(introIndex>=INTRO_SCENES.length-1){finishIntro();return;}introText.classList.add('changing');introCg.classList.add('changing');setTimeout(()=>{introIndex++;renderIntroScene();},180);
}
function finishIntro(){
introActive=false;introScreen.classList.add('hidden');beginPlay();discoverRoom(0,true);showToast('探索 SEKAI · M 查看记忆地图',3000);setTimeout(()=>{if(running&&!paused&&!mapOpen)showNC('K','听得见。我们一直在连接里。先沿着散落的歌词走吧。',4300);},850);tone(360,.35,'sine',.035);
}
function roomIndexAt(x){return Math.max(0,Math.min(ROOMS.length-1,Math.floor(Math.max(0,x)/ROOM_W)));}
function discoverRoom(index,silent=false){
if(index<0||discoveredRooms.has(index))return;discoveredRooms.add(index);if(!silent){playSfx('transition',.28,1.15);showToast(`地图更新 · ${ROOMS[index].name}`,1800);}
}
function renderMap(){
const current=roomIndexAt(player.x);discoveredRooms.add(current);
mapRooms.innerHTML=ROOMS.map((room,index)=>{const known=discoveredRooms.has(index),classes=`map-room${known?' discovered':''}${index===current?' current':''}`;return `<div class="${classes}" style="left:${room.x}%;top:${room.y}%;width:${room.w}%;height:${room.h}%;--room-tone:${areas[room.area].tone}" title="${known?room.name:'未探索区域'}"><em>${known?room.name:'?'}</em>${index===current?'<span class="room-player">◆</span>':''}</div>`;}).join('');
const markers=[
...[3,9,12,15,17,19].map(room=>({room,text:'▰',type:'bench',label:'记忆长椅'})),
{room:4,text:'◇',type:'shrine',label:hasDash?'已取得:静音冲刺':'共鸣水晶'},
{room:14,text:'◇',type:'shrine',label:hasDoubleJump?'已取得:返声跃迁':'镜声祭坛'},
{room:6,text:'║',type:'gate',label:'静音冲刺封印'},
{room:16,text:'║',type:'gate',label:'返声跃迁封印'},
...[4,5,13,17].map(room=>({room,text:'⇄',type:'relay',label:'回声捷径'})),
...[0,3,7,10,12,14,17,18].map(room=>({room,text:'▣',type:'terminal',label:'记忆终端'}))
];
for(const marker of markers){if(!discoveredRooms.has(marker.room))continue;const room=ROOMS[marker.room],node=document.createElement('span');node.className=`map-marker ${marker.type}`;node.textContent=marker.text;node.title=marker.label;node.style.left=`${room.x+room.w*.82}%`;node.style.top=`${room.y+room.h*.2}%`;mapRooms.appendChild(node);}
const abilities=[hasDash?'静音冲刺':'冲刺未共鸣',hasDoubleJump?'返声跃迁':'空中跃迁未共鸣'].join(' · ');mapSummary.textContent=`探索 ${discoveredRooms.size} / ${ROOMS.length} 房间 · 歌词 ${fragmentsFound} / ${fragments.length} · 雨音灯 ${memoryLamps.filter(l=>l.lit).length}/${memoryLamps.length} · ${abilities}`;
}
function toggleMap(force){
if(!running||introActive)return;mapOpen=typeof force==='boolean'?force:!mapOpen;clearInput();mapScreen.classList.toggle('hidden',!mapOpen);if(mapOpen){tutorial.flags.map=true;updateTutorialState();renderMap();playSfx('confirm',.38,.96,0);}else{playSfx('back',.35,1.05,0);last=performance.now();}syncMobileControls();
}
function renderJournal(){
const minutes=Math.floor(playTime/60),seconds=Math.floor(playTime%60),lit=memoryLamps.filter(lamp=>lamp.lit).length,records=terminals.filter(terminal=>storyFlags.has(`terminal-${terminal.id}`)).length;
journalPlaytime.textContent=`${String(minutes).padStart(2,'0')}:${String(seconds).padStart(2,'0')}`;journalObjective.textContent=objectiveText();journalRoute.textContent=`当前位置:${ROOMS[currentRoom].name}。地图已记录 ${discoveredRooms.size}/${ROOMS.length} 个房间;在记忆长椅同步可保存当前进度。`;
journalAbilities.innerHTML=[['静音冲刺',hasDash,'K / SHIFT · 穿越粉色封印'],['返声跃迁',hasDoubleJump,'空中再次跳跃'],['冰之弓',true,'25 能量 · 概率冻结'],['蓄力冰剑',true,'移动蓄力 · 免费重斩']].map(([name,done,detail])=>`<span class="${done?'done':''}">${name}<b>${done?detail:'未共鸣'}</b></span>`).join('');
journalQuests.innerHTML=[['主线歌词',fragmentsFound===fragments.length,`${fragmentsFound}/${fragments.length}`],['雨后的绕路',lit===memoryLamps.length,`${lit}/${memoryLamps.length} 盏灯`],['未发送的记录',records===terminals.length,`${records}/${terminals.length} 终端`],['第一幕演出',midBossDefeated,midBossDefeated?'完成':'未完成'],['最终剧本',bossDefeated,bossDefeated?'破碎':'未完成']].map(([name,done,detail])=>`<span class="${done?'done':''}">${name}<b>${detail}</b></span>`).join('');
const completion=Math.round((discoveredRooms.size/ROOMS.length*.35+fragmentsFound/fragments.length*.25+lit/memoryLamps.length*.1+(Number(hasDash)+Number(hasDoubleJump))/2*.1+(Number(midBossDefeated)+Number(bossDefeated))/2*.2)*100);journalCompletion.innerHTML=`<i style="width:${completion}%"></i>`;let copy=journalCompletion.nextElementSibling;if(!copy||!copy.classList.contains('journal-progress-copy')){copy=document.createElement('p');copy.className='journal-progress-copy';journalCompletion.after(copy);}copy.textContent=`${completion}% · ${bossDefeated?'空白已经成为新的开头':'仍有声音等待被找到'}`;
}
function toggleJournal(force){
if(!running||introActive)return;journalOpen=typeof force==='boolean'?force:!journalOpen;clearInput();journalScreen.classList.toggle('hidden',!journalOpen);pauseScreen.classList.add('hidden');if(journalOpen){paused=false;renderJournal();playSfx('confirm',.38,1.03,0);}else{playSfx('back',.35,1.05,0);last=performance.now();}syncMobileControls();
}
function toggleMute(){
muted=!muted;storageSet('silent-sekai-muted',String(muted));if(!muted){unlockAudio();playSfx('confirm',.7);tone(330,.1,'sine',.025);}updateMuteButtons();syncAudioUI();
}
function updateMuteButtons(){
const label=muted?'声音:关闭':'声音:开启';
const menu=document.querySelector('#muteButton');menu.querySelector('span').childNodes[0].nodeValue=label;menu.querySelector('small').textContent=muted?'SOUND OFF':'SOUND ON';
document.querySelector('#pauseMuteButton').textContent=label;
}
function syncAudioUI(){
musicVolumeInput.value=Math.round(musicVolume*100);sfxVolumeInput.value=Math.round(sfxVolume*100);musicVolumeValue.textContent=`${musicVolumeInput.value}%`;sfxVolumeValue.textContent=`${sfxVolumeInput.value}%`;setAudioStatus(muted?'当前处于静音状态':`BGM ${musicVolumeInput.value}% · SFX ${sfxVolumeInput.value}%`);
}
function setAudioStatus(message,state=''){audioStatus.textContent=message;if(state)audioStatus.dataset.state=state;else delete audioStatus.dataset.state;}
function unlockAudio(){
const firstUnlock=!audioUnlocked,needsRetry=firstUnlock||!musicKey||musicChannels[activeMusic].paused;audioUnlocked=true;if(audioCtx?.state==='suspended')audioCtx.resume().catch(()=>{});if(needsRetry)setAudioStatus(firstUnlock?'正在启用音频…':'正在重试 BGM…');ensureMusicPlaying(needsRetry);
}
function ensureMusicPlaying(force=false){
if(muted||!audioUnlocked)return;const active=musicChannels[activeMusic],requested=pendingMusic||'empty';if(force||!musicKey||active.paused)playMusic(requested,.25,true);
}
function playSfx(name,volume=1,rate=1,variance=.035){
if(muted||!audioUnlocked)return false;const template=sfxTemplates[name];if(!template)return false;const sound=template.cloneNode();sound.volume=Math.max(0,Math.min(1,sfxVolume*volume));sound.playbackRate=Math.max(.5,Math.min(2,rate+(Math.random()*2-1)*variance));sound.play().then(()=>setAudioStatus(`音频已启用 · BGM ${Math.round(musicVolume*100)}% · SFX ${Math.round(sfxVolume*100)}%`,'ready')).catch(error=>setAudioStatus(`音效播放失败:${error.name||'浏览器阻止'}`,'error'));return true;
}
function playMusic(key,fade=1.2,restart=false){
if(!MUSIC_TRACKS[key])return;pendingMusic=key;if(!audioUnlocked)return;if(key===musicKey&&!restart)return;
const request=++musicRequestId,from=activeMusic,to=1-activeMusic,next=musicChannels[to];next.pause();next.src=MUSIC_TRACKS[key];next.currentTime=0;next.volume=0;
next.play().then(()=>{if(request!==musicRequestId){next.pause();return;}musicFade={from,to,t:0,duration:Math.max(.05,fade)};activeMusic=to;musicKey=key;setAudioStatus(`音频已启用 · BGM ${Math.round(musicVolume*100)}% · SFX ${Math.round(sfxVolume*100)}%`,'ready');}).catch(error=>{if(request!==musicRequestId)return;musicKey='';musicFade=null;setAudioStatus(`BGM 播放失败:请再次点击画面重试(${error.name||'浏览器阻止'})`,'error');});
}
function setMusicGain(value){musicGain=Math.max(0,Math.min(1.15,value));}
function updateAudio(dt){
const target=muted?0:Math.min(1,musicVolume*musicGain);
if(musicFade){musicFade.t+=dt;const p=Math.min(1,musicFade.t/musicFade.duration),ease=p*p*(3-2*p);musicChannels[musicFade.from].volume=target*(1-ease);musicChannels[musicFade.to].volume=target*ease;if(p>=1){musicChannels[musicFade.from].pause();musicChannels[musicFade.from].removeAttribute('src');musicFade=null;}}
else{const active=musicChannels[activeMusic];active.volume+=(target-active.volume)*(1-Math.pow(.0001,dt));}
}
const ENEMY_AI={
shade:{detect:350,vertical:180,reaction:.22,memory:2.2,roam:125,patrol:46,chase:112},
wisp:{detect:440,vertical:260,reaction:.28,memory:2.7,roam:105,patrol:30,chase:52},
crawler:{detect:420,vertical:170,reaction:.18,memory:2.1,roam:140,patrol:58,chase:178},
sentinel:{detect:570,vertical:300,reaction:.36,memory:3.1,roam:0,patrol:0,chase:0},
maskling:{detect:520,vertical:290,reaction:.2,memory:2.8,roam:135,patrol:38,chase:118},
metronome:{detect:470,vertical:190,reaction:.25,memory:2.7,roam:130,patrol:42,chase:102},
rainChoir:{detect:590,vertical:330,reaction:.32,memory:3.2,roam:120,patrol:28,chase:48},
mirrorHound:{detect:480,vertical:180,reaction:.16,memory:2.5,roam:155,patrol:64,chase:195},
mirror:{detect:900,vertical:500,reaction:0,memory:9,roam:0,patrol:0,chase:0}
};
const isBossType=type=>type==='conductor'||type==='mirror';
function makeEnemy(x,y,type){
const stats={wisp:[42,42,2],shade:[46,55,3],crawler:[54,34,3],sentinel:[42,62,4],maskling:[48,54,4],metronome:[50,72,6],rainChoir:[66,58,5],mirrorHound:[72,42,5],conductor:[104,128,26],mirror:[86,138,42]}[type]||[46,55,3];
return{x,y,homeX:x,homeY:y,w:stats[0],h:stats[1],vx:0,vy:0,hp:stats[2],maxHp:stats[2],type,dir:Math.random()<.5?-1:1,hit:0,frozen:0,dead:false,defeating:0,t:Math.random()*3,attackClock:1+Math.random(),phase:0,state:isBossType(type)?'boss':'idle',stateClock:.55+Math.random()*1.2,notice:0,memory:0,stateFlash:0,patrolDir:Math.random()<.5?-1:1,lastSeenX:x,turnLock:0};
}
function showToast(text,ms=2200){ toast.textContent=text; toast.classList.remove('hidden'); clearTimeout(showToast.t); showToast.t=setTimeout(()=>toast.classList.add('hidden'),ms); }
function showNC(name,text,ms=3600){
nightcordMessages.innerHTML=`<div class="nc-msg"><span class="nc-name">${name}</span>${text}</div>`;
nightcord.classList.remove('hidden');clearTimeout(showNC.t);showNC.t=setTimeout(()=>nightcord.classList.add('hidden'),ms);
if(name.includes('まふゆ')||name.includes('真冬')){const now=performance.now();portraitVisibleUntil=now+ms;portraitSpeakingUntil=now+ms*.72;characterPortrait.classList.remove('hidden');characterPortrait.setAttribute('aria-hidden','false');}
}
function updatePortrait(){
const now=performance.now();if(now>=portraitVisibleUntil){characterPortrait.classList.add('hidden');characterPortrait.setAttribute('aria-hidden','true');return;}
const speaking=now<portraitSpeakingUntil,row=speaking?1:0,cycle=now/1000;
let frame=speaking?Math.floor(cycle*7)%4:0;if(!speaking){const blink=cycle%4.6;frame=blink>.1&&blink<.19?2:blink>=.19&&blink<.29?3:blink>=.29&&blink<.38?2:Math.floor(cycle*.7)%2;}
if(frame===portraitFrame&&portraitSprite.dataset.row===String(row))return;portraitFrame=frame;portraitSprite.dataset.row=String(row);portraitSprite.style.backgroundPosition=`${frame*(100/3)}% ${row*100}%`;
}
function tutorialInputLabel(lesson){return resolvedControlMode()==='touch'?lesson.touch:lesson.keyboard;}
function updateTutorialGuide(){
const visible=running&&!paused&&!mapOpen&&!tutorial.complete&&currentRoom===0&&!roomTransition.active;if(!visible){tutorialGuide.classList.add('hidden');return;}
const lesson=TUTORIAL_LESSONS[tutorial.step];tutorialIndex.textContent=`LESSON ${String(tutorial.step+1).padStart(2,'0')} / ${TUTORIAL_LESSONS.length}`;tutorialTitle.textContent=lesson.title;tutorialInput.textContent=tutorialInputLabel(lesson);tutorialProgress.innerHTML=TUTORIAL_LESSONS.map((_,index)=>`<i class="${index<tutorial.step?'done':''}"></i>`).join('');tutorialGuide.classList.remove('hidden');
}
function updateTutorialState(){
if(tutorial.complete)return;const order=['moved','jumped','dummyHit','perfect','ranged','map'];let next=order.findIndex(flag=>!tutorial.flags[flag]);if(next<0){tutorial.complete=true;tutorial.hideTimer=2.6;tutorialGuide.classList.add('hidden');score+=750;showToast('入门同步完成 · 前方是第一段正式探索',2600);showNC('まふゆ','……先继续前进吧。至少这一次,是我自己决定的。',3900);return;}if(next!==tutorial.step){tutorial.step=next;playSfx('confirm',.28,1.14);updateTutorialGuide();}
}
function updateTutorial(dt){
if(currentRoom!==0){tutorial.complete=true;updateTutorialGuide();return;}if(tutorial.complete){tutorial.hideTimer=Math.max(0,tutorial.hideTimer-dt);return;}if(Math.abs(player.x-180)>90)tutorial.flags.moved=true;trainingDummy.flash=Math.max(0,trainingDummy.flash-dt);updateTutorialState();
}
function showArea(index){
const a=areas[index];areaTitle.querySelector('strong').textContent=a.name;areaTitle.querySelector('span').textContent=a.sub;areaTitle.classList.remove('hidden');clearTimeout(showArea.t);showArea.t=setTimeout(()=>areaTitle.classList.add('hidden'),2600);
}
function roomCameraTarget(x,roomIndex=currentRoom,lookahead=0){const room=ROOMS[roomIndex]||ROOMS[0];return Math.max(room.start,Math.min(room.end-W,x-W*.5+lookahead));}
function startRoomTransition(to,direction){
if(roomTransition.active||to<0||to>=ROOMS.length||to===currentRoom)return;
roomTransition={active:true,t:0,duration:1.15,from:currentRoom,to,direction,revealed:false};clearInput();finishPlayerAction();player.vx=0;player.vy=0;playSfx('transition',.76,.94);tone(135,.28,'sine',.025);
}
function updateRoomTransition(dt){
roomTransition.t+=dt;const phase=roomTransition.t/roomTransition.duration;
if(phase>=.5&&!roomTransition.revealed){
roomTransition.revealed=true;currentRoom=roomTransition.to;const room=ROOMS[currentRoom],previousArea=currentArea;currentArea=room.area;player.x=roomTransition.direction>0?room.start+86:room.end-player.w-86;player.y=505;player.vx=0;player.vy=0;cameraLookahead=roomTransition.direction*28;camera.x=roomCameraTarget(player.x,currentRoom,cameraLookahead);projectiles=[];resonanceShots=[];discoverRoom(currentRoom,true);showToast(`${String(currentRoom+1).padStart(2,'0')} · ${room.name}`,1800);
if(currentArea!==previousArea){showArea(currentArea);triggerAreaStory(currentArea);playMusic(['empty','aquarium','corridor','stage','aquarium','stage'][currentArea],1.1);tone(360,.38,'sine',.03);}else playSfx('transition',.35,1.08);
}
if(phase>=1){roomTransition.active=false;last=performance.now();updateTutorialGuide();}
pressed.clear();released.clear();
}
function checkRoomBoundary(){
const room=ROOMS[currentRoom],edge=18;if(player.x+player.w>=room.end-edge){player.x=room.end-player.w-edge;if(currentRoom<ROOMS.length-1)startRoomTransition(currentRoom+1,1);}else if(player.x<=room.start+edge){player.x=room.start+edge;if(currentRoom>0)startRoomTransition(currentRoom-1,-1);}
}
function triggerAreaStory(index){
if(index===1&&!storyFlags.has('aquarium')){storyFlags.add('aquarium');showNC('K','まふゆ,这里像你说过喜欢的水族馆。');}
if(index===2&&!storyFlags.has('corridor')){storyFlags.add('corridor');showNC('Amia','连接很不稳定……但我们还听得见哦。');}
if(index===3&&!storyFlags.has('stage')){storyFlags.add('stage');showNC('Enanan','舞台中央的那个人影……和まふゆ长得一样。');}
if(index===4&&!storyFlags.has('rain-campus')){storyFlags.add('rain-campus');showNC('Amia','这里像放学后的学校,却没有任何人的脚步声。雨音灯也许能留下路标。');}
if(index===5&&!storyFlags.has('unwritten')){storyFlags.add('unwritten');showNC('K','前面没有谱面,也没有规定好的结尾。接下来只能由你写。');}
}
function drawRoomTransition(){
if(!roomTransition.active)return;const phase=Math.min(1,roomTransition.t/roomTransition.duration),fade=phase<.5?phase*2:(1-phase)*2,eased=1-Math.pow(1-Math.max(0,fade),3),target=ROOMS[roomTransition.to],tone=areas[target.area].tone;
ctx.save();ctx.globalAlpha=eased;ctx.fillStyle='#03050d';ctx.fillRect(0,0,W,H);const shutter=eased*W*.54;ctx.fillStyle='#080b18';ctx.fillRect(0,0,shutter,H);ctx.fillRect(W-shutter,0,shutter,H);ctx.strokeStyle=tone;ctx.globalAlpha=eased*.55;ctx.lineWidth=1;for(let i=-8;i<=8;i++){const x=W/2+i*34*(1-eased);ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(W/2+(x-W/2)*.2,H);ctx.stroke();}
if(phase>.34&&phase<.72){ctx.globalAlpha=Math.min(1,eased*1.4);ctx.textAlign='center';ctx.fillStyle='#eef8ff';ctx.font='500 28px "Shippori Mincho",serif';ctx.fillText(target.name,W/2,H/2-2);ctx.fillStyle=tone;ctx.font='700 9px sans-serif';ctx.letterSpacing='4px';ctx.fillText(`ROOM ${String(roomTransition.to+1).padStart(2,'0')} / ${ROOMS.length}`,W/2,H/2+25);}
ctx.restore();
}
function overlap(a,b){return a.x<b.x+b.w&&a.x+a.w>b.x&&a.y<b.y+b.h&&a.y+a.h>b.y;}
function refreshPlayerSafeZone(){playerSafeZoneActive=safeZonesByRoom[currentRoom].some(zone=>overlap(player,zone));}
function playerInSafeZone(){return playerSafeZoneActive;}
function enemyApproachesSafeZone(e,dir){const probeX=e.x+dir*46,room=roomIndexAt(e.homeX);return safeZonesByRoom[room].some(zone=>probeX<zone.x+zone.w&&probeX+e.w>zone.x&&e.y<zone.y+zone.h&&e.y+e.h>zone.y);}
function collideEntityAxis(e,p,axis,previousBottom=Infinity,oneWay=false){
if(oneWay&&e===player){if(axis==='x'||player.dropTimer>0||e.vy<=0||previousBottom>p.y+6)return;}
if(!overlap(e,p))return;if(axis==='x'){if(e.vx>0)e.x=p.x-e.w;else if(e.vx<0)e.x=p.x+p.w;e.vx=0;}else{if(e.vy>0){e.y=p.y-e.h;e.onGround=true;}else if(e.vy<0)e.y=p.y+p.h;e.vy=0;}
}
function collideActiveSolids(e,axis,previousBottom=Infinity){
for(const p of platformsByRoom[currentRoom])collideEntityAxis(e,p,axis,previousBottom,p.h<=24);
if(currentRoom===roomIndexAt(door.x)&&doorPhaseGrace<=0)collideEntityAxis(e,door,axis,previousBottom);
if(memoryArenaActive&&!memoryArenaCleared&&currentRoom===5)for(const gate of memoryGates)collideEntityAxis(e,gate,axis,previousBottom);
if(arenaActive&&!midBossDefeated&&currentRoom===11)for(const gate of arenaGates)collideEntityAxis(e,gate,axis,previousBottom);
if(rainArenaActive&&!rainArenaCleared&&currentRoom===14)for(const gate of rainGates)collideEntityAxis(e,gate,axis,previousBottom);
if(finalArenaActive&&!bossDefeated&&currentRoom===19)for(const gate of finalGates)collideEntityAxis(e,gate,axis,previousBottom);
if(currentRoom===roomIndexAt(mobilityGate.x)&&!hasDoubleJump)collideEntityAxis(e,mobilityGate,axis,previousBottom);
}
function overlapsActiveSolid(entity){
if(platformsByRoom[currentRoom].some(platform=>overlap(entity,platform)))return true;
if(currentRoom===roomIndexAt(door.x)&&doorPhaseGrace<=0&&overlap(entity,door))return true;
if(memoryArenaActive&&!memoryArenaCleared&&currentRoom===5&&memoryGates.some(gate=>overlap(entity,gate)))return true;
if(arenaActive&&!midBossDefeated&&currentRoom===11&&arenaGates.some(gate=>overlap(entity,gate)))return true;
if(rainArenaActive&&!rainArenaCleared&&currentRoom===14&&rainGates.some(gate=>overlap(entity,gate)))return true;
if(finalArenaActive&&!bossDefeated&&currentRoom===19&&finalGates.some(gate=>overlap(entity,gate)))return true;
return currentRoom===roomIndexAt(mobilityGate.x)&&!hasDoubleJump&&overlap(entity,mobilityGate);
}
function moveEntity(e,dt){
e.x += e.vx*dt;
collideActiveSolids(e,'x');
const previousBottom=e.y+e.h;e.y += e.vy*dt;e.onGround=false;
collideActiveSolids(e,'y',previousBottom);
}
function movePlayerWithLanding(dt){
const wasGrounded=player.onGround,impactVelocity=player.vy;moveEntity(player,dt);if(player.onGround)player.airJumps=0;if(!wasGrounded&&player.onGround&&impactVelocity>300){player.landSquash=Math.min(.18,.08+(impactVelocity-300)/5000);if(impactVelocity>470){spawn(player.x+player.w/2,player.y+player.h,'#bcefff',reducedMotion?3:7,70);playSfx('footstep2',.1,.72,.04);}}
}
function standingOnOneWay(){const bottom=player.y+player.h;return platformsByRoom[currentRoom].some(platform=>platform.h<=24&&player.x+player.w>platform.x+4&&player.x<platform.x+platform.w-4&&Math.abs(bottom-platform.y)<=5);}
function jumpHeld(){return held('Space')||held('ArrowUp')||held('KeyW');}
function applyPlayerGravity(dt){
let scale=1;if(player.vy<0&&!jumpHeld())scale=JUMP_CUT_GRAVITY_SCALE;else if(Math.abs(player.vy)<95)scale=APEX_GRAVITY_SCALE;else if(player.vy>0)scale=FALL_GRAVITY_SCALE;player.vy=Math.min(980,player.vy+GRAVITY*scale*dt);
}
function spawn(x,y,color,n=8,speed=150){
const count=Math.min(reducedMotion?Math.ceil(n*.45):n,MAX_PARTICLES-particles.length);for(let i=0;i<count;i++){const a=Math.random()*Math.PI*2,s=Math.random()*speed;particles.push({x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s-20,life:.25+Math.random()*.45,max:.7,color,size:2+Math.random()*4});}
}
function fireProjectile(x,y,vx,vy,kind='note',damage=1){if(projectiles.length>=MAX_PROJECTILES)return;const size={chord:22,blade:20,rain:16,script:24}[kind]||14;projectiles.push({x,y,vx,vy,w:size,h:size,kind,damage,life:5,t:0});}
function objectiveText(){
if(bossDefeated)return '前往舞台出口';
if(finalArenaActive)return '击败「未写下的真冬」';
if(rainArenaActive)return '净化镜像教室的雨噪';
if(arenaActive)return '击败第一幕 Boss「无声指挥者」';
if(memoryArenaActive)return '清除水族馆记忆污染';
if(!memoryArenaCleared)return fragmentsFound<4?`收集歌词碎片 ${fragmentsFound}/4`:'深入水族馆 · 寻找记忆核心';
if(!hasDash)return '返回沉水展厅 · 唤醒共鸣水晶';
if(currentRoom<=6)return '进入封音门房间 · 用静音冲刺穿过封印';
if(currentRoom<9)return '绘制 25 时回廊的地图';
if(!midBossDefeated)return '穿过无声剧场 · 完成第一幕演出';
if(currentRoom<14&&!rainArenaCleared)return '穿过雨幕校舍 · 寻找镜声祭坛';
if(!hasDoubleJump)return fragmentsFound<10?`收集歌词碎片 ${fragmentsFound}/10`:'唤醒镜声祭坛 · 取得返声跃迁';
if(currentRoom<16)return '探索无人放学路 · 点亮雨音灯';
if(currentRoom<19)return '进入未完成乐章 · 找到真正的舞台';
return '面对「未写下的真冬」';
}
function onEnemyDefeated(enemy){
const boss=isBossType(enemy.type);if(boss){enemy.defeating=enemy.type==='mirror'?1.8:1.15;enemy.vx=0;enemy.vy=0;enemy.hit=0;}else enemy.dead=true;score+=boss?(enemy.type==='mirror'?24000:12000):1500;
spawn(enemy.x+enemy.w/2,enemy.y+enemy.h/2,boss?'#ffc4eb':'#af9cff',boss?70:26,boss?380:260);
if(enemy.type==='conductor'){
midBossDefeated=true;arenaActive=false;shake=24;flash=.6;hitStop=Math.max(hitStop,.1);projectiles=[];saveGame();
setMusicGain(.72);playSfx('victory',.8,1,0);
showToast('第一幕完成 · 通往雨幕校舍的道路开启',4200);
showNC('まふゆ','……这不是结束。那道雨声后面,还有一句我没有说完。',5200);
tone(660,.8,'sine',.1);
}else if(enemy.type==='mirror'){
bossDefeated=true;finalArenaActive=false;shake=28;flash=.7;hitStop=Math.max(hitStop,.12);projectiles=[];saveGame();setMusicGain(.72);playSfx('victory',1,1,0);showToast('未写下的剧本已经破碎 · 出口开启',4600);showNC('まふゆ','我还不能立刻写出答案。但空白也可以是我的第一行。',5600);tone(740,1,'sine',.11);
}
}
function hurt(amount,sourceX){
if(player.action==='bench'||player.invuln>0||player.dashTimer>0||player.respawnTimer>0)return;
finishPlayerAction();player.attackBuffer=0;player.dashBuffer=0;player.rangedBuffer=0;player.rangedTimer=0;player.rangedFired=false;player.chargeActive=false;player.chargeTimer=0;player.chargeReady=false;player.chargeReleaseTimer=0;
player.hp-=amount;combo=0;player.invuln=1.15;player.hurtControlTimer=.16;player.vx=(player.x<sourceX?-1:1)*360;player.vy=-330;
shake=13;flash=.18;hitStop=Math.max(hitStop,reducedMotion?.035:.055);spawn(player.x+player.w/2,player.y+30,'#f6a5d5',16,250);playSfx('hurt',.9,.96);tone(115,.12,'sawtooth',.045);
if(player.hp<=0){player.respawnTimer=1.25;playSfx('death',.9,.9);showToast('声音沉入了更深的地方……');}
}
function attack(){
if(player.action||player.attackCooldown>0||player.respawnTimer>0)return false;player.attackBuffer=0;
const inputTime=player.attackInputTime||time,phase=(inputTime%BEAT)/BEAT,distance=Math.min(phase,1-phase)*BEAT;player.attackInputTime=0;
const perfect=distance<.085, good=distance<.18;
judgement=perfect?'PERFECT':good?'GREAT':'MISS';judgeTimer=.52;
if(perfect){combo++;score+=1000+combo*25;player.energy=Math.min(player.maxEnergy,player.energy+25);tutorial.flags.perfect=true;showToast(`PERFECT · 共鸣能量 ${Math.round(player.energy)}/${player.maxEnergy}`,1050);}else if(good){combo++;score+=550+combo*10;}else combo=0;
bestCombo=Math.max(bestCombo,combo);
player.attackTimer=.34;player.attackCooldown=perfect?.28:.34;if(player.onGround)player.vx+=player.dir*(perfect?92:68);const box={x:player.dir>0?player.x+30:player.x-62,y:player.y+6,w:perfect?92:74,h:66,life:.2,dir:player.dir,damage:perfect?2:1};slashes.push(box);
playSfx('attack',.65,perfect?1.12:1);tone(310,.07,'triangle',.025); spawn(box.x+(player.dir>0?box.w:0),box.y+30,'#b8efff',7,120);
for(const e of enemies){
if(!e.dead&&e.hp>0&&e.hit<=0&&overlap(box,e)){
e.hp-=box.damage;e.hit=.3;e.vx=player.dir*(isBossType(e.type)?110:250);if(!isBossType(e.type)){e.state='alert';e.memory=ENEMY_AI[e.type].memory;e.notice=ENEMY_AI[e.type].reaction;e.stateFlash=.65;}shake=perfect?11:7;hitStop=Math.max(hitStop,reducedMotion?.025:perfect?.065:.04);
spawn(e.x+e.w/2,e.y+e.h/2,perfect?'#f1b8ff':'#9cecff',perfect?20:12,220);playSfx('hit',perfect ? 0.8 : 0.58,perfect ? 1.08 : 0.94);tone(perfect?230:170,.08,'square',.018);
if(e.hp<=0)onEnemyDefeated(e);
}
}
if(currentRoom===0&&overlap(box,trainingDummy)){trainingDummy.flash=.24;trainingDummy.hits++;tutorial.flags.dummyHit=true;hitStop=Math.max(hitStop,reducedMotion?.018:.032);spawn(trainingDummy.x+trainingDummy.w/2,trainingDummy.y+44,perfect?'#efc5ff':'#9ff2ff',perfect?14:8,150);playSfx('hit',.35,perfect?1.18:1.04);}
updateTutorialState();
if(combo>0&&combo%8===0){player.hp=Math.min(player.maxHp,player.hp+1);showToast('SYNC × 8 · 声音正在回应');}return true;
}
function beginChargeAttack(){
if(player.action||player.rangedTimer>0||player.chargeReleaseTimer>0||player.attackCooldown>0||player.respawnTimer>0)return false;
player.chargeActive=true;player.chargeTimer=0;player.chargeReady=false;player.chargeSoundPlayed=false;player.chargeInputTime=player.attackInputTime||time;player.attackBuffer=0;player.attackInputTime=0;return true;
}
function releaseChargedAttack(){
player.chargeActive=false;player.chargeReleaseTimer=CHARGE_RELEASE_DURATION;player.chargeHitDone=false;player.chargeReady=false;player.attackCooldown=.72;player.vx*=.5;playSfx('iceHeavy',.82,.96);tone(145,.22,'triangle',.035);
}
function performChargedHit(){
if(player.chargeHitDone)return;player.chargeHitDone=true;
const box={x:player.dir>0?player.x+18:player.x-118,y:player.y-4,w:138,h:86,life:.24,dir:player.dir,damage:3,heavy:true};slashes.push(box);shake=12;hitStop=Math.max(hitStop,reducedMotion?.025:.06);spawn(box.x+(player.dir>0?box.w*.72:box.w*.28),box.y+42,'#b9f7ff',24,260);
for(const e of enemies){
if(e.dead||e.hp<=0||e.hit>0||!overlap(box,e))continue;
e.hp-=box.damage;e.hit=.34;e.vx=player.dir*(isBossType(e.type)?135:330);if(!isBossType(e.type)){e.state='alert';e.memory=ENEMY_AI[e.type].memory;e.notice=ENEMY_AI[e.type].reaction;e.stateFlash=.65;}
spawn(e.x+e.w/2,e.y+e.h/2,'#d8fbff',28,290);playSfx('hit',.82,.78);if(e.hp<=0)onEnemyDefeated(e);
}
if(currentRoom===0&&overlap(box,trainingDummy)){trainingDummy.flash=.24;trainingDummy.hits+=2;tutorial.flags.dummyHit=true;spawn(trainingDummy.x+trainingDummy.w/2,trainingDummy.y+44,'#d8fbff',20,220);}
updateTutorialState();
}
function updateChargedRelease(dt){
if(player.chargeReleaseTimer<=0)return false;player.chargeReleaseTimer=Math.max(0,player.chargeReleaseTimer-dt);player.vx*=Math.pow(.03,dt);applyPlayerGravity(dt);
if(!player.chargeHitDone&&player.chargeReleaseTimer<=.34)performChargedHit();
movePlayerWithLanding(dt);checkRoomBoundary();return true;
}
function dash(){
if(!hasDash){player.dashBuffer=0;showToast('某种能力尚未苏醒');return false;}
if(player.action||player.chargeActive||player.chargeReleaseTimer>0||player.dashCooldown>0||player.respawnTimer>0)return false;player.dashBuffer=0;
player.dashTimer=.18;player.dashCooldown=.68;doorPhaseGrace=.34;player.vx=player.dir*760;player.vy=0;player.invuln=.22;playSfx('dash',.75,1.05);tone(90,.15,'sine',.035);return true;
}
function rangedAttack(){
const cost=25;if(player.action||player.rangedTimer>0||player.rangedCooldown>0||player.respawnTimer>0)return false;
if(player.energy<cost){player.rangedBuffer=0;showToast('共鸣能量不足 · 用节拍音刃获得 PERFECT');playSfx('back',.3,.82);return false;}
player.rangedBuffer=0;player.energy-=cost;player.rangedTimer=.78;player.rangedCooldown=.9;player.rangedFired=false;player.chargeActive=false;player.chargeTimer=0;player.vx*=.46;playSfx('iceBowCharge',.7,1);tone(420,.22,'sine',.028);return true;
}
function updateRangedAction(dt){
if(player.rangedTimer<=0)return false;player.rangedTimer=Math.max(0,player.rangedTimer-dt);player.vx*=Math.pow(.08,dt);applyPlayerGravity(dt);
if(!player.rangedFired&&player.rangedTimer<=.31){player.rangedFired=true;const x=player.dir>0?player.x+player.w+12:player.x-58;if(resonanceShots.length<MAX_RESONANCE_SHOTS)resonanceShots.push({x,y:player.y+24,w:48,h:14,vx:player.dir*760,life:1.65,t:0,damage:2,dir:player.dir,freezeChance:FREEZE_CHANCE});tutorial.flags.ranged=true;updateTutorialState();spawn(x+24,player.y+31,'#d8fbff',18,150);playSfx('iceArrow',.78,1.04);tone(780,.14,'triangle',.03);}
movePlayerWithLanding(dt);checkRoomBoundary();return true;
}
let audioCtx;
function tone(freq,duration,type='sine',gain=.03){
if(muted)return;
try{audioCtx ||= new (window.AudioContext||window.webkitAudioContext)();const o=audioCtx.createOscillator(),g=audioCtx.createGain();o.type=type;o.frequency.setValueAtTime(freq,audioCtx.currentTime);o.frequency.exponentialRampToValueAtTime(Math.max(40,freq*.65),audioCtx.currentTime+duration);g.gain.setValueAtTime(gain,audioCtx.currentTime);g.gain.exponentialRampToValueAtTime(.0001,audioCtx.currentTime+duration);o.connect(g).connect(audioCtx.destination);o.start();o.stop(audioCtx.currentTime+duration);}catch{}
}
function interactionRange(target,padding=34){
return overlap(player,{x:target.x-padding,y:target.y-padding,w:target.w+padding*2,h:target.h+padding*2});
}
function beginPlayerAction(action,target,duration){
if(player.action||player.rangedTimer>0||player.chargeActive||player.chargeReleaseTimer>0)return false;
Object.assign(player,{action,actionTimer:0,actionDuration:duration,actionTarget:target,actionApplied:false,vx:0,vy:0});
if(action==='bench'){
player.dir=1;player.x=target.x+target.w*.5-player.w*.5;player.y=target.y+target.h-player.h;player.onGround=true;
playSfx('checkpoint',.42,.86);showToast('正在同步 SEKAI 记忆…',1500);
}else playSfx('confirm',.42,1.08);
return true;
}
function finishPlayerAction(){
if(!player.action)return;
Object.assign(player,{action:'',actionTimer:0,actionDuration:0,actionTarget:null,actionApplied:false});
}
function applyPlayerAction(){
const target=player.actionTarget;if(!target||player.actionApplied)return;player.actionApplied=true;
if(player.action==='bench'){
checkpoint={x:target.x+target.w*.5-player.w*.5,y:target.y+target.h-player.h};player.hp=player.maxHp;saveGame();playSfx('checkpoint',.9,1.02);showToast('SEKAI 记忆已同步 · 生命完全恢复',2700);showNC('K','慢慢呼吸吧。我们会一直在连接里。');tone(420,.34,'sine',.025);spawn(target.x+target.w*.5,target.y+38,'#bba4ff',20,100);
}else if(target.kind==='terminal'){
const first=!storyFlags.has(`terminal-${target.id}`);storyFlags.add(`terminal-${target.id}`);if(first)score+=400;
showToast(`${target.title}${first?' · 记忆记录 +1':''}`,2600);showNC(target.speaker,target.text,5200);playSfx('collect',.45,1.22);tone(510,.22,'sine',.018);spawn(target.x+target.w*.5,target.y+24,'#7fe7ed',12,90);
}else if(target.kind==='shrine'){
if(!memoryArenaCleared){showToast('沉睡的共鸣水晶 · 回声来自水族馆深处',3100);showNC('Amia','它认识你,但现在听不到回应。深处一定有什么东西压住了声音。');return;}
if(fragmentsFound<4){showToast('共鸣不足 · 至少收集 4 枚歌词碎片');return;}
shrine.taken=true;hasDash=true;shake=18;flash=.5;spawn(shrine.x+shrine.w/2,shrine.y+shrine.h*.38,'#d1b8ff',40,320);playSfx('collect',1,.82);showToast('SEKAI 共鸣「静音冲刺」 · 按 K / Shift 穿越粉色封印',4400);showNC('Amia','找到了!沿着回声捷径回去,再像滑键一样穿过那扇门吧!');saveGame();tone(520,.55,'sine',.04);
}else if(target.kind==='airShrine'){
if(!rainArenaCleared){showToast('镜声祭坛仍被雨噪封锁');return;}if(fragmentsFound<10){showToast(`共鸣不足 · 歌词碎片 ${fragmentsFound}/10`);return;}
airShrine.taken=true;hasDoubleJump=true;player.airJumps=0;shake=18;flash=.42;spawn(target.x+target.w/2,target.y+target.h*.38,'#a9e9ff',46,330);playSfx('collect',1,.96);showToast('SEKAI 共鸣「返声跃迁」 · 在空中再次跳跃',4400);showNC('K','不是回到原点。把刚才的声音当作落脚点,再向上一步。');saveGame();tone(620,.6,'sine',.04);
}else if(target.kind==='lamp'){
if(target.lit){showToast('这盏雨音灯已经记录了你的声音',1400);return;}target.lit=true;const lit=memoryLamps.filter(lamp=>lamp.lit).length;player.energy=Math.min(player.maxEnergy,player.energy+35);score+=900;spawn(target.x+target.w/2,target.y+42,'#9ff6ff',28,180);playSfx('collect',.72,1.15);showToast(`雨音灯 ${lit}/${memoryLamps.length} · 共鸣能量恢复`,2200);if(lit===3){player.maxHp=Math.max(player.maxHp,6);player.hp=player.maxHp;showNC('Enanan','这些灯不是在照正确的路,是在照你自己选过的路。');showToast('记忆回响 · 最大生命 +1',2800);}if(lit===memoryLamps.length){player.maxEnergy=Math.max(player.maxEnergy,125);player.energy=player.maxEnergy;showNC('まふゆ','我记得每一次停下来的雨声。它们不是浪费的时间。');showToast('支线完成「雨后的绕路」 · 最大共鸣 125',3600);}saveGame();
}
}
function updatePlayerAction(dt){
if(!player.action)return false;
player.actionTimer+=dt;player.vx=0;player.vy=0;
if(player.action==='bench'){
const target=player.actionTarget;player.x=target.x+target.w*.5-player.w*.5;player.y=target.y+target.h-player.h;player.onGround=true;
if(player.actionTimer>=.68)applyPlayerAction();
}else if(player.actionTimer>=.38)applyPlayerAction();
if(player.actionTimer>=player.actionDuration)finishPlayerAction();
return true;
}
function useRelay(index){
const relay=relays[index],target=relays.find((candidate,candidateIndex)=>candidateIndex!==index&&candidate.pair===relay.pair);if(!target)return;relayCooldown=.8;player.x=target.x;player.y=target.y+target.h-player.h;player.vx=0;player.vy=0;currentRoom=roomIndexAt(player.x);currentArea=ROOMS[currentRoom].area;discoverRoom(currentRoom,true);cameraLookahead=0;camera.x=roomCameraTarget(player.x,currentRoom);shake=10;flash=.22;projectiles=[];resonanceShots=[];spawn(relay.x+18,relay.y+28,'#83e0d5',24,220);spawn(target.x+18,target.y+28,'#83e0d5',24,220);playSfx('transition',.72,1.15);showToast(`回声捷径 · ${ROOMS[currentRoom].name}`,1900);
}
function handleInteractions(){
if(player.action||player.rangedTimer>0||!pressed.has('ArrowDown'))return;
const bench=benchesByRoom[currentRoom].find(target=>interactionRange(target,24));if(bench){beginPlayerAction('bench',bench,3.4);return;}
const terminal=terminalsByRoom[currentRoom].find(target=>interactionRange(target,30));if(terminal){beginPlayerAction('interact',terminal,.92);return;}
if(memoryArenaCleared&&relayCooldown<=0){const relay=relaysByRoom[currentRoom].find(target=>interactionRange(target,40));if(relay){useRelay(relays.indexOf(relay));return;}}
const lamp=lampsByRoom[currentRoom].find(target=>interactionRange(target,30));if(lamp){beginPlayerAction('interact',lamp,.9);return;}
if(!shrine.taken&&interactionRange(shrine,34)){beginPlayerAction('interact',shrine,1.05);return;}
if(!airShrine.taken&&interactionRange(airShrine,34))beginPlayerAction('interact',airShrine,1.05);
}
function advanceRhythmClock(dt){time+=dt;judgeTimer=Math.max(0,judgeTimer-dt);const nextBeat=Math.floor(time/BEAT);if(nextBeat!==beatIndex){beatIndex=nextBeat;tone(nextBeat%4===0?220:160,.025,'sine',.009);}}
function update(dt){
if(mapOpen||journalOpen){pressed.clear();released.clear();return;}playTime+=dt;advanceRhythmClock(dt);relayCooldown=Math.max(0,relayCooldown-dt);doorPhaseGrace=Math.max(0,doorPhaseGrace-dt);if(roomTransition.active){updateRoomTransition(dt);return;}if(player.respawnTimer>0){player.respawnTimer-=dt;if(player.respawnTimer<=0)resetGame(false);return;}
const attackPressed=pressed.has('KeyJ')||pressed.has('KeyX');
if(attackPressed){if(!player.attackInputTime)player.attackInputTime=time;beginChargeAttack();}if(pressed.has('KeyK')||pressed.has('ShiftLeft'))player.dashBuffer=ACTION_BUFFER_TIME;if(pressed.has('KeyL')||pressed.has('KeyC'))player.rangedBuffer=ACTION_BUFFER_TIME;
player.invuln=Math.max(0,player.invuln-dt);player.hurtControlTimer=Math.max(0,player.hurtControlTimer-dt);player.attackCooldown=Math.max(0,player.attackCooldown-dt);player.attackTimer=Math.max(0,player.attackTimer-dt);player.attackBuffer=Math.max(0,player.attackBuffer-dt);player.dashCooldown=Math.max(0,player.dashCooldown-dt);player.dashBuffer=Math.max(0,player.dashBuffer-dt);player.rangedCooldown=Math.max(0,player.rangedCooldown-dt);player.rangedBuffer=Math.max(0,player.rangedBuffer-dt);player.dropTimer=Math.max(0,player.dropTimer-dt);player.landSquash=Math.max(0,player.landSquash-dt);player.turnFxCooldown=Math.max(0,player.turnFxCooldown-dt);player.coyote=player.onGround?COYOTE_TIME:Math.max(0,player.coyote-dt);player.jumpBuffer=Math.max(0,player.jumpBuffer-dt);
const actionLocked=updatePlayerAction(dt);
if(!actionLocked&&player.rangedBuffer>0)rangedAttack();
const rangedLocked=!actionLocked&&updateRangedAction(dt);
if(!actionLocked&&!rangedLocked&&player.chargeActive){
const attackHeld=held('KeyJ')||held('KeyX');
if(attackHeld){player.chargeTimer=Math.min(CHARGE_FULL_TIME,player.chargeTimer+dt);if(!player.chargeSoundPlayed&&player.chargeTimer>=.14){player.chargeSoundPlayed=true;playSfx('iceCharge',.58,.92);tone(240,.28,'sine',.022);}if(!player.chargeReady&&player.chargeTimer>=CHARGE_FULL_TIME){player.chargeReady=true;playSfx('freeze',.4,1.35);tone(680,.18,'sine',.026);showToast('冰之剑凝聚完成 · 松开攻击挥出重斩',1050);}if(player.chargeReady&&Math.floor(time*12)%3===0)spawn(player.x+player.w/2+player.dir*18,player.y+47,'#c9faff',1,32);}
else{const charged=player.chargeReady;if(charged)releaseChargedAttack();else{player.chargeActive=false;player.chargeTimer=0;player.attackInputTime=player.chargeInputTime;player.attackBuffer=ATTACK_BUFFER_TIME;}}
}
const chargedReleaseLocked=!actionLocked&&!rangedLocked&&updateChargedRelease(dt);
if(!actionLocked&&!rangedLocked&&!chargedReleaseLocked){
const jumpPressed=pressed.has('Space')||pressed.has('ArrowUp')||pressed.has('KeyW'),downHeld=held('ArrowDown')||held('KeyS');
if(jumpPressed&&downHeld&&player.onGround&&standingOnOneWay()){player.dropTimer=.19;player.onGround=false;player.coyote=0;player.jumpBuffer=0;player.y+=7;spawn(player.x+player.w/2,player.y+player.h,'#8fdde9',4,42);playSfx('footstep1',.12,.68,.02);}else if(jumpPressed)player.jumpBuffer=JUMP_BUFFER_TIME;
if(player.attackBuffer>0)attack();if(player.dashBuffer>0)dash();
const keyboardAxis=(held('KeyD')||held('ArrowRight')?1:0)-(held('KeyA')||held('ArrowLeft')?1:0),axis=keyboardAxis||touchAxis;
if(player.dashTimer>0){player.dashTimer=Math.max(0,player.dashTimer-dt);player.vx=player.dir*(player.dashTimer>0?760:420);spawn(player.x+player.w/2,player.y+player.h/2,'#9edfff',2,40);}else{
if(axis){const direction=Math.sign(axis),reversing=Math.sign(player.vx)&&Math.sign(player.vx)!==direction,accel=(reversing?TURN_ACCEL:(player.onGround?GROUND_ACCEL:AIR_ACCEL))*(player.hurtControlTimer>0?.42:1),moveSpeed=RUN_SPEED*(player.chargeActive?.68:1);if(reversing&&player.onGround&&Math.abs(player.vx)>80&&player.turnFxCooldown<=0){player.turnFxCooldown=.12;spawn(player.x+player.w/2,player.y+player.h,'#c3eff6',5,65);}player.vx=approach(player.vx,axis*moveSpeed,accel*dt);player.dir=direction;}else player.vx=approach(player.vx,0,(player.onGround?(player.attackTimer>0?900:GROUND_DECEL):AIR_DECEL)*dt);
let jumped=false;if(player.jumpBuffer>0&&player.coyote>0&&player.dropTimer<=0){player.vy=-JUMP_SPEED;player.onGround=false;player.coyote=0;player.jumpBuffer=0;jumped=true;tutorial.flags.jumped=true;updateTutorialState();playSfx('jump',.55,1.08);tone(260,.08,'sine',.018);spawn(player.x+20,player.y+player.h,'#b5eefe',7,80);}else if(player.jumpBuffer>0&&hasDoubleJump&&!player.onGround&&player.airJumps<1){player.airJumps=1;player.jumpBuffer=0;player.vy=-JUMP_SPEED*.88;jumped=true;playSfx('dash',.45,1.34);tone(520,.12,'sine',.024);spawn(player.x+player.w/2,player.y+player.h*.72,'#a9ecff',16,135);showToast('返声跃迁',650);}if(!jumped)applyPlayerGravity(dt);
}
movePlayerWithLanding(dt);checkRoomBoundary();player.anim+=Math.abs(player.vx)*dt*.035;if(player.onGround&&Math.abs(player.vx)>80){footstepClock-=dt;if(footstepClock<=0){playSfx(Math.floor(time*4)%2?'footstep1':'footstep2',.16,.9,.08);footstepClock=.27;}}else footstepClock=0;
}else footstepClock=0;
discoverRoom(currentRoom);
for(const f of fragmentsByRoom[currentRoom]){if(!f.taken&&Math.hypot(player.x+20-f.x,player.y+30-f.y)<62){f.taken=true;fragmentsFound++;score+=2500;spawn(f.x,f.y,'#f1c2ff',32,260);playSfx('collect',.78,1+fragmentsFound*.018);tone(620,.35,'sine',.035);showToast(`歌词碎片 ${fragmentsFound}/${fragments.length} ${f.text}`,2600);if(fragmentsFound===4)showNC('Enanan','这些词……都是まふゆ真正想说的吗?');if(fragmentsFound===8)showNC('Amia','快连起来了。你的声音一直都在这里。');if(fragmentsFound===fragments.length)showNC('まふゆ','……这是,我写下来的词。');}}
for(const s of spikesByRoom[currentRoom])if(player.x<s.x+s.w-8&&player.x+player.w>s.x+8&&player.y<s.y+18&&player.y+player.h>s.y)hurt(1,s.x+s.w/2);
if(player.y>850)hurt(9,player.x);
if(currentRoom===5&&player.x>ROOMS[5].start+180&&!memoryArenaCleared&&!memoryArenaActive){memoryArenaActive=true;shake=12;showToast('记忆污染封锁 · 击败当前房间内的敌人',3200);showNC('Enanan','这些怪物贴在记忆上……先把它们清掉!',4000);tone(105,.4,'sawtooth',.05);}
if(memoryArenaActive&&enemies.filter(e=>roomIndexAt(e.homeX)===5&&e.type!=='conductor').every(e=>e.dead)){
memoryArenaActive=false;memoryArenaCleared=true;score+=4000;shake=16;flash=.35;spawn(13900,390,'#88e6ef',45,300);playSfx('checkpoint',.75,1.08);showToast('记忆污染已清除 · 回声捷径与共鸣水晶恢复',4200);showNC('まふゆ','水族馆……我确实说过,喜欢那里。那枚水晶,也许正在等我回去。',4700);tone(540,.5,'sine',.035);
}
if(!shrine.taken&&interactionRange(shrine,34)){
if(!memoryArenaCleared){if(!storyFlags.has('shrine-sleep')){storyFlags.add('shrine-sleep');showToast('沉睡的共鸣水晶 · 回声来自水族馆深处',3100);showNC('Amia','它认识你,但现在听不到回应。深处一定有什么东西压住了声音。');}}
else if(fragmentsFound<4){if(!storyFlags.has('shrine-lock')){storyFlags.add('shrine-lock');showToast('共鸣不足 · 至少收集 4 枚歌词碎片');}}
}
handleInteractions();
if(currentRoom===11&&player.x>ROOMS[11].start+180&&!midBossDefeated&&!arenaActive){arenaActive=true;shake=16;setMusicGain(1.1);playSfx('bossCast',.9,.75);showToast('第一幕守门战 · 无声指挥者',3200);showNC('K','那个影子在扭曲你的节拍。不要让它替你决定声音。',4600);tone(82,.7,'sawtooth',.04);}
if(currentRoom===14&&player.x>ROOMS[14].start+820&&!rainArenaCleared&&!rainArenaActive){rainArenaActive=true;shake=13;showToast('雨噪封锁 · 击破镜像教室的合唱',3000);showNC('Amia','这些雨声在重复别人写好的回答。把你自己的节拍放进去!',4300);playSfx('bossCast',.55,1.16);}
if(rainArenaActive&&enemies.filter(e=>roomIndexAt(e.homeX)===14&&!isBossType(e.type)).every(e=>e.dead)){rainArenaActive=false;rainArenaCleared=true;score+=6500;shake=18;flash=.34;spawn(airShrine.x+airShrine.w/2,airShrine.y+45,'#a9eaff',50,300);playSfx('checkpoint',.9,1.12);showToast('雨噪已净化 · 镜声祭坛开始回应',3600);showNC('まふゆ','雨没有停。但我好像可以在声音之间,找到下一步。',4700);saveGame();}
if(currentRoom===19&&player.x>ROOMS[19].start+700&&!bossDefeated&&!finalArenaActive){finalArenaActive=true;shake=18;setMusicGain(1.12);playSfx('bossCast',1,.68);showToast('FINAL ACT · 未写下的真冬',3400);showNC('K','那不是你的正确答案。是还没有被你写下的空白。',4700);tone(74,.8,'sawtooth',.05);}
if(overlap(player,exit)&&!ending){
if(!bossDefeated){if(!storyFlags.has('exit-lock')){storyFlags.add('exit-lock');showToast('出口被无声的演出封锁');}}
else{ending=true;running=false;const trueEnding=fragmentsFound===fragments.length;setMusicGain(.72);playMusic('ending',1.6);playSfx('victory',.95,1,0);endingCg.src=trueEnding?'assets/cg-ending-true.png':'assets/cg-ending-return.png';endingScreen.querySelector('.ending-copy').innerHTML=trueEnding?'散落的歌词已经连成了第一段旋律。<br />「我想活下去」——声音确实抵达了 Nightcord。':`你带回了 ${fragmentsFound}/${fragments.length} 枚歌词碎片。<br />剩下的声音仍在等待;真冬可以再次回到这里。`;endingScreen.classList.remove('hidden');syncMobileControls();}
}
refreshPlayerSafeZone();updateTutorial(dt);updateEnemies(dt);updateProjectiles(dt);updateResonanceShots(dt);let alive=0;for(const p of particles){p.life-=dt;p.x+=p.vx*dt;p.y+=p.vy*dt;p.vy+=420*dt;p.vx*=.98;if(p.life>0)particles[alive++]=p;}particles.length=alive;alive=0;for(const slash of slashes){slash.life-=dt;if(slash.life>0)slashes[alive++]=slash;}slashes.length=alive;
const desiredLookahead=Math.max(-92,Math.min(92,player.dir*34+player.vx*.18));cameraLookahead+=(desiredLookahead-cameraLookahead)*(1-Math.pow(.025,dt));camera.x+=(roomCameraTarget(player.x,currentRoom,cameraLookahead)-camera.x)*(1-Math.pow(.003,dt));shake=Math.max(0,shake-40*dt);flash=Math.max(0,flash-dt);
pressed.clear();released.clear();
}
function approach(value,target,amount){return value<target?Math.min(target,value+amount):Math.max(target,value-amount);}
function groundAhead(e,dir,distance=28,drop=72){
if(!dir)return true;const foot=e.y+e.h,probeX=dir>0?e.x+e.w+distance:e.x-distance,room=ROOMS[roomIndexAt(e.homeX)];if(probeX<=room.start+28||probeX>=room.end-28)return false;
return platformsByRoom[roomIndexAt(e.homeX)].some(platform=>probeX>=platform.x+3&&probeX<=platform.x+platform.w-3&&platform.y>=foot-10&&platform.y<=foot+drop);
}
function safePounceLanding(e,dir){
const foot=e.y+e.h,landingX=e.x+e.w/2+dir*150,room=ROOMS[roomIndexAt(e.homeX)];
if(landingX<=room.start+52||landingX>=room.end-52)return false;
return platformsByRoom[roomIndexAt(e.homeX)].some(platform=>landingX>=platform.x+12&&landingX<=platform.x+platform.w-12&&platform.y>=foot-40&&platform.y<=foot+115);
}
function enemySightBlocked(e){
const eyeY=e.y+e.h*.42,targetY=player.y+player.h*.42,left=Math.min(e.x+e.w/2,player.x+player.w/2),right=Math.max(e.x+e.w/2,player.x+player.w/2),blocks=[door];
if(memoryArenaActive&&!memoryArenaCleared)blocks.push(...memoryGates);if(arenaActive&&!midBossDefeated)blocks.push(...arenaGates);if(rainArenaActive&&!rainArenaCleared)blocks.push(...rainGates);if(finalArenaActive&&!bossDefeated)blocks.push(...finalGates);if(!hasDoubleJump)blocks.push(mobilityGate);
return blocks.some(block=>block.x<right&&block.x+block.w>left&&block.y<Math.max(eyeY,targetY)+8&&block.y+block.h>Math.min(eyeY,targetY)-8);
}
function setEnemyState(e,state,duration=0){if(e.state===state)return;e.state=state;e.stateClock=duration;if(state==='alert')e.stateFlash=.72;}
function holdEnemyFacing(e,desired,cooldown=.2){if(desired&&desired!==e.dir&&e.turnLock<=0){e.dir=desired;e.turnLock=cooldown;}return e.dir;}
function updateEnemyAwareness(e,dt){
const config=ENEMY_AI[e.type];if(!config)return;if(playerInSafeZone()){e.notice=0;e.memory=0;e.lastSeenX=e.homeX;if(e.state==='alert')setEnemyState(e,'return');return;}const dx=player.x+player.w/2-(e.x+e.w/2),dy=player.y+player.h/2-(e.y+e.h/2),sees=Math.abs(dx)<config.detect&&Math.abs(dy)<config.vertical&&!enemySightBlocked(e);
if(sees){if(Math.abs(dx)>34)e.lastSeenX=player.x;e.notice=Math.min(config.reaction,e.notice+dt);e.memory=config.memory;if(e.notice>=config.reaction)setEnemyState(e,'alert');}
else{e.notice=Math.max(0,e.notice-dt*.75);if(e.state==='alert'){e.memory-=dt;if(e.memory<=0)setEnemyState(e,'return');}}
if(e.state==='idle'){e.stateClock-=dt;if(e.stateClock<=0){e.patrolDir=Math.random()<.5?-1:1;setEnemyState(e,'patrol',1.4+Math.random()*2.2);}}
else if(e.state==='patrol'){e.stateClock-=dt;if(e.stateClock<=0)setEnemyState(e,'idle',.5+Math.random()*1.1);}
else if(e.state==='return'&&Math.abs(e.x-e.homeX)<18){e.x=approach(e.x,e.homeX,35*dt);setEnemyState(e,'idle',.65+Math.random());}
}
function steerGroundEnemy(e,dt,speed,accel){
let dir=0;if(e.state==='patrol'){dir=e.patrolDir;if(Math.abs(e.x-e.homeX)>ENEMY_AI[e.type].roam){dir=Math.sign(e.homeX-e.x)||-dir;e.patrolDir=dir;}}
else if(e.state==='alert'){const delta=e.lastSeenX-e.x;dir=Math.abs(delta)>38?Math.sign(delta):0;}else if(e.state==='return'){const delta=e.homeX-e.x;dir=Math.abs(delta)>20?Math.sign(delta):0;}
if(dir&&dir!==e.dir){if(e.turnLock>0)dir=e.dir;else{e.dir=dir;e.turnLock=.24;}}
if(dir&&e.onGround&&(!groundAhead(e,dir)||enemyApproachesSafeZone(e,dir))){e.vx=0;e.turnLock=Math.max(e.turnLock,.32);if(e.state==='patrol'){e.patrolDir=-dir;setEnemyState(e,'idle',.35+Math.random()*.45);}else if(e.state==='alert')setEnemyState(e,'return');return false;}
if(dir)e.vx=approach(e.vx,dir*speed,accel*dt);else e.vx*=Math.pow(.015,dt);return Boolean(dir);
}
function moveGroundEnemySafely(e,dt){
const intended=Math.sign(e.vx),wasGrounded=e.onGround,before=e.x;if(wasGrounded&&intended&&!groundAhead(e,intended)){e.vx=0;if(e.state==='patrol')e.patrolDir=-intended;}
e.vy=Math.min(880,e.vy+1750*dt);moveEntity(e,dt);
if(wasGrounded&&intended&&Math.abs(e.x-before)<.35&&e.turnLock<=0){e.patrolDir=-intended;e.dir=-intended;e.turnLock=.3;}
}
function containEnemyInHomeRoom(e){
const room=ROOMS[roomIndexAt(e.homeX)],margin=34,left=room.start+margin,right=room.end-margin-e.w;
if(e.x<left){e.x=left;e.vx=Math.max(0,e.vx);e.patrolDir=1;holdEnemyFacing(e,1,.34);}
else if(e.x>right){e.x=right;e.vx=Math.min(0,e.vx);e.patrolDir=-1;holdEnemyFacing(e,-1,.34);}
}
function repelEnemyFromSafeZones(e){
for(const zone of safeZonesByRoom[roomIndexAt(e.homeX)]){if(!overlap(e,zone))continue;const moveLeft=e.homeX<zone.x+zone.w/2;e.x=moveLeft?zone.x-e.w-8:zone.x+zone.w+8;e.vx=0;e.patrolDir=moveLeft?-1:1;setEnemyState(e,'return');e.turnLock=.35;}
}
function updateEnemies(dt){
for(const e of enemies){
if(e.dead||roomIndexAt(e.homeX)!==currentRoom)continue;e.t+=dt;e.turnLock=Math.max(0,e.turnLock-dt);e.stateFlash=Math.max(0,e.stateFlash-dt);if(e.defeating>0){e.defeating-=dt;if(e.defeating<=0)e.dead=true;continue;}e.hit=Math.max(0,e.hit-dt);e.frozen=Math.max(0,e.frozen-dt);
if(e.frozen>0){e.vx*=Math.pow(.004,dt);if(['shade','crawler','metronome','mirrorHound','conductor','mirror'].includes(e.type)){e.vy=Math.min(880,e.vy+1750*dt);moveEntity(e,dt);}repelEnemyFromSafeZones(e);containEnemyInHomeRoom(e);continue;}
e.attackClock-=dt;
const dx=player.x-e.x,near=Math.abs(dx);updateEnemyAwareness(e,dt);
if(e.type!=='conductor'&&e.hit>0&&(e.type==='shade'||e.type==='crawler')){e.vy=Math.min(880,e.vy+1750*dt);moveEntity(e,dt);e.vx*=Math.pow(.22,dt);}
else if(e.type==='shade'){
const config=ENEMY_AI.shade,speed=e.state==='alert'?config.chase:config.patrol;steerGroundEnemy(e,dt,speed,e.state==='alert'?520:240);moveGroundEnemySafely(e,dt);if(e.onGround&&e.state!=='alert')e.vx*=Math.pow(.2,dt);
}else if(e.type==='wisp'){
const config=ENEMY_AI.wisp,bob=Math.sin(e.t*2.2)*34;
if(e.state==='alert'){holdEnemyFacing(e,Math.abs(dx)>32?Math.sign(dx):0);e.x=approach(e.x,e.lastSeenX,e.hit>0?0:config.chase*dt);e.y=approach(e.y,player.y-10,42*dt);if(e.attackClock<=0){const px=player.x-e.x,py=player.y-e.y,d=Math.hypot(px,py)||1;fireProjectile(e.x+21,e.y+21,px/d*185,py/d*185,'note');playSfx('enemyShot',.3,1.18);e.attackClock=2.15;}}
else{const targetX=e.state==='return'?e.homeX:e.homeX+Math.sin(e.t*.7)*config.roam,delta=targetX-e.x;holdEnemyFacing(e,Math.abs(delta)>18?Math.sign(delta):0,.28);e.x=approach(e.x,targetX,config.patrol*dt);e.y=approach(e.y,e.homeY+bob,55*dt);}
}else if(e.type==='crawler'){
const config=ENEMY_AI.crawler,targetDelta=e.lastSeenX-e.x,desired=e.state==='alert'&&Math.abs(targetDelta)>42?Math.sign(targetDelta):e.dir,dir=holdEnemyFacing(e,desired,.26);
if(e.state==='alert'&&e.onGround&&e.attackClock<=0&&near>70&&near<350&&safePounceLanding(e,dir)){e.vy=-430;e.vx=dir*265;e.onGround=false;e.attackClock=2.25;e.turnLock=.48;}
else steerGroundEnemy(e,dt,e.state==='alert'?config.chase:config.patrol,e.state==='alert'?720:310);
moveGroundEnemySafely(e,dt);if(e.onGround&&e.state!=='alert')e.vx*=Math.pow(.16,dt);
}else if(e.type==='sentinel'){
e.y=approach(e.y,e.homeY+Math.sin(e.t*1.6)*10,38*dt);if(e.state==='alert'){holdEnemyFacing(e,Math.abs(dx)>32?Math.sign(dx):0);if(e.attackClock<=0){for(let i=-1;i<=1;i++){const a=Math.atan2(player.y-e.y,dx)+i*.17;fireProjectile(e.x+21,e.y+25,Math.cos(a)*210,Math.sin(a)*210,'note');}playSfx('enemyShot',.42,.92);e.attackClock=2.65;}}
}else if(e.type==='maskling'){
const config=ENEMY_AI.maskling,targetX=e.state==='alert'?e.lastSeenX:e.homeX+Math.sin(e.t*.72)*config.roam,targetY=e.state==='alert'?player.y+8:e.homeY+Math.sin(e.t*2.1)*28;e.dir=holdEnemyFacing(e,Math.abs(targetX-e.x)>24?Math.sign(targetX-e.x):0,.2);
if(e.attackClock>1.58){e.x+=e.vx*dt;e.y+=e.vy*dt;e.vx*=Math.pow(.2,dt);e.vy*=Math.pow(.24,dt);}
else{e.x=approach(e.x,targetX,(e.state==='alert'?config.chase:config.patrol)*dt);e.y=approach(e.y,targetY,(e.state==='alert'?88:44)*dt);}
if(e.state==='alert'&&e.attackClock<=0&&near<420){const d=Math.hypot(dx,player.y-e.y)||1;e.vx=dx/d*330;e.vy=(player.y-e.y)/d*260;e.attackClock=2.05;playSfx('enemyShot',.32,1.34);}
}else if(e.type==='metronome'){
const config=ENEMY_AI.metronome;steerGroundEnemy(e,dt,e.state==='alert'?config.chase:config.patrol,e.state==='alert'?590:280);moveGroundEnemySafely(e,dt);if(e.state==='alert'&&e.attackClock<=0&&near<390){const a=Math.atan2(player.y+30-(e.y+34),dx);fireProjectile(e.x+e.w/2,e.y+34,Math.cos(a)*255,Math.sin(a)*255,'blade');playSfx('enemyShot',.38,.76);e.attackClock=2.4;}
}else if(e.type==='rainChoir'){
const config=ENEMY_AI.rainChoir,targetX=e.state==='alert'?player.x:e.homeX+Math.sin(e.t*.55)*config.roam;e.dir=holdEnemyFacing(e,Math.abs(targetX-e.x)>22?Math.sign(targetX-e.x):0,.24);e.x=approach(e.x,targetX,(e.state==='alert'?config.chase:config.patrol)*dt);e.y=approach(e.y,e.homeY+Math.sin(e.t*1.45)*22,42*dt);if(e.state==='alert'&&e.attackClock<=0){for(let i=-1;i<=1;i++)fireProjectile(e.x+e.w/2+i*18,e.y+e.h*.65,i*34,225+Math.abs(i)*22,'rain');playSfx('enemyShot',.4,1.08);e.attackClock=2.55;}
}else if(e.type==='mirrorHound'){
const config=ENEMY_AI.mirrorHound,targetDelta=e.lastSeenX-e.x,desired=e.state==='alert'&&Math.abs(targetDelta)>38?Math.sign(targetDelta):e.dir,dir=holdEnemyFacing(e,desired,.22);if(e.state==='alert'&&e.onGround&&e.attackClock<=0&&near>65&&near<390&&safePounceLanding(e,dir)){e.vy=-470;e.vx=dir*320;e.onGround=false;e.attackClock=1.85;e.turnLock=.44;playSfx('dash',.28,1.48);}else steerGroundEnemy(e,dt,e.state==='alert'?config.chase:config.patrol,e.state==='alert'?840:340);moveGroundEnemySafely(e,dt);
}else if(e.type==='conductor'){
if(!arenaActive)continue;
e.phase=e.hp<e.maxHp*.42?2:e.hp<e.maxHp*.72?1:0;holdEnemyFacing(e,Math.abs(dx)>48?Math.sign(dx):0,.16);e.vy=Math.min(900,e.vy+1700*dt);
if(near>170)e.vx+=e.dir*(e.phase===2?460:300)*dt;else e.vx*=Math.pow(.04,dt);e.vx=Math.max(-150-e.phase*30,Math.min(150+e.phase*30,e.vx));moveEntity(e,dt);
if(e.attackClock<=0){
const count=5+e.phase*2,speed=190+e.phase*28;
for(let i=0;i<count;i++){const a=-Math.PI*.92+i*(Math.PI*1.84/(count-1));fireProjectile(e.x+e.w/2,e.y+38,Math.cos(a)*speed,Math.sin(a)*speed,'chord');}
if(e.phase>0){const aim=Math.atan2(player.y-e.y,dx);fireProjectile(e.x+e.w/2,e.y+45,Math.cos(aim)*310,Math.sin(aim)*310,'note');}
e.attackClock=2.25-e.phase*.38;shake=7;playSfx('bossCast',.72,.82+e.phase*.08);tone(95,.24,'sawtooth',.025);
}
}else if(e.type==='mirror'){
if(!finalArenaActive)continue;e.phase=e.hp<e.maxHp*.34?2:e.hp<e.maxHp*.68?1:0;const facing=Math.abs(dx)>44?Math.sign(dx):e.dir;holdEnemyFacing(e,facing,.13);e.vy=Math.min(900,e.vy+1700*dt);if(near>210)e.vx=approach(e.vx,e.dir*(105+e.phase*26),410*dt);else e.vx*=Math.pow(.035,dt);moveEntity(e,dt);
if(e.attackClock<=0){const pattern=(Math.floor(e.t*2.7)+e.phase)%3;if(pattern===0){const count=7+e.phase*2;for(let i=0;i<count;i++){const a=-Math.PI*.92+i*(Math.PI*1.84/(count-1));fireProjectile(e.x+e.w/2,e.y+42,Math.cos(a)*(205+e.phase*24),Math.sin(a)*(205+e.phase*24),'script');}}else if(pattern===1){const room=ROOMS[19];for(let i=0;i<6+e.phase;i++){const x=room.start+190+((i*337+Math.floor(e.t*100))%(ROOM_W-380));fireProjectile(x,70+(i%2)*34,(i%2?28:-28),235+e.phase*24,'rain');}}else{e.dir=Math.sign(dx)||e.dir;e.vx=e.dir*(430+e.phase*70);spawn(e.x+e.w/2,e.y+64,'#f4a8e4',18,190);}e.attackClock=2.15-e.phase*.32;shake=8+e.phase*2;playSfx('bossCast',.78,.92+e.phase*.06);tone(118,.28,'sawtooth',.03);}
}
repelEnemyFromSafeZones(e);containEnemyInHomeRoom(e);
if(!isBossType(e.type)&&e.y>H+120){onEnemyDefeated(e);continue;}
if(overlap(player,e)&&!playerInSafeZone())hurt(isBossType(e.type)?2:1,e.x+e.w/2);
}
}
function updateProjectiles(dt){
for(const p of projectiles){
p.life-=dt;p.t+=dt;p.x+=p.vx*dt;p.y+=p.vy*dt;
if(p.kind==='chord')p.vy+=80*dt;if(p.kind==='rain')p.vy+=34*dt;
if(safeZonesByRoom[currentRoom].some(zone=>overlap(p,zone)))p.life=0;
else if(overlap(player,p)){hurt(p.damage,p.x);p.life=0;spawn(p.x,p.y,'#eea8dc',8,120);}
if(platformsByRoom[currentRoom].some(platform=>overlap(p,platform)))p.life=0;
}
projectiles=projectiles.filter(p=>p.life>0&&p.x>camera.x-200&&p.x<camera.x+W+500&&p.y>-120&&p.y<H+180);
}
function updateResonanceShots(dt){
for(const shot of resonanceShots){
shot.life-=dt;shot.t+=dt;shot.x+=shot.vx*dt;
if(currentRoom===0&&overlap(shot,trainingDummy)){trainingDummy.flash=.24;trainingDummy.hits++;tutorial.flags.dummyHit=true;shot.life=0;spawn(trainingDummy.x+trainingDummy.w/2,trainingDummy.y+44,'#9ff8ff',12,180);continue;}
const enemy=enemies.find(e=>!e.dead&&e.hp>0&&roomIndexAt(e.homeX)===currentRoom&&overlap(shot,e));
if(enemy){const boss=isBossType(enemy.type);enemy.hp-=shot.damage;enemy.hit=.28;enemy.vx=shot.dir*(boss?90:210);if(!boss){enemy.state='alert';enemy.memory=ENEMY_AI[enemy.type].memory;enemy.notice=ENEMY_AI[enemy.type].reaction;enemy.stateFlash=.65;}const froze=enemy.hp>0&&Math.random()<(shot.freezeChance||0)*(boss?.24:1);if(froze){enemy.frozen=boss?.62:2.15;enemy.vx=0;spawn(enemy.x+enemy.w/2,enemy.y+enemy.h/2,'#d9fbff',26,165);playSfx('freeze',.72,boss?.78:1.05);showToast(boss?'寒霜迟滞':'冻结 · 敌人暂时无法行动',850);}shot.life=0;shake=8;hitStop=Math.max(hitStop,reducedMotion?.02:.035);spawn(shot.x+shot.w/2,shot.y+shot.h/2,'#9ff8ff',18,245);playSfx('hit',.72,1.18);tone(260,.1,'square',.022);if(enemy.hp<=0)onEnemyDefeated(enemy);continue;}
if(overlapsActiveSolid(shot))shot.life=0;
}
const room=ROOMS[currentRoom];resonanceShots=resonanceShots.filter(shot=>shot.life>0&&shot.x>room.start-80&&shot.x<room.end+80);
}
function render(){
ctx.clearRect(0,0,W,H);const sx=shake?(Math.random()-.5)*shake:0,sy=shake?(Math.random()-.5)*shake:0;ctx.save();ctx.translate(sx,sy);
drawBackground();ctx.save();ctx.translate(-camera.x,0);const room=ROOMS[currentRoom]||ROOMS[0];ctx.beginPath();ctx.rect(room.start,-120,room.end-room.start,H+240);ctx.clip();drawWorld();drawAmbientWorld();drawProjectiles();drawResonanceShots();drawEnemies();drawPlayer();drawParticles();ctx.restore();drawAtmosphereForeground();drawHud();ctx.restore();
if(flash>0){const glow=ctx.createRadialGradient(W/2,H/2,40,W/2,H/2,Math.max(W,H)*.7);glow.addColorStop(0,`rgba(210,240,255,${Math.min(.13,flash*.16)})`);glow.addColorStop(1,'rgba(210,240,255,0)');ctx.fillStyle=glow;ctx.fillRect(0,0,W,H);}
drawRoomTransition();
updatePortrait();
}
function drawBackground(){
const a=areas[Math.max(0,currentArea)]||areas[0];ctx.fillStyle=backgroundGradients[currentArea]||backgroundGradients[0];ctx.fillRect(0,0,W,H);
if(bg.complete){const scale=H/bg.height,w=bg.width*scale,offset=-(camera.x*.1)%(w*.72);ctx.globalAlpha=currentArea===0 ? .16 : .36;ctx.drawImage(bg,offset,0,w,H);ctx.drawImage(bg,offset+w*.72,0,w,H);ctx.globalAlpha=1;}
if(currentArea===0){
ctx.strokeStyle='rgba(255,255,255,.23)';ctx.lineWidth=1;for(let x=-100-(camera.x*.15%220);x<W+200;x+=220){ctx.strokeRect(x,80,130,460);ctx.beginPath();ctx.moveTo(x+65,80);ctx.lineTo(x+65,540);ctx.stroke();}
}else if(currentArea===1){
ctx.fillStyle='rgba(80,220,244,.06)';ctx.fillRect(0,0,W,H);for(let i=0;i<18;i++){const x=(i*131-camera.x*.18)%(W+120),y=70+(i*73)%420;ctx.strokeStyle=`rgba(127,229,244,${.08+(i%4)*.025})`;ctx.beginPath();ctx.arc(x,y,18+(i%5)*6,0,Math.PI*2);ctx.stroke();ctx.beginPath();ctx.moveTo(x-20,y+35);ctx.quadraticCurveTo(x,y+50+Math.sin(time+i)*8,x+20,y+35);ctx.stroke();}
ctx.fillStyle='rgba(118,220,236,.18)';for(let i=0;i<12;i++){const x=(i*173-time*12-camera.x*.12)%(W+140),y=110+(i*97)%350;ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x-16,y-7);ctx.lineTo(x-16,y+7);ctx.closePath();ctx.fill();}
}else if(currentArea===2){
ctx.strokeStyle='rgba(191,137,255,.16)';for(let y=80;y<560;y+=62){ctx.beginPath();ctx.moveTo(0,y);for(let x=0;x<W;x+=12)ctx.lineTo(x,y+Math.sin(x*.025+time*2+y)*8);ctx.stroke();}
ctx.fillStyle='rgba(196,159,255,.12)';for(let i=0;i<16;i++){const x=(i*197-camera.x*.25)%(W+120),y=70+(i*89)%450;ctx.save();ctx.translate(x,y);ctx.rotate(time*.08+i);ctx.fillRect(-7,-7,14,14);ctx.restore();}
}else if(currentArea===3){
ctx.fillStyle='rgba(244,146,205,.07)';for(let x=-100-(camera.x*.2%260);x<W+200;x+=260){ctx.fillRect(x,110,150,390);ctx.strokeStyle='rgba(255,184,225,.18)';ctx.strokeRect(x,110,150,390);ctx.beginPath();ctx.moveTo(x+75,110);ctx.lineTo(x+75,500);ctx.stroke();}
ctx.strokeStyle='rgba(255,184,225,.14)';for(let y=145;y<520;y+=70){ctx.beginPath();ctx.moveTo(0,y);ctx.bezierCurveTo(W*.3,y-28,W*.7,y+28,W,y);ctx.stroke();}
}else if(currentArea===4){
ctx.fillStyle='rgba(105,164,206,.08)';ctx.fillRect(0,0,W,H);ctx.strokeStyle='rgba(157,207,235,.18)';for(let x=-120-(camera.x*.16%240);x<W+200;x+=240){ctx.strokeRect(x,92,180,430);for(let pane=1;pane<3;pane++){ctx.beginPath();ctx.moveTo(x+pane*60,92);ctx.lineTo(x+pane*60,522);ctx.stroke();}}ctx.fillStyle='rgba(179,220,239,.11)';for(let i=0;i<10;i++){const x=(i*181-time*8-camera.x*.1)%(W+160),y=135+(i*67)%320;ctx.fillRect(x,y,70,2);}
}else{
ctx.strokeStyle='rgba(232,181,250,.16)';for(let y=110;y<520;y+=54){ctx.beginPath();ctx.moveTo(0,y);for(let x=0;x<W;x+=14)ctx.lineTo(x,y+Math.sin(x*.018+time*1.4+y*.01)*12);ctx.stroke();}ctx.fillStyle='rgba(218,165,243,.08)';for(let x=-120-(camera.x*.12%300);x<W+220;x+=300)ctx.fillRect(x,140,210,330);
}
for(let i=0;i<22;i++){const x=(i*173-camera.x*.22)%(W+100),y=70+(i*83)%420;ctx.fillStyle=`rgba(215,240,255,${.08+(i%3)*.03})`;ctx.fillRect(x,y,1,1+(i%4));}
ctx.fillStyle=a.tone;ctx.globalAlpha=.035;ctx.fillRect(0,0,W,H);ctx.globalAlpha=1;
}
function drawWorld(){
const room=ROOMS[currentRoom];for(const p of platformsByRoom[currentRoom]){const zone=currentArea,body=['#252938','#0d2431','#1a1129','#251020','#142233','#21132f'][zone],edge=['#e0e4ea','#58cadd','#a877e8','#ed8dc5','#78b9e8','#e0a5f4'][zone],detail=['rgba(240,245,250,.1)','rgba(112,220,225,.13)','rgba(191,137,255,.13)','rgba(239,142,201,.12)','rgba(130,196,235,.12)','rgba(232,171,247,.12)'][zone];ctx.fillStyle=body;ctx.fillRect(p.x,p.y,p.w,p.h);ctx.fillStyle=edge;ctx.globalAlpha=.66;ctx.fillRect(p.x,p.y,p.w,5);ctx.globalAlpha=1;ctx.fillStyle=detail;for(let x=p.x+14;x<p.x+p.w;x+=48)ctx.fillRect(x,p.y+10,1,Math.min(36,p.h));}
for(const zone of safeZonesByRoom[currentRoom]){ctx.fillStyle=safeZoneGlow;ctx.fillRect(zone.x,zone.y,zone.w,zone.h);ctx.strokeStyle='rgba(159,239,245,.24)';ctx.setLineDash([6,12]);ctx.strokeRect(zone.x+8,zone.y+8,zone.w-16,zone.h-16);ctx.setLineDash([]);if(player.x>zone.x-120&&player.x<zone.x+zone.w+120){ctx.fillStyle='rgba(184,246,248,.62)';ctx.font='9px sans-serif';ctx.fillText(`SAFE · ${zone.label}`,zone.x+18,zone.y+25);}}
// PJSK-style note lanes and digital fragments integrated into the world.
if(currentArea===0){ctx.strokeStyle='rgba(198,226,236,.18)';ctx.lineWidth=2;for(let x=room.start+100;x<room.end-120;x+=330){ctx.beginPath();ctx.moveTo(x,610);ctx.lineTo(x+90,210);ctx.stroke();ctx.fillStyle='rgba(235,248,250,.38)';ctx.fillRect(x+82,218,16,6);}}
else if(currentArea===1)for(let x=room.start+90;x<room.end-180;x+=360){ctx.fillStyle='rgba(83,211,232,.09)';ctx.fillRect(x,170,240,340);ctx.strokeStyle='rgba(123,225,240,.2)';ctx.strokeRect(x,170,240,340);ctx.fillStyle='rgba(118,220,236,.12)';ctx.beginPath();ctx.arc(x+120,300,58,0,Math.PI*2);ctx.fill();}
else if(currentArea===2)for(let x=room.start+100;x<room.end-170;x+=300){ctx.fillStyle='rgba(167,112,230,.12)';ctx.fillRect(x,120,170,16);ctx.fillStyle='rgba(110,221,237,.18)';ctx.fillRect(x+30,148,110,7);ctx.fillStyle='rgba(255,255,255,.08)';ctx.fillRect(x+12,170,145,70);ctx.fillStyle='rgba(190,145,255,.3)';ctx.font='10px sans-serif';ctx.fillText('25:00 SIGNAL LOST',x+21,198);}
else if(currentArea===3)for(let x=room.start+100;x<room.end-200;x+=340){ctx.strokeStyle='rgba(242,143,202,.24)';ctx.strokeRect(x,145,210,330);ctx.fillStyle='rgba(244,153,207,.08)';ctx.fillRect(x+22,167,166,286);ctx.fillStyle='rgba(255,224,240,.25)';ctx.font='11px serif';ctx.fillText('MASK / VOICE',x+56,208);}
else if(currentArea===4)for(let x=room.start+90;x<room.end-180;x+=360){ctx.fillStyle='rgba(111,167,207,.11)';ctx.fillRect(x,135,260,370);ctx.strokeStyle='rgba(132,195,233,.25)';ctx.strokeRect(x,135,260,370);for(let pane=1;pane<4;pane++){ctx.beginPath();ctx.moveTo(x+pane*65,135);ctx.lineTo(x+pane*65,505);ctx.stroke();}ctx.fillStyle='rgba(190,225,242,.22)';ctx.font='10px sans-serif';ctx.fillText('AFTER SCHOOL · RAIN',x+55,175);}
else for(let x=room.start+100;x<room.end-200;x+=330){ctx.strokeStyle='rgba(232,171,247,.24)';for(let line=0;line<5;line++){ctx.beginPath();ctx.moveTo(x,190+line*18);ctx.lineTo(x+230,190+line*18);ctx.stroke();}ctx.fillStyle='rgba(226,169,245,.12)';ctx.fillRect(x+40,310,150,170);ctx.fillStyle='rgba(238,203,250,.25)';ctx.font='10px serif';ctx.fillText('UNWRITTEN',x+76,344);}
for(const s of spikesByRoom[currentRoom]){ctx.fillStyle='#46516b';for(let x=s.x;x<s.x+s.w;x+=20){ctx.beginPath();ctx.moveTo(x,610);ctx.lineTo(x+10,580);ctx.lineTo(x+20,610);ctx.fill();}}
if(currentRoom===roomIndexAt(door.x)){ctx.save();ctx.globalAlpha=doorPhaseGrace>0?.24:1;ctx.fillStyle=hasDash?'rgba(121,35,100,.2)':'rgba(18,21,44,.94)';ctx.fillRect(door.x,door.y,door.w,door.h);ctx.strokeStyle=hasDash?'#ed83c4':'#8edff066';ctx.lineWidth=2;ctx.shadowColor=ctx.strokeStyle;ctx.shadowBlur=hasDash?16:0;for(let y=door.y+12;y<door.y+door.h;y+=28){ctx.beginPath();ctx.moveTo(door.x+7,y);ctx.lineTo(door.x+door.w-7,y+12);ctx.stroke();}ctx.restore();}
if(currentRoom===5&&memoryArenaActive&&!memoryArenaCleared)for(const gate of memoryGates){ctx.fillStyle='rgba(91,214,232,.15)';ctx.fillRect(gate.x,gate.y,gate.w,gate.h);ctx.strokeStyle='#63d6e8';for(let y=gate.y;y<gate.y+gate.h;y+=24){ctx.beginPath();ctx.moveTo(gate.x,y);ctx.lineTo(gate.x+gate.w,y+18);ctx.stroke();}}
if(currentRoom===11&&arenaActive&&!midBossDefeated)for(const gate of arenaGates)drawScoreGate(gate,false);
if(currentRoom===14&&rainArenaActive&&!rainArenaCleared)for(const gate of rainGates)drawScoreGate(gate,false);
if(currentRoom===19&&finalArenaActive&&!bossDefeated)for(const gate of finalGates)drawScoreGate(gate,false);
if(currentRoom===roomIndexAt(mobilityGate.x)&&!hasDoubleJump)drawScoreGate(mobilityGate,false);
terminalsByRoom[currentRoom].forEach(drawTerminal);benchesByRoom[currentRoom].forEach(drawBench);relaysByRoom[currentRoom].forEach(drawRelay);lampsByRoom[currentRoom].forEach(drawLamp);if(currentRoom===4)drawShrine();if(currentRoom===14)drawAirShrine();if(currentRoom===0)drawTrainingDummy();drawFragments();
if(currentRoom===19){ctx.fillStyle=bossDefeated?'rgba(139,225,255,.18)':'rgba(120,90,130,.13)';ctx.fillRect(exit.x,exit.y,exit.w,exit.h);ctx.strokeStyle=bossDefeated?'#8de9ff':'#805f78';ctx.strokeRect(exit.x+8,exit.y+8,exit.w-16,exit.h-8);ctx.fillStyle=bossDefeated?'#ccefff':'#9b7b91';ctx.font='12px sans-serif';ctx.fillText(bossDefeated?'EXIT':'LOCK',exit.x+22,exit.y+65);}
ctx.font='13px sans-serif';for(const bench of benchesByRoom[currentRoom])if(Math.abs(player.x-(bench.x+bench.w/2))<175){ctx.fillStyle='#d2c8ef';ctx.fillText('↓ 坐下 · 同步记忆',bench.x+18,bench.y-12);}for(const terminal of terminalsByRoom[currentRoom])if(Math.abs(player.x-terminal.x)<155){ctx.fillStyle='#8feaf0';ctx.fillText('↓ 读取记忆终端',terminal.x-6,terminal.y-14);}
ctx.font='12px sans-serif';if(Math.abs(player.x-shrine.x)<180&&!shrine.taken){ctx.fillStyle=memoryArenaCleared?'#d8c4ff':'#786f91';ctx.fillText(memoryArenaCleared?'↓ 唤醒共鸣水晶':'沉睡的共鸣水晶',shrine.x-18,shrine.y-18);}if(Math.abs(player.x-airShrine.x)<180&&!airShrine.taken){ctx.fillStyle=rainArenaCleared?'#bcecff':'#756c8c';ctx.fillText(rainArenaCleared?'↓ 倾听镜中的返声':'被雨噪覆盖的祭坛',airShrine.x-24,airShrine.y-18);}if(Math.abs(player.x-door.x)<190){ctx.fillStyle=hasDash?'#f0a8d3':'#8a7690';ctx.fillText(hasDash?'K 冲刺穿越封印':'需要 SEKAI 共鸣',door.x-45,door.y-20);}if(Math.abs(player.x-mobilityGate.x)<190&&!hasDoubleJump){ctx.fillStyle='#9a87b8';ctx.fillText('需要返声跃迁',mobilityGate.x-36,mobilityGate.y-18);}if(memoryArenaCleared)for(const relay of relays)if(Math.abs(player.x-relay.x)<150){ctx.fillStyle='#9aece4';ctx.fillText('↓ 使用回声捷径',relay.x-45,relay.y-16);}for(const lamp of lampsByRoom[currentRoom])if(Math.abs(player.x-lamp.x)<150){ctx.fillStyle=lamp.lit?'#8ba7b6':'#a7ecf5';ctx.fillText(lamp.lit?'雨音已记录':'↓ 点亮雨音灯',lamp.x-18,lamp.y-14);}
}
function drawFragments(){for(const f of fragmentsByRoom[currentRoom]){if(f.taken)continue;const pulse=.7+Math.sin(time*4+f.x)*.2;ctx.save();ctx.translate(f.x,f.y);ctx.rotate(Math.sin(time*1.8+f.x)*.2);ctx.shadowColor='#dbb8ff';ctx.shadowBlur=24;ctx.globalAlpha=pulse;ctx.fillStyle='#efe2ff';ctx.beginPath();ctx.moveTo(0,-15);ctx.lineTo(13,0);ctx.lineTo(0,15);ctx.lineTo(-13,0);ctx.closePath();ctx.fill();ctx.restore();}}
function drawInteractableFrame(row,frame,x,bottom,targetHeight,alpha=1){
if(!interactableSprite.complete||!interactableSprite.naturalWidth)return false;const source=INTERACTABLE_FRAMES[row][frame],scale=targetHeight/source.sh,w=source.sw*scale;ctx.save();ctx.globalAlpha=alpha;ctx.drawImage(interactableSprite,source.sx,source.sy,source.sw,source.sh,x-w/2,bottom-targetHeight,w,targetHeight);ctx.restore();return true;
}
function smoothStep(value){return value*value*(3-2*value);}
function drawInteractablePhase(row,phase,x,bottom,targetHeight,alpha=1){const frame=Math.floor(((phase%16)+16)%16);return drawInteractableFrame(row,frame,x,bottom,targetHeight,alpha);}
function drawExpansionPropPhase(row,phase,x,bottom,targetHeight,alpha=1){
if(!expansionPropSprite.complete||!expansionPropSprite.naturalWidth)return false;const frame=Math.floor(((phase%16)+16)%16),source=EXPANSION_PROP_FRAMES[row][frame],scale=targetHeight/source.sh,w=source.sw*scale;ctx.save();ctx.globalAlpha=alpha;ctx.drawImage(expansionPropSprite,source.sx,source.sy,source.sw,source.sh,x-w/2,bottom-targetHeight,w,targetHeight);ctx.restore();return true;
}
function drawBench(bench){if(drawInteractablePhase(0,time*8+bench.x*.01,bench.x+bench.w/2,bench.y+bench.h,100))return;ctx.fillStyle='#302d48';ctx.fillRect(bench.x+20,bench.y+45,bench.w-40,18);ctx.fillRect(bench.x+32,bench.y+60,8,38);ctx.fillRect(bench.x+bench.w-40,bench.y+60,8,38);}
function drawTerminal(terminal){if(terminal.x>=28800&&drawExpansionPropPhase(1,time*12+terminal.x*.013,terminal.x+terminal.w/2,terminal.y+terminal.h,132))return;if(drawInteractablePhase(3,time*12+terminal.x*.013,terminal.x+terminal.w/2,terminal.y+terminal.h,110))return;ctx.fillStyle='#21172f';ctx.fillRect(terminal.x,terminal.y,terminal.w,terminal.h);ctx.fillStyle='#7ee6db';ctx.fillRect(terminal.x+16,terminal.y+15,terminal.w-32,30);}
function drawRelay(relay){const active=memoryArenaCleared;if(drawInteractablePhase(2,active?time*14+relay.x*.01:0,relay.x+relay.w/2,relay.y+relay.h,92,active?1:.38))return;const pulse=.55+Math.sin(time*4+relay.x)*.2;ctx.save();ctx.translate(relay.x+relay.w/2,relay.y+relay.h/2);ctx.strokeStyle=active?`rgba(126,230,219,${pulse})`:'rgba(91,103,126,.42)';ctx.beginPath();ctx.arc(0,0,15,0,Math.PI*2);ctx.stroke();ctx.restore();}
function drawShrine(){if(shrine.taken)return;const active=memoryArenaCleared;if(drawInteractablePhase(1,active?time*10:0,shrine.x+shrine.w/2,shrine.y+shrine.h,120,active?1:.48))return;ctx.fillStyle=active?'#bba9ff':'#555a72';ctx.beginPath();ctx.moveTo(shrine.x+shrine.w/2,shrine.y);ctx.lineTo(shrine.x+shrine.w,shrine.y+shrine.h*.58);ctx.lineTo(shrine.x,shrine.y+shrine.h*.58);ctx.closePath();ctx.fill();}
function drawLamp(lamp){drawExpansionPropPhase(0,lamp.lit?time*14+lamp.x*.01:0,lamp.x+lamp.w/2,lamp.y+lamp.h,145,lamp.lit?1:.54);}
function drawAirShrine(){if(airShrine.taken)return;drawExpansionPropPhase(2,rainArenaCleared?time*12:0,airShrine.x+airShrine.w/2,airShrine.y+airShrine.h,150,rainArenaCleared?1:.42);}
function drawScoreGate(gate,open=false){const center=gate.x+gate.w/2;drawExpansionPropPhase(3,open?time*12:0,center,gate.y+gate.h,Math.min(260,gate.h+34),open?.5:.88);}
function drawTrainingDummy(){const center=trainingDummy.x+trainingDummy.w/2,pulse=.5+Math.sin(time*4)*.18;ctx.save();ctx.globalAlpha=trainingDummy.flash>0?.74:1;ctx.strokeStyle=`rgba(142,230,255,${pulse})`;ctx.lineWidth=2;ctx.setLineDash([5,8]);ctx.beginPath();ctx.arc(center,trainingDummy.y+57,54+Math.sin(time*2)*3,0,Math.PI*2);ctx.stroke();ctx.setLineDash([]);ctx.restore();drawInteractablePhase(1,time*9,center,trainingDummy.y+trainingDummy.h,110,trainingDummy.flash>0?.8:.9);ctx.fillStyle='rgba(180,241,249,.65)';ctx.font='8px sans-serif';ctx.textAlign='center';ctx.fillText(`PRACTICE SIGNAL · ${String(trainingDummy.hits).padStart(2,'0')}`,center,trainingDummy.y-10);ctx.textAlign='left';}
function drawPlayer(){
const hurtAlpha=player.invuln>0&&Math.floor(player.invuln*12)%2===0?.48:1;
let state='idle',phase=0,looped=true;
if(player.action==='bench'){
const settle=.68,standUp=.64,remaining=player.actionDuration-player.actionTimer;
if(player.actionTimer<settle){state='sit';phase=Math.min(3,player.actionTimer/settle*3);looped=false;}
else if(remaining<standUp){state='sit';phase=Math.max(0,Math.min(3,remaining/standUp*3));looped=false;}
else{state='rest';phase=(player.actionTimer-settle)*6;}
}
else if(player.action){state='interact';phase=Math.min(3,player.actionTimer/player.actionDuration*3);looped=false;}
else if(player.rangedTimer>0){state='iceBow';phase=Math.max(0,Math.min(15,(1-player.rangedTimer/.78)*15));looped=false;}
else if(player.chargeReleaseTimer>0){state='iceRelease';phase=Math.max(0,Math.min(15,(1-player.chargeReleaseTimer/CHARGE_RELEASE_DURATION)*15));looped=false;}
else if(player.chargeActive){state='iceCharge';phase=time*13;looped=true;}
else if(player.attackTimer>0){state='attack';phase=Math.min(15,(1-player.attackTimer/.34)*15);looped=false;}
else if(!player.onGround){state='jump';phase=Math.max(0,Math.min(3,(player.vy+620)/1450*3));looped=false;}
else if(player.dashTimer>0){state='run';phase=3;looped=false;}
else if(Math.abs(player.vx)>35){state='run';phase=player.anim*1.35;}
else phase=time*3.2;
const set=spriteSets[state];
if(!set.image.complete||!set.image.naturalWidth){drawPlayerFallback();return;}
const count=set.frames.length,wrapped=looped?((phase%count)+count)%count:Math.max(0,Math.min(count-1,phase)),current=Math.floor(wrapped),next=looped?(current+1)%count:Math.min(count-1,current+1),highFrame=count>=16,mix=highFrame||reducedMotion?0:smoothStep(wrapped-current),squash=player.landSquash>0?player.landSquash/.18:0,actionLean=state==='attack'?Math.sin(Math.min(1,phase/15)*Math.PI)*5*player.dir:state==='iceRelease'?Math.sin(Math.min(1,phase/15)*Math.PI)*4*player.dir:0;
const drawFrame=(index,offset=0,alpha=1)=>{const f=set.frames[index],targetHeight=highFrame?136:112,scale=targetHeight/f.sh,dw=f.sw*scale,anchorX=(f.ax??f.sw*.65)*scale;ctx.save();ctx.globalAlpha=alpha;ctx.translate(player.x+player.w/2+offset+actionLean,player.y+player.h+3);ctx.scale(player.dir*(1+squash*.08),1-squash*.1);ctx.drawImage(set.image,f.sx,f.sy,f.sw,f.sh,-anchorX,-targetHeight,dw,targetHeight);ctx.restore();};
const drawBlend=(offset=0,alpha=1)=>{drawFrame(current,offset,alpha*(1-mix));if(mix>.01)drawFrame(next,offset,alpha*mix);};
if(player.dashTimer>0){drawBlend(-player.dir*44,.08);drawBlend(-player.dir*28,.15);drawBlend(-player.dir*14,.24);}
if(state==='attack'&&judgement==='PERFECT'){ctx.save();ctx.globalCompositeOperation='lighter';ctx.strokeStyle='rgba(226,190,255,.48)';ctx.lineWidth=2;ctx.beginPath();ctx.arc(player.x+player.w/2+player.dir*36,player.y+38,48,-1.1,1.1);ctx.stroke();ctx.restore();}
drawBlend(0,hurtAlpha);
}
function drawPlayerFallback(){
const x=player.x+player.w/2,y=player.y,run=Math.sin(player.anim)*5,lean=player.vx/260*3;ctx.save();ctx.globalAlpha=player.invuln>0&&Math.floor(player.invuln*12)%2===0?.48:1;ctx.translate(x,y);ctx.scale(player.dir,1);
if(player.dashTimer>0){for(let i=1;i<5;i++){ctx.globalAlpha=.18/i;ctx.fillStyle=i%2?'#90dff4':'#c49cff';ctx.beginPath();ctx.ellipse(-i*25,36,17,36,0,0,Math.PI*2);ctx.fill();}ctx.globalAlpha=1;}
// Mafuyu's long purple hair, split into animated back locks for a readable silhouette.
ctx.strokeStyle='#26203c';ctx.lineCap='round';ctx.lineWidth=9;for(let i=-1;i<=1;i++){ctx.beginPath();ctx.moveTo(-7+i*6,22);ctx.quadraticCurveTo(-20-i*3,45+run*.25,-14-i*6,69+run*.35);ctx.stroke();}
ctx.strokeStyle='#171827';ctx.lineWidth=7;ctx.beginPath();ctx.moveTo(-7,58);ctx.lineTo(-9+run,76);ctx.moveTo(7,58);ctx.lineTo(8-run,76);ctx.stroke();
// Miyamasuzaka-inspired sailor uniform, cardigan and pleated skirt.
ctx.fillStyle='#222c43';ctx.beginPath();ctx.moveTo(-16,30);ctx.lineTo(17,30);ctx.lineTo(15,57);ctx.lineTo(-15,57);ctx.closePath();ctx.fill();
ctx.strokeStyle='#6d7893';ctx.lineWidth=1.5;ctx.beginPath();ctx.moveTo(-12,34);ctx.lineTo(0,46);ctx.lineTo(12,34);ctx.stroke();
ctx.fillStyle='#b76f93';ctx.beginPath();ctx.moveTo(-5,39);ctx.lineTo(0,47);ctx.lineTo(5,39);ctx.lineTo(0,36);ctx.fill();
ctx.fillStyle='#31364c';ctx.beginPath();ctx.moveTo(-15,55);ctx.lineTo(16,55);ctx.lineTo(21,68);ctx.lineTo(-21,68);ctx.closePath();ctx.fill();ctx.strokeStyle='#737d95';ctx.lineWidth=1;for(let i=-13;i<=13;i+=7){ctx.beginPath();ctx.moveTo(i,57);ctx.lineTo(i*1.25,67);ctx.stroke();}
ctx.fillStyle='#f1e8ea';ctx.beginPath();ctx.ellipse(lean,19,14,17,0,0,Math.PI*2);ctx.fill();
ctx.fillStyle='#302544';ctx.beginPath();ctx.arc(lean,14,17,Math.PI,Math.PI*2);ctx.lineTo(17,37);ctx.quadraticCurveTo(8,28,5,25);ctx.lineTo(-15,37);ctx.closePath();ctx.fill();ctx.fillRect(-17,12,5,30);
ctx.fillStyle='#765b97';ctx.fillRect(4+lean,18,4,3);ctx.fillStyle='#d8f4ff';ctx.fillRect(5+lean,18,1,1);
ctx.strokeStyle='#22283b';ctx.lineWidth=6;ctx.beginPath();ctx.moveTo(13,38);ctx.lineTo(22,51);ctx.stroke();
if(player.attackTimer>0){const perfect=judgement==='PERFECT';ctx.strokeStyle=perfect?'#f3c3ff':'#c5f3ff';ctx.lineWidth=perfect?9:6;ctx.shadowColor=perfect?'#d081ff':'#8be8ff';ctx.shadowBlur=perfect?30:18;ctx.beginPath();ctx.arc(29,35,perfect?52:45,-1.15,1.18);ctx.stroke();for(let i=0;i<(perfect?4:2);i++){ctx.fillStyle=perfect?'#f4ccff':'#b5efff';ctx.fillRect(40+i*8,19+i*10,4,4);}}else if(player.rangedTimer>0){ctx.fillStyle='#bdfcff';ctx.shadowColor='#9f8cff';ctx.shadowBlur=24;ctx.beginPath();ctx.arc(27,35,7+Math.sin(time*22)*2,0,Math.PI*2);ctx.fill();}
ctx.restore();
}
function drawAtlasFrame(image,frames,row,frame,x,y,scale,flip=false,alpha=1){
if(!image.complete||!image.naturalWidth)return false;const source=frames[row][frame],w=source.sw*scale,h=source.sh*scale;ctx.save();ctx.translate(x,y);if(flip)ctx.scale(-1,1);ctx.globalAlpha=alpha;ctx.drawImage(image,source.sx,source.sy,source.sw,source.sh,-w/2,-h,w,h);ctx.restore();return true;
}
function drawAtlasEightPhase(image,frames,row,phase,x,y,scale,flip=false,alpha=1){
const eightPhase=((phase%8)+8)%8,atlasPhase=eightPhase*.5,frame=Math.floor(atlasPhase)%4,next=(frame+1)%4,mix=reducedMotion?0:smoothStep(atlasPhase-Math.floor(atlasPhase));
if(!drawAtlasFrame(image,frames,row,frame,x,y,scale,flip,alpha*(1-mix)))return false;
if(mix>0)drawAtlasFrame(image,frames,row,next,x,y,scale,flip,alpha*mix);
return true;
}
function drawAtlasSixteenPhase(image,frames,row,phase,x,y,scale,flip=false,alpha=1){const frame=Math.floor(((phase%16)+16)%16);return drawAtlasFrame(image,frames,row,frame,x,y,scale,flip,alpha);}
function drawBossImage(e){
let row=0,frame=Math.floor(e.t*6)%4;
if(e.defeating>0){row=3;frame=e.defeating>.58?2:3;}
else if(e.hit>0){row=3;frame=Math.floor(e.t*12)%2;}
else if(e.attackClock<.48){row=1;frame=Math.max(0,Math.min(3,Math.floor((.48-e.attackClock)/.12)));}
else if(Math.abs(e.vx)>145){row=2;frame=Math.floor(e.t*9)%4;}
const alpha=(!arenaActive&&!bossDefeated)?.55:1;if((row===0||row===2)&&e.hit<=0&&e.defeating<=0)return drawAtlasEightPhase(bossSprite,BOSS_FRAMES,row,e.t*(row===2?10:6),e.x+e.w/2,e.y+e.h+10,.82,e.dir>0,alpha);return drawAtlasFrame(bossSprite,BOSS_FRAMES,row,frame,e.x+e.w/2,e.y+e.h+10,.82,e.dir>0,alpha);
}
function drawEnemyImage(e){
const baseRow={shade:0,wisp:1,crawler:2,sentinel:3}[e.type],expansionRow={maskling:0,metronome:1,rainChoir:2,mirrorHound:3}[e.type];
if(baseRow===undefined&&expansionRow===undefined)return false;const expansion=expansionRow!==undefined,row=expansion?expansionRow:baseRow;
const fps=e.frozen>0?2:e.state==='idle'?12:e.state==='alert'?(['crawler','mirrorHound'].includes(e.type)?18:16):14,scale={shade:.4,wisp:.45,crawler:.46,sentinel:.44,maskling:.5,metronome:.58,rainChoir:.56,mirrorHound:.57}[e.type],alpha=e.hit>0?.78:1;
if(e.type==='sentinel'&&e.state==='alert'&&e.attackClock<.5){const frame=e.attackClock<.2?13:11;return drawAtlasFrame(enemySprite,ENEMY_FRAMES,row,frame,e.x+e.w/2,e.y+e.h+6,scale,e.dir>0,alpha);}
if(expansion){let phase=e.t*fps;if(e.state==='alert'&&e.attackClock<.42)phase=12+(1-e.attackClock/.42)*3;return drawAtlasSixteenPhase(expansionEnemySprite,EXPANSION_ENEMY_FRAMES,row,phase,e.x+e.w/2,e.y+e.h+6,scale,e.dir>0,alpha);}
return drawAtlasSixteenPhase(enemySprite,ENEMY_FRAMES,row,e.t*fps,e.x+e.w/2,e.y+e.h+6,scale,e.dir>0,alpha);
}
function drawFinalBossImage(e){
let row=0,phase=e.t*10;if(e.defeating>0){row=3;phase=Math.min(15,(1-e.defeating/1.8)*15);}else if(e.hit>0){row=3;phase=Math.min(7,e.hit*22);}else if(Math.abs(e.vx)>330){row=2;phase=Math.min(15,(Math.abs(e.vx)-330)/170*15);}else if(e.attackClock<.72){row=1;phase=Math.min(15,(.72-e.attackClock)/.72*15);}return drawAtlasSixteenPhase(finalBossSprite,FINAL_BOSS_FRAMES,row,phase,e.x+e.w/2,e.y+e.h+8,.72,e.dir>0,e.hit>0?.82:1);
}
function drawEnemyFallback(e){
ctx.save();ctx.translate(e.x+e.w/2,e.y+e.h/2);ctx.globalAlpha=e.hit>0 ? .45 : 1;ctx.shadowColor=isBossType(e.type)?'#ed7fbe':'#8fddeb';ctx.shadowBlur=18;ctx.fillStyle=isBossType(e.type)?'#251125':'#28243f';ctx.beginPath();ctx.ellipse(0,0,e.w*.48,e.h*.48,0,0,Math.PI*2);ctx.fill();ctx.fillStyle='#d9f5fa';ctx.fillRect(-9,-3,5,3);ctx.fillRect(5,-3,5,3);ctx.restore();
}
function drawEnemies(){
for(const e of enemies){
if(e.dead||roomIndexAt(e.homeX)!==currentRoom)continue;const drawn=e.type==='conductor'?drawBossImage(e):e.type==='mirror'?drawFinalBossImage(e):drawEnemyImage(e);if(!drawn)drawEnemyFallback(e);if(e.frozen>0){ctx.save();ctx.translate(e.x+e.w/2,e.y+e.h/2);ctx.globalAlpha=Math.min(.78,.34+e.frozen*.15);ctx.strokeStyle='#c9f8ff';ctx.fillStyle='rgba(174,239,255,.16)';ctx.lineWidth=2;ctx.beginPath();ctx.moveTo(-e.w*.62,e.h*.48);ctx.lineTo(-e.w*.48,-e.h*.28);ctx.lineTo(-e.w*.12,-e.h*.62);ctx.lineTo(e.w*.5,-e.h*.36);ctx.lineTo(e.w*.64,e.h*.48);ctx.closePath();ctx.fill();ctx.stroke();for(let i=-1;i<=1;i++){ctx.beginPath();ctx.moveTo(i*e.w*.25,e.h*.42);ctx.lineTo(i*e.w*.2-5,-e.h*.22);ctx.stroke();}ctx.restore();}
if(e.hit>0||isBossType(e.type)){ctx.fillStyle='rgba(6,7,16,.75)';ctx.fillRect(e.x,e.y-12,e.w,4);ctx.fillStyle=isBossType(e.type)?'#ed82c0':'#92dce8';ctx.fillRect(e.x,e.y-12,e.w*Math.max(0,e.hp/e.maxHp),4);}
if(!isBossType(e.type)&&(e.stateFlash>0||e.notice>0)){const alert=e.state==='alert',alpha=alert?Math.min(1,e.stateFlash*3):Math.min(.8,e.notice/(ENEMY_AI[e.type].reaction||1));ctx.save();ctx.globalAlpha=alpha;ctx.translate(e.x+e.w/2,e.y-28);ctx.fillStyle=alert?'#ee9acb':'#a8e6f0';ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=14;ctx.beginPath();ctx.arc(0,0,10,0,Math.PI*2);ctx.fill();ctx.fillStyle='#111321';ctx.font='700 13px sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(alert?'!':'?',0,1);ctx.restore();}
}
}
function drawProjectiles(){
for(const p of projectiles){ctx.save();ctx.translate(p.x+p.w/2,p.y+p.h/2);ctx.rotate(p.kind==='rain'?0:p.t*5);ctx.shadowColor=['chord','script'].includes(p.kind)?'#f08ac5':'#8fe7f4';ctx.shadowBlur=18;ctx.fillStyle=['chord','script'].includes(p.kind)?'#f1a3d1':'#c7f5fa';if(p.kind==='chord'){ctx.beginPath();ctx.arc(0,0,10,0,Math.PI*2);ctx.fill();ctx.strokeStyle='#fff8';ctx.beginPath();ctx.moveTo(-13,0);ctx.lineTo(13,0);ctx.moveTo(0,-13);ctx.lineTo(0,13);ctx.stroke();}else if(p.kind==='rain'){ctx.beginPath();ctx.moveTo(0,-9);ctx.quadraticCurveTo(8,2,0,10);ctx.quadraticCurveTo(-8,2,0,-9);ctx.fill();}else if(p.kind==='blade'){ctx.rotate(Math.atan2(p.vy,p.vx)-p.t*5);ctx.beginPath();ctx.moveTo(12,0);ctx.lineTo(-9,-5);ctx.lineTo(-5,0);ctx.lineTo(-9,5);ctx.closePath();ctx.fill();}else if(p.kind==='script'){ctx.strokeStyle='#f5b6e5';ctx.lineWidth=3;ctx.beginPath();ctx.arc(0,0,9,-2.4,2.4);ctx.stroke();ctx.fillRect(5,-12,4,8);}else{ctx.rotate(Math.PI/4);ctx.fillRect(-6,-6,12,12);}ctx.restore();}
}
function drawResonanceShots(){
for(const shot of resonanceShots){ctx.save();ctx.translate(shot.x+shot.w/2,shot.y+shot.h/2);ctx.scale(shot.dir,1);ctx.globalCompositeOperation='lighter';ctx.shadowColor='#86f4ff';ctx.shadowBlur=22;ctx.strokeStyle='#eaffff';ctx.fillStyle='#bcefff';ctx.lineWidth=2.5;ctx.beginPath();ctx.moveTo(25,0);ctx.lineTo(10,-6);ctx.lineTo(14,-2);ctx.lineTo(-17,-2);ctx.lineTo(-23,-8);ctx.lineTo(-20,0);ctx.lineTo(-23,8);ctx.lineTo(-17,2);ctx.lineTo(14,2);ctx.lineTo(10,6);ctx.closePath();ctx.fill();ctx.stroke();ctx.strokeStyle='rgba(151,226,255,.64)';for(let i=0;i<4;i++){ctx.globalAlpha=.6-i*.12;ctx.lineWidth=3-i*.45;ctx.beginPath();ctx.moveTo(-20-i*12,Math.sin(shot.t*24+i)*3);ctx.lineTo(-7-i*8,0);ctx.stroke();}ctx.restore();}
}
function drawAmbientWorld(){
const room=ROOMS[currentRoom];ctx.save();ctx.globalCompositeOperation='lighter';
for(let i=0;i<18;i++){const seed=i*137+currentRoom*61,x=room.start+70+(seed%(ROOM_W-140)),speed=11+(i%5)*3,y=90+((seed*.7-time*speed+900) % 470+470)%470,r=1.5+(i%4)*1.15,color=currentArea===1?'#79e9ff':currentArea===3?'#f5a7db':'#bda6ff';ctx.globalAlpha=.12+(i%5)*.045;ctx.fillStyle=color;ctx.shadowColor=color;ctx.shadowBlur=12+r*2;ctx.beginPath();ctx.arc(x+Math.sin(time*.7+i)*16,y,r,0,Math.PI*2);ctx.fill();}
ctx.restore();
}
function drawAtmosphereForeground(){
ctx.save();ctx.lineCap='round';
if(currentArea===0||currentArea===3||currentArea===4){ctx.strokeStyle=currentArea===3?'rgba(238,158,210,.13)':currentArea===4?'rgba(166,211,239,.22)':'rgba(193,231,245,.16)';ctx.lineWidth=currentArea===4?1.5:1.2;const speed=currentArea===3?250:currentArea===4?360:330;for(let i=0;i<(currentArea===4?58:42);i++){const x=((i*193+time*speed*.22)%(W+180))-90,y=((i*83+time*speed)%(H+170))-120;ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x-(currentArea===4?20:16),y+(currentArea===4?68:56));ctx.stroke();}}
else if(currentArea===1){for(let i=0;i<22;i++){const x=(i*151+currentRoom*29)%W,y=H-((i*97+time*(18+i%4*7))%(H+80));ctx.strokeStyle='rgba(137,235,248,.18)';ctx.beginPath();ctx.arc(x+Math.sin(time+i)*10,y,2+i%3,0,Math.PI*2);ctx.stroke();}}
else{ctx.fillStyle='rgba(194,151,255,.14)';for(let i=0;i<34;i++){const x=(i*109+time*(12+i%3*8))%W,y=(i*67+Math.sin(time*.8+i)*30+H)%H;ctx.fillRect(x,y,1+i%2,7+i%5);}}
ctx.restore();
}
function drawParticles(){for(const p of particles){ctx.globalAlpha=Math.max(0,p.life/p.max);ctx.fillStyle=p.color;ctx.fillRect(p.x,p.y,p.size,p.size);ctx.globalAlpha=1;}for(const s of slashes){const alpha=Math.max(0,Math.min(1,s.life/(s.heavy?.24:.15)));ctx.save();ctx.globalAlpha=alpha;ctx.strokeStyle=s.heavy?'#d8fbff':'#b7efff';ctx.shadowColor=s.heavy?'#83dfff':'transparent';ctx.shadowBlur=s.heavy?22:0;ctx.lineWidth=s.heavy?8:3;if(s.heavy){ctx.translate(s.dir>0?s.x:s.x+s.w,s.y+s.h*.53);ctx.scale(s.dir,1);ctx.beginPath();ctx.arc(0,0,s.w*.78,-.88,.88);ctx.stroke();}else ctx.strokeRect(s.x,s.y,s.w,s.h);ctx.restore();}}
function drawHud(){
ctx.save();ctx.translate(34,31);ctx.fillStyle='rgba(7,8,20,.78)';ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(286,0);ctx.lineTo(274,108);ctx.lineTo(0,108);ctx.closePath();ctx.fill();ctx.fillStyle='#b99cf4';ctx.fillRect(0,0,5,108);
ctx.fillStyle='#edf8fb';ctx.font='500 15px sans-serif';ctx.fillText('朝比奈 まふゆ',18,23);ctx.font='9px sans-serif';ctx.fillStyle='#8c91aa';ctx.fillText('LYRICIST / OWN VOICE : SEARCHING',18,40);
for(let i=0;i<player.maxHp;i++){ctx.save();ctx.translate(177+i*18,20);ctx.rotate(Math.PI/4);ctx.strokeStyle='#b9a9d7';ctx.strokeRect(-5,-5,10,10);if(i<player.hp){ctx.fillStyle=i===player.hp-1?'#d9f7ff':'#8e82c5';ctx.fillRect(-4,-4,8,8);}ctx.restore();}
ctx.fillStyle='#676b80';ctx.fillRect(18,57,164,4);ctx.fillStyle=player.dashCooldown<=0?'#94e9f4':'#725c9a';ctx.fillRect(18,57,164*(hasDash?1-player.dashCooldown/.68:0),4);ctx.font='9px sans-serif';ctx.fillStyle=hasDash?'#b7eaf1':'#656a7c';ctx.fillText(hasDash?'K SEKAI SHIFT':'SEKAI SHIFT — LOCKED',18,73);
ctx.fillStyle='#b6a4d8';ctx.fillText(`LYRIC ${fragmentsFound}/${fragments.length}`,205,73);ctx.fillStyle='#353b50';ctx.fillRect(18,86,164,5);ctx.fillStyle='#8ceee9';ctx.shadowColor='#8ceee9';ctx.shadowBlur=player.energy>=25?9:0;ctx.fillRect(18,86,164*(player.energy/player.maxEnergy),5);ctx.shadowBlur=0;ctx.font='9px sans-serif';ctx.fillStyle=player.energy>=25?'#b9fff8':'#788695';ctx.fillText(`L RESONANCE ${Math.round(player.energy)}/${player.maxEnergy}`,18,102);if(hasDoubleJump){ctx.fillStyle='#a9dcff';ctx.fillText('AIR ECHO READY',192,102);}ctx.restore();
ctx.save();ctx.translate(34,151);ctx.fillStyle='rgba(7,8,20,.72)';ctx.fillRect(0,0,250,32);ctx.fillStyle='#756693';ctx.fillRect(0,0,4,32);ctx.font='8px sans-serif';ctx.fillStyle='#827c96';ctx.fillText('CURRENT OBJECTIVE',14,12);ctx.font='500 11px sans-serif';ctx.fillStyle='#d7eaf0';ctx.fillText(objectiveText(),14,25);ctx.restore();
// Rhythm-game beat lane: attacking when the moving diamonds meet the center yields PERFECT.
const phase=(time%BEAT)/BEAT;ctx.save();ctx.translate(W/2,H-66);ctx.fillStyle='rgba(5,7,18,.72)';ctx.fillRect(-185,-20,370,40);ctx.strokeStyle='rgba(184,226,239,.35)';ctx.beginPath();ctx.moveTo(-165,0);ctx.lineTo(165,0);ctx.stroke();ctx.strokeStyle='#d9f7ff';ctx.strokeRect(-11,-11,22,22);
const bx=(phase<.5?(phase*2):((phase-1)*2))*165;ctx.save();ctx.translate(bx,0);ctx.rotate(Math.PI/4);ctx.fillStyle=Math.abs(bx)<38?'#e5b6ff':'#7cd9ed';ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=16;ctx.fillRect(-7,-7,14,14);ctx.restore();ctx.font='9px sans-serif';ctx.fillStyle='#999fb2';ctx.textAlign='center';ctx.fillText('J ON BEAT',0,34);
if(judgeTimer>0){ctx.globalAlpha=Math.min(1,judgeTimer*4);ctx.fillStyle=judgement==='PERFECT'?'#f0baff':judgement==='GREAT'?'#92e8f3':'#8b8498';ctx.font='700 18px sans-serif';ctx.fillText(judgement,0,-32);}
if(player.chargeActive){const progress=Math.min(1,player.chargeTimer/CHARGE_FULL_TIME);ctx.globalAlpha=1;ctx.fillStyle='rgba(5,13,24,.86)';ctx.fillRect(-96,46,192,18);ctx.fillStyle='#24364b';ctx.fillRect(-88,53,176,4);ctx.fillStyle=player.chargeReady?'#e7fdff':'#8ee8f6';ctx.shadowColor='#7ee9ff';ctx.shadowBlur=player.chargeReady?14:5;ctx.fillRect(-88,53,176*progress,4);ctx.shadowBlur=0;ctx.font='700 8px sans-serif';ctx.fillStyle=player.chargeReady?'#e8fdff':'#9bbaca';ctx.fillText(player.chargeReady?'ICE SWORD · RELEASE':'J HOLD · ICE SWORD',0,43);}
ctx.restore();
ctx.save();ctx.textAlign='right';ctx.fillStyle='#eef5ff';ctx.font='700 25px sans-serif';ctx.fillText(String(score).padStart(7,'0'),W-34,48);ctx.font='10px sans-serif';ctx.fillStyle='#998cac';ctx.fillText('SCORE',W-34,62);if(combo>1){ctx.fillStyle='#c9a7f2';ctx.font='700 28px sans-serif';ctx.fillText(`${combo} COMBO`,W-34,96);}
ctx.fillStyle='rgba(6,7,18,.65)';ctx.fillRect(W-290,H-35,256,4);for(const a of areas){ctx.fillStyle=a.tone;ctx.globalAlpha=.22;ctx.fillRect(W-290+a.start/WORLD_W*256,H-35,(a.end-a.start)/WORLD_W*256,4);}ctx.globalAlpha=1;ctx.fillStyle='#fff';ctx.fillRect(W-290+player.x/WORLD_W*256-2,H-39,4,12);ctx.font='9px sans-serif';ctx.fillStyle='#9ea7bb';const minutes=Math.floor(playTime/60),seconds=Math.floor(playTime%60);ctx.fillText(`${ROOMS[roomIndexAt(player.x)].name} · ${minutes}:${String(seconds).padStart(2,'0')} · M MAP`,W-34,H-49);ctx.restore();
const boss=enemies.find(e=>((arenaActive&&e.type==='conductor')||(finalArenaActive&&e.type==='mirror'))&&!e.dead);if(boss){ctx.save();ctx.translate(W/2-260,26);ctx.fillStyle='rgba(10,5,17,.82)';ctx.fillRect(0,0,520,44);ctx.fillStyle='#8b376d';ctx.fillRect(14,27,492,5);ctx.fillStyle='#ef8ac6';ctx.fillRect(14,27,492*Math.max(0,boss.hp/boss.maxHp),5);ctx.textAlign='center';ctx.fillStyle='#f2d9e8';ctx.font='500 13px serif';ctx.fillText(boss.type==='mirror'?'未写下的真冬 · THE UNWRITTEN':'无声指挥者 · SILENT CONDUCTOR',260,18);ctx.restore();}
}
function loop(ts){const dt=Math.min(.033,(ts-last)/1000||0);last=ts;updateAudio(dt);if(running&&!paused){if(hitStop>0){hitStop=Math.max(0,hitStop-dt);advanceRhythmClock(dt);}else update(dt);}render();requestAnimationFrame(loop);}
function updateJoystickFromPointer(event){
const rect=touchJoystick.getBoundingClientRect(),cx=rect.left+rect.width/2,cy=rect.top+rect.height/2,max=rect.width*.31,dx=event.clientX-cx,dy=event.clientY-cy,length=Math.hypot(dx,dy)||1,scale=Math.min(1,max/length),x=dx*scale,y=dy*scale;
joystickKnob.style.transform=`translate(calc(-50% + ${x}px),calc(-50% + ${y}px))`;const normalized=x/max,deadzone=.18;touchAxis=Math.abs(normalized)<=deadzone?0:Math.sign(normalized)*(Math.abs(normalized)-deadzone)/(1-deadzone);
}
function releaseJoystick(event){
if(joystickPointerId!==null&&event.pointerId!==joystickPointerId)return;try{touchJoystick.releasePointerCapture(event.pointerId);}catch{}resetJoystick();
}
const touchActionCodes={jump:'Space',attack:'KeyJ',ranged:'KeyL',dash:'KeyK',interact:'ArrowDown'};
function pressTouchAction(action,button){
button.classList.add('is-active');if(action==='map'){toggleMap(true);return;}if(action==='journal'){toggleJournal(true);return;}if(action==='pause'){setPaused(true);return;}const code=touchActionCodes[action];if(!code)return;if(!touchHeld.has(code)){pressed.add(code);if(code==='KeyJ')player.attackInputTime=time;}touchHeld.add(code);
}
function releaseTouchAction(action,button){const code=touchActionCodes[action];if(code){if(touchHeld.has(code))released.add(code);touchHeld.delete(code);}button.classList.remove('is-active');}
document.addEventListener('keydown',e=>{
if(!settingsScreen.classList.contains('hidden')){if(e.code==='Escape'){e.preventDefault();closeSettings();}return;}
if(introActive){if(['Space','Enter'].includes(e.code)){e.preventDefault();advanceIntro();}else if(e.code==='Escape')finishIntro();return;}
if(journalOpen){if(['KeyQ','Escape'].includes(e.code)){e.preventDefault();toggleJournal(false);}return;}
if(mapOpen){if(['KeyM','Tab','Escape'].includes(e.code)){e.preventDefault();toggleMap(false);}return;}
if(running&&!paused&&['KeyM','Tab'].includes(e.code)){e.preventDefault();toggleMap(true);return;}
if(running&&!paused&&e.code==='KeyQ'){e.preventDefault();toggleJournal(true);return;}
if(e.code==='Escape'){
if(!controlsScreen.classList.contains('hidden')){controlsScreen.classList.add('hidden');titleScreen.classList.remove('hidden');return;}
if(running){setPaused(!paused);return;}
}
if(!running||paused)return;
if(!keys.has(e.code)){pressed.add(e.code);if(e.code==='KeyJ'||e.code==='KeyX')player.attackInputTime=time;}keys.add(e.code);
if(['Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.code))e.preventDefault();
});
document.addEventListener('keyup',e=>{if(keys.has(e.code))released.add(e.code);keys.delete(e.code);});
document.querySelector('#newGameButton').addEventListener('click',startNewGame);
document.querySelector('#introNextButton').addEventListener('click',advanceIntro);
document.querySelector('#introSkipButton').addEventListener('click',finishIntro);
document.querySelector('#mapCloseButton').addEventListener('click',()=>toggleMap(false));
document.querySelector('#journalCloseButton').addEventListener('click',()=>toggleJournal(false));
continueButton.addEventListener('click',continueGame);
document.querySelector('#controlsButton').addEventListener('click',()=>{playSfx('confirm',.65);titleScreen.classList.add('hidden');controlsScreen.classList.remove('hidden');tone(280,.08,'sine',.015);});
document.querySelector('#closeControlsButton').addEventListener('click',()=>{playSfx('back',.65);controlsScreen.classList.add('hidden');titleScreen.classList.remove('hidden');tone(220,.08,'sine',.015);});
document.querySelector('#settingsButton').addEventListener('click',()=>openSettings('title'));
document.querySelector('#pauseSettingsButton').addEventListener('click',()=>openSettings('pause'));
document.querySelector('#closeSettingsButton').addEventListener('click',closeSettings);
controlModeSelect.addEventListener('change',()=>setControlMode(controlModeSelect.value));
fullscreenButton.addEventListener('click',toggleFullscreen);
document.addEventListener('fullscreenchange',updateFullscreenUI);
document.addEventListener('webkitfullscreenchange',updateFullscreenUI);
document.querySelector('#muteButton').addEventListener('click',toggleMute);
document.querySelector('#resumeButton').addEventListener('click',()=>setPaused(false));
document.querySelector('#retryButton').addEventListener('click',()=>{resetGame(false);setPaused(false);playMusic(['empty','aquarium','corridor','stage','aquarium','stage'][areas.findIndex(a=>checkpoint.x>=a.start&&checkpoint.x<a.end)]||'empty',.6,true);showToast('已返回最近的 SEKAI 记忆');});
document.querySelector('#pauseJournalButton').addEventListener('click',()=>{paused=false;pauseScreen.classList.add('hidden');toggleJournal(true);});
document.querySelector('#pauseMuteButton').addEventListener('click',toggleMute);
document.querySelector('#mainMenuButton').addEventListener('click',returnToMainMenu);
document.querySelector('#restartButton').addEventListener('click',startNewGame);
document.querySelector('#endingMenuButton').addEventListener('click',returnToMainMenu);
document.querySelectorAll('button:not([data-touch-action])').forEach(button=>button.addEventListener('mouseenter',()=>{if(!button.disabled){playSfx('hover',.32,1,0);tone(245,.025,'sine',.004);}}));
musicVolumeInput.addEventListener('input',()=>{musicVolume=Number(musicVolumeInput.value)/100;musicVolumeValue.textContent=`${musicVolumeInput.value}%`;storageSet('silent-sekai-music-volume',String(musicVolume));setAudioStatus(`BGM ${musicVolumeInput.value}% · SFX ${Math.round(sfxVolume*100)}%`);});
sfxVolumeInput.addEventListener('input',()=>{sfxVolume=Number(sfxVolumeInput.value)/100;sfxVolumeValue.textContent=`${sfxVolumeInput.value}%`;storageSet('silent-sekai-sfx-volume',String(sfxVolume));setAudioStatus(`BGM ${Math.round(musicVolume*100)}% · SFX ${sfxVolumeInput.value}%`);});
sfxVolumeInput.addEventListener('change',()=>playSfx('confirm',.7));
document.querySelector('#audioTestButton').addEventListener('click',()=>{if(muted){muted=false;storageSet('silent-sekai-muted','false');updateMuteButtons();}if(musicVolume===0&&sfxVolume===0){musicVolume=.55;sfxVolume=.7;storageSet('silent-sekai-music-volume',String(musicVolume));storageSet('silent-sekai-sfx-volume',String(sfxVolume));syncAudioUI();}unlockAudio();tone(523.25,.18,'sine',.06);setMusicGain(running ? 1 : .45);playMusic(running?(['empty','aquarium','corridor','stage','aquarium','stage'][Math.max(0,currentArea)]||'empty'):'empty',.2,true);playSfx('checkpoint',.9,1,0);});
touchJoystick.addEventListener('pointerdown',event=>{if(!document.body.classList.contains('touch-controls-active'))return;event.preventDefault();joystickPointerId=event.pointerId;touchJoystick.setPointerCapture(event.pointerId);updateJoystickFromPointer(event);});
touchJoystick.addEventListener('pointermove',event=>{if(event.pointerId!==joystickPointerId)return;event.preventDefault();updateJoystickFromPointer(event);});
touchJoystick.addEventListener('pointerup',releaseJoystick);touchJoystick.addEventListener('pointercancel',releaseJoystick);
document.querySelectorAll('[data-touch-action]').forEach(button=>{
const action=button.dataset.touchAction;
button.addEventListener('pointerdown',event=>{event.preventDefault();event.stopPropagation();button.setPointerCapture(event.pointerId);pressTouchAction(action,button);});
const release=event=>{event.preventDefault();releaseTouchAction(action,button);};button.addEventListener('pointerup',release);button.addEventListener('pointercancel',release);button.addEventListener('lostpointercapture',()=>releaseTouchAction(action,button));
});
mobileControls.addEventListener('contextmenu',event=>event.preventDefault());
document.addEventListener('pointerdown',()=>{unlockAudio();if(!running&&!introActive&&!ending)playMusic('empty',.35);});
document.addEventListener('visibilitychange',()=>{if(!document.hidden)ensureMusicPlaying();});
window.addEventListener('blur',()=>{if(mapOpen)toggleMap(false);if(running&&!paused)setPaused(true,true);});
window.addEventListener('resize',syncMobileControls);
resetGame(true);updateContinueUI();updateMuteButtons();syncAudioUI();updateFullscreenUI();syncMobileControls();requestAnimationFrame(loop);
})();