refactor: 使用flutter对原先的web项目重构,正在进行中

This commit is contained in:
cancerai committed 2026-10-25 00:06:51 +08:00
1 parent 273224f5cf
commit 18017f819a
205 files changed
+13563

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
// 纯 WebAudio 合成音效,无外部资源
let ctx = null, master = null;
export const Audio2 = { enabled: true, volume: 0.5 };
function ac() {
if (!ctx) {
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return null;
ctx = new AC();
master = ctx.createGain();
master.gain.value = Audio2.volume;
master.connect(ctx.destination);
}
if (ctx.state === 'suspended') ctx.resume();
return ctx;
}
export function unlockAudio() { ac(); }
function tone({ f = 440, f2 = null, d = 0.1, type = 'square', vol = 0.25, delay = 0, decay = 0 }) {
if (!Audio2.enabled) return;
const c = ac(); if (!c) return;
const t0 = c.currentTime + delay;
const o = c.createOscillator();
const g = c.createGain();
o.type = type;
o.frequency.setValueAtTime(f, t0);
if (f2 !== null) o.frequency.exponentialRampToValueAtTime(Math.max(20, f2), t0 + d);
g.gain.setValueAtTime(0.0001, t0);
g.gain.linearRampToValueAtTime(vol, t0 + 0.008);
const end = t0 + d + decay;
g.gain.exponentialRampToValueAtTime(0.0001, end);
o.connect(g); g.connect(master);
o.start(t0); o.stop(end + 0.02);
}
function noise({ d = 0.2, vol = 0.25, delay = 0, hp = 400 }) {
if (!Audio2.enabled) return;
const c = ac(); if (!c) return;
const t0 = c.currentTime + delay;
const len = Math.floor(c.sampleRate * d);
const buf = c.createBuffer(1, len, c.sampleRate);
const data = buf.getChannelData(0);
for (let i = 0; i < len; i++) data[i] = (Math.random() * 2 - 1) * (1 - i / len);
const src = c.createBufferSource(); src.buffer = buf;
const f = c.createBiquadFilter(); f.type = 'highpass'; f.frequency.value = hp;
const g = c.createGain(); g.gain.value = vol;
src.connect(f); f.connect(g); g.connect(master);
src.start(t0);
}
export const sfx = {
jump() { tone({ f: 380, f2: 700, d: 0.09, type: 'square', vol: 0.16 }); },
djump() { tone({ f: 520, f2: 900, d: 0.09, type: 'square', vol: 0.14 }); },
shoot() { tone({ f: 900, f2: 260, d: 0.07, type: 'square', vol: 0.14 }); noise({ d: 0.05, vol: 0.06, hp: 2000 }); },
death() { tone({ f: 620, f2: 60, d: 0.55, type: 'sawtooth', vol: 0.26 });
noise({ d: 0.35, vol: 0.16, hp: 300, delay: 0.02 }); },
save() { tone({ f: 700, d: 0.08, type: 'triangle', vol: 0.2 });
tone({ f: 1050, d: 0.13, type: 'triangle', vol: 0.18, delay: 0.07 }); },
goal() { [523, 659, 784, 1047].forEach((f, i) =>
tone({ f, d: 0.16, type: 'triangle', vol: 0.2, delay: i * 0.1 })); },
warp() { tone({ f: 300, f2: 1400, d: 0.2, type: 'sine', vol: 0.18 }); },
hit() { tone({ f: 200, f2: 90, d: 0.08, type: 'square', vol: 0.16 }); },
bossHit() { tone({ f: 260, f2: 140, d: 0.1, type: 'sawtooth', vol: 0.14 }); },
bossDie() { [400, 330, 260, 180, 110].forEach((f, i) =>
tone({ f, d: 0.22, type: 'sawtooth', vol: 0.22, delay: i * 0.11 }));
noise({ d: 0.8, vol: 0.2, hp: 150, delay: 0.1 }); },
menu() { tone({ f: 620, d: 0.05, type: 'square', vol: 0.12 }); },
vanish() { tone({ f: 700, f2: 300, d: 0.12, type: 'sine', vol: 0.1 }); },
troll() { tone({ f: 180, f2: 900, d: 0.3, type: 'sine', vol: 0.18 }); },
splash() { noise({ d: 0.18, vol: 0.12, hp: 800 }); },
};
+325
View File
@@ -0,0 +1,325 @@
// BOSS 战系统:多阶段弹幕 / 冲撞 / 刺雨
import { clamp, sgn, rand, randInt, overlap } from './util.js';
import { sfx } from './audio.js';
import { TILE } from './util.js';
const DEFS = {
guy: { hp: 42, w: 64, h: 74, name: 'THE GUY' },
mecha: { hp: 62, w: 78, h: 62, name: 'MECHA KID' },
devil: { hp: 84, w: 74, h: 90, name: 'THE DEVIL' },
};
export class Boss {
constructor(level, e) {
const d = DEFS[e.kind] || DEFS.guy;
this.level = level;
this.kind = e.kind;
this.name = d.name;
this.x = e.x; this.y = e.y;
this.w = d.w; this.h = d.h;
this.maxHp = e.hp || d.hp;
this.hp = this.maxHp;
this.flash = 0;
this.dead = false;
this.deathT = 0;
this.bodyKill = true;
this.t = 0;
this.phase = 1;
this.vx = 0; this.vy = 0;
this.state = 'idle';
this.stateT = 0;
// BOSS 贴地活动:保证玩家在地面平射就能命中
this.bounds = {
x0: 40, x1: level.pxW - 40 - this.w,
y0: 40, y1: level.pxH - 32 - this.h, // 底部贴地
};
this.homeY = clamp(e.y, this.bounds.y0, this.bounds.y1);
this.y = this.homeY;
this.homeX = e.x;
this.wing = 0;
}
get rect() { return { x: this.x, y: this.y, w: this.w, h: this.h }; }
shoot(level, x, y, vx, vy, col = '#ff5c7a', big = false) {
level.ebullets.push({ x: x - 4, y: y - 4, w: big ? 12 : 8, h: big ? 12 : 8, vx, vy, dead: false, col, big, life: 500 });
}
hit(dmg = 1) {
if (this.dead || this.flash > 6) return;
this.hp -= dmg;
this.flash = 10;
sfx.bossHit();
this.level.particles.spawn(this.x + this.w / 2, this.y + this.h / 2, 6,
{ colors: ['#fff', '#ffc63a'], speed: 2.6, life: 18 });
const r = this.hp / this.maxHp;
this.phase = r > 0.6 ? 1 : r > 0.3 ? 2 : 3;
if (this.hp <= 0) this.die();
}
die() {
this.dead = true; this.hp = 0; this.bodyKill = false;
sfx.bossDie();
this.level.shake = 16;
this.level.particles.burst(this.x + this.w / 2, this.y + this.h / 2,
{ n: 40, colors: ['#ff5c7a', '#ffc63a', '#fff', '#e03050'], speed: 5, life: 60, size: 4 });
}
update(dt, player) {
if (this.dead) {
this.deathT++;
if (this.deathT % 8 === 0 && this.deathT < 90) {
this.level.particles.burst(this.x + rand(0, this.w), this.y + rand(0, this.h),
{ n: 6, colors: ['#ffc63a', '#ff5c7a', '#fff'], speed: 3, life: 30, size: 3 });
sfx.hit();
}
if (this.deathT === 90) { if (this.onDefeat) this.onDefeat(); }
return;
}
this.t++;
this.stateT++;
if (this.flash > 0) this.flash--;
// 子类型行为
if (this.kind === 'guy') this.updateGuy(player);
else if (this.kind === 'mecha') this.updateMecha(player);
else this.updateDevil(player);
this.x += this.vx; this.y += this.vy;
this.x = clamp(this.x, this.bounds.x0, Math.max(this.bounds.x0, this.bounds.x1));
this.y = clamp(this.y, this.bounds.y0, Math.max(this.bounds.y0, this.bounds.y1));
// 被子弹击中
for (const b of this.level.bullets) {
if (b.dead) continue;
if (overlap(b, this.rect)) {
b.dead = true;
this.hit(1);
}
}
}
// ---------- THE GUY:飘移 + 扇形弹 + 砸地 ----------
updateGuy(player) {
const L = this.level;
if (this.phase === 1) {
this.vx = Math.sin(this.t / 60) * 1.5;
this.y = this.homeY + Math.sin(this.t / 45) * 8;
if (this.t % 96 === 0) {
const cx = this.x + this.w / 2, cy = this.y + this.h / 2;
for (let i = -1; i <= 1; i++) {
const a = Math.atan2(player.cy - cy, player.cx - cx) + i * 0.28;
this.shoot(L, cx, cy, Math.cos(a) * 2.8, Math.sin(a) * 2.8);
}
sfx.shoot();
}
} else {
// 追踪 + 砸地
const dir = sgn(player.cx - (this.x + this.w / 2));
if (this.state === 'idle') {
this.vx = dir * 1.9;
this.y = this.homeY + Math.sin(this.t / 30) * 6;
if (this.stateT > 70) { this.state = 'slam'; this.stateT = 0; this.vy = 0; }
} else if (this.state === 'slam') {
this.vx *= 0.9;
this.vy = Math.min(this.vy + 0.7, 11);
if (this.y + this.h >= this.bounds.y1 + this.h * 0.2 || this.y >= this.homeY + 150) {
// 落地冲击:左右各飞出 3 发
this.state = 'idle'; this.stateT = 0; this.vy = -3;
L.shake = 10; sfx.hit();
for (let i = 0; i < 4; i++) {
this.shoot(L, this.x + this.w / 2, this.y + this.h - 6, -2.6 - i * 0.4, -1.2 - i * 0.15, '#ffc63a');
this.shoot(L, this.x + this.w / 2, this.y + this.h - 6, 2.6 + i * 0.4, -1.2 - i * 0.15, '#ffc63a');
}
}
}
}
}
// ---------- MECHA KID:冲撞 + 刺雨 ----------
updateMecha(player) {
const L = this.level;
if (this.state === 'idle') {
this.vx *= 0.92;
this.y = this.homeY + Math.sin(this.t / 40) * 5;
if (this.stateT > 100 - this.phase * 18) {
this.state = 'dash'; this.stateT = 0;
this.vx = sgn(player.cx - (this.x + this.w / 2)) * (5 + this.phase * 0.8);
sfx.shoot();
}
if (this.t % 150 === 0) {
// 刺雨
for (let i = 0; i < 4 + this.phase; i++) {
const tx = randInt(1, L.w - 2);
L.entities.push({
type: 'dropspike', x: tx * TILE, y: -TILE, w: TILE, h: TILE,
falling: true, vy: 0, homeY: -TILE, t: 0, temp: true,
});
}
L.showToast('刺雨来了!', 80);
sfx.troll();
}
} else if (this.state === 'dash') {
this.vy = 0;
if (this.x <= this.bounds.x0 + 1 || this.x >= this.bounds.x1 - 1 || this.stateT > 90) {
this.state = 'idle'; this.stateT = 0; this.vx = 0;
L.shake = 6;
L.particles.spawn(this.x + this.w / 2, this.y + this.h / 2, 8,
{ colors: ['#9ad8ff', '#fff'], speed: 3, life: 20 });
}
}
}
// ---------- THE DEVIL:追踪弹 / 激光 / 环形弹幕 ----------
updateDevil(player) {
const L = this.level;
this.wing += 0.16;
const cx = this.x + this.w / 2, cy = this.y + this.h / 2;
const p2 = this.phase;
// 移动
if (p2 === 1) { this.vx = Math.sin(this.t / 70) * 1.6; this.y = this.homeY + Math.sin(this.t / 50) * 8; }
else if (p2 === 2) { this.vx = Math.sin(this.t / 40) * 2.6; this.y = this.homeY + Math.sin(this.t / 28) * 11; }
else { this.vx = Math.sin(this.t / 25) * 3.4; this.y = this.homeY + Math.sin(this.t / 20) * 14; }
if (p2 === 1) {
if (this.t % 60 === 0) {
const a = Math.atan2(player.cy - cy, player.cx - cx);
for (let i = -1; i <= 1; i++)
this.shoot(L, cx, cy, Math.cos(a + i * 0.2) * 3, Math.sin(a + i * 0.2) * 3, '#ff9a3a');
sfx.shoot();
}
} else if (p2 === 2) {
if (this.t % 110 === 0) { this.state = 'laser'; this.stateT = 0; }
if (this.state === 'laser' && this.stateT < 40 && this.stateT % 5 === 0) {
// 横向激光弹幕(从上往下扫)
const yy = 40 + (this.stateT / 40) * (L.pxH - 90);
this.shoot(L, 8, yy, 6.5, 0, '#ff4060', true);
this.shoot(L, L.pxW - 12, L.pxH - yy, -6.5, 0, '#ff4060', true);
sfx.shoot();
}
if (this.stateT > 44) this.state = 'idle';
} else {
if (this.t % 34 === 0) {
const n = 10;
const off = this.t / 200;
for (let i = 0; i < n; i++) {
const a = off + (i / n) * Math.PI * 2;
this.shoot(L, cx, cy, Math.cos(a) * 2.6, Math.sin(a) * 2.6, '#ff5c7a');
}
sfx.shoot();
}
if (this.t % 170 === 0) {
const a = Math.atan2(player.cy - cy, player.cx - cx);
this.shoot(L, cx, cy, Math.cos(a) * 4.4, Math.sin(a) * 4.4, '#ffc63a', true);
}
}
}
// ---------------- 绘制 ----------------
draw(ctx, t) {
if (this.dead && this.deathT > 96) return;
const x = this.x, y = this.y, w = this.w, h = this.h;
const fl = this.flash > 0;
ctx.save();
if (this.dead) ctx.globalAlpha = Math.max(0, 1 - this.deathT / 96);
const body = fl ? '#fff' : null;
if (this.kind === 'guy') this.drawGuy(ctx, x, y, w, h, body, t);
else if (this.kind === 'mecha') this.drawMecha(ctx, x, y, w, h, body, t);
else this.drawDevil(ctx, x, y, w, h, body, t);
ctx.restore();
}
drawGuy(ctx, x, y, w, h, fl, t) {
const c = fl || '#2a1020', c2 = fl || '#5a1a34';
ctx.fillStyle = c;
ctx.beginPath(); ctx.ellipse(x + w / 2, y + h * 0.62, w * 0.42, h * 0.34, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = c2;
ctx.beginPath(); ctx.ellipse(x + w / 2, y + h * 0.3, w * 0.36, h * 0.3, 0, 0, Math.PI * 2); ctx.fill();
// 角
ctx.fillStyle = fl || '#c8305a';
ctx.beginPath();
ctx.moveTo(x + w * 0.2, y + h * 0.16); ctx.lineTo(x + w * 0.05, y - h * 0.12); ctx.lineTo(x + w * 0.34, y + h * 0.06);
ctx.closePath(); ctx.fill();
ctx.beginPath();
ctx.moveTo(x + w * 0.8, y + h * 0.16); ctx.lineTo(x + w * 0.95, y - h * 0.12); ctx.lineTo(x + w * 0.66, y + h * 0.06);
ctx.closePath(); ctx.fill();
// 眼
ctx.fillStyle = fl ? '#000' : '#ffe14a';
ctx.fillRect(x + w * 0.3, y + h * 0.28, w * 0.14, h * 0.1);
ctx.fillRect(x + w * 0.56, y + h * 0.28, w * 0.14, h * 0.1);
// 嘴
ctx.fillStyle = fl ? '#000' : '#801025';
ctx.fillRect(x + w * 0.34, y + h * 0.46, w * 0.32, h * 0.06);
if (this.phase >= 2) {
ctx.strokeStyle = fl ? '#000' : '#ff4060'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(x + w / 2, y + h / 2, w * 0.62 + Math.sin(t / 90) * 3, 0, Math.PI * 2); ctx.stroke();
}
}
drawMecha(ctx, x, y, w, h, fl, t) {
ctx.fillStyle = fl || '#3a4258';
ctx.fillRect(x + 4, y + 6, w - 8, h - 10);
ctx.fillStyle = fl || '#68728e';
ctx.fillRect(x + 8, y + 10, w - 16, h - 20);
// 眼
const blink = (Math.floor(t / 200) % 5) === 0;
ctx.fillStyle = fl ? '#000' : (this.state === 'dash' ? '#ff4060' : '#7ae0ff');
ctx.fillRect(x + w * 0.22, y + h * 0.34, w * 0.18, h * 0.14);
ctx.fillRect(x + w * 0.6, y + h * 0.34, w * 0.18, h * 0.14);
// 炮口
ctx.fillStyle = fl || '#2a2f40';
ctx.fillRect(x + w * 0.42, y + h - 8, w * 0.16, 10);
// 天线
ctx.fillStyle = fl || '#8a94ad';
ctx.fillRect(x + w / 2 - 1, y - 6, 2, 8);
ctx.fillStyle = (Math.floor(t / 120) % 2) ? '#ff4060' : '#601020';
ctx.beginPath(); ctx.arc(x + w / 2, y - 8, 3, 0, Math.PI * 2); ctx.fill();
// 推进器
if (this.state === 'dash') {
ctx.fillStyle = '#ffb040';
ctx.fillRect(x - 6, y + h * 0.4, 8, h * 0.2);
ctx.fillRect(x + w - 2, y + h * 0.4, 8, h * 0.2);
}
}
drawDevil(ctx, x, y, w, h, fl, t) {
// 翅膀
const fl2 = Math.sin(this.wing) * 8;
ctx.fillStyle = fl || '#4a0f22';
ctx.beginPath();
ctx.moveTo(x + 6, y + h * 0.4);
ctx.quadraticCurveTo(x - 26, y + h * 0.1 + fl2, x - 4, y + h * 0.72 + fl2);
ctx.closePath(); ctx.fill();
ctx.beginPath();
ctx.moveTo(x + w - 6, y + h * 0.4);
ctx.quadraticCurveTo(x + w + 26, y + h * 0.1 + fl2, x + w + 4, y + h * 0.72 + fl2);
ctx.closePath(); ctx.fill();
// 身体
ctx.fillStyle = fl || '#8e1030';
ctx.beginPath(); ctx.ellipse(x + w / 2, y + h * 0.6, w * 0.4, h * 0.33, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = fl || '#c01a3a';
ctx.beginPath(); ctx.ellipse(x + w / 2, y + h * 0.32, w * 0.34, h * 0.29, 0, 0, Math.PI * 2); ctx.fill();
// 角
ctx.fillStyle = fl || '#ffc63a';
ctx.beginPath();
ctx.moveTo(x + w * 0.18, y + h * 0.14); ctx.lineTo(x - w * 0.06, y - h * 0.16); ctx.lineTo(x + w * 0.32, y + h * 0.04);
ctx.closePath(); ctx.fill();
ctx.beginPath();
ctx.moveTo(x + w * 0.82, y + h * 0.14); ctx.lineTo(x + w * 1.06, y - h * 0.16); ctx.lineTo(x + w * 0.68, y + h * 0.04);
ctx.closePath(); ctx.fill();
// 眼(阶段变色)
const ec = this.phase === 3 ? '#7ae0ff' : this.phase === 2 ? '#ffb040' : '#ffe14a';
ctx.fillStyle = fl ? '#000' : ec;
ctx.fillRect(x + w * 0.26, y + h * 0.26, w * 0.16, h * 0.12);
ctx.fillRect(x + w * 0.58, y + h * 0.26, w * 0.16, h * 0.12);
// 牙
ctx.fillStyle = fl ? '#000' : '#fff';
for (let i = 0; i < 4; i++) ctx.fillRect(x + w * 0.32 + i * w * 0.1, y + h * 0.46, 4, 6);
}
}
export function bossName(kind) { return (DEFS[kind] || DEFS.guy).name; }
export { DEFS as BOSS_DEFS };
+90
View File
@@ -0,0 +1,90 @@
// 摄像机:跟随 / 锁定 / 缩放(坑向关的"摄像头"道具靠它搞事)
import { clamp, lerp } from './util.js';
export class Camera {
constructor(w = 800, h = 608) {
this.w = w; this.h = h;
this.x = 0; this.y = 0;
this.zoom = 1;
this.tz = 1;
this.mode = 'follow';
this.lockX = 0; this.lockY = 0;
this.shakeX = 0; this.shakeY = 0;
this.snapped = false;
}
reset(level, player) {
this.zoom = 1; this.tz = 1; this.mode = 'follow';
this.snapTo(player, level);
}
viewW() { return this.w / this.zoom; }
viewH() { return this.h / this.zoom; }
snapTo(player, level) {
this.x = clamp(player.cx - this.viewW() / 2, 0, Math.max(0, level.pxW - this.viewW()));
this.y = clamp(player.cy - this.viewH() / 2, 0, Math.max(0, level.pxH - this.viewH()));
this.mode = 'follow';
this.zoom = 1; this.tz = 1;
}
update(level, player, dt) {
const zone = level.camZone;
let tx, ty, tz = 1, speed = 0.16;
if (zone) {
if (zone.mode === 'lock') {
this.mode = 'lock';
tx = zone.lx !== null ? zone.lx : zone.x;
ty = zone.ly !== null ? zone.ly : zone.y;
tz = zone.zoom || 1;
speed = 0.05; // 缓慢移动,制造迷失感
} else if (zone.mode === 'zoom') {
this.mode = 'zoom';
tz = zone.zoom || 1;
tx = player.cx - this.w / tz / 2;
ty = player.cy - this.h / tz / 2;
speed = 0.14;
} else if (zone.mode === 'off') {
this.mode = 'off';
tx = this.x; ty = this.y; tz = zone.zoom || this.zoom; speed = 0;
}
} else {
this.mode = 'follow';
tx = player.cx - this.w / this.zoom / 2;
ty = player.cy - this.h / this.zoom / 2;
tz = 1;
speed = 0.16;
}
this.tz = lerp(this.tz, tz, 0.06);
if (Math.abs(this.tz - this.zoom) > 0.002) this.zoom = this.tz;
if (speed > 0) {
this.x = lerp(this.x, tx, speed);
this.y = lerp(this.y, ty, speed);
}
this.clampToLevel(level);
// 抖动
const sh = level.shake || 0;
if (sh > 0.2) {
this.shakeX = (Math.random() - 0.5) * sh;
this.shakeY = (Math.random() - 0.5) * sh;
} else { this.shakeX = 0; this.shakeY = 0; }
}
clampToLevel(level) {
const vw = this.viewW(), vh = this.viewH();
if (level.pxW <= vw) { this.x = (level.pxW - vw) / 2; }
else this.x = clamp(this.x, 0, level.pxW - vw);
if (level.pxH <= vh) { this.y = (level.pxH - vh) / 2; }
else this.y = clamp(this.y, 0, level.pxH - vh);
}
apply(ctx) {
ctx.translate(this.shakeX, this.shakeY);
if (this.zoom !== 1) ctx.scale(this.zoom, this.zoom);
ctx.translate(-this.x, -this.y);
}
}
+555
View File
@@ -0,0 +1,555 @@
// 自制关卡编辑器(多面地图 + 可变宽高 + 属性面板)
import { TILE } from './util.js';
import { Save } from './save.js';
import { makeCustomLevel } from './levels/index.js';
import * as S from './sprites.js';
const $ = s => document.querySelector(s);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
export const PALETTE = [
['#', '方块', '#6b6b7e'], ['@', '草地', '#4f9e46'], ['=', '砖块', '#a8543c'], ['M', '金属', '#5a6478'],
['%', '冰面', '#8fd8f0'], ['~', '水', '#2a6fd8'], ['-', '单向台', '#9aa6bd'], ['V', '消失块', '#7a7a8c'],
['^', '刺', '#c8c8d8'],
['*', '美味水果', '#e03050'], ['S', '出生点', '#3ddc84'], ['G', '存档点', '#b06bff'], ['X', '终点', '#ffc63a'],
['P', '手枪', '#b8b8c8'], ['F', '苹果', '#ff8095'], ['J', '跳刷新', '#3ddc84'], ['W', '传送门', '#a86bff'],
['T', '提示牌', '#c9a86b'], ['O', '炮台', '#6a6a80'], ['D', '掉落刺', '#8a5a6a'], ['C', '摄像头', '#7ae0ff'],
['B', 'BOSS', '#ff5c7a'], ['!', '触发器', '#ff9a3a'], ['.', '橡皮', '#20202c'],
];
// 每个方块类型可编辑的属性(属性面板按此渲染)
// type: portal(传送门目标) | text | num | select
const SCHEMA = {
'^': [{ type: 'select', key: 'dir', label: '方向', def: 'up', opts: [['up', '上'], ['down', '下'], ['left', '左'], ['right', '右']] }],
W: [{ type: 'portal' }],
T: [{ type: 'text', key: 'msg', label: '提示文字', placeholder: '这块牌子显示的话' }],
O: [
{ type: 'select', key: 'dir', label: '朝向', opts: [['left', '左'], ['right', '右'], ['up', '上'], ['down', '下']] },
{ type: 'num', key: 'period', label: '发射间隔(帧)', min: 10, max: 600, def: 90 },
{ type: 'num', key: 'speed', label: '子弹速度', min: 0.5, max: 10, step: 0.1, def: 2.4 },
{ type: 'num', key: 'offset', label: '初始延迟(帧)', min: 0, max: 600, def: 0 },
],
C: [
{ type: 'num', key: 'w', label: '区域宽(格)', min: 1, max: 40, def: 3 },
{ type: 'num', key: 'h', label: '区域高(格)', min: 1, max: 40, def: 3 },
{ type: 'select', key: 'mode', label: '镜头模式', opts: [['lock', '锁定'], ['zoom', '缩放'], ['follow-off', '跟随关闭']] },
{ type: 'num', key: 'zoom', label: '缩放倍数', min: 0.3, max: 3, step: 0.1, def: 1 },
],
B: [
{ type: 'select', key: 'kind', label: 'BOSS 类型', opts: [['guy', '小兵'], ['mecha', '机甲']] },
{ type: 'num', key: 'hp', label: '血量', min: 1, max: 999, def: 40 },
],
};
function charLabel(ch) { const it = PALETTE.find(p => p[0] === ch); return it ? it[1] : ch; }
// 把某个方块按「游戏内真实外观」画到 ctx 的 (px,py) 处 —— 编辑器所见即所得
function drawTileReal(ctx, ch, px, py, props, t) {
const P = props || {};
switch (ch) {
case '#': S.drawBlock(ctx, px, py, 0); break; // 方块
case '@': S.drawBlock(ctx, px, py, 1); break; // 草地
case '=': S.drawBlock(ctx, px, py, 2); break; // 砖块
case 'M': S.drawBlock(ctx, px, py, 3); break; // 金属
case '%': S.drawIce(ctx, px, py); break; // 冰面
case '~': S.drawWater(ctx, px, py, t); break; // 水
case '-': S.drawOneWay(ctx, px, py); break; // 单向台
case 'V': S.drawVanish(ctx, px, py, 0, t); break; // 消失块
case '^': { // 刺:真实三角形,按道具方向
const di = { up: 0, down: 1, left: 2, right: 3 }[P.dir || 'up'] || 0;
S.drawSpike(ctx, px, py, di, t);
break;
}
case '*': S.drawKiller(ctx, px, py, t); break; // 美味水果
case 'D': S.drawDropSpike(ctx, { x: px, y: py, falling: false }, t); break; // 掉落刺
case 'X': S.drawGoal(ctx, { x: px, y: py, w: TILE, h: TILE }, t); break; // 终点
case 'G': S.drawSave(ctx, { x: px, y: py, w: TILE, h: TILE, active: false }, t); break; // 存档点
case 'P': S.drawGun(ctx, { x: px, y: py }, t); break; // 手枪
case 'F': S.drawApple(ctx, { x: px, y: py, w: TILE, h: TILE }, t); break; // 苹果
case 'J': S.drawJumpRef(ctx, px, py, t); break; // 跳刷新
case 'W': S.drawWarp(ctx, { x: px, y: py, w: TILE, h: TILE }, t); break; // 传送门
case 'T': S.drawSign(ctx, { x: px, y: py, w: TILE, h: TILE }, t); break; // 提示牌
case 'O': S.drawTurret(ctx, { x: px, y: py, dir: P.dir || 'left' }, t); break; // 炮台
case 'C': S.drawCamera(ctx, { x: px, y: py, w: TILE, h: TILE }, t); break; // 摄像头
case 'S': S.drawKid(ctx, { // 出生点:画一个小人
x: px + (TILE - 11) / 2, y: py + (TILE - 21), w: 11, h: 21,
facing: 1, grounded: true, hasGun: false, dead: false,
}, t); break;
default: drawMarker(ctx, px, py, ch); break; // BOSS / 触发器等无独立美术:色块+字母兜底
}
}
// 没有独立 sprite 的方块(BOSS / 触发器等):保留「色块 + 字母」保证可见
function drawMarker(ctx, px, py, ch) {
const item = PALETTE.find(p => p[0] === ch);
const col = item ? item[2] : '#555';
ctx.fillStyle = col; ctx.globalAlpha = 0.85;
ctx.fillRect(px + 1, py + 1, TILE - 2, TILE - 2);
ctx.globalAlpha = 1;
ctx.fillStyle = '#fff';
ctx.font = 'bold 14px monospace';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(ch, px + TILE / 2, py + TILE / 2);
}
// 编辑器中刺统一用 '^',方向存在 props.dir;导出时翻译成引擎的四个字符
const SPIKE_CHAR = { up: '^', down: 'v', left: '<', right: '>' };
const SPIKE_DIR = { '^': 'up', 'v': 'down', '<': 'left', '>': 'right' };
export const Editor = {
api: {},
map: null, w: 25, sel: '#',
scroll: 0, drag: 0, cur: null,
canvas: null, ctx: null,
// 多面地图状态
faces: null, face: 0,
// 当前选中的方块坐标(属性面板依据它渲染)
selTile: null,
init(api) {
this.api = api;
this.canvas = $('#ed-canvas');
this.ctx = this.canvas.getContext('2d');
this.buildPalette();
this.bind();
$('#ed-w').addEventListener('change', () => this.resize(+$('#ed-w').value, +$('#ed-h').value));
$('#ed-h').addEventListener('change', () => this.resize(+$('#ed-w').value, +$('#ed-h').value));
},
buildPalette() {
const p = $('#palette');
p.innerHTML = '';
PALETTE.forEach(([ch, label]) => {
const d = document.createElement('div');
d.className = 'pal' + (ch === this.sel ? ' on' : '');
// 用真实绘制函数渲染缩略图,所见即所得
const cv = document.createElement('canvas');
cv.className = 'pal-cv'; cv.width = TILE; cv.height = TILE;
drawTileReal(cv.getContext('2d'), ch, 0, 0, null, 0);
d.appendChild(cv);
const sp = document.createElement('span');
sp.textContent = label;
d.appendChild(sp);
d.onclick = () => {
this.sel = ch;
Array.from(p.children).forEach(c => c.classList.remove('on'));
d.classList.add('on');
};
p.appendChild(d);
});
},
bind() {
const c = this.canvas;
const pos = e => {
const r = c.getBoundingClientRect();
const sx = (e.clientX - r.left) * (c.width / r.width);
const sy = (e.clientY - r.top) * (c.height / r.height);
return { tx: Math.floor((sx + this.scroll) / TILE), ty: Math.floor(sy / TILE) };
};
const act = (e, erase) => {
const f = this.curFace();
const { tx, ty } = pos(e);
if (tx < 0 || ty < 0 || tx >= f.w || ty >= f.h) return;
// 无论手上拿的是什么方块,点击格子都选中它,属性面板立即显示该方块的属性
this.selTile = { tx, ty };
const prev = f.grid[ty][tx];
const ch = erase ? '.' : (this.sel === '.' ? '.' : this.sel);
// 放置不覆盖:放实方块时若该格已有方块则跳过,仅选中查看属性
if (!erase && ch !== '.' && prev !== '.') { this.renderProps(); return; }
// 门的增删:放上传送门自动登记一扇门;擦掉或覆盖传送门则移除对应门
if (prev === 'W' && ch !== 'W') this.removeDoor(f, tx, ty);
if (ch === 'W' && prev !== 'W') { f.seq = (f.seq || 0) + 1; f.doors.push({ id: f.seq, tx, ty, to: null }); }
// 改变方块种类时清空该格属性(属性按类型存储)
if (prev !== ch) f.props[ty][tx] = null;
f.grid[ty][tx] = ch;
this.draw();
this.renderProps();
};
c.addEventListener('mousedown', e => {
e.preventDefault();
this.drag = e.button === 2 ? 2 : 1;
act(e, e.button === 2);
});
c.addEventListener('mousemove', e => { if (this.drag) act(e, this.drag === 2); });
addEventListener('mouseup', () => { this.drag = 0; });
c.addEventListener('contextmenu', e => e.preventDefault());
c.addEventListener('wheel', e => {
e.preventDefault();
this.scroll = Math.max(0, Math.min((this.curFace().w - 25) * TILE, this.scroll + Math.sign(e.deltaY) * TILE * 2));
this.draw();
}, { passive: false });
const on = (actName, fn) => { const el = document.querySelector(`[data-act="${actName}"]`); if (el) el.onclick = fn; };
on('ed-resize', () => this.resize(+$('#ed-w').value, +$('#ed-h').value));
on('ed-fill', () => { const f = this.curFace(); for (let x = 0; x < f.w; x++) f.grid[f.h - 1][x] = '#'; this.draw(); });
on('ed-clear', () => { if (typeof confirm === 'function' && !confirm('清空当前面?')) return; const f = this.curFace(); f.grid = blank(f.w, f.h); f.doors = []; f.props = propsBlank(f.w, f.h); this.selTile = null; this.draw(); this.renderProps(); });
on('ed-test', () => this.test());
on('ed-save', () => this.save());
on('ed-import', () => this.openImport());
on('ed-import-cancel', () => this.closeImport());
on('ed-addface', () => this.addFace());
on('ed-copyface', () => this.copyFace());
on('ed-delface', () => this.delFace());
},
// ---------------- 多面地图状态 ----------------
curFace() { return this.faces[this.face]; },
open() {
// 从菜单进入编辑器:始终是新地图(宽高沿用输入框里的值)
const w = +$('#ed-w').value || 25, h = +$('#ed-h').value || 19;
this.faces = [{ name: '面1', w, h, seq: 0, grid: blank(w, h), doors: [], props: propsBlank(w, h) }];
this.face = 0;
this.cur = null; // 未关联任何已存地图 → 首次保存为新建
this.show();
},
/** 仅重绘当前状态(不从零重置):用于试玩后「返回编辑器」等场景,保留正在编辑的地图 */
show() {
if (!this.faces) { this.open(); return; }
this.selTile = null;
$('#ed-w').value = this.curFace().w;
$('#ed-h').value = this.curFace().h;
this.draw();
this.renderFaces();
this.renderProps();
this.updateSaveState();
},
/** 「保存」按钮旁的提示:会更新哪张图,还是另存为新图 */
updateSaveState() {
const el = $('#ed-savestate');
if (!el) return;
const l = this.cur ? Save.customs().find(o => o.id === this.cur) : null;
el.textContent = l ? '→ 更新「' + (l.name || 'MY MAP') + '」' : '→ 另存为新图';
el.classList.toggle('on', !!l);
},
resize(w, h) {
w = clamp(w || 25, 12, 160);
h = clamp(h || 19, 8, 80);
const f = this.curFace();
const og = f.grid, op = f.props;
f.grid = blank(w, h);
f.props = propsBlank(w, h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
if (og[y] && og[y][x] !== undefined) f.grid[y][x] = og[y][x];
if (op[y] && op[y][x] !== undefined) f.props[y][x] = op[y][x];
}
f.doors = f.doors.filter(d => d.tx < w && d.ty < h);
f.w = w; f.h = h;
$('#ed-w').value = w; $('#ed-h').value = h;
this.canvas.height = h * TILE;
this.selTile = null;
this.draw();
this.renderProps();
},
addFace() {
const w = this.curFace().w, h = this.curFace().h;
this.faces.push({ name: '面' + (this.faces.length + 1), w, h, seq: 0, grid: blank(w, h), doors: [], props: propsBlank(w, h) });
this.face = this.faces.length - 1;
this.afterFaceSwitch();
},
copyFace() {
const f = this.curFace();
const copy = {
name: f.name + ' 副本', w: f.w, h: f.h, seq: f.seq,
grid: f.grid.map(r => r.slice()),
doors: f.doors.map(d => ({ ...d })),
props: f.props.map(r => r.map(c => (c ? { ...c } : null))),
};
this.faces.push(copy);
this.face = this.faces.length - 1;
this.afterFaceSwitch();
},
delFace() {
if (this.faces.length <= 1) { alert('至少保留一个面'); return; }
if (typeof confirm === 'function' && !confirm('删除「' + this.curFace().name + '」?该面的门与连接都会消失')) return;
this.faces.splice(this.face, 1);
this.face = Math.max(0, this.face - 1);
this.afterFaceSwitch();
},
afterFaceSwitch() {
$('#ed-w').value = this.curFace().w;
$('#ed-h').value = this.curFace().h;
this.scroll = 0;
this.selTile = null;
this.draw();
this.renderFaces();
this.renderProps();
},
removeDoor(f, tx, ty) {
const i = f.doors.findIndex(d => d.tx === tx && d.ty === ty);
if (i >= 0) f.doors.splice(i, 1);
},
// ---------------- 绘制 ----------------
draw() {
const ctx = this.ctx, c = this.canvas;
const f = this.curFace();
c.width = 800; c.height = f.h * TILE;
ctx.fillStyle = '#101018'; ctx.fillRect(0, 0, c.width, c.height);
ctx.save();
ctx.translate(-this.scroll, 0);
const t = 0; // 编辑器为静态预览,不跑动画
for (let y = 0; y < f.h; y++) {
for (let x = 0; x < f.w; x++) {
const ch = f.grid[y][x];
const px = x * TILE, py = y * TILE;
// 真实外观绘制(刺→三角形,方块→纹理,实体→对应精灵)
if (ch !== '.') drawTileReal(ctx, ch, px, py, f.props[y][x] || null, t);
// 淡网格线(编辑对位用)
ctx.strokeStyle = 'rgba(255,255,255,.06)';
ctx.lineWidth = 1;
ctx.strokeRect(px + .5, py + .5, TILE - 1, TILE - 1);
// 传送门:叠加门编号与连接状态(编辑器元数据,游戏内无此显示)
if (ch === 'W') {
const d = f.doors.find(o => o.tx === x && o.ty === y);
ctx.fillStyle = (d && d.to) ? '#bfffd0' : '#ffe6a0';
ctx.font = 'bold 9px monospace';
ctx.textAlign = 'left'; ctx.textBaseline = 'top';
ctx.fillText('W' + (d ? d.id : ''), px + 2, py + 2);
}
}
}
// 选中方块高亮
if (this.selTile && this.selTile.tx >= 0 && this.selTile.ty >= 0 && this.selTile.tx < f.w && this.selTile.ty < f.h) {
const sx = this.selTile.tx * TILE, sy = this.selTile.ty * TILE;
ctx.strokeStyle = '#ffd23a'; ctx.lineWidth = 2;
ctx.strokeRect(sx + 1, sy + 1, TILE - 2, TILE - 2);
}
ctx.restore();
},
// ---------------- 面列表面板 ----------------
renderFaces() {
const box = $('#ed-faces');
if (!box) return;
box.innerHTML = '';
this.faces.forEach((f, i) => {
const d = document.createElement('div');
d.className = 'face-row' + (i === this.face ? ' on' : '');
d.innerHTML = `<input class="face-name" value="${escapeHtml(f.name)}" title="面名称"><span class="face-wh">${f.w}×${f.h} · ${f.doors.length}门</span>`;
d.querySelector('.face-name').addEventListener('change', e => { f.name = e.target.value; });
d.querySelector('.face-name').addEventListener('click', e => e.stopPropagation());
d.onclick = () => { this.face = i; this.afterFaceSwitch(); };
box.appendChild(d);
});
},
// ---------------- 属性面板(选中方块) ----------------
renderProps() {
const box = $('#ed-props');
if (!box) return;
const f = this.curFace();
if (!this.selTile) { box.innerHTML = '<div class="prop-empty">点击画布上的方块,查看并设置它的属性</div>'; return; }
const { tx, ty } = this.selTile;
if (tx < 0 || ty < 0 || tx >= f.w || ty >= f.h) { box.innerHTML = '<div class="prop-empty">(越界)</div>'; return; }
const ch = f.grid[ty][tx];
const label = charLabel(ch);
const fields = SCHEMA[ch];
if (!fields) {
box.innerHTML = `<div class="prop-head">「${ch}」 ${label}</div><div class="prop-empty">该方块没有可设置的属性</div>`;
return;
}
box.innerHTML = `<div class="prop-head">「${ch}」 ${label}</div>`;
for (const fd of fields) {
const row = document.createElement('div');
row.className = 'prop-row';
if (fd.type === 'portal') {
const door = f.doors.find(d => d.tx === tx && d.ty === ty);
if (!door) { row.innerHTML = '<span class="prop-lab">跳转到下一关</span><span class="prop-note">(此格未登记为门,请重新放置 W)</span>'; box.appendChild(row); continue; }
const cur = door.to || null;
const tf = cur ? cur.face : this.face;
const td = cur ? cur.door : -1;
const faceOpts = this.faces.map((gf, gi) => `<option value="${gi}" ${gi === tf ? 'selected' : ''}>面${gi + 1}${gf.name !== ('面' + (gi + 1)) ? '·' + escapeHtml(gf.name) : ''}</option>`).join('');
const tface = this.faces[tf];
const doorOpts = (tface.doors.length
? tface.doors.filter(od => !(od.id === door.id && tf === this.face)).map(od => `<option value="${od.id}" ${td === od.id ? 'selected' : ''}>门${od.id}</option>`).join('')
: '') || '<option value="-1">(该面暂无其他门)</option>';
row.innerHTML = `<span class="prop-lab">跳转到下一关</span><div class="prop-ctl"><select class="p-face">${faceOpts}</select><select class="p-door">${doorOpts}</select></div>`;
const fsel = row.querySelector('.p-face');
const dsel = row.querySelector('.p-door');
const apply = () => {
const ntf = +fsel.value, ntd = +dsel.value;
door.to = (ntd >= 0) ? { face: ntf, door: ntd } : null;
this.draw();
this.renderProps();
};
fsel.onchange = apply;
dsel.onchange = apply;
} else if (fd.type === 'text') {
const val = (f.props[ty][tx] || {})[fd.key] || '';
row.innerHTML = `<span class="prop-lab">${fd.label}</span><input class="prop-in" type="text" placeholder="${fd.placeholder || ''}" value="${escapeHtml(val)}">`;
const inp = row.querySelector('.prop-in');
inp.oninput = () => { ensureProp(f, tx, ty)[fd.key] = inp.value; };
} else if (fd.type === 'num') {
const raw = (f.props[ty][tx] || {})[fd.key];
const val = raw !== undefined && raw !== null && raw !== '' ? raw : (fd.def !== undefined ? fd.def : '');
row.innerHTML = `<span class="prop-lab">${fd.label}</span><input class="prop-in" type="number" min="${fd.min !== undefined ? fd.min : ''}" max="${fd.max !== undefined ? fd.max : ''}" step="${fd.step !== undefined ? fd.step : 1}" value="${val}">`;
const inp = row.querySelector('.prop-in');
inp.oninput = () => {
const v = inp.value === '' ? (fd.def !== undefined ? fd.def : null) : (fd.step && String(fd.step).includes('.') ? +inp.value : +inp.value);
ensureProp(f, tx, ty)[fd.key] = v;
};
} else if (fd.type === 'select') {
const cur = (f.props[ty][tx] || {})[fd.key];
const val = cur !== undefined && cur !== '' ? cur : (fd.def !== undefined ? fd.def : '');
const opts = fd.opts.map(([v, t]) => `<option value="${v}" ${val === v ? 'selected' : ''}>${t}</option>`).join('');
row.innerHTML = `<span class="prop-lab">${fd.label}</span><select class="prop-in">${opts}</select>`;
const sel = row.querySelector('.prop-in');
sel.onchange = () => { ensureProp(f, tx, ty)[fd.key] = sel.value; };
}
box.appendChild(row);
}
},
// ---------------- 数据 ----------------
buildData() {
const faces = this.faces.map(f => {
// 编辑器刺统一为 '^'+props.dir,导出时按方向翻译成引擎字符 ^ v < >
const grid = f.grid.map((r, y) => r.map((ch, x) => {
if (ch === '^') return SPIKE_CHAR[((f.props[y][x] || {}).dir) || 'up'];
return ch;
}).join(''));
// 按扫描顺序收集各类型属性,整型数组(引擎按扫描下标读取)
const messages = [], turrets = [], camzones = [], bosses = [];
for (let y = 0; y < f.h; y++) for (let x = 0; x < f.w; x++) {
const ch = f.grid[y][x];
const p = f.props[y][x];
if (ch === 'T' && p && p.msg !== undefined && p.msg !== '') messages.push(p.msg);
if (ch === 'O' && p) turrets.push({ dir: p.dir || 'left', period: +(p.period || 90), speed: +(p.speed || 2.4), offset: +(p.offset || 0), kind: p.kind || 'ball' });
if (ch === 'C' && p) camzones.push({ w: +(p.w || 3), h: +(p.h || 3), mode: p.mode || 'lock', zoom: +(p.zoom || 1) });
if (ch === 'B' && p) bosses.push({ kind: p.kind || 'guy', hp: +(p.hp || 40) });
}
return {
name: f.name,
width: f.w,
height: f.h,
grid,
doors: f.doors.map(d => ({ id: d.id, tx: d.tx, ty: d.ty, to: d.to || null })),
messages, turrets, camzones, bosses,
};
});
return {
name: ($('#ed-name').value || 'MY MAP').toUpperCase(),
type: 'custom',
startFace: 0,
faces,
};
},
validate() {
for (let i = 0; i < this.faces.length; i++) {
const g = this.faces[i].grid.map(r => r.join(''));
const s = g.join('').split('S').length - 1;
const x = g.join('').split('X').length - 1;
if (s !== 1) return `面${i + 1}(${this.faces[i].name})必须且只能有 1 个 S,当前 ${s} 个`;
if (x < 1) return `面${i + 1}(${this.faces[i].name})至少要 1 个 X(终点)`;
}
// 门不能指向自己所在格子
for (let i = 0; i < this.faces.length; i++) {
for (const d of this.faces[i].doors) {
if (d.to && d.to.face === i && d.to.door === d.id) return `面${i + 1} 的门${d.id} 不能指向自己`;
}
}
return null;
},
test() {
const err = this.validate();
if (err) { alert(err); return; }
this.api.startLevel(makeCustomLevel(this.buildData()));
},
save() {
const err = this.validate();
if (err) { alert(err); return; }
let lv = makeCustomLevel(this.buildData());
if (this.cur) lv.id = this.cur; // 保存当前地图:沿用已有 id,就地更新
Save.updateCustom(lv);
this.cur = lv.id;
this.updateSaveState();
this.api.refresh?.();
},
// ---------------- 导入地图(从已保存的地图里选) ----------------
openImport() {
const box = $('#ed-importbox');
if (!box) return;
const list = $('#ed-import-list');
const customs = Save.customs();
list.innerHTML = '';
if (!customs.length) {
list.innerHTML = '<div class="imp-empty">还没有保存过的地图,先「保存」一个吧</div>';
} else {
customs.forEach(l => {
const fn = (l.faces || []).length;
const d = document.createElement('div');
d.className = 'imp-row' + (l.id === this.cur ? ' on' : '');
d.innerHTML = `<span class="imp-nm">${escapeHtml(l.name || 'MY MAP')}</span><span class="imp-meta">${fn ? fn + ' 面' : '单关'}</span>`;
d.onclick = () => this.pickImport(l.id);
list.appendChild(d);
});
}
box.classList.remove('hidden');
},
closeImport() { $('#ed-importbox')?.classList.add('hidden'); },
pickImport(id) {
const l = Save.customs().find(o => o.id === id);
if (!l) return;
this.cur = l.id;
this.hydrate(l);
$('#ed-name').value = l.name || '';
this.closeImport();
this.afterFaceSwitch();
this.updateSaveState();
},
// 从存档/数据对象恢复多面 + 每格属性(按扫描顺序回填 messages/turrets/camzones/bosses)
hydrate(o) {
this.faces = o.faces.map(f => {
const w = f.width || (f.grid[0] ? f.grid[0].length : 25);
const h = f.height || f.grid.length;
const grid = f.grid.map(r => r.split(''));
const props = propsBlank(w, h);
const face = {
name: f.name || '面',
w, h,
seq: (f.doors || []).reduce((m, d) => Math.max(m, d.id), 0),
grid,
doors: (f.doors || []).map(d => ({ id: d.id, tx: d.tx, ty: d.ty, to: d.to || null })),
props,
};
let mi = 0, ti = 0, ci = 0, bi = 0;
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
const ch = grid[y][x];
if (ch === 'T') { const m = (f.messages || [])[mi++]; if (m !== undefined) props[y][x] = { msg: m }; }
else if (ch === 'O') { const t = (f.turrets || [])[ti++]; if (t) props[y][x] = { ...t }; }
else if (ch === 'C') { const c = (f.camzones || [])[ci++]; if (c) props[y][x] = { ...c }; }
else if (ch === 'B') { const b = (f.bosses || [])[bi++]; if (b) props[y][x] = { ...b }; }
// 引擎的四个刺字符 ^ v < > 统一还原为编辑器 '^' + props.dir
else if (SPIKE_DIR[ch] !== undefined) { grid[y][x] = '^'; props[y][x] = { dir: SPIKE_DIR[ch] }; }
}
return face;
});
this.face = 0;
},
};
function blank(w, h) {
return Array.from({ length: h }, () => Array.from({ length: w }, () => '.'));
}
function propsBlank(w, h) {
return Array.from({ length: h }, () => Array.from({ length: w }, () => null));
}
function ensureProp(f, tx, ty) {
if (!f.props[ty][tx]) f.props[ty][tx] = {};
return f.props[ty][tx];
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
+92
View File
@@ -0,0 +1,92 @@
// 输入:IWBT 经典键位(Shift 跳 / Z 跳 / X 射击 / R 重来)
export const BIND = {
left: ['ArrowLeft', 'KeyA'],
right: ['ArrowRight', 'KeyD'],
up: ['ArrowUp', 'KeyW'],
down: ['ArrowDown', 'KeyS'],
jump: ['ShiftLeft', 'ShiftRight', 'Space', 'KeyZ', 'KeyN'],
shoot: ['KeyX', 'KeyJ', 'KeyC', 'KeyM'],
suicide: ['KeyR'], // IWBT 标准:自杀并回到最近存档点
restart: ['Backspace'], // 整关从头再来(放弃所有存档点)
pause: ['Escape', 'KeyP'],
menu: ['KeyQ'],
};
// 出厂键位快照(供设置里的「恢复默认」使用)
const DEFAULT_BIND = JSON.parse(JSON.stringify(BIND));
const down = new Set(); // 当前按住的原始 code
const now = {}; // action 是否按下
const prev = {}; // 上一帧
const touch = {}; // action -> bool(来自触屏虚拟按键)
const blocked = new Set(['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Tab']);
export const Input = {
enabled: true,
/** 是否按下 */
is(action) { return !!now[action]; },
/** 本帧刚按下 */
hit(action) { return !!now[action] && !prev[action]; },
/** 本帧刚松开 */
released(action) { return !now[action] && !!prev[action]; },
raw(code) { return down.has(code); },
anyHit() { for (const k in now) if (now[k] && !prev[k]) return true; return false; },
clear() {
down.clear();
for (const k in now) now[k] = false;
for (const k in prev) prev[k] = false;
},
/** 每逻辑帧末尾调用 */
endFrame() {
for (const k in now) prev[k] = now[k];
},
};
function refresh() {
for (const act in BIND) {
let v = false;
for (const c of BIND[act]) if (down.has(c)) { v = true; break; }
if (touch[act]) v = true; // 触屏虚拟按键
now[act] = Input.enabled ? v : false;
}
}
// ---------------- 触屏虚拟按键接口 ----------------
export function setTouch(action, on) {
if (!(action in touch)) touch[action] = false;
if (touch[action] === on) return;
touch[action] = on;
refresh();
}
export function clearTouch() {
let any = false;
for (const k in touch) if (touch[k]) { touch[k] = false; any = true; }
if (any) refresh();
}
addEventListener('keydown', e => {
if (blocked.has(e.code)) e.preventDefault();
if (e.repeat) return;
down.add(e.code);
refresh();
});
addEventListener('keyup', e => {
down.delete(e.code);
refresh();
});
addEventListener('blur', () => { down.clear(); refresh(); });
// ---------------- 键位自定义(设置界面调用) ----------------
/** 返回一份出厂键位的深拷贝 */
export function defaultBindings() { return JSON.parse(JSON.stringify(DEFAULT_BIND)); }
/** 用一份 {action: [code,...]} 映射覆盖当前生效键位(设置确定后调用) */
export function applyBindings(map) {
if (!map) return;
for (const act in map) if (act in BIND) BIND[act] = map[act].slice();
}
// 初始化
for (const act in BIND) { now[act] = false; prev[act] = false; }
export const ACTIONS = Object.keys(BIND);
+712
View File
@@ -0,0 +1,712 @@
// 关卡解析与运行时:ASCII 网格 -> tiles + 实体 + 事件
import { TILE, clamp, overlap, hashNoise } from './util.js';
import * as S from './sprites.js';
import { sfx } from './audio.js';
import { Particles } from './particles.js';
import { Boss } from './boss.js';
export const T = {
EMPTY: 0, BLOCK: 1, GRASS: 2, BRICK: 3, METAL: 4,
ICE: 5, WATER: 6, ONEWAY: 7, KILLER: 8, VANISH: 9,
SPIKE_U: 10, SPIKE_D: 11, SPIKE_L: 12, SPIKE_R: 13,
};
const SOLID = { 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 9: 1 };
const DEADLY = { 8: 1, 10: 1, 11: 1, 12: 1, 13: 1 };
/** ASCII 字符 -> tile */
export const CHAR2TILE = {
'#': T.BLOCK, '@': T.GRASS, '=': T.BRICK, 'M': T.METAL,
'%': T.ICE, '~': T.WATER, '-': T.ONEWAY, '*': T.KILLER, 'V': T.VANISH,
'^': T.SPIKE_U, 'v': T.SPIKE_D, '<': T.SPIKE_L, '>': T.SPIKE_R,
};
/** ASCII 字符 -> 实体类型 */
const CHAR2ENT = {
S: 'spawn', G: 'save', X: 'goal', P: 'gun', F: 'apple', J: 'jumpref',
W: 'warp', T: 'sign', O: 'turret', B: 'boss', D: 'dropspike',
C: 'camzone', '!': 'trigger',
};
const ESIZE = {
spawn: [16, 26], save: [20, 22], goal: [30, 42], gun: [28, 24], apple: [18, 20],
jumpref: [26, 26], warp: [28, 28], sign: [30, 26], turret: [32, 32],
boss: [64, 64], dropspike: [32, 32], camzone: [96, 96], trigger: [32, 32],
};
export class Level {
constructor(data) {
this.data = data;
this.name = data.name || 'STAGE';
this.type = data.type || 'jump';
this.parse(data);
this.particles = new Particles();
this.reset(true);
}
// ---------------- 解析 ----------------
parse(data) {
const rows = data.grid || [];
this.h = rows.length || 19;
this.w = data.width || Math.max(...rows.map(r => r.length), 25);
this.pxW = this.w * TILE;
this.pxH = this.h * TILE;
this.tiles = [];
const srcEntities = [];
const order = { warp: 0, boss: 0, sign: 0, turret: 0, camzone: 0, trigger: 0 };
for (let y = 0; y < this.h; y++) {
const line = rows[y] || '';
const row = [];
for (let x = 0; x < this.w; x++) {
const ch = line[x] || ' ';
if (CHAR2TILE[ch] !== undefined) {
row.push(CHAR2TILE[ch]);
} else if (CHAR2ENT[ch] !== undefined) {
const type = CHAR2ENT[ch];
const [ew, eh] = ESIZE[type];
const idx = order[type] !== undefined ? order[type]++ : 0;
srcEntities.push({ type, idx, tx: x, ty: y, ch });
row.push(T.EMPTY);
} else row.push(T.EMPTY);
}
this.tiles.push(row);
}
// 构建实体
this.srcEntities = srcEntities;
this.moversSrc = data.movers || [];
this.eventSrc = data.events || [];
this.msgs = data.messages || [];
this.bossSrc = data.bosses || [];
this.warpSrc = data.warps || [];
this.turretSrc = data.turrets || [];
this.camSrc = data.camzones || [];
this.spawnExtra = data.spawn || null;
this.hint = data.hint || '';
this.bgTheme = data.bg || (this.type === 'boss' ? 'boss' : this.type === 'troll' ? 'troll' : this.type === 'endur' ? 'endur' : 'jump');
}
/** 完整重置(死亡 / 重开) */
reset(full = false) {
// tiles 状态(vanish 等)
if (full) { this.deathMarks = []; this.deathFX = []; } // 血迹/死亡特效只在整关重开时清空,复活后保留
this.vanish = new Map();
this.bullets = [];
this.ebullets = [];
this.entities = [];
this.movers = [];
this.bosses = [];
this.events = [];
this.time = 0;
this.toast = null;
this.toastT = 0;
this.particles?.clear();
this.shake = 0;
this.beat = false;
// 实体实例化
let saveNo = 0;
for (const s of this.srcEntities) {
const [ew, eh] = ESIZE[s.type];
const e = {
type: s.type, idx: s.idx,
tx: s.tx, ty: s.ty,
x: s.tx * TILE + (TILE - ew) / 2,
y: s.ty * TILE + (TILE - eh),
w: ew, h: eh,
active: false, dead: false, t: 0,
};
if (s.type === 'goal') e.y = s.ty * TILE + TILE - eh;
if (s.type === 'save') { e.fake = false; e.no = ++saveNo; }
if (s.type === 'sign') e.text = this.msgs[e.idx] || '...';
if (s.type === 'turret') {
const cfg = this.turretSrc[e.idx] || {};
e.dir = cfg.dir || 'left';
e.period = cfg.period || 90;
e.speed = cfg.speed || 2.4;
e.timer = cfg.offset || 0;
e.kind = cfg.kind || 'ball';
}
if (s.type === 'warp') {
const cfg = this.warpSrc[e.idx] || {};
// 自制多面地图:门的目标直接挂在 door.to 上
// door.to 可以是跨面 {face, door}(自制门),或原有 'spawn' / {x,y}(内置同关传送)
const door = (this.data.doors || []).find(d => d.tx === s.tx && d.ty === s.ty);
e.doorId = door ? door.id : e.idx;
e.pair = cfg.pair !== undefined ? cfg.pair : (e.idx % 2 === 0 ? e.idx + 1 : e.idx - 1);
e.to = (door && door.to) ? door.to : (cfg.to || null);
e.cool = 0;
e.hidden = !!cfg.hidden;
}
if (s.type === 'camzone') {
const cfg = this.camSrc[e.idx] || {};
e.w = (cfg.w || 3) * TILE; e.h = (cfg.h || 3) * TILE;
e.x = s.tx * TILE; e.y = s.ty * TILE;
e.mode = cfg.mode || 'lock'; // lock | zoom | follow-off
e.zoom = cfg.zoom || 1;
e.lx = cfg.lx !== undefined ? cfg.lx * TILE : null;
e.ly = cfg.ly !== undefined ? cfg.ly * TILE : null;
}
if (s.type === 'dropspike') {
e.falling = false; e.vy = 0; e.homeY = e.y;
e.triggerX = (this.srcEntities.length ? 0 : 0);
}
if (s.type === 'boss') {
const cfg = this.bossSrc[e.idx] || { kind: 'guy' };
e.kind = cfg.kind || 'guy';
e.hp = cfg.hp || 40;
e.w = cfg.w || 64; e.h = cfg.h || 64;
e.x = s.tx * TILE + TILE / 2 - e.w / 2;
e.y = s.ty * TILE + TILE - e.h;
}
this.entities.push(e);
}
// 移动平台
for (const m of this.moversSrc) {
const path = (m.path || []).map(p => ({ x: p[0] * TILE, y: p[1] * TILE }));
const a = path[0] || { x: m.x * TILE, y: m.y * TILE };
this.movers.push({
x: a.x, y: a.y,
w: (m.w || 3) * TILE, h: (m.h || 1) * TILE,
path, i: 0, dir: 1, speed: m.speed || 1.2, t: 0,
mode: m.mode || 'loop', // loop | pingpong
dx: 0, dy: 0,
ax: a.x, ay: a.y, aw: (m.w || 3) * TILE, ah: (m.h || 1) * TILE,
bx: (path[1] || a).x, by: (path[1] || a).y,
});
}
// 事件(坑向触发器)
for (const ev of this.eventSrc) {
this.events.push({
x: ev.x * TILE, y: ev.y * TILE, w: (ev.w || 1) * TILE, h: (ev.h || 1) * TILE,
once: ev.once !== false, fired: false,
actions: ev.actions || [], hidden: ev.hidden !== false,
});
}
// 补齐未在 ASCII 中放置的摄像头区域(camzones 数组独立定义)
const camPlaced = this.srcEntities.filter(s => s.type === 'camzone').length;
for (let i = camPlaced; i < this.camSrc.length; i++) {
const cfg = this.camSrc[i];
this.entities.push({
type: 'camzone', idx: i, tx: cfg.x, ty: cfg.y,
x: cfg.x * TILE, y: cfg.y * TILE,
w: (cfg.w || 3) * TILE, h: (cfg.h || 3) * TILE,
mode: cfg.mode || 'lock', zoom: cfg.zoom || 1,
lx: cfg.lx !== undefined ? cfg.lx * TILE : null,
ly: cfg.ly !== undefined ? cfg.ly * TILE : null,
active: false, dead: false, t: 0,
});
}
// BOSS
for (const e of this.entities) {
if (e.type !== 'boss') continue;
this.bosses.push(new Boss(this, e));
}
// 出生点
const sp = this.entities.find(e => e.type === 'spawn');
this.spawn = sp
? { x: sp.x + sp.w / 2 - 5.5, y: sp.y + sp.h - 21 }
: (this.spawnExtra ? { x: this.spawnExtra[0] * TILE, y: this.spawnExtra[1] * TILE } : { x: 40, y: 40 });
// 总苹果数 / 存档点数
this.totalApples = this.entities.filter(e => e.type === 'apple').length;
this.totalSaves = saveNo;
}
/** 死亡后的软重置:保留存档点与已拾取道具,其余复位。
* 粒子与震屏是"演出层":不清场——无论主动按 R 还是被动死亡后秒按 R,
* 死亡特效都留在死亡位置自然播完(粒子 34 帧 / 冲击环 14 帧 / 震屏衰减),
* 重生只重置关卡逻辑状态,不掐断演出。整关重开(reset(true))才会清空 */
softReset() {
this.vanish.clear();
if (this.vanishT) this.vanishT.clear();
this.bullets.length = 0;
this.ebullets.length = 0;
for (const m of this.movers) {
const a = m.path[0];
if (a) { m.x = a.x; m.y = a.y; m.i = 0; }
m.dx = m.dy = 0;
const nx = m.path[1] || a;
m.ax = m.x; m.ay = m.y; m.bx = nx?.x ?? m.x; m.by = nx?.y ?? m.y;
}
for (const e of this.entities) {
if (e.type === 'dropspike') {
if (e.temp) { e.dead = true; continue; }
e.y = e.homeY; e.falling = false; e.vy = 0; e.landed = false; e.landT = 0;
}
if (e.type === 'warp') e.cool = 0;
}
this.entities = this.entities.filter(e => !e.dead);
for (const ev of this.events) ev.fired = false;
for (const b of this.bosses) {
b.hp = b.maxHp; b.dead = false; b.deathT = 0; b.bodyKill = true;
b.t = 0; b.state = 'idle'; b.stateT = 0; b.phase = 1;
b.x = b.homeX; b.y = b.homeY; b.vx = 0; b.vy = 0;
}
}
// 死亡标记:在死亡地点留下一个常驻「红叉」(IWBTG 风格死亡指示)。
// 只保留上一次死亡的红叉:新增前先清空,多次死亡不会累积。
addDeathMark(x, y) {
this.deathMarks.length = 0;
this.deathMarks.push({ x, y });
}
// 死亡特效(扩散冲击环):记录到关卡层而非玩家——主动重生时玩家当帧就复活了,
// 环要留在死亡位置播完。t 由 update 推进,14 帧扩散淡出后移除
addDeathFX(x, y) {
this.deathFX.push({ x, y, t: 0 });
}
drawDeathRing(ctx, fx) {
const t = fx.t;
if (t > 14) return;
const r = 4 + t * 1.8, a = Math.max(0, 1 - t / 14);
ctx.save();
ctx.globalAlpha = a * 0.85;
ctx.strokeStyle = '#ff8fa3';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(fx.x, fx.y, r, 0, Math.PI * 2);
ctx.stroke();
ctx.globalAlpha = a * 0.3;
ctx.fillStyle = '#ff5c7a';
ctx.beginPath();
ctx.arc(fx.x, fx.y, r * 0.55, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
drawDeathMark(ctx, dm) {
const s = 4; // 红叉半边长(< kid 的 11×21,整体约 8px)
ctx.lineCap = 'round';
// 深色描边,保证在任意背景下都清晰
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(0,0,0,0.55)';
ctx.beginPath();
ctx.moveTo(dm.x - s, dm.y - s); ctx.lineTo(dm.x + s, dm.y + s);
ctx.moveTo(dm.x + s, dm.y - s); ctx.lineTo(dm.x - s, dm.y + s);
ctx.stroke();
// 红色主体
ctx.lineWidth = 2;
ctx.strokeStyle = '#ff2535';
ctx.beginPath();
ctx.moveTo(dm.x - s, dm.y - s); ctx.lineTo(dm.x + s, dm.y + s);
ctx.moveTo(dm.x + s, dm.y - s); ctx.lineTo(dm.x - s, dm.y + s);
ctx.stroke();
}
// ---------------- 查询 ----------------
tileAt(tx, ty) {
if (tx < 0 || ty < 0 || tx >= this.w || ty >= this.h) return ty < 0 ? T.EMPTY : T.BLOCK;
return this.tiles[ty][tx];
}
pxTile(px, py) { return this.tileAt(Math.floor(px / TILE), Math.floor(py / TILE)); }
isSolidTile(t, tx, ty) {
if (!SOLID[t]) return false;
if (t === T.VANISH) {
const st = this.vanishState(tx, ty);
return st !== 2;
}
return true;
}
vanishState(tx, ty) { return this.vanish.get(ty * 1000 + tx) ?? 0; }
setVanish(tx, ty, st) { this.vanish.set(ty * 1000 + tx, st); }
/** 矩形是否与实心地形相交(可指定忽略单向平台的下落判定) */
solidRect(x, y, w, h, opts = {}) {
const x0 = Math.floor(x / TILE), x1 = Math.floor((x + w - 0.001) / TILE);
const y0 = Math.floor(y / TILE), y1 = Math.floor((y + h - 0.001) / TILE);
for (let ty = y0; ty <= y1; ty++) {
for (let tx = x0; tx <= x1; tx++) {
const t = this.tileAt(tx, ty);
if (t === T.ONEWAY) {
if (!opts.dropThrough && opts.prevBottom !== undefined && opts.prevBottom <= ty * TILE + 6) {
// 从上方落下:只有当前底部穿过平台面时才碰撞
if (y + h <= ty * TILE + 8) continue;
if (opts.prevBottom > ty * TILE + 2) continue;
return true;
}
continue;
}
if (this.isSolidTile(t, tx, ty)) return true;
}
}
// 移动平台
for (const m of this.movers) {
if (m.gone) continue;
if (x < m.x + m.w && x + w > m.x && y < m.y + m.h && y + h > m.y) {
if (opts.moverExclude === m) continue;
return true;
}
}
return false;
}
/** 致死判定(刺 / 美味水果 / 敌人子弹) */
deadlyRect(x, y, w, h) {
const x0 = Math.floor(x / TILE), x1 = Math.floor((x + w - 0.001) / TILE);
const y0 = Math.floor(y / TILE), y1 = Math.floor((y + h - 0.001) / TILE);
for (let ty = y0; ty <= y1; ty++) {
for (let tx = x0; tx <= x1; tx++) {
const t = this.tileAt(tx, ty);
if (!DEADLY[t]) continue;
const tr = spikeTri(t, tx * TILE, ty * TILE);
if (triRectOverlap(tr.ax, tr.ay, tr.bx, tr.by, tr.cx, tr.cy, x, y, w, h)) return true;
}
}
for (const e of this.entities) {
if (e.type === 'dropspike' && e.falling) {
const tr = spikeTri(T.SPIKE_L, e.x, e.y); // 与 drawDropSpike 的 dir=2(朝左)一致
if (triRectOverlap(tr.ax, tr.ay, tr.bx, tr.by, tr.cx, tr.cy, x, y, w, h)) return true;
}
}
for (const b of this.ebullets) {
if (b.dead) continue;
const r = { x: b.x, y: b.y, w: b.w, h: b.h };
if (overlap({ x, y, w, h }, r)) return true;
}
for (const bs of this.bosses) {
if (bs.dead || !bs.bodyKill) continue;
if (overlap({ x, y, w, h }, bs)) return true;
}
return false;
}
waterRect(x, y, w, h) {
const x0 = Math.floor(x / TILE), x1 = Math.floor((x + w - 0.001) / TILE);
const y0 = Math.floor(y / TILE), y1 = Math.floor((y + h - 0.001) / TILE);
for (let ty = y0; ty <= y1; ty++)
for (let tx = x0; tx <= x1; tx++)
if (this.tileAt(tx, ty) === T.WATER) return true;
return false;
}
iceAtBottom(x, y, w, h) {
const tx0 = Math.floor(x / TILE), tx1 = Math.floor((x + w - 1) / TILE);
const ty = Math.floor((y + h + 1) / TILE);
for (let tx = tx0; tx <= tx1; tx++) if (this.tileAt(tx, ty) === T.ICE) return true;
return false;
}
// ---------------- 更新 ----------------
update(dt, player, cam) {
this.time += dt;
const t = this.time;
// 死亡特效(冲击环)推进:14 帧后移除;粒子由 particles.update 自理
for (let i = this.deathFX.length - 1; i >= 0; i--) {
if (++this.deathFX[i].t > 14) this.deathFX.splice(i, 1);
}
// 移动平台
for (const m of this.movers) {
if (!m.path.length) continue;
const tgt = m.path[(m.i + 1) % m.path.length];
const ox = m.x, oy = m.y;
const dx = tgt.x - m.x, dy = tgt.y - m.y;
const dist = Math.hypot(dx, dy);
if (dist <= m.speed) {
m.x = tgt.x; m.y = tgt.y;
m.i = (m.i + 1) % m.path.length;
} else {
m.x += dx / dist * m.speed;
m.y += dy / dist * m.speed;
}
m.dx = m.x - ox; m.dy = m.y - oy;
const next = m.path[(m.i + 1) % m.path.length];
m.ax = m.x; m.ay = m.y; m.bx = next.x; m.by = next.y;
}
// 消失方块计时
for (const [key, st] of this.vanish) {
if (st === 0) continue;
const tt = (this.vanishT?.get(key) || 0) + 1;
this.vanishT = this.vanishT || new Map();
this.vanishT.set(key, tt);
if (st === 1 && tt > 55) { this.vanish.set(key, 2); this.vanishT.set(key, 0); }
else if (st === 2 && tt > 110) { this.vanish.set(key, 0); this.vanishT.set(key, 0); }
}
// 掉落刺
for (const e of this.entities) {
if (e.type !== 'dropspike') continue;
if (!e.falling) {
const px = player.x + player.w / 2;
if (Math.abs(px - (e.x + e.w / 2)) < 26 && Math.abs(player.y - e.y) < 260 && player.y > e.y) {
e.falling = true; e.vy = 0;
sfx.vanish();
}
} else if (e.landed) {
// 落地后插在地上,80 帧后碎掉(否则会永久堵死落脚点)
e.landT = (e.landT || 0) + 1;
if (e.landT > 80) { e.dead = true; e.falling = false; }
} else {
e.vy = Math.min(e.vy + 0.5, 11);
e.y += e.vy;
const ty = Math.floor((e.y + e.h) / TILE);
const tx = Math.floor((e.x + e.w / 2) / TILE);
if (this.isSolidTile(this.tileAt(tx, ty), tx, ty)) {
e.y = ty * TILE - e.h; e.vy = 0; e.landed = true; e.landT = 0;
this.shake = Math.max(this.shake, 5);
}
if (e.y > this.pxH + 100) e.dead = true;
}
}
// 炮台
for (const e of this.entities) {
if (e.type !== 'turret') continue;
e.t++;
if (e.t % (e.period || 90) === 0) {
const cx = e.x + e.w / 2, cy = e.y + e.h / 2;
let vx = 0, vy = 0;
if (e.dir === 'left') vx = -e.speed;
else if (e.dir === 'right') vx = e.speed;
else if (e.dir === 'up') vy = -e.speed;
else vy = e.speed;
if (e.kind === 'aim' && player.alive) {
const dx = (player.x + player.w / 2) - cx, dy = (player.y + player.h / 2) - cy;
const d = Math.hypot(dx, dy) || 1;
vx = dx / d * e.speed; vy = dy / d * e.speed;
}
this.ebullets.push({ x: cx - 4, y: cy - 4, w: 8, h: 8, vx, vy, dead: false, col: '#ff5c7a', life: 400 });
sfx.shoot();
}
}
// 敌人子弹
for (const b of this.ebullets) {
b.x += b.vx; b.y += b.vy; b.life--;
if (b.life <= 0) b.dead = true;
const tx = Math.floor((b.x + b.w / 2) / TILE), ty = Math.floor((b.y + b.h / 2) / TILE);
if (this.isSolidTile(this.tileAt(tx, ty), tx, ty)) {
b.dead = true;
this.particles.spawn(b.x + 4, b.y + 4, 4, { colors: ['#ff5c7a', '#fff'], speed: 2, life: 14 });
}
}
this.ebullets = this.ebullets.filter(b => !b.dead);
// 玩家子弹
for (const b of this.bullets) {
b.x += b.vx; b.y += b.vy; b.life--;
if (b.life <= 0) b.dead = true;
const tx = Math.floor((b.x + b.w / 2) / TILE), ty = Math.floor((b.y + b.h / 2) / TILE);
const tt = this.tileAt(tx, ty);
if (tt === T.BLOCK || tt === T.GRASS || tt === T.BRICK || tt === T.METAL) {
b.dead = true;
this.particles.spawn(b.x + 3, b.y + 3, 5, { colors: ['#fff6a0', '#ffb040'], speed: 2.4, life: 16 });
}
}
this.bullets = this.bullets.filter(b => !b.dead);
// 事件触发
for (const ev of this.events) {
if (ev.fired && ev.once) continue;
if (overlap(player, ev)) this.fireEvent(ev, player);
}
// 摄像机区域
this.camZone = null;
for (const e of this.entities) {
if (e.type !== 'camzone') continue;
if (overlap({ x: player.x + player.w / 2 - 1, y: player.y + player.h / 2 - 1, w: 2, h: 2 }, e)) {
this.camZone = e; break;
}
}
if (this.shake > 0) this.shake *= 0.86;
if (this.toastT > 0 && --this.toastT === 0) this.toast = null;
this.particles.update();
// 死亡红叉为常驻静态标记,无需逐帧演化,复活后仍保留
}
fireEvent(ev, player) {
ev.fired = true;
for (const a of ev.actions) {
if (a.type === 'msg') { this.showToast(a.text, a.dur || 150); }
else if (a.type === 'spikes') {
// 生成一排下落刺
for (let i = 0; i < (a.count || 5); i++) {
const x = (a.x + i * (a.gap || 1)) * TILE;
this.entities.push({
type: 'dropspike', x, y: (a.y || 0) * TILE, w: TILE, h: TILE,
falling: true, vy: 0, homeY: (a.y || 0) * TILE, t: 0, temp: true,
});
}
sfx.troll();
} else if (a.type === 'vanish') {
for (let i = 0; i < (a.count || 3); i++) {
const tx = (a.x + i), ty = a.y;
if (this.tileAt(tx, ty) === T.EMPTY) continue;
this.setVanish(tx, ty, 1);
this.vanishT = this.vanishT || new Map();
this.vanishT.set(ty * 1000 + tx, 0);
}
sfx.vanish();
} else if (a.type === 'warp') {
player.x = a.x * TILE; player.y = a.y * TILE;
player.vx = 0; player.vy = 0;
sfx.warp();
} else if (a.type === 'kill') { player.kill(); }
else if (a.type === 'shake') { this.shake = a.v || 10; }
}
}
showToast(text, dur = 150) { this.toast = text; this.toastT = dur; }
// ---------------- 绘制 ----------------
drawBg(ctx, cam, t) {
const g = ctx.createLinearGradient(0, 0, 0, cam.h);
const th = {
jump: ['#1a1830', '#0a0a14'],
endur: ['#101f24', '#080c10'],
boss: ['#2a1018', '#0d0810'],
troll: ['#221432', '#0b0812'],
custom: ['#141428', '#08080f'],
}[this.bgTheme] || ['#1a1830', '#0a0a14'];
g.addColorStop(0, th[0]); g.addColorStop(1, th[1]);
ctx.fillStyle = g;
ctx.fillRect(0, 0, cam.w, cam.h);
// 远景装饰(视差)
const px = -cam.x * 0.25, py = -cam.y * 0.15;
ctx.globalAlpha = 0.16;
ctx.fillStyle = '#ffffff';
for (let i = 0; i < 60; i++) {
const nx = hashNoise(i, 7) * 2000, ny = hashNoise(i, 13) * 900;
const sx = ((nx + px) % (cam.w + 200)) - 100;
const sy = ((ny + py) % (cam.h + 120)) - 60;
ctx.fillRect(sx, sy, 2, 2);
}
ctx.globalAlpha = 1;
// 网格
ctx.strokeStyle = 'rgba(255,255,255,.035)';
ctx.lineWidth = 1;
ctx.beginPath();
const off = TILE * 2;
const sx0 = -((cam.x % off));
const sy0 = -((cam.y % off));
for (let x = sx0; x < cam.w; x += off) { ctx.moveTo(x + .5, 0); ctx.lineTo(x + .5, cam.h); }
for (let y = sy0; y < cam.h; y += off) { ctx.moveTo(0, y + .5); ctx.lineTo(cam.w, y + .5); }
ctx.stroke();
}
draw(ctx, cam, t) {
const vx0 = Math.max(0, Math.floor(cam.x / TILE) - 1);
const vx1 = Math.min(this.w - 1, Math.ceil((cam.x + cam.w / (cam.zoom || 1)) / TILE) + 1);
const vy0 = Math.max(0, Math.floor(cam.y / TILE) - 1);
const vy1 = Math.min(this.h - 1, Math.ceil((cam.y + cam.h / (cam.zoom || 1)) / TILE) + 1);
ctx.save();
// 摄像机变换由外部处理
for (let ty = vy0; ty <= vy1; ty++) {
for (let tx = vx0; tx <= vx1; tx++) {
const v = this.tiles[ty][tx];
if (v === T.EMPTY) continue;
const x = tx * TILE, y = ty * TILE;
switch (v) {
case T.BLOCK: S.drawBlock(ctx, x, y, 0); break;
case T.GRASS: S.drawBlock(ctx, x, y, 1); break;
case T.BRICK: S.drawBlock(ctx, x, y, 2); break;
case T.METAL: S.drawBlock(ctx, x, y, 3); break;
case T.ICE: S.drawIce(ctx, x, y); break;
case T.WATER: S.drawWater(ctx, x, y, t); break;
case T.ONEWAY: S.drawOneWay(ctx, x, y); break;
case T.KILLER: S.drawKiller(ctx, x, y, t); break;
case T.VANISH: S.drawVanish(ctx, x, y, this.vanishState(tx, ty), t); break;
case T.SPIKE_U: S.drawSpike(ctx, x, y, 0, t); break;
case T.SPIKE_D: S.drawSpike(ctx, x, y, 1, t); break;
case T.SPIKE_L: S.drawSpike(ctx, x, y, 2, t); break;
case T.SPIKE_R: S.drawSpike(ctx, x, y, 3, t); break;
}
}
}
// 移动平台
for (const m of this.movers) S.drawMovingPlatform(ctx, m);
// 实体
for (const e of this.entities) {
if (e.dead) continue;
switch (e.type) {
case 'save': S.drawSave(ctx, e, t); break;
case 'goal': S.drawGoal(ctx, e, t); break;
case 'gun': if (!e.taken) S.drawGun(ctx, e, t); break;
case 'apple': if (!e.taken) S.drawApple(ctx, e, t); break;
case 'jumpref': S.drawJumpRef(ctx, e, t); break;
case 'warp': if (!e.hidden) S.drawWarp(ctx, e, t); break;
case 'sign': S.drawSign(ctx, e, t); break;
case 'turret': S.drawTurret(ctx, e, t); break;
case 'camzone': S.drawCamera(ctx, e, t); break;
case 'dropspike': S.drawDropSpike(ctx, e, t); break;
}
}
// 子弹
for (const b of this.bullets) S.drawBullet(ctx, b);
for (const b of this.ebullets) S.drawEBullet(ctx, b, t);
// 死亡血迹(IWBTG 风格,常驻于死亡地点)
for (const dm of this.deathMarks) this.drawDeathMark(ctx, dm);
// 死亡特效(扩散冲击环,14 帧淡出)
for (const fx of this.deathFX) this.drawDeathRing(ctx, fx);
this.particles.draw(ctx);
ctx.restore();
}
/** 屏幕空间 UI:提示牌文字 / toast */
drawOverlay(ctx, cam, t) {
for (const e of this.entities) {
if (e.type !== 'sign') continue;
const sx = (e.x + e.w / 2 - cam.x) * (cam.zoom || 1);
const sy = (e.y - 6 - cam.y) * (cam.zoom || 1);
if (sx < -80 || sx > cam.w + 80) continue;
ctx.font = 'bold 11px "Courier New",monospace';
ctx.textAlign = 'center';
const txt = e.text;
const wd = ctx.measureText(txt).width;
ctx.fillStyle = 'rgba(0,0,0,.72)';
ctx.fillRect(sx - wd / 2 - 5, sy - 13, wd + 10, 16);
ctx.fillStyle = '#ffe9a8';
ctx.fillText(txt, sx, sy);
}
}
}
// 单三角形刺的顶点(与 sprites.drawSpike 完全一致)。
// 尖端指向刺的方向,底边贴在相反一侧(地面 / 天花板 / 墙面)。
function spikeTri(t, x, y) {
const s = TILE;
if (t === T.SPIKE_U) return { ax: x + s / 2, ay: y, bx: x, by: y + s, cx: x + s, cy: y + s };
if (t === T.SPIKE_D) return { ax: x + s / 2, ay: y + s, bx: x, by: y, cx: x + s, cy: y };
if (t === T.SPIKE_L) return { ax: x, ay: y + s / 2, bx: x + s, by: y, cx: x + s, cy: y + s };
if (t === T.SPIKE_R) return { ax: x + s, ay: y + s / 2, bx: x, by: y, cx: x, cy: y + s };
return { ax: x, ay: y, bx: x + s, by: y, cx: x, cy: y + s }; // 兜底(不应到达)
}
// 三角形与轴对齐矩形的相交判定(分离轴定理,凸多边形充要条件)。
function triRectOverlap(ax, ay, bx, by, cx, cy, rx, ry, rw, rh) {
const rMinX = rx, rMaxX = rx + rw, rMinY = ry, rMaxY = ry + rh;
const tMinX = Math.min(ax, bx, cx), tMaxX = Math.max(ax, bx, cx);
const tMinY = Math.min(ay, by, cy), tMaxY = Math.max(ay, by, cy);
if (tMaxX < rMinX || tMinX > rMaxX || tMaxY < rMinY || tMinY > rMaxY) return false; // AABB 快速排除
const edges = [[bx - ax, by - ay], [cx - bx, cy - by], [ax - cx, ay - cy]];
for (const [ex, ey] of edges) {
const nx = -ey, ny = ex; // 边法线
const t0 = nx * ax + ny * ay, t1 = nx * bx + ny * by, t2 = nx * cx + ny * cy;
const tMin = Math.min(t0, t1, t2), tMax = Math.max(t0, t1, t2);
const p0 = nx * rMinX + ny * rMinY, p1 = nx * rMaxX + ny * rMinY,
p2 = nx * rMinX + ny * rMaxY, p3 = nx * rMaxX + ny * rMaxY;
const rMin = Math.min(p0, p1, p2, p3), rMax = Math.max(p0, p1, p2, p3);
if (tMax < rMin || rMax < tMin) return false; // 找到分离轴
}
return true;
}
export { spikeTri, triRectOverlap };
+63
View File
@@ -0,0 +1,63 @@
// BOSS 战关卡(击败 BOSS 即通关)
import { G, rep, E, plat, ent } from './kit.js';
export default [
{
id: 'b1', name: 'THE GUY', type: 'boss', diff: 3, bg: 'boss', width: 48,
hint: 'X 键射击。他放扇形弹+砸地冲击波,站在平台边缘躲开再输出。',
startGun: true,
bosses: [{ kind: 'guy', hp: 72 }],
grid: G(48, [
rep('#', 48), // 0
E(48), E(48), E(48), E(48), E(48), E(48), E(48),// 1-7
'#' + rep('.', 5) + '######' + rep('.', 24) + '######', // 8
E(48), E(48), E(48), // 9-11
'#' + rep('.', 15) + '######' + rep('.', 8) + '######', // 12
E(48), E(48), E(48), // 13-15
'#' + rep('.', 5) + '######' + rep('.', 24) + '######', // 16
E(48), E(48), E(48), // 17-19
ent(48, [2, 'S'], [24, 'B']), // 20
rep('#', 48), // 21
]),
},
{
id: 'b2', name: 'MECHA KID', type: 'boss', diff: 4, bg: 'boss', width: 48,
hint: '冲刺时贴地必死。跳上高台躲,等他停下再打。',
startGun: true,
bosses: [{ kind: 'mecha', hp: 96 }],
grid: G(48, [
rep('#', 48), // 0
E(48), E(48), E(48), E(48), // 1-4
'#' + rep('.', 12) + '######' + rep('.', 10) + '######', // 5
E(48), E(48), E(48), // 6-8
'#' + rep('.', 3) + '######' + rep('.', 28) + '######', // 9
E(48), E(48), E(48), // 10-12
'#' + rep('.', 15) + '######' + rep('.', 8) + '######', // 13
E(48), E(48), E(48), // 14-16
'#' + rep('.', 3) + '######' + rep('.', 28) + '######', // 17
E(48), E(48), E(48), // 18-19
ent(48, [2, 'S'], [24, 'B']), // 20
rep('#', 48), // 21
]),
},
{
id: 'b3', name: 'THE DEVIL', type: 'boss', diff: 5, bg: 'boss', width: 48,
hint: '三阶段:追踪弹 → 激光横扫 → 环形弹幕。地上还有刺。活下来。',
startGun: true,
bosses: [{ kind: 'devil', hp: 128 }],
grid: G(48, [
rep('#', 48), // 0
E(48), E(48), E(48), // 1-3
'#' + rep('.', 5) + '######' + rep('.', 24) + '######', // 4
E(48), E(48), E(48), // 5-7
'#' + rep('.', 15) + '######' + rep('.', 8) + '######', // 8
E(48), E(48), E(48), // 9-11
'#' + rep('.', 3) + '######' + rep('.', 28) + '######', // 12
E(48), E(48), E(48), // 13-15
'#' + rep('.', 15) + '######' + rep('.', 8) + '######', // 16
E(48), E(48), E(48), // 17-19
ent(48, [2, 'S'], [24, 'B'], [12, '^'], [13, '^'], [34, '^'], [35, '^']), // 20
rep('#', 48), // 21
]),
},
];
+131
View File
@@ -0,0 +1,131 @@
// 耐久(Endurance)关卡:长距离连续考验,存档点稀疏
import { G, rep, E, plat, ent, flr } from './kit.js';
export default [
// ---------------- 1 ----------------
{
id: 'e1', name: 'LONG ROAD', type: 'endur', diff: 3, bg: 'endur', width: 100,
hint: '100 格长路,8 个刺坑,只有 5 个存档点。别急。',
messages: ['才刚刚开始'],
grid: G(100, [
rep('#', 100), // 0
E(100), E(100), E(100), E(100), E(100), // 1-5
E(100), E(100), E(100), E(100), E(100), // 6-10
E(100), // 11
ent(100, [15, 'v'], [17, 'v'], [30, 'v'], [32, 'v'], [55, 'v'], [57, 'v'], [75, 'v'], [77, 'v']), // 12
ent(100, [43, 'F'], [90, 'F']), // 13
'#' + rep('.', 40) + '######' + rep('.', 41) + '######', // 14
E(100), E(100), // 15-16
ent(100, [2, 'S'], [16, 'G'], [30, 'G'], [52, 'G'], [76, 'G'], [98, 'X'], // 17
[26, '^'], [27, '^'], [40, '^'], [41, '^'], [63, '^'], [64, '^'], [78, '^'], [79, '^']),
flr(['#', 9], ['^', 3], ['#', 7], ['^', 4], ['#', 11], ['^', 3], ['#', 6], ['^', 5],
['#', 9], ['^', 3], ['#', 8], ['^', 4], ['#', 10], ['^', 3], ['#', 6], ['^', 5], ['#', 3]), // 18
]),
},
// ---------------- 2 ----------------
{
id: 'e2', name: 'TURRET HELL', type: 'endur', diff: 4, bg: 'endur', width: 88,
hint: '炮台沿路扫射。踩空就是刺海,别站在开阔地。',
turrets: [
{ dir: 'right', period: 78, speed: 2.8, offset: 0 },
{ dir: 'left', period: 92, speed: 2.6, offset: 25 },
{ dir: 'right', period: 70, speed: 3.0, offset: 10 },
{ dir: 'left', period: 86, speed: 2.7, offset: 40 },
{ dir: 'right', period: 74, speed: 2.9, offset: 20 },
{ dir: 'aim', period: 110, speed: 2.4, offset: 55 },
],
grid: G(88, [
rep('#', 88), // 0
E(88), E(88), E(88), E(88), E(88), E(88), // 1-6
E(88), E(88), E(88), // 7-9
E(88), // 10
ent(88, [83, 'X']), // 11
plat(88, 82, 5), // 12
E(88), // 13
plat(88, 78, 5), // 14
E(88), // 15
ent(88, [83, 'G']), // 16
plat(88, 82, 5), // 17
E(88), // 18
plat(88, 78, 5), // 19
E(88), // 20
ent(88, [2, 'S'], [4, 'O'], [10, 'G'], [20, 'O'], [30, 'G'], [36, 'O'],
[50, 'G'], [52, 'O'], [68, 'O'], [70, 'G'], [84, 'O']), // 21
'#' + '.' + rep('#####...', 10) + '#####', // 22
'#' + rep('^', 87), // 23
rep('#', 88), // 24
]),
},
// ---------------- 3 ----------------
{
id: 'e3', name: 'THE PIT', type: 'endur', diff: 4, bg: 'endur', width: 64,
hint: '先从左侧竖井下到底,游过水下刺池,再从右边一路爬回顶端。',
messages: ['下面有东西在等你'],
grid: G(64, [
rep('#', 64), // 0
E(64), E(64), // 1-2
ent(64, [57, 'X']), // 3
'#' + '..' + 'S' + rep('.', 52) + rep('#', 7), // 4 出生 + 右·顶台
'#.' + rep('#', 7), // 5 左
'#' + rep('.', 50) + 'G', // 6
'#' + rep('.', 48) + rep('#', 7), // 7 右
'#' + rep('.', 10) + rep('#', 7), // 8 左
'#' + rep('.', 58) + 'G', // 9
'#' + '...' + 'G' + rep('.', 51) + rep('#', 7), // 10 右
'#.' + rep('#', 7), // 11 左
'#' + rep('.', 50) + 'G', // 12
'#' + rep('.', 48) + rep('#', 7), // 13 右
'#' + rep('.', 10) + rep('#', 7), // 14 左
E(64), // 15
'#' + '...' + 'G' + rep('.', 51) + rep('#', 7), // 16 右
'#.' + rep('#', 7), // 17 左
E(64), // 18
'#' + rep('.', 48) + rep('#', 7), // 19 右
'#' + rep('.', 10) + rep('#', 7), // 20 左
E(64), // 21
'#' + rep('.', 12) + 'G' + rep('.', 42) + rep('#', 7), // 22 右
'#' + rep('.', 10) + rep('#', 7), // 23 左·井底台
'#' + rep('.', 50) + 'G', // 24 出水台
'#' + rep('.', 17) + rep('~', 31) + rep('#', 7) + rep('.', 8), // 25
'#' + rep('.', 17) + rep('~', 31) + rep('.', 14), // 26
'#' + rep('.', 17) + rep('~', 31) + rep('.', 14), // 27
'#' + rep('^', 63), // 28
rep('#', 64), // 29
]),
},
// ---------------- 4 ----------------
{
id: 'e4', name: 'MARATHON', type: 'endur', diff: 5, bg: 'endur', width: 120,
hint: '120 格:冰面、炮台、刺坑、移动平台全都有。5 个存档,自求多福。',
turrets: [
{ dir: 'right', period: 76, speed: 2.9, offset: 0 },
{ dir: 'left', period: 88, speed: 2.7, offset: 30 },
{ dir: 'right', period: 68, speed: 3.1, offset: 15 },
{ dir: 'aim', period: 120, speed: 2.3, offset: 50 },
{ dir: 'left', period: 80, speed: 2.8, offset: 25 },
],
grid: G(120, [
rep('#', 120), // 0
E(120), E(120), E(120), E(120), E(120), // 1-5
E(120), E(120), E(120), E(120), E(120), // 6-10
E(120), E(120), E(120), E(120), E(120), // 11-15
E(120), // 16
ent(120, [20, 'v'], [22, 'v'], [36, 'v'], [38, 'v'], [52, 'v'], [54, 'v'],
[70, 'v'], [72, 'v'], [88, 'v'], [90, 'v'], [104, 'v'], [106, 'v']), // 17
E(120), E(120), E(120), E(120), // 18-21
ent(120, [2, 'S'], [20, 'O'], [24, 'G'], [36, 'O'], [40, 'G'], [52, 'O'],
[66, 'G'], [70, 'O'], [88, 'G'], [100, 'O'], [104, 'G'], [116, 'X'],
[17, '^'], [18, '^'], [54, '^'], [55, '^'], [72, '^'], [73, '^'], [105, '^'], [106, '^']), // 22
flr(['%', 10], ['^', 4], ['#', 12], ['^', 5], ['%', 12], ['^', 4],
['#', 10], ['^', 5], ['#', 15], ['^', 4], ['%', 10], ['^', 5],
['#', 12], ['^', 4], ['#', 7]), // 23
rep('#', 120), // 24
]),
movers: [
{ x: 57, y: 22, w: 3, h: 1, path: [[57, 22], [63, 22]], speed: 1.3 },
],
},
];
+26
View File
@@ -0,0 +1,26 @@
import tutorial from './tutorial.js';
import jump from './jump.js';
import endurance from './endurance.js';
import boss from './boss.js';
import troll from './troll.js';
const raw = [...tutorial, ...jump, ...endurance, ...boss, ...troll];
raw.forEach((l, i) => { l.index = i; l.builtin = true; });
export const LEVELS = raw;
export const TYPE_LABEL = {
jump: '跳刺', endur: '耐久', boss: 'BOSS', troll: '坑向', custom: '自制',
};
export const TYPE_CLASS = {
jump: 't-jump', endur: 't-endur', boss: 't-boss', troll: 't-troll', custom: 't-custom',
};
let uid = 0;
export function makeCustomLevel(data) {
return { ...data, id: 'u' + (Date.now() % 100000) + (uid++), type: 'custom', builtin: false, index: -1 };
}
export function findLevel(id) {
return LEVELS.find(l => l.id === id);
}
+519
View File
@@ -0,0 +1,519 @@
// 跳刺(Needle)10 关 —— IWBT 经典密集针刺风格
// 设计语法(已经 tools/solve.mjs 验证):
// 刺毯缺口每 3 格一个(跳 2 连刺 = 64px 单跳节奏);钻石中心 = 地板上方 2~3 格;
// 垂刺离最低落脚点 5 格(单跳安全、二段跳必死);2 格高矮洞可用撞头跳;
// 竖井台阶每级升 2~3 格横移 3 格内;钢丝柱间距 ≤4(单跳)/ ≤6(二段)。
import { Grid } from './kit.js';
import { vgap, hgap, diamond, spikeRun, block, corner, ceil, wall, well } from './needle.js';
// 刺毯:从 x0 起 n 格留落脚缺口。
// 缺口间距统一 3 格(跳 2 连刺 = 64px)。
// 2026-10-23:JUMP 7.5 + GRAV_FALL 0.55 下单跳水平实测 118.8px(tools/jumpdist.mjs),
// 但落地前一帧竖直速度已达 8.9px/帧,3 连刺(96px)的起拍窗被压到 0~1 帧(不可玩);
// 2 连刺留 55px 射程余量,落地窗恢复充裕。井口/左端右行出口处的 3 连刺须显式拆断(见各关 gaps 注释)
const carpet = (m, x0, y, n, gaps = []) => {
const g = [];
let i = 3;
while (i < n) { g.push(i); i += 3; }
return spikeRun(m, x0, y, n, '^', g.concat(gaps));
};
export const JUMP_LEVELS = [
// ============================================================ j1 刺巷
{
id: 'j1', name: 'SPIKE ALLEY', cn: '刺巷', type: 'jump', diff: 2,
hint: '针刺入门:刺毯单跳节奏、钻石缝、矮洞撞头跳、竖井、对刺门。',
width: 104,
grid: (() => {
const W = 104, H = 26, R = 22;
const m = new Grid(W, H);
m.border('#');
m.rect(1, R, W - 2, 1, '#'); // 主地板
// --- x1-9 起步 ---
m.set(3, R - 1, 'S');
m.set(8, R - 1, 'G');
// --- x10-26 刺毯(单跳节奏,垂刺压顶禁二段,两道上下夹缝)---
carpet(m, 10, R - 1, 17);
ceil(m, 10, 26, R - 6);
vgap(m, 15, R - 2); vgap(m, 21, R - 2);
// --- x28-43 钻石门三连(中心 R-2,单跳穿缝)---
carpet(m, 28, R - 1, 16, [0, 4, 8, 12, 15]); // 加密缺口便于站位
ceil(m, 28, 43, R - 6);
vgap(m, 30, R - 2); vgap(m, 34, R - 2); vgap(m, 38, R - 2);
m.set(28, R - 1, 'G');
// --- x44-56 矮洞(顶 row 18,3 格高,撞头跳 + 对刺门)---
m.rect(44, R - 4, 13, 1, '#');
carpet(m, 45, R - 1, 11);
hgap(m, 48, R - 1); hgap(m, 53, R - 1);
m.set(45, R - 1, 'G');
// --- x57-71 刺坑上的钢丝柱 ---
for (let x = 57; x <= 70; x++) { m.set(x, R, '.'); m.set(x, R + 1, '^'); }
const wires = [[58, 20], [61, 19], [64, 20], [67, 18], [70, 20]];
for (const [x, top] of wires) m.vline(x, top, R - 1, '#');
m.set(72, R - 1, 'G');
// --- x74-79 竖井上上层(井底留 3 格入口)---
m.vline(74, R - 10, R - 4, '#');
m.vline(79, R - 12, R - 1, '#');
block(m, 75, R - 3, 2); // 19
block(m, 77, R - 6, 2); // 16
block(m, 75, R - 9, 2); // 13
wall(m, 79, R - 5, R - 5, '<'); wall(m, 74, R - 7, R - 7, '>');
// --- 上层回廊(地板 row 12)x80-97 ---
m.rect(80, R - 10, 18, 1, '#');
carpet(m, 81, R - 11, 15, [0, 8]); // 8=x89:给对刺门留左侧起拍位(新物理下跳台落点偏右,须能走进 x90)
ceil(m, 81, 95, R - 16); // row 6 垂刺
hgap(m, 92, R - 11); // 对刺门
m.set(82, R - 11, 'G'); m.set(94, R - 11, 'G');
// --- x98-102 下落井 + 终点 ---
wall(m, 99, R - 7, R - 3, '>');
wall(m, 102, R - 5, R - 2, '<');
m.set(100, R - 1, 'X');
return m.out();
})(),
},
// ============================================================ j2 垂直地狱
{
id: 'j2', name: 'VERTICAL HELL', cn: '垂直地狱', type: 'jump', diff: 3,
hint: '52 格高塔:四段之字竖井,每层刺毯+上下夹缝,垂刺压顶、掉落刺追身。',
width: 68,
grid: (() => {
const W = 68, H = 52;
const m = new Grid(W, H);
m.border('#');
// ---- L0 地板 row 48(向右:刺毯 + 三道上下夹缝)----
m.rect(1, 48, 66, 1, '#');
m.set(3, 47, 'S');
carpet(m, 5, 47, 50, [1, 18]); // 1=x6 出生旁缺口;18=x23 放宽落点窗(3 连刺落点贴右腰会被 6px 状态桶卡死)
ceil(m, 5, 54, 43);
vgap(m, 16, 46); vgap(m, 30, 46); vgap(m, 46, 46);
m.set(11, 47, 'G'); m.set(39, 47, 'G');
// ---- 右井 x58..65:L0 → L1(井底 3 格敞口,之字每级升 2 格)----
well(m, 58, 65, 40, 48, 'l');
m.set(65, 45, '^'); m.set(58, 43, '^'); // 踏石外沿刺,逼迫精准落点
// ---- L1 地板 row 40(向左;垂刺避开左井 x2..9)----
m.rect(2, 40, 56, 1, '#');
carpet(m, 10, 39, 44);
ceil(m, 10, 54, 35);
vgap(m, 42, 38); vgap(m, 26, 38); vgap(m, 12, 38);
m.set(47, 39, 'G'); m.set(19, 39, 'G');
// ---- 左井 x2..8:L1 → L2 ----
well(m, 2, 8, 32, 40, 'r');
m.set(2, 37, '^'); m.set(8, 35, '^');
// ---- L2 地板 row 32(向右,井底延伸到右井下方)----
m.rect(9, 32, 57, 1, '#');
carpet(m, 11, 31, 46, [1, 11, 31]); // 1=x12 拆井口 3 连刺;11=x22/31=x42 是 hgap 夹缝通道列(必须为空,否则整门变 3 连刺、4 格跳超射程)
ceil(m, 11, 54, 27);
hgap(m, 22, 31); hgap(m, 42, 31);
vgap(m, 32, 30); vgap(m, 50, 30);
m.set(19, 31, 'G'); m.set(47, 31, 'G');
// ---- 右井 x58..65:L2 → L3 ----
well(m, 58, 65, 24, 32, 'l');
m.set(65, 29, '^'); m.set(58, 27, '^');
// ---- L3 地板 row 24(向左,掉落刺;垂刺避开左井 x2..9)----
m.rect(2, 24, 56, 1, '#');
carpet(m, 10, 23, 44, [0]); // 0=x10:拆掉左端 3 连刺(左行跳落点差 0.8px 蹭 x10 左坡;L1 同位置能过是因 vgap(12) 清空了 x10-14,L3 没有)
ceil(m, 10, 54, 19);
[14, 24, 34, 44].forEach(x => m.set(x, 18, 'D'));
vgap(m, 40, 22); vgap(m, 22, 22);
m.set(47, 23, 'G'); m.set(19, 23, 'G');
// ---- 左井 x2..8:L3 → L4 ----
well(m, 2, 8, 16, 24, 'r');
m.set(2, 21, '^'); m.set(8, 19, '^');
// ---- L4 地板 row 16(向右到终点)----
m.rect(9, 16, 57, 1, '#');
carpet(m, 11, 15, 52, [1, 41]); // 1=x12 拆井口 3 连刺;41=x52 是 hgap 夹缝通道列(必须为空)
ceil(m, 11, 60, 11);
hgap(m, 26, 15); vgap(m, 40, 14); hgap(m, 52, 15);
[18, 34, 56].forEach(x => m.set(x, 10, 'D'));
m.set(27, 15, 'G'); m.set(51, 15, 'G');
m.set(62, 15, 'X');
return m.out();
})(),
},
// ============================================================ j3 钢丝
{
id: 'j3', name: 'TIGHTROPE', cn: '钢丝', type: 'jump', diff: 3,
hint: '一格宽的柱子立在刺海上,高矮间距都不同,垂刺压着头顶。',
width: 132,
grid: (() => {
const W = 132, H = 24, R = 20;
const m = new Grid(W, H);
m.border('#');
m.rect(1, R, W - 2, 1, '#'); // 基座
spikeRun(m, 4, R - 1, W - 6, '^'); // 刺海
// 钢丝柱(顶可站 1 格),高矮错落、间距 3~5
const cols = [
[4, 18], [8, 17], [12, 19], [15, 17], [19, 18], [23, 16], [27, 19],
[30, 17], [34, 18], [38, 16], [42, 19], [46, 17], [50, 15], [54, 18],
[58, 17], [62, 19], [66, 16], [70, 18], [74, 17], [78, 19], [82, 15],
[86, 18], [90, 17], [94, 19], [98, 16], [102, 18], [106, 17], [110, 19],
[114, 16], [118, 18], [122, 17],
];
for (const [x, top] of cols) m.vline(x, top, R - 1, '#');
// 起点/终点平台
m.rect(1, R - 1, 3, 1, '#'); m.set(2, R - 2, 'S');
m.rect(126, R - 1, 4, 1, '#'); m.set(128, R - 2, 'X');
// 垂刺段(离最低柱顶 5 格:单跳安全,二段跳死)
ceil(m, 6, 28, 11); // 段内最低顶 16
ceil(m, 32, 56, 10); // 最低顶 15
ceil(m, 60, 88, 10);
ceil(m, 92, 120, 11);
// 存档(柱顶)
m.set(23, 15, 'G'); m.set(58, 16, 'G'); m.set(90, 16, 'G'); m.set(122, 16, 'G');
return m.out();
})(),
},
// ============================================================ j4 冰刺
{
id: 'j4', name: 'ICE NEEDLES', cn: '冰刺', type: 'jump', diff: 4,
hint: '冰面刹不住车:滑坑、冰上钻石、冰柱钢丝,最后还有一段冰顶矮洞。',
width: 132,
grid: (() => {
const W = 132, H = 26, R = 22;
const m = new Grid(W, H);
m.border('#');
m.rect(1, R, W - 2, 1, '%'); // 冰地板
m.set(3, R - 1, 'S');
// --- x6-30 冰面刺坑(3 格宽:新物理单跳 108.8px > 96px;旧 4~5 格坑跳不过)---
for (const [a, b] of [[7, 9], [13, 15], [19, 21], [25, 27]])
for (let x = a; x <= b; x++) { m.set(x, R, '.'); m.set(x, R + 1, '^'); }
ceil(m, 6, 24, R - 5); // 压顶垂刺:冰面上禁二段跳
m.set(12, R - 1, 'G');
// --- x32-52 冰台阶 + 角刺 + 钻石 ---
block(m, 33, R - 2, 2, '%');
block(m, 38, R - 2, 2);
block(m, 43, R - 4, 2, '%');
ceil(m, 31, 52, R - 5);
vgap(m, 48, R - 2);
m.set(41, R - 1, 'G');
// --- x54-78 冰柱钢丝 ---
spikeRun(m, 54, R - 1, 25, '^');
const ice = [[56, 19], [60, 18], [64, 20], [68, 17], [72, 19], [76, 18]];
for (const [x, top] of ice) m.vline(x, top, R - 1, '%');
ceil(m, 55, 77, 12); // 最低柱顶 17 → 12
m.set(64, 19, 'G');
// --- x80-100 冰顶矮洞(2 格高,撞头跳越刺)---
m.rect(80, R - 3, 21, 1, '%'); // 冰顶 row 19
spikeRun(m, 83, R - 1, 15, '^', [0, 4, 8, 12, 14]);
m.set(81, R - 1, 'G'); m.set(99, R - 1, 'G');
// --- x102-124 冰上钻石阵 ---
carpet(m, 102, R - 1, 23, '%'.length ? [] : []); // 冰面刺毯
ceil(m, 102, 124, R - 5);
vgap(m, 106, R - 2); vgap(m, 111, R - 2);
vgap(m, 116, R - 2); vgap(m, 121, R - 2);
m.set(103, R - 1, 'G');
m.set(126, R - 1, 'G');
m.set(129, R - 1, 'X');
return m.out();
})(),
},
// ============================================================ j5 关口
{
id: 'j5', name: 'THE GAUNTLET', cn: '关口', type: 'jump', diff: 4,
hint: '移动平台跨刺海,炮台点名,矮洞与钻石阵穿插。',
width: 122,
grid: (() => {
const W = 122, H = 28, R = 24;
const m = new Grid(W, H);
m.border('#');
m.rect(1, R, W - 2, 1, '#');
m.set(3, R - 1, 'S');
// --- x5-22 热身刺毯(三道上下夹缝)---
carpet(m, 5, R - 1, 17);
ceil(m, 5, 21, R - 6);
vgap(m, 9, R - 2); vgap(m, 15, R - 2); vgap(m, 21, R - 2);
m.set(7, R - 1, 'G');
// --- x23-49 移动平台跨海 ---
for (let x = 23; x <= 49; x++) { m.set(x, R, '.'); m.set(x, R + 1, '^'); }
m.set(50, R - 1, 'G');
// --- x51-72 矮洞 + 炮台 ---
m.rect(51, R - 4, 22, 1, '#'); // 顶 row 20
carpet(m, 52, R - 1, 20, [0]);
hgap(m, 57, R - 1); hgap(m, 64, R - 1); hgap(m, 70, R - 1);
m.set(56, R - 5, 'O');
m.set(52, R - 1, 'G');
// --- x73-97 浮块跨刺海 + 交叉火力 ---
spikeRun(m, 73, R - 1, 24, '^');
block(m, 76, R - 2, 2); block(m, 82, R - 4, 2); block(m, 88, R - 2, 2); block(m, 93, R - 3, 2);
ceil(m, 75, 96, R - 9); // 浮块区压顶:高块上二段跳必死
m.set(79, R - 6, 'O'); m.set(91, R - 6, 'O');
m.set(95, R - 1, 'G');
// --- x98-118 钻石收尾 ---
carpet(m, 98, R - 1, 20, [0, 1, 19]);
ceil(m, 98, 117, R - 6);
vgap(m, 101, R - 2); vgap(m, 106, R - 2); vgap(m, 111, R - 2); vgap(m, 116, R - 2);
m.set(98, R - 1, 'G');
m.set(119, R - 1, 'G');
m.set(120, R - 1, 'X');
return m.out();
})(),
movers: [
{ x: 25, y: 22, w: 2, h: 1, path: [[25, 22], [35, 22]], speed: 1.6 },
{ x: 39, y: 20, w: 2, h: 1, path: [[39, 20], [47, 20]], speed: 1.9 },
],
turrets: [
{ dir: 'left', period: 70, speed: 2.8, offset: 0 },
{ dir: 'left', period: 62, speed: 3.0, offset: 24 },
{ dir: 'left', period: 66, speed: 2.7, offset: 40 },
],
},
// ============================================================ j6 针刺教堂
{
id: 'j6', name: 'NEEDLE CATHEDRAL', cn: '针刺教堂', type: 'jump', diff: 5,
hint: '三层殿堂:底层向右,竖井爬升,中层折返向左,再爬升,顶层冲刺。',
width: 132,
grid: (() => {
const W = 132, H = 36;
const m = new Grid(W, H);
m.border('#');
// ============ L0 底层(地板 row 30)============
m.rect(1, 30, W - 2, 1, '#');
m.set(3, 29, 'S');
carpet(m, 5, 29, 116);
ceil(m, 5, 120, 24);
vgap(m, 18, 28); vgap(m, 46, 28); vgap(m, 74, 28); vgap(m, 102, 28);
block(m, 32, 29, 2); block(m, 60, 29, 2);
block(m, 88, 29, 2); block(m, 112, 29, 2);
m.set(11, 29, 'G'); m.set(55, 29, 'G'); m.set(95, 29, 'G');
// ============ 右井 x122-129 → L1(左墙底部留 3 格入口)============
m.vline(122, 17, 26, '#'); m.vline(129, 16, 29, '#');
block(m, 124, 27, 2); block(m, 126, 24, 2); block(m, 124, 21, 2); block(m, 126, 18, 2);
wall(m, 129, 26, 26, '<'); wall(m, 122, 23, 23, '>'); wall(m, 129, 20, 20, '<');
// ============ L1 中层(地板 row 16,向左折返,延伸到两侧井底)============
m.rect(1, 16, 122, 1, '#');
carpet(m, 9, 15, 112, [86]); // 86=x95:补 hgap(95) 通道列(否则门芯留一根 '^',GRAV_FALL 0.40 下回跳轨迹下降慢正好嵌进去)
ceil(m, 9, 118, 10);
vgap(m, 108, 14); vgap(m, 82, 14); vgap(m, 56, 14); vgap(m, 30, 14);
hgap(m, 95, 15); hgap(m, 43, 15);
m.set(44, 15, '.'); // 拆掉对刺门左刺'<':GRAV 0.33 下从 x45 起跳第 3 帧必被刺尖别住(起拍窗窄到 2px),清掉后留 ^+> 双刺门,整格起拍都能过
block(m, 69, 15, 2); block(m, 17, 15, 2);
m.set(113, 15, 'G'); m.set(63, 15, 'G'); m.set(21, 15, 'G');
// ============ 左井 x2-7 → L2(右墙底部留 3 格入口,桥接块接 L2 地板边)============
m.vline(8, 9, 12, '#');
block(m, 4, 13, 2); block(m, 2, 10, 2); block(m, 4, 7, 2);
block(m, 6, 7, 2); // 桥
wall(m, 8, 11, 11, '<'); wall(m, 2, 10, 10, '>');
// ============ L2 顶层(地板 row 8,向右到终点)============
m.rect(8, 8, 118, 1, '#');
carpet(m, 9, 7, 114);
m.set(8, 7, '.'); m.set(9, 7, '.'); m.set(10, 7, '.'); m.set(11, 7, '.'); // 井口净空
ceil(m, 9, 122, 2);
vgap(m, 24, 6); vgap(m, 60, 6); vgap(m, 96, 6);
hgap(m, 36, 7); hgap(m, 84, 7);
m.set(15, 7, 'G'); m.set(51, 7, 'G'); m.set(87, 7, 'G');
m.set(122, 7, 'X');
return m.out();
})(),
},
// ============================================================ j7 天降刺
{
id: 'j7', name: 'SKY SPIKES', cn: '天降刺', type: 'jump', diff: 4,
hint: '之字爬塔,每层头顶悬着掉落刺。走近就掉。别停。',
width: 72,
grid: (() => {
const W = 72, H = 52;
const m = new Grid(W, H);
m.border('#');
m.rect(1, 48, W - 2, 1, '#');
m.set(3, 47, 'S');
// 6 层之字平台:每层刺毯 + 钻石 + 掉落刺
const tiers = [
{ y: 44, x0: 4, x1: 30 }, { y: 38, x0: 34, x1: 62 },
{ y: 32, x0: 6, x1: 34 }, { y: 26, x0: 38, x1: 64 },
{ y: 20, x0: 8, x1: 36 }, { y: 14, x0: 40, x1: 64 },
];
for (const t of tiers) {
m.rect(t.x0, t.y, t.x1 - t.x0 + 1, 1, '#');
// 3/4 格交替刺毯;两端各留 2 格净空作为上一层跃入 / 下一层起跳的落脚点
const n = t.x1 - t.x0 + 1;
carpet(m, t.x0, t.y - 1, n, [0, 1, n - 2, n - 1]);
for (let x = t.x0 + 5; x <= t.x1 - 3; x += 7) m.set(x, t.y - 8, 'D');
ceil(m, t.x0 + 2, t.x1 - 2, t.y - 5); // 压顶垂刺:层内二段跳必死
vgap(m, Math.floor((t.x0 + t.x1) / 2), t.y - 2);
}
// 层间连接块(升 2 格,落点对准缺口)
block(m, 32, 46, 2);
block(m, 32, 42, 2); block(m, 34, 40, 2);
block(m, 32, 36, 2); block(m, 30, 34, 2);
block(m, 36, 30, 2); block(m, 38, 28, 2);
block(m, 36, 24, 2); block(m, 34, 22, 2);
block(m, 38, 18, 2); block(m, 40, 16, 2);
// 存档(各层缺口上)
m.set(7, 43, 'G'); m.set(37, 37, 'G'); m.set(9, 31, 'G');
m.set(41, 25, 'G'); m.set(11, 19, 'G'); m.set(43, 13, 'G');
m.set(60, 13, 'X');
return m.out();
})(),
},
// ============================================================ j8 三重威胁
{
id: 'j8', name: 'TRIPLE THREAT', cn: '三重威胁', type: 'jump', diff: 4,
hint: '冰面滑行、塌陷浮桥、单向台攀爬三连考,中间不许喘气。',
width: 130,
grid: (() => {
const W = 130, H = 26, R = 22;
const m = new Grid(W, H);
m.border('#');
m.rect(1, R, W - 2, 1, '#');
m.set(3, R - 1, 'S');
// --- x1-34 冰面段 ---
m.rect(1, R, 36, 1, '%');
for (const [a, b] of [[7, 9], [13, 15], [19, 21], [26, 29]])
for (let x = a; x <= b; x++) { m.set(x, R, '.'); m.set(x, R + 1, '^'); }
vgap(m, 11, R - 2); vgap(m, 17, R - 2); vgap(m, 24, R - 2); vgap(m, 30, R - 2);
m.set(11, R - 1, 'G'); m.set(32, R - 1, 'G');
// --- x38-74 塌陷浮桥(桥下刺海)---
for (let x = 38; x <= 74; x++) { m.set(x, R, '.'); m.set(x, R + 1, '^'); }
for (let x = 38; x <= 74; x++) m.set(x, R - 3, 'V');
m.set(46, R - 4, '^'); m.set(50, R - 4, '^'); m.set(54, R - 4, '^');
m.set(58, R - 4, '^'); m.set(62, R - 4, '^'); m.set(66, R - 4, '^'); m.set(70, R - 4, '^');
ceil(m, 40, 72, R - 9); // 垂刺限高
m.set(51, R - 4, 'G');
// --- x76-100 单向台攀爬 ---
for (let x = 76; x <= 99; x++) { m.set(x, R, '.'); m.set(x, R + 1, '^'); }
m.set(78, R - 2, '-'); m.set(79, R - 2, '-');
m.set(83, R - 4, '-'); m.set(84, R - 4, '-');
m.set(87, R - 6, '-'); m.set(88, R - 6, '-'); m.set(89, R - 6, '-');
m.set(93, R - 4, '-'); m.set(94, R - 4, '-');
m.set(97, R - 2, '-'); m.set(98, R - 2, '-');
// x86 只留压顶刺:JUMP 8.0 下 apex 盒底 479 与 '^' 顶点 480 只差 1px,
// 上升航线有 4 帧顶点落在盒内必死(8.5 时 apex 466 可从容擦过),故去掉地刺
m.set(86, R - 9, 'v');
vgap(m, 93, R - 6);
m.set(101, R - 1, 'G');
// --- x102-126 钻石收尾 ---
carpet(m, 102, R - 1, 24, [0, 1, 20, 21]);
ceil(m, 102, 125, R - 5);
vgap(m, 105, R - 2); vgap(m, 110, R - 2);
vgap(m, 115, R - 2); vgap(m, 120, R - 2);
m.set(102, R - 1, 'G');
m.set(126, R - 1, 'X');
return m.out();
})(),
},
// ============================================================ j9 樱花
{
id: 'j9', name: 'CHERRY BLOSSOM', cn: '樱花', type: 'jump', diff: 5,
hint: '双层结构收 3 个苹果:钻石缝中央一个,矮洞里一个,中层对刺门后一个。',
width: 128,
grid: (() => {
const W = 128, H = 34;
const m = new Grid(W, H);
m.border('#');
// ============ L0 下层(地板 row 28)============
m.rect(1, 28, W - 2, 1, '#');
m.set(3, 27, 'S');
carpet(m, 5, 27, 116, [54]); // 54=x59:拆开矮洞入口的四格跳(洞顶 row24 会挡跳的横向漂移)
ceil(m, 5, 120, 22);
vgap(m, 14, 26); vgap(m, 38, 26);
vgap(m, 86, 26); vgap(m, 110, 26);
block(m, 26, 27, 2); block(m, 50, 27, 2);
block(m, 74, 27, 2); block(m, 98, 27, 2);
m.set(11, 27, 'G'); m.set(55, 27, 'G'); m.set(95, 27, 'G');
// 井口前净空(否则刺毯把竖井入口封死)
m.set(117, 27, '.'); m.set(118, 27, '.'); m.set(119, 27, '.'); m.set(120, 27, '.');
// 苹果 1:钻石缝中央
m.set(62, 26, 'F');
// ============ L0 中段矮洞(顶 row 24,3 格高;撞头跳射程≈3 格,洞内缺口加密到 3)============
m.rect(60, 24, 16, 1, '#');
[63, 66, 69, 72, 75].forEach(x => m.set(x, 27, '.'));
// 苹果 2:矮洞里(跳跃途中拾取)
m.set(66, 26, 'F');
// ============ 右井 x120-126 → L1(左墙底部留 3 格入口)============
m.vline(119, 15, 24, '#'); m.vline(126, 14, 27, '#');
block(m, 121, 25, 2); block(m, 124, 22, 2); block(m, 121, 19, 2); block(m, 124, 16, 2);
wall(m, 126, 24, 24, '<'); wall(m, 119, 21, 21, '>'); wall(m, 126, 18, 18, '<');
// ============ L1 上层(地板 row 14,向左折返,延伸到井底)============
m.rect(2, 14, 118, 1, '#');
carpet(m, 9, 13, 108, [27, 59]); // 27=x36 / 59=x68:补对刺门通道列(否则整门是一面 3 连刺,往回跳必被 < 刺别住)
ceil(m, 9, 116, 8);
hgap(m, 100, 13); hgap(m, 68, 13); hgap(m, 36, 13);
vgap(m, 84, 12); vgap(m, 52, 12); vgap(m, 20, 12);
m.set(105, 13, 'G'); m.set(59, 13, 'G');
// 苹果 3:对刺门后
m.set(44, 12, 'F');
// ============ 终点(上层左端)============
m.set(10, 13, 'X');
return m.out();
})(),
},
// ============================================================ j10 毕业
{
id: 'j10', name: 'FINAL NEEDLE', cn: '毕业针刺', type: 'jump', diff: 5,
hint: '四层大考场:刺毯长廊 → 冰面折返 → 矮洞 → 高空钢丝。全程无尿点。',
width: 150,
grid: (() => {
const W = 150, H = 44;
const m = new Grid(W, H);
m.border('#');
// ============ L0 刺毯长廊(地板 row 38,向右)============
m.rect(1, 38, W - 2, 1, '#');
m.set(3, 37, 'S');
carpet(m, 5, 37, 134);
ceil(m, 5, 138, 32);
vgap(m, 20, 36); vgap(m, 48, 36); vgap(m, 76, 36);
vgap(m, 104, 36); vgap(m, 128, 36);
block(m, 34, 37, 2); block(m, 62, 37, 2);
block(m, 90, 37, 2); block(m, 118, 37, 2);
m.set(11, 37, 'G'); m.set(59, 37, 'G'); m.set(107, 37, 'G');
// ============ 右井 A x140-147 → L1(左墙底部留 3 格入口)============
m.vline(139, 29, 34, '#'); m.vline(147, 28, 37, '#');
block(m, 141, 35, 2); block(m, 144, 32, 2); block(m, 141, 29, 2); block(m, 144, 26, 2);
wall(m, 147, 34, 34, '<'); wall(m, 139, 31, 31, '>');
// ============ L1 冰面层(地板 row 28,向左,延伸到井底)============
m.rect(2, 28, 138, 1, '%');
carpet(m, 11, 27, 126);
m.set(136, 27, '.'); m.set(137, 27, '.'); m.set(138, 27, '.'); // 井 A 出口落点净空
ceil(m, 11, 136, 22);
vgap(m, 116, 26); vgap(m, 88, 26); vgap(m, 60, 26); vgap(m, 32, 26);
block(m, 102, 27, 2); block(m, 74, 27, 2); block(m, 46, 27, 2);
m.set(121, 27, 'G'); m.set(69, 27, 'G'); m.set(23, 27, 'G');
// ============ 左井 B x2-8 → L2(右墙底部留 3 格入口)============
m.vline(8, 17, 24, '#');
block(m, 4, 25, 2); block(m, 2, 22, 2); block(m, 4, 19, 2); block(m, 5, 17, 2);
wall(m, 8, 21, 21, '<'); wall(m, 2, 20, 20, '>'); wall(m, 8, 18, 18, '<');
// ============ L2 矮洞层(地板 row 16,向右,延伸到井 C 底)============
m.rect(8, 16, 138, 1, '#');
m.rect(10, 12, 128, 1, '#'); // 矮洞顶(3 格高洞)
carpet(m, 10, 15, 128);
m.set(8, 15, '.'); m.set(9, 15, '.'); // 井 B 出口净空
hgap(m, 72, 15);
m.set(19, 15, 'G'); m.set(67, 15, 'G'); m.set(115, 15, 'G');
// ============ 右井 C x140-147 → L3(左墙底部留 3 格入口,桥接块接 L3)============
m.vline(139, 9, 12, '#'); m.vline(147, 8, 15, '#');
block(m, 141, 13, 2); block(m, 144, 10, 2); block(m, 141, 7, 2);
block(m, 137, 7, 4); // 桥:向左落到 L3 基座
wall(m, 147, 12, 12, '<'); wall(m, 139, 10, 10, '>');
// ============ L3 高空钢丝(基座 row 8 + 刺毯 row 7,开放高空,向左到终点)============
m.rect(8, 8, 130, 1, '#');
spikeRun(m, 9, 7, 128, '^'); // 刺毯基底
for (let x = 133; x <= 137; x++) m.set(x, 7, '.'); // 井口落脚区
// 钢丝柱:间距 3~6 不规则,柱顶 row 5~7 错落
const wires = [];
const steps = [4, 5, 3, 6, 4, 3, 5, 4, 6, 3, 5, 4, 4, 6, 3, 5, 4, 6, 4, 3, 5, 4, 6, 3, 5, 4, 4, 3];
let wx = 132;
wires.push(wx);
for (const s of steps) { wx -= s; if (wx < 14) break; wires.push(wx); }
wires.forEach((x, i) => m.vline(x, [6, 5, 7, 6, 7, 5][i % 6], 7, '#'));
m.vline(55, 5, 7, '#'); // 过渡柱:x58→x52 原为 6 格跳,HSPD 2.6 下"晚二段"落点整体左移 8px 掉过柱顶摔死;x55 拆成 3+3 格两跳(dj=12 轨迹实测两跳都能精确接住)
// 存档放在两根钢丝顶上
const g1 = wires[6], g2 = wires[Math.floor(wires.length / 2) + 4];
const topOf = i => [6, 5, 7, 6, 7, 5][i % 6];
m.set(g1, topOf(6) - 1, 'G'); m.set(g2, topOf(wires.indexOf(g2)) - 1, 'G');
m.rect(8, 7, 4, 1, '#'); // 终点台
m.set(9, 6, 'X');
return m.out();
})(),
},
];
export default JUMP_LEVELS;
+72
View File
@@ -0,0 +1,72 @@
// 关卡地图工具:让手工 ASCII 不必逐格数点
// G(w, rows) —— 每行不足宽度自动补 '.',最后一列强制为 '#'(外墙)
export function G(w, rows) {
return rows.map(r => {
const s = r.length >= w ? r.slice(0, w) : r + '.'.repeat(w - r.length);
return s.slice(0, w - 1) + '#';
});
}
// 重复字符:rep('%', 20)
export const rep = (ch, n) => ch.repeat(Math.max(0, n | 0));
// 空格行
export const E = w => '#' + rep('.', w - 2);
// 实心跳台:plat(w, 起列, 长度) => 一行带 '#####' 的字符串
export function plat(w, x0, len, ch = '#') {
if (x0 < 1) x0 = 1;
return '#' + rep('.', x0 - 1) + rep(ch, len);
}
// 实体行:ent(w, [列, 字符], ...) => 一行只在指定列放实体字符
export function ent(w, ...items) {
const a = new Array(w).fill('.');
a[0] = '#';
for (const [x, ch] of items) if (x > 0 && x < w - 1) a[x] = ch;
return a.join('');
}
// 地板行:从 col1 开始按 [字符, 长度] 铺满,最后一列由 G 补 '#'
export function flr(...parts) {
let s = '#';
for (const [ch, n] of parts) s += rep(ch, n);
return s;
}
// ---------------- 2D 网格构建器 ----------------
// 大地图用拼字符串极易出错(宽度对不齐 / 数错列),改用网格对象:
// const m = new Map(120, 30); m.rect(x,y,w,h,'#'); ... m.out()
export class Grid {
constructor(w, h, fill = '.') {
this.w = w; this.h = h;
this.g = Array.from({ length: h }, () => new Array(w).fill(fill));
}
set(x, y, ch) {
if (x >= 0 && x < this.w && y >= 0 && y < this.h) this.g[y][x] = ch;
return this;
}
rect(x, y, w, h, ch) {
for (let iy = y; iy < y + h; iy++)
for (let ix = x; ix < x + w; ix++) this.set(ix, iy, ch);
return this;
}
hline(y, x0, x1, ch) { for (let x = x0; x <= x1; x++) this.set(x, y, ch); return this; }
vline(x, y0, y1, ch) { for (let y = y0; y <= y1; y++) this.set(x, y, ch); return this; }
border(ch = '#') {
this.hline(0, 0, this.w - 1, ch);
this.hline(this.h - 1, 0, this.w - 1, ch);
this.vline(0, 0, this.h - 1, ch);
this.vline(this.w - 1, 0, this.h - 1, ch);
return this;
}
out() { return this.g.map(r => r.join('')); }
}
/** 落脚台序列:chain(起始列, 起始宽, [间隙...], 台宽) => [{x,w}, ...] */
export function chain(x0, w0, gaps, padW = 2) {
const out = [{ x: x0, w: w0 }];
let x = x0 + w0;
for (const g of gaps) { x += g; out.push({ x, w: padW }); x += padW; }
return out;
}
+79
View File
@@ -0,0 +1,79 @@
// 经典针刺阵型库(IWBT 风格):所有函数基于 Grid,坐标单位 = 格
import { Grid } from './kit.js';
// 上下对刺夹缝(横向穿越 1 格高的缝):缝在行 y。
// 自动清理两侧地毯刺作起跳/落点(否则有效跳距翻倍,无解)。
export function vgap(m, x, y) {
m.set(x, y - 1, 'v'); m.set(x, y + 1, '^');
m.set(x - 1, y + 1, '.'); m.set(x + 1, y + 1, '.');
m.set(x - 2, y + 1, '.'); m.set(x + 2, y + 1, '.');
}
// 左右对刺夹缝(竖向穿越 1 格宽的缝):缝在列 x,自动清理两侧落点。
export function hgap(m, x, y) {
m.set(x - 1, y, '>'); m.set(x + 1, y, '<');
m.set(x - 2, y, '.'); m.set(x + 2, y, '.');
}
// 钻石阵:中心空格 + 四向刺(经典 diamond jump)
// 注意:矩形判定盒下,完整钻石的横向穿越窗口只有几像素——
// 作为"跳穿门"请用 vgap/hgap;diamond 只用作翻越/绕行的障碍或装饰。
export function diamond(m, x, y) { vgap(m, x, y); hgap(m, x, y); }
// 一排刺,gaps 为留空偏移(相对 x0)
export function spikeRun(m, x0, y, n, ch = '^', gaps = []) {
for (let i = 0; i < n; i++) if (!gaps.includes(i)) m.set(x0 + i, y, ch);
}
// 悬浮块,顶面铺刺(不可站)/ 或纯块
export function block(m, x, y, w = 1, h = 1, ch = '#') { m.rect(x, y, w, h, ch); }
// 悬浮块 + 顶刺
export function spikedBlock(m, x, y, w = 1) { m.rect(x, y, w, 1, '#'); spikeRun(m, x, y - 1, w, '^'); }
// 天花板垂刺
export function ceil(m, x0, x1, y) { m.hline(y, x0, x1, 'v'); }
// 墙刺竖段
export function wall(m, x, y0, y1, ch) { m.vline(x, y0, y1, ch); }
// 角刺块:w×h 实心块,某个外角带 L 形双刺(经典 corner)
// dir: 'tl' 左上角 / 'tr' 右上 / 'bl' 左下 / 'br' 右下
export function corner(m, x, y, w, h, dir) {
m.rect(x, y, w, h, '#');
if (dir === 'tl') { m.set(x, y - 1, '^'); m.set(x - 1, y, '>'); }
if (dir === 'tr') { m.set(x + w - 1, y - 1, '^'); m.set(x + w, y, '<'); }
if (dir === 'bl') { m.set(x, y + h, 'v'); m.set(x - 1, y + h - 1, '>'); }
if (dir === 'br') { m.set(x + w - 1, y + h, 'v'); m.set(x + w, y + h - 1, '<'); }
}
// 之字踏石竖井(可解性已用 tools/solve.mjs 验证)
// xL..xR 为井内列;topRow = 上层地板行,botRow = 下层地板行(差须为偶数且 ≥4)
// floorSide: 'l' 上层地板在井的左侧(井在右侧)/ 'r' 反之
// 规则:
// 1) 踏石每级升 2 格(单跳 90px > 64px),左右交替,宽度 w 使两级有 2 格重叠
// —— overlap 让"上升后横移"只需 1 格左右,避免横向距离超过滞空距离。
// 2) 靠地板一侧的井壁从 topRow+1 起到 botRow-4,底部留 3 格入口。
// 3) 顶台位于 topRow 且与上层地板紧邻(同高相接),不存在"洞口被顶台封死"。
export function well(m, xL, xR, topRow, botRow, floorSide = 'l', opts = {}) {
const w = opts.w || 5;
let i = 0;
for (let r = topRow; r <= botRow - 2; r += 2, i++) {
const onLeft = (i % 2 === 0) === (floorSide === 'l');
m.rect(onLeft ? xL : xR - w + 1, r, w, 1, '#');
}
const floorX = floorSide === 'l' ? xL - 1 : xR + 1;
const backX = floorSide === 'l' ? xR + 1 : xL - 1;
m.vline(backX, topRow, botRow, '#');
m.vline(floorX, topRow + 1, botRow - 4, '#');
return m;
}
// 竖井:在 (x0..x1) 之间开竖直通道,交替放小平台,两侧可布墙刺
// plats: [{y, side:'l'|'r', w}],spikeEvery: 每隔几行在对面墙上放刺
export function shaft(m, x0, x1, yTop, yBot, plats, opts = {}) {
for (const p of plats) {
const px = p.side === 'l' ? x0 : x1 - p.w + 1;
m.rect(px, p.y, p.w, 1, '#');
if (p.spike) spikeRun(m, px, p.y - 1, p.w, '^', p.spikeGaps || []);
}
if (opts.wallSpikes) {
const { side = 'r', every = 3, from = yTop + 1, to = yBot - 1 } = opts.wallSpikes;
for (let y = from; y <= to; y += every) {
if (plats.some(p => Math.abs(p.y - y) <= 1)) continue;
m.set(side === 'r' ? x1 : x0, y, side === 'r' ? '<' : '>');
}
}
}
export { Grid };
+91
View File
@@ -0,0 +1,91 @@
// 坑向(Troll / Trap)关卡:背叛玩家的一切直觉
import { G, rep, E, plat, ent, flr } from './kit.js';
export default [
// ---------------- 1 ----------------
{
id: 'r1', name: 'TRUST NO ONE', type: 'troll', diff: 3, bg: 'troll', width: 56,
hint: '路牌在骗你。那两颗"补给"也不怀好意。地板会塌。',
messages: ['← 地板很结实,放心走 →', '这颗苹果看起来很好吃'],
grid: G(56, [
rep('#', 56), // 0
E(56), E(56), E(56), E(56), E(56), E(56), // 1-6
E(56), E(56), E(56), E(56), E(56), E(56), // 7-12
E(56), // 13
ent(56, [20, 'D'], [38, 'D']), // 14
E(56), // 15
E(56), // 16
ent(56, [2, 'S'], [5, 'T'], [9, '*'], [22, 'G'], [36, '*'], [48, 'T'], [52, 'X']), // 17
flr(['#', 10], ['V', 8], ['#', 8], ['^', 5], ['#', 9], ['V', 6], ['#', 9]), // 18
]),
},
// ---------------- 2 ----------------
{
id: 'r2', name: 'FALSE GOAL', type: 'troll', diff: 4, bg: 'troll', width: 56,
hint: '地上那扇门是假的——走过去就死。真正的终点在右上角。',
messages: ['终点就在前面!→', '真的在上面。'],
grid: G(56, [
rep('#', 56), // 0
E(56), E(56), E(56), E(56), E(56), E(56), // 1-6
ent(56, [50, 'X']), // 7
plat(56, 48, 5), // 8
E(56), // 9
plat(56, 44, 5), // 10
E(56), // 11
plat(56, 38, 5), // 12
E(56), // 13
plat(56, 44, 5), // 14
E(56), // 15
plat(56, 38, 5), // 16
ent(56, [2, 'S'], [8, 'T'], [15, 'G'], [24, '^'], [25, '^'],
[30, 'X'], [36, 'G']), // 17
rep('#', 56), // 18
]),
events: [
{ x: 28, y: 14, w: 6, h: 5, once: false, actions: [{ type: 'kill' }] },
],
},
// ---------------- 3 ----------------
{
id: 'r3', name: 'BLIND', type: 'troll', diff: 4, bg: 'troll', width: 56,
hint: '摄像头接管了视野:你只能看见身边一小块地方。天上下刺也看不见。',
messages: ['摄像头已启动 ★'],
grid: G(56, [
rep('#', 56), // 0
E(56), E(56), E(56), E(56), E(56), E(56), // 1-6
E(56), E(56), E(56), E(56), E(56), E(56), // 7-12
E(56), // 13
ent(56, [18, 'D'], [30, 'D'], [44, 'D']), // 14
E(56), // 15
E(56), // 16
ent(56, [2, 'S'], [6, 'T'], [15, 'G'], [32, 'G'], [45, 'X']), // 17
flr(['#', 8], ['^', 3], ['#', 10], ['^', 4], ['#', 12], ['^', 3], ['#', 9], ['^', 4], ['#', 2]), // 18
]),
camzones: [{ x: 1, y: 14, w: 54, h: 5, mode: 'zoom', zoom: 2.6 }],
},
// ---------------- 4 ----------------
{
id: 'r4', name: 'TROLL PARADISE', type: 'troll', diff: 5, bg: 'troll', width: 64,
hint: '漩涡送你回起点,"补给"会杀你,地板会塌,天上还会下刺雨。',
messages: ['这是最后的考验(笑)', '前面的门是假的'],
grid: G(64, [
rep('#', 64), // 0
E(64), E(64), E(64), E(64), E(64), E(64), // 1-6
E(64), E(64), E(64), E(64), E(64), E(64), // 7-12
E(64), // 13
ent(64, [12, 'D'], [25, 'D'], [38, 'D'], [55, 'D']), // 14
E(64), // 15
E(64), // 16
ent(64, [2, 'S'], [5, 'T'], [7, '*'], [19, 'G'], [30, '*'],
[44, 'W'], [47, 'T'], [58, 'X']), // 17
flr(['#', 8], ['V', 6], ['#', 8], ['^', 4], ['#', 8], ['V', 6], ['#', 8], ['^', 3], ['#', 12]), // 18
]),
warps: [{ to: 'spawn' }],
events: [
{ x: 28, y: 14, w: 5, h: 5, once: false, actions: [{ type: 'spikes', x: 26, y: 0, count: 8, gap: 2 }] },
],
},
];
+47
View File
@@ -0,0 +1,47 @@
// 教学关(短,用来熟悉手感)
import { G, rep, E, plat, ent } from './kit.js';
export default [
{
id: 't1', name: 'FIRST STEPS', type: 'jump', diff: 1, bg: 'jump', width: 36,
hint: '← → 移动,Shift / Z / 空格跳跃。刺碰到就死,R 键重来。',
messages: ['← → 移动 Shift 跳跃 R 重来'],
grid: G(36, [
rep('#', 36),
E(36), E(36), E(36), E(36), E(36), E(36),
ent(36, [30, 'X']),
plat(36, 29, 5),
E(36),
plat(36, 26, 5),
E(36),
plat(36, 22, 5),
E(36),
plat(36, 18, 5),
E(36),
plat(36, 13, 5),
ent(36, [2, 'S'], [4, 'T'], [7, '^'], [8, '^'], [9, '^'], [22, 'G']),
rep('#', 36),
]),
},
{
id: 't2', name: 'DOUBLE JUMP', type: 'jump', diff: 1, bg: 'custom', width: 40,
hint: '空中再按一次跳跃=二段跳。5 格宽的刺坑只能靠二段跳过去。',
messages: ['空中再按一次 Shift = 二段跳'],
grid: G(40, [
rep('#', 40),
E(40), E(40), E(40), E(40), E(40), E(40), E(40),
ent(40, [19, 'X']),
plat(40, 18, 4),
E(40),
plat(40, 26, 4),
E(40),
plat(40, 18, 4),
E(40),
plat(40, 26, 4),
E(40),
plat(40, 18, 4),
ent(40, [2, 'S'], [4, 'T'], [11, '^'], [12, '^'], [13, '^'], [14, '^'], [15, '^'], [19, 'G']),
rep('#', 40),
]),
},
];
+352
View File
@@ -0,0 +1,352 @@
// 入口:游戏循环 / 状态机
import { LEVELS, findLevel } from './levels/index.js';
import { Level } from './level.js';
import { Player } from './player.js';
import { Camera } from './camera.js';
import { Input } from './input.js';
import { UI } from './ui.js';
import { Save } from './save.js';
import { Touch } from './touch.js';
import { sfx, unlockAudio, Audio2 } from './audio.js';
import { Editor } from './editor.js';
import { Settings } from './settings.js';
import { clamp } from './util.js';
const W = 800, H = 608;
const STEP = 1000 / 60;
// 移动端检测:触屏设备自动启用虚拟手柄;?touch=1 强制开启,?touch=0 强制关闭(桌面调试用)
// 判定条件:① 是移动端(存在 ontouchstart)/ 支持触屏(maxTouchPoints>0)/ 粗指针(触屏笔或手指)
// 只有命中才给 <html> 加 .touch 类;CSS 里 html:not(.touch) #touch 会强制隐藏,桌面端永远不显示按钮
const _qp = new URLSearchParams(location.search);
const _force = _qp.get('touch');
const _isTouch = ('ontouchstart' in window) || navigator.maxTouchPoints > 0 || matchMedia('(pointer: coarse)').matches;
const useTouch = _force === '1' || (_force !== '0' && _isTouch);
if (useTouch) document.documentElement.classList.add('touch');
function showTouch() { if (useTouch) Touch.show(); }
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d', { alpha: false });
ctx.imageSmoothingEnabled = false;
const G = {
state: 'menu', // menu | playing | paused | result | editor
level: null, player: null, cam: null,
data: null, idx: -1,
map: null, face: 0, // 多面地图:map=各面 Level 数组,face=当前面下标
fromEditor: false, // 是否从编辑器「试玩」进入(决定暂停菜单末项去向)
deaths: 0, ms: 0, hudTick: 0,
time: 0,
lastLevelId: null,
};
// ---------------- 关卡流程 ----------------
// 把一张「面」的数据包装成 Level 可用的 data(门目标来自面自身的 doors)
function faceData(map, face, i) {
return {
id: (map.id || 'map') + '-' + i,
name: face.name || ('面' + (i + 1)),
type: 'custom',
width: face.width || (face.grid[0] ? face.grid[0].length : 25),
grid: face.grid,
doors: face.doors || [],
bg: 'custom', hint: '', messages: [],
};
}
function startLevel(data, idx = -1) {
unlockAudio();
G.data = data; G.idx = idx; G.lastLevelId = data.id;
// 自制多面地图:data.faces 存在则构建每面一个 Level;否则按传统单关处理
if (data.faces && data.faces.length) {
G.map = data.faces.map((f, i) => { const L = new Level(faceData(data, f, i)); L.faceIndex = i; return L; });
G.face = Math.max(0, Math.min(data.startFace || 0, G.map.length - 1));
} else {
G.map = [new Level(data)]; G.face = 0;
}
G.level = G.map[G.face];
G.player = new Player(G.level);
G.cam = new Camera(W, H);
G.cam.reset(G.level, G.player);
G.player.onDeath = () => { G.deaths++; };
G.player.onClear = () => finish();
G.player.onPortal = (e) => doPortal(e);
G.player.onRespawnFace = () => doRespawnFace();
G.level.bosses.forEach(b => { b.onDefeat = () => finish(); });
G.deaths = 0; G.ms = 0; G.hudTick = 0;
G.state = 'playing';
UI.showGame();
showTouch();
UI.toast('');
if (data.hint) UI.toast(data.hint);
}
// 把玩家放到某面某门上(不切面的同面传送也用)
function placeOnDoor(dest) {
const P = G.player;
P.x = dest.x + dest.w / 2 - P.w / 2;
P.y = dest.y + dest.h - P.h;
P.vx = 0; P.vy = 0; P.jumps = 0;
}
// 踩到门:e.to = {face, door}
function doPortal(e) {
const to = e.to;
const tp = Math.max(0, Math.min(G.map.length - 1, to.face | 0));
if (tp === G.face) {
const dest = G.map[tp].entities.find(o => o.type === 'warp' && o.doorId === to.door);
if (dest) { placeOnDoor(dest); dest.cool = 40; }
sfx.warp();
} else {
switchFace(tp, to.door);
}
}
// 切换到第 f 面,并落到该面的目标门上
function switchFace(f, doorId) {
G.face = f;
G.level = G.map[f];
G.level.reset(true); // 进入该面时重置其运行时
G.player.level = G.level;
const dest = G.level.entities.find(o => o.type === 'warp' && o.doorId === doorId);
if (dest) { placeOnDoor(dest); dest.cool = 40; }
else { const sp = G.level.spawn; G.player.x = sp.x; G.player.y = sp.y; G.player.vx = 0; G.player.vy = 0; }
G.cam.reset(G.level, G.player);
sfx.warp();
G.level.particles.spawn(G.player.cx, G.player.cy, 12, { colors: ['#a86bff', '#fff'], speed: 2.5, life: 24 });
}
// 复活回到存档点所在面(跨面)
function doRespawnFace() {
const sp = G.player.savePoint;
if (sp && typeof sp.face === 'number' && sp.face !== G.face) {
G.face = sp.face;
G.level = G.map[sp.face];
G.level.reset(true);
G.player.level = G.level;
G.cam.reset(G.level, G.player);
}
}
/** 整关从头再来:保留死亡数,丢弃所有存档点进度 */
function restart() {
if (!G.data) return;
const d = G.deaths;
startLevel(G.data, G.idx);
G.deaths = d; // 死亡数不重置
}
/** R 键 / 触屏重生键:直接重生回最近的存档点——死亡中按 = 立即复活;活着按 = 原地播死亡动画后当帧重生 */
function suicide() {
if (!G.player || G.state !== 'playing') return;
if (G.player.dead) G.player.respawn();
// 活着按:原地播死亡动画(粒子+轻震+冲击环),但不留红叉、不计死亡数,当帧就回存档点——
// 不等待,特效由 Level 层留在死亡位置自然播完(重生不清粒子/震屏)
else { G.player.deathBurst(); G.player.respawn(); }
}
/** 触屏射击:仅在持枪、未死亡且游戏进行中时发射(受玩家自身冷却限制) */
function shoot() {
const P = G.player;
if (G.state !== 'playing' || !P || !P.alive || !P.hasGun || P.shootCool !== 0) return;
P.shoot();
}
function finish() {
if (G.state !== 'playing') return;
G.state = 'result';
Touch.hide();
sfx.goal();
const apples = G.player.apples || 0;
const total = G.level.totalApples || 0;
const better = Save.clear(G.data.id, G.deaths, G.ms, apples);
const hasNext = G.idx >= 0 && G.idx + 1 < LEVELS.length;
UI.result({
name: G.data.name, ms: G.ms, deaths: G.deaths,
apples, totalApples: total, better, hasNext,
});
}
function nextLevel() {
if (G.idx >= 0 && G.idx + 1 < LEVELS.length) startLevel(LEVELS[G.idx + 1], G.idx + 1);
else toLevels();
}
function toLevels() { G.state = 'menu'; UI.show('scr-levels'); Touch.hide(); }
function toTitle() { G.state = 'menu'; UI.show('scr-title'); Touch.hide(); }
function toEditor() {
G.state = 'editor';
UI.show('scr-editor');
Touch.hide();
// 试玩后返回:保留正在编辑的地图;从未进过编辑器时才新建
if (Editor.faces) Editor.show(); else Editor.open();
}
function pause() {
if (G.state !== 'playing') return;
G.state = 'paused';
// 暂停菜单末项:从编辑器试玩进来 → 「返回编辑器」;否则 → 「返回关卡选择」
const q = document.querySelector('#scr-pause [data-act="quit"]');
if (q) q.textContent = G.fromEditor ? '返回编辑器' : '返回关卡选择';
UI.show('scr-pause');
Touch.hide();
}
function resume() { if (G.state === 'paused') { G.state = 'playing'; UI.showGame(); showTouch(); } }
// ---------------- 更新 ----------------
function update() {
const P = G.player;
// R = 重生回存档点;Backspace = 整关重开
if (Input.hit('suicide')) { suicide(); return; }
if (Input.hit('restart')) { restart(); return; }
if (Input.hit('pause')) { pause(); return; }
const wasDead = P.dead;
G.level.update(1, P, G.cam);
for (const b of G.level.bosses) b.update(1, P);
P.update(1);
// 刚从死亡中复活:若存档点在别的面,先切回该面,再镜头瞬移
if (P.justRespawned) {
if (P.savePoint && typeof P.savePoint.face === 'number' && P.savePoint.face !== G.face) doRespawnFace();
G.cam.snapTo(P, G.level);
P.justRespawned = false;
}
G.cam.update(G.level, P, 1);
G.ms += STEP;
G.time++;
if (++G.hudTick % 5 === 0) {
const L = G.level;
UI.hud({
name: G.data.name + (G.map.length > 1 ? ` · 面${G.face + 1}/${G.map.length}` : ''),
deaths: G.deaths, ms: G.ms,
apples: P.apples, totalApples: L.totalApples, hasGun: P.hasGun,
save: P.saveIdx || 0, totalSaves: L.totalSaves || 0,
});
Touch.setGun(P.hasGun);
const boss = L.bosses.find(b => !b.dead) || L.bosses[0];
UI.bossBar(L.bosses.length ? boss : null);
}
}
// ---------------- 渲染 ----------------
function render() {
const t = G.time;
if (G.state === 'playing' || G.state === 'paused' || G.state === 'result') {
const L = G.level, P = G.player, C = G.cam;
ctx.fillStyle = '#0a0a14';
ctx.fillRect(0, 0, W, H);
L.drawBg(ctx, C, t);
ctx.save();
C.apply(ctx);
L.draw(ctx, C, t);
for (const b of L.bosses) b.draw(ctx, t);
P.draw(ctx);
ctx.restore();
L.drawOverlay(ctx, C, t);
UI.toast(L.toast || '');
// 死亡中:提示手动重生(呼吸闪烁,不抢死亡动画镜头)
if (G.state === 'playing' && P.dead) {
const blink = Math.sin(t / 12) > -0.3;
ctx.save();
ctx.textAlign = 'center';
ctx.globalAlpha = blink ? 1 : 0.3;
ctx.fillStyle = '#ff8fa3';
ctx.font = 'bold 20px monospace';
ctx.fillText(useTouch ? '按右下角重生键' : '按 R 重生', W / 2, H / 2 - 36);
ctx.globalAlpha = 0.7;
ctx.fillStyle = '#a8a8c0';
ctx.font = '12px monospace';
ctx.fillText('Backspace 整关重来', W / 2, H / 2 - 12);
ctx.restore();
}
} else {
drawTitleBg(t);
}
}
function drawTitleBg(t) {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, '#181828'); g.addColorStop(1, '#08080f');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
// 漂浮的刺
ctx.globalAlpha = 0.5;
for (let i = 0; i < 26; i++) {
const x = ((i * 137 + t * 0.15) % (W + 60)) - 30;
const y = 120 + ((i * 71) % (H - 160));
ctx.fillStyle = i % 3 === 0 ? '#3a3a4c' : '#2a2a38';
ctx.beginPath();
ctx.moveTo(x, y + 18); ctx.lineTo(x + 11, y); ctx.lineTo(x + 22, y + 18);
ctx.closePath(); ctx.fill();
}
ctx.globalAlpha = 1;
// 底部刺海
ctx.fillStyle = '#1a1a26';
ctx.fillRect(0, H - 30, W, 30);
ctx.fillStyle = '#c8c8d8';
for (let x = 0; x < W; x += 22) {
ctx.beginPath();
ctx.moveTo(x, H - 4); ctx.lineTo(x + 11, H - 26); ctx.lineTo(x + 22, H - 4);
ctx.closePath(); ctx.fill();
}
}
// ---------------- 主循环 ----------------
let last = performance.now(), acc = 0;
function loop(now) {
requestAnimationFrame(loop);
let dt = now - last; last = now;
if (dt > 200) dt = 200;
acc += dt;
let guard = 0;
while (acc >= STEP && guard++ < 6) {
acc -= STEP;
if (G.state === 'playing') update();
else if (G.state === 'paused' && Input.hit('pause')) resume();
Input.endFrame();
}
if (G.state !== 'playing') G.time++;
render();
}
// ---------------- 启动 ----------------
let settingsFrom = 'scr-title'; // 进入设置前的界面,确定后返回
Save.load();
Audio2.enabled = Save.data.audio !== false;
UI.init({
play: (lv) => { G.fromEditor = false; startLevel(lv, lv.builtin === false ? -1 : (lv.index ?? -1)); },
levels: toLevels,
manage: () => UI.setManage(!UI.manage),
editor: toEditor,
settings: () => { settingsFrom = UI.cur; Settings.enter(); UI.show('scr-settings'); },
'set-ok': () => { Settings.confirm(); UI.show(settingsFrom); },
'set-reset': () => Settings.reset(),
back: toTitle,
resume,
restart: () => { restart(); },
quit: () => (G.fromEditor ? toEditor() : toLevels()),
retry: () => startLevel(G.data, G.idx),
next: nextLevel,
wipe: () => {
if (confirm('确定清除所有通关记录与自制关卡?')) { Save.wipe(); UI.renderLevels(); }
},
});
Editor.init({
startLevel: (data) => { G.fromEditor = true; startLevel(data, -1); },
refresh: () => UI.renderLevels(),
});
// 首次交互解锁音频
const unlock = () => { unlockAudio(); removeEventListener('pointerdown', unlock); removeEventListener('keydown', unlock); };
addEventListener('pointerdown', unlock);
addEventListener('keydown', unlock);
// 移动端虚拟手柄
Touch.init({ pause, suicide, shoot });
Settings.init(useTouch);
UI.show('scr-title');
requestAnimationFrame(loop);
// 调试钩子
window.__IW = { G, LEVELS, Save, startLevel, pause, resume, restart, suicide };
+44
View File
@@ -0,0 +1,44 @@
// 粒子系统
import { rand, randInt } from './util.js';
export class Particles {
constructor() { this.list = []; }
clear() { this.list.length = 0; }
spawn(x, y, n, opt = {}) {
const {
colors = ['#fff', '#ff5c7a', '#ffc63a'],
speed = 3, life = 40, size = 3, grav = 0.12, spread = Math.PI * 2, dir = 0,
} = opt;
for (let i = 0; i < n; i++) {
const a = dir + (Math.random() - 0.5) * spread;
const s = rand(speed * 0.35, speed);
this.list.push({
x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s,
life: life * rand(0.6, 1.25), max: life,
c: colors[randInt(0, colors.length - 1)],
s: size * rand(0.6, 1.3), g: grav,
});
}
}
burst(x, y, opt = {}) { this.spawn(x, y, opt.n || 18, opt); }
update() {
for (let i = this.list.length - 1; i >= 0; i--) {
const p = this.list[i];
p.x += p.vx; p.y += p.vy; p.vy += p.g;
p.vx *= 0.985;
if (--p.life <= 0) this.list.splice(i, 1);
}
}
draw(ctx) {
for (const p of this.list) {
ctx.globalAlpha = Math.min(1, p.life / (p.max * 0.5));
ctx.fillStyle = p.c;
ctx.fillRect(p.x | 0, p.y | 0, p.s | 0, p.s | 0);
}
ctx.globalAlpha = 1;
}
}
+396
View File
@@ -0,0 +1,396 @@
// 玩家:还原 IWBT 的硬核手感 —— 松手即停、无加速、可变跳跃高度、二段跳
import { TILE, clamp, sgn, overlap } from './util.js';
import { Input } from './input.js';
import { sfx } from './audio.js';
import * as S from './sprites.js';
import { T } from './level.js';
export const PHY = {
GRAV: 0.25, // 上升段重力:小 = 跳跃飘
GRAV_FALL: 0.32, // 下落段重力:小 = 下坠轻、飘落感(0.35→0.32,用户反馈"下落有点沉")
GRAV_DJ: 0.35, // 二段跳上升段专属重力:比 GRAV 稍重——初速 6.7 与一段 6.6 一致,配 0.35 才能又冲(不起悬停)又只有 4.5 格总高
MAXFALL: 9,
JUMP: 6.6,
DJUMP: 6.7, // 二段跳冲量:起跳初速与一段 JUMP 6.6 几乎一致(起跳"嘭"感同款);顶点接二段总高 = 4.51 格
DJ_INERTIA: 0, // 二段跳时下落速度对冲量的抵消比例:0=任何时机接二段都满力起跳(初速恒 -DJUMP,同 IWBT 原版),
// 1=全额抵消(旧 bug:顶点晚几帧接二段直接归零)。0.35/0.5 都被用户反馈"好沉+短"——起跳初速被下落速度
// 吃掉才是"沉"的根源(初速从 6.7 掉到 3~4,起跳那一下没劲),与上升重力无关。
HSPD: 2.6,
WATER_GRAV: 0.16,
WATER_FALL: 2.6,
WATER_RISE: 0.42,
ICE_ACC: 0.18,
ICE_FRIC: 0.07,
// 滑出冰块后的惯性:空中几乎不损失,地面缓慢收住
SLIDE_FRIC: 0.12, // 非冰地面上收住惯性的摩擦
SLIDE_AIR: 0.02, // 空中惯性衰减(≈0,滑出冰块边缘能一路飞出去)
SLIDE_EASE: 0.14, // 超速滑行时按住同向键,收敛回正常走速的速度
SLIDE_BRAKE: 0.45, // 滑行中按反向键的刹车
SLIDE_MIN: 0.35, // 冰面上攒到多大速度才算进入滑行状态
SLIDE_STOP: 0.05, // 低于此速度惯性结束
ICE_TOP: 1.6, // 冰面最高速度 = HSPD × ICE_TOP(调大=冰上能滑得更快,留更猛的惯性)
};
export class Player {
constructor(level) {
this.level = level;
// IWBT 官方判定盒:11×21 像素(比精灵视觉略小,支持像素级擦弹/贴刺)
this.w = 11; this.h = 21;
this.reset(true);
}
reset(full) {
const sp = full ? this.level.spawn : (this.savePoint || this.level.spawn);
this.x = sp.x; this.y = sp.y;
this.vx = 0; this.vy = 0;
this.jumps = 0;
this.djUp = false;
this.grounded = false;
this.facing = 1;
this.alive = true;
this.dead = false;
this.deadT = 0;
this.deathX = 0; this.deathY = 0; // 死亡动画圆心(掉坑死亡时 clamp 到关卡内)
this.inWater = false;
this.animT = 0;
this.shootCool = 0;
this.mover = null;
this.sliding = false; // 冰面滑行惯性状态:离开冰块后仍保留
this.justRespawned = false; // 本帧刚复活(供镜头瞬移)
if (full) {
this.hasGun = !!this.level.data.startGun;
this.apples = 0;
this.savePoint = null;
this.saveIdx = 0;
}
}
get cx() { return this.x + this.w / 2; }
get cy() { return this.y + this.h / 2; }
// 纯死亡演出(不进死亡状态):粒子爆开 + 屏幕轻震 + 死亡点扩散冲击环(Level 层,见 addDeathFX)。
// 主动按重生键时直接调它再当帧 respawn——特效留在死亡位置自然播完。
// 圆心 clamp 到关卡内:掉坑死亡时玩家已在屏幕外,保证红叉/粒子/圆环可见
deathBurst() {
const L = this.level;
const dx = clamp(this.cx, 10, Math.max(10, L.pxW - 10));
const dy = clamp(this.cy, 10, Math.max(10, L.pxH - 10));
sfx.death();
L.particles.spawn(dx, dy, 16, {
colors: ['#ff5c7a', '#ff8095', '#fff', '#ffc63a'], speed: 3.4, life: 34, size: 3, grav: 0.16,
});
L.shake = Math.max(L.shake || 0, 6);
L.addDeathFX(dx, dy);
return { dx, dy };
}
// 死亡:定格在原地,等玩家手动按重生键(R / 触屏重生键)。
// 视觉:① 死亡地点留下常驻红叉(IWBTG 血迹,复活后仍在;opts.mark=false 时不留)
// ② deathBurst() 的"小"死亡动画(粒子+轻震+冲击环)
// opts:
// mark=false → 不留红叉
// count=false → 不触发 onDeath 计数(不计入死亡数)
kill(opts = {}) {
if (this.dead || !this.alive) return;
this.dead = true; this.alive = false; this.deadT = 0;
this.vx = 0; this.vy = 0; this.sliding = false;
const { dx, dy } = this.deathBurst();
this.deathX = dx; this.deathY = dy;
if (opts.mark !== false) this.level.addDeathMark(dx, dy);
if (opts.count !== false && this.onDeath) this.onDeath();
}
respawn() {
this.dead = false; this.alive = true;
const L = this.level;
const sp = this.savePoint || L.spawn;
this.x = sp.x; this.y = sp.y;
this.vx = 0; this.vy = 0; this.jumps = 0;
this.djUp = false;
this.shootCool = 0; this.sliding = false;
this.deadT = 0;
// 安全兜底:万一重生点被地形/消失块堵住,向上顶出,别一复活就卡死
let guard = 0;
while (L.solidRect(this.x, this.y, this.w, this.h) && guard++ < 48) this.y -= 2;
L.softReset(); // 不清粒子/震屏:死亡特效留在死亡位置自然播完
this.justRespawned = true; // 供 main.js 把镜头直接吸附到重生点
}
// ---------------- 每帧更新 ----------------
update(dt) {
const L = this.level;
this.animT++;
if (this.shootCool > 0) this.shootCool--;
// 死亡:定格在原地等玩家手动重生(R 键 / 触屏重生键),
// 世界继续运转(敌人/子弹/粒子照走),但玩家不响应任何输入
if (this.dead) { this.deadT++; return; }
const inWater = L.waterRect(this.x + 2, this.y + 4, this.w - 4, this.h - 4);
if (inWater && !this.inWater) sfx.splash();
this.inWater = inWater;
// ---- 水平输入(IWBT:普通地面瞬时、无惯性;冰面打滑并保留惯性)----
const moveL = Input.is('left'), moveR = Input.is('right');
const onIce = this.grounded && L.iceAtBottom(this.x, this.y, this.w, this.h);
let target = 0;
if (moveL && !moveR) target = -PHY.HSPD;
else if (moveR && !moveL) target = PHY.HSPD;
const ICE_MAX = PHY.HSPD * PHY.ICE_TOP;
const decel = f => {
if (Math.abs(this.vx) <= f) this.vx = 0;
else this.vx -= sgn(this.vx) * f;
};
if (onIce) {
// 冰面:加速/减速都很慢,速度上限也更高
if (target !== 0) this.vx += sgn(target) * PHY.ICE_ACC;
else decel(PHY.ICE_FRIC);
this.vx = clamp(this.vx, -ICE_MAX, ICE_MAX);
// 攒出一定速度即进入「滑行」状态——这是惯性得以保留的关键
if (Math.abs(this.vx) > PHY.SLIDE_MIN) this.sliding = true;
} else if (this.sliding && Math.abs(this.vx) > PHY.SLIDE_STOP) {
// 滑出冰块后:惯性依然保留 —— 空中几乎不衰减,地面才慢慢收住
if (target !== 0) {
const dir = sgn(this.vx);
if (dir === 0 || sgn(target) === dir) {
if (Math.abs(this.vx) >= PHY.HSPD) {
// 还在超速滑行:同向按键只让它缓慢收敛回正常走速,不再继续加速
this.vx -= dir * PHY.SLIDE_EASE;
if (Math.abs(this.vx) < PHY.HSPD) { this.vx = target; this.sliding = false; }
} else {
this.vx = target; // 已低于走速:交还玩家控制
this.sliding = false;
}
} else {
this.vx -= dir * PHY.SLIDE_BRAKE; // 反向按键:刹车,刹住后立刻反向
if (sgn(this.vx) === sgn(target)) { this.vx = target; this.sliding = false; }
}
this.vx = clamp(this.vx, -ICE_MAX, ICE_MAX);
} else {
decel(this.grounded ? PHY.SLIDE_FRIC : PHY.SLIDE_AIR);
if (this.vx === 0) this.sliding = false;
}
if (this.vx !== 0 && Math.abs(this.vx) < PHY.SLIDE_STOP) { this.vx = 0; this.sliding = false; }
} else {
// 常规地面/空中(非滑行):IWBT 标准手感,松手即停、无惯性
this.vx = target;
this.sliding = false;
}
if (target !== 0) this.facing = sgn(target);
// ---- 跳跃 ----
if (inWater) {
if (Input.is('jump')) this.vy -= PHY.WATER_RISE;
if (Input.is('down')) this.vy += 0.25;
this.vy = clamp(this.vy, -3.2, PHY.WATER_FALL);
this.jumps = 0; this.djUp = false;
} else {
if (Input.hit('jump')) {
if (this.grounded || this.jumps === 0) {
this.vy = -PHY.JUMP; this.jumps = 1; this.grounded = false;
// 不再做起跳拉伸:空中保持身体比例,避免跳跃时视觉上下晃动
sfx.jump();
L.particles.spawn(this.cx, this.y + this.h, 5,
{ colors: ['#fff', '#cfcfe0'], speed: 1.6, life: 16, size: 2, dir: -Math.PI / 2, spread: 2 });
} else if (this.jumps === 1) {
// 二段跳冲量叠减当前速度:上升中按 = 原版语义(直接获得 -DJUMP);
// 下落中按 = 下落惯性只抵消一部分冲量(DJUMP 前乘 DJ_INERTIA)——
// 全额抵消会让"满力一段跳到顶点、晚几帧接二段"的二段塌到接近 0(非常短),
// 只抵消一半则顶点附近接二段保持满力,摔得快时才明显变弱
this.vy = Math.max(this.vy, 0) * PHY.DJ_INERTIA - PHY.DJUMP; this.jumps = 2;
this.djUp = this.vy < 0; // 二段上升段启用专属轻重力(与一段同款飘)
sfx.djump();
L.particles.spawn(this.cx, this.cy, 10,
{ colors: ['#fff', '#9ad8ff'], speed: 2.2, life: 20, size: 2, spread: Math.PI * 2 });
}
}
// 可变跳跃高度
if (!Input.is('jump') && this.vy < -3) this.vy = -3;
// 上升轻、下落重:分手感。二段上升段用更轻的 GRAV_DJ(初速小,同款飘)
this.vy = Math.min(this.vy + (this.vy < 0 ? (this.djUp ? PHY.GRAV_DJ : PHY.GRAV) : PHY.GRAV_FALL), PHY.MAXFALL);
if (this.djUp && this.vy >= 0) this.djUp = false; // 二段到顶,交回普通重力
}
// ---- 站在移动平台上则跟随 ----
if (this.mover && !this.mover.gone) {
this.x += this.mover.dx;
this.y += this.mover.dy;
}
// ---- X 轴移动 ----
const prevBottom = this.y + this.h;
this.mover = null;
let steps = Math.abs(this.vx);
const dx = sgn(this.vx);
while (steps > 0) {
const m = Math.min(1, steps);
if (!L.solidRect(this.x + dx * m, this.y, this.w, this.h)) { this.x += dx * m; steps -= m; }
else break;
}
if (L.solidRect(this.x + dx, this.y, this.w, this.h) && Math.abs(this.vx) > 0) this.vx = 0;
// ---- Y 轴移动 ----
const dropThrough = Input.is('down');
steps = Math.abs(this.vy);
const dy = sgn(this.vy);
let hitGround = false;
while (steps > 0) {
const m = Math.min(1, steps);
const ny = this.y + dy * m;
const solidHere = L.solidRect(this.x, ny, this.w, this.h, {
prevBottom, dropThrough,
});
if (!solidHere) { this.y = ny; steps -= m; }
else {
if (dy > 0) hitGround = true;
this.vy = 0;
break;
}
}
// 检查是否踩到移动平台
for (const m of L.movers) {
if (m.gone) continue;
if (this.x + this.w > m.x && this.x < m.x + m.w) {
if (this.y + this.h >= m.y - 2 && this.y + this.h <= m.y + m.h) {
this.mover = m; hitGround = true;
}
}
}
const wasAir = !this.grounded;
this.grounded = hitGround || (this.vy === 0 && L.solidRect(this.x, this.y + 1, this.w, this.h));
if (this.grounded) {
this.jumps = 0; this.djUp = false;
}
// ---- 滑行反馈:超速滑行(冰上,或刚滑出冰块仍带惯性)时脚下溅起冰屑 ----
if (this.sliding && this.grounded && Math.abs(this.vx) > PHY.HSPD && this.animT % 5 === 0) {
L.particles.spawn(this.cx - sgn(this.vx) * 5, this.y + this.h - 2, 2, {
colors: ['#dff4ff', '#8fd8f0', '#fff'], speed: 1.1, life: 16, size: 2,
dir: -Math.PI / 2, spread: 1.7, grav: 0.1,
});
}
// ---- 边界 ----
this.x = clamp(this.x, 0, L.pxW - this.w);
if (this.y > L.pxH + 200) { this.kill(); return; }
if (this.y < -300) { this.y = -300; this.vy = 0; }
// ---- 致死:同帧立刻复活,画面上不留任何死亡状态 ----
if (L.deadlyRect(this.x, this.y, this.w, this.h)) { this.kill(); return; }
// ---- 射击 ----
if (this.hasGun && Input.hit('shoot') && this.shootCool === 0 && L.bullets.length < 5) {
this.shoot();
}
// ---- 实体交互 ----
this.touchEntities();
// ---- 消失方块踩踏 ----
if (this.grounded) {
const ty = Math.floor((this.y + this.h + 2) / TILE);
for (let tx = Math.floor(this.x / TILE); tx <= Math.floor((this.x + this.w - 1) / TILE); tx++) {
if (L.tiles[ty] && L.tiles[ty][tx] === T.VANISH && L.vanishState(tx, ty) === 0) {
L.setVanish(tx, ty, 1);
L.vanishT = L.vanishT || new Map();
L.vanishT.set(ty * 1000 + tx, 0);
}
}
}
}
shoot() {
const L = this.level;
this.shootCool = 9;
L.bullets.push({
x: this.facing > 0 ? this.x + this.w - 2 : this.x - 6,
y: this.y + 8, w: 10, h: 5,
vx: 9 * this.facing, vy: 0, life: 130, dead: false,
});
sfx.shoot();
L.particles.spawn(this.facing > 0 ? this.x + this.w : this.x, this.y + 10, 3,
{ colors: ['#fff6a0'], speed: 1.5, life: 10, size: 2 });
}
touchEntities() {
const L = this.level;
for (const e of L.entities) {
if (e.dead) continue;
// 存档点判定放宽 6px:跑得太快或从旁边擦过去也能吃到
const hit = e.type === 'save'
? overlap({ x: this.x - 6, y: this.y - 6, w: this.w + 12, h: this.h + 12 }, e)
: overlap(this, e);
if (!hit) continue;
switch (e.type) {
case 'save':
if (!e.active) {
e.active = true;
this.savePoint = { x: e.x + e.w / 2 - this.w / 2, y: e.y + e.h - this.h, face: (this.level.faceIndex ?? 0) };
this.saveIdx = e.no || 1;
sfx.save();
L.particles.spawn(e.x + e.w / 2, e.y + e.h / 2, 18,
{ colors: ['#b06bff', '#fff', '#e5d0ff'], speed: 2.6, life: 30 });
// 假存档:立刻复活回上一个存档点,不播死亡动画
if (e.fake) { L.showToast('假的。', 90); this.kill(); return; }
}
break;
case 'goal':
if (!this.clearing) { this.clearing = true; if (this.onClear) this.onClear(); }
break;
case 'gun':
if (!e.taken) {
e.taken = true; this.hasGun = true;
L.particles.spawn(e.x + e.w / 2, e.y + e.h / 2, 12, { colors: ['#dfe0f0', '#fff'], speed: 2.2, life: 24 });
L.showToast('获得手枪!按 X 射击', 120);
sfx.save();
}
break;
case 'apple':
if (!e.taken) { e.taken = true; this.apples++; sfx.save(); }
break;
case 'jumpref':
if (this.animT % 4 === 0) this.jumps = 0;
break;
case 'warp': {
if (e.cool > 0) break;
e.cool = 40;
const to = e.to;
// 自制多面地图的跨面传送门:to = {face, door} —— 交给 main 切换面
if (to && typeof to === 'object' && !('x' in to) && !('y' in to) && typeof to.face === 'number') {
if (this.onPortal) this.onPortal(e);
break;
}
// 原有逻辑(同关内传送 / 回出生点 / 绝对坐标 / pair 配对)
const tgt = to === 'spawn' ? L.spawn
: to && ('x' in to) ? { x: to.x * TILE, y: to.y * TILE }
: (() => {
const p = L.entities.find(o => o.type === 'warp' && o.idx === e.pair);
return p ? { x: p.x + p.w / 2 - this.w / 2, y: p.y + p.h - this.h } : null;
})();
if (tgt) {
this.x = tgt.x; this.y = tgt.y;
this.vx = 0; this.vy = 0;
const partner = L.entities.find(o => o.type === 'warp' && o.idx === e.pair);
if (partner) partner.cool = 40;
sfx.warp();
L.particles.spawn(this.cx, this.cy, 12, { colors: ['#a86bff', '#fff'], speed: 2.5, life: 24 });
}
break;
}
case 'sign':
if (this.animT % 30 === 0) L.showToast(e.text, 90);
break;
}
}
}
draw(ctx) {
// 死亡中:kid 已爆开,不画本体(粒子/冲击环由 Level 层渲染,重生后仍能播完)
if (this.dead) return;
S.drawKid(ctx, this, this.animT);
}
}
+59
View File
@@ -0,0 +1,59 @@
// 本地存档:通关记录、最佳成绩、自制关卡
const KEY = 'iwbtc_fan_v1';
const blank = () => ({ cleared: {}, customs: [], audio: true });
export const Save = {
data: blank(),
load() {
try {
const s = localStorage.getItem(KEY);
if (s) this.data = Object.assign(blank(), JSON.parse(s));
} catch (e) { this.data = blank(); }
return this.data;
},
flush() {
try { localStorage.setItem(KEY, JSON.stringify(this.data)); } catch (e) { }
},
get(id) { return this.data.cleared[id] || null; },
isCleared(id) { return !!this.data.cleared[id]; },
/** 记录通关,返回是否刷新纪录 */
clear(id, deaths, ms, apples) {
const old = this.data.cleared[id];
const rec = { deaths, time: ms, apples: apples || 0, at: Date.now() };
let better = false;
if (!old) { this.data.cleared[id] = rec; better = true; }
else {
const nd = Math.min(old.deaths, deaths);
const nt = Math.min(old.time, ms);
better = deaths < old.deaths || ms < old.time;
this.data.cleared[id] = { ...old, deaths: nd, time: nt, apples: Math.max(old.apples || 0, apples || 0) };
}
this.flush();
return better;
},
wipe() { this.data = blank(); this.flush(); },
customs() { return this.data.customs || []; },
addCustom(lv) {
this.data.customs = this.data.customs || [];
this.data.customs.push(lv);
this.flush();
return lv;
},
/** 更新已保存的自制关卡(按 id 就地替换,不新增);id 不存在则追加 */
updateCustom(lv) {
this.data.customs = this.data.customs || [];
const i = this.data.customs.findIndex(l => l.id === lv.id);
if (i >= 0) this.data.customs[i] = lv;
else this.data.customs.push(lv);
this.flush();
return lv;
},
removeCustom(id) {
this.data.customs = (this.data.customs || []).filter(l => l.id !== id);
this.flush();
},
setAudio(on) { this.data.audio = on; this.flush(); },
};
+335
View File
@@ -0,0 +1,335 @@
// 设置:用户名 + 设备相关自定义
// · PC(电脑端)→ 键盘按键映射
// · 移动端 → 手机虚拟手柄按钮的位置/大小(拖动调整)
import { Save } from './save.js';
import { applyBindings, defaultBindings, BIND } from './input.js';
// 每个可自定义的手柄按钮:key 对应 touch.js 里的 data-touch,
// def 为默认布局(cx/cy 为相对舞台中心的百分比,size 为按钮边长 px)
const BUTTONS = [
{ key: 'left', label: '◀', shape: 'round', def: { cx: 12, cy: 80, size: 62 } },
{ key: 'right', label: '▶', shape: 'round', def: { cx: 24, cy: 80, size: 62 } },
{ key: 'jump', label: '跳', shape: 'jump', def: { cx: 88, cy: 84, size: 94 } },
{ key: 'shoot', label: '🔫', shape: 'item', label2: '射击', def: { cx: 79, cy: 72, size: 54 } },
{ key: 'down', label: '▼', shape: 'item', label2: '下蹲', def: { cx: 90, cy: 72, size: 54 } },
{ key: 'pause', label: '❚❚', shape: 'sm', def: { cx: 81, cy: 58, size: 42 } },
{ key: 'suicide', label: '↺', shape: 'sm', def: { cx: 90, cy: 58, size: 42 } },
];
// 设置界面里可重绑的键盘动作(标签 + action)
const KEY_ACTIONS = [
['left', '左移'], ['right', '右移'],
['up', '上(上浮)'],
['jump', '跳跃'], ['shoot', '射击'],
['suicide', '自杀 / 重生'], ['restart', '整关重来'],
['pause', '暂停'],
];
const clone = (o) => JSON.parse(JSON.stringify(o));
const DEFAULT_TOUCH = {};
BUTTONS.forEach(b => { DEFAULT_TOUCH[b.key] = clone(b.def); });
const makeDefaults = () => ({ username: '', touch: clone(DEFAULT_TOUCH), keys: defaultBindings() });
// 工作副本(未点「确定」前不落盘,点「返回」即丢弃)
let work = makeDefaults();
let wrap = null;
let pcMode = false; // true=电脑端(键盘映射),false=移动端(手柄按钮)
let listening = null; // 重绑监听:{act, idx}
let conflict = null; // 冲突警告:{code, label, act}
const els = {};
let keysBox = null; // 键盘映射容器
/** 读取/补全存档里的设置对象(保证 touch / keys 字段齐全) */
function meta() {
if (!Save.data.settings) Save.data.settings = {};
const s = Save.data.settings;
if (typeof s.username !== 'string') s.username = '';
if (!s.touch) s.touch = clone(DEFAULT_TOUCH);
if (!s.keys) s.keys = defaultBindings();
return s;
}
/** 把某个按钮按 p={cx,cy,size} 绝对定位(百分比定位 + 像素边长) */
function place(el, p) {
el.style.left = p.cx + '%';
el.style.top = p.cy + '%';
el.style.width = p.size + 'px';
el.style.height = p.size + 'px';
}
/** 把当前存档布局应用到真正的 #touch 手柄按钮(游戏内生效) */
function apply() {
const t = meta().touch;
for (const b of BUTTONS) {
const el = document.querySelector(`#touch [data-touch="${b.key}"]`);
if (!el) continue;
const p = t[b.key];
if (!p) continue;
el.style.left = p.cx + '%';
el.style.top = p.cy + '%';
el.style.width = p.size + 'px';
el.style.height = p.size + 'px';
}
}
/** 标题界面显示当前用户名 */
function showUsername() {
const el = document.getElementById('title-user');
if (el) el.textContent = '玩家:' + (meta().username || '无名氏');
}
/** 把键盘 code 转成可读标签 */
function keyLabel(code) {
const M = {
Space: '空格', ShiftLeft: 'Shift', ShiftRight: 'Shift', ControlLeft: 'Ctrl', ControlRight: 'Ctrl',
AltLeft: 'Alt', AltRight: 'Alt', Tab: 'Tab', Backspace: '⌫', Escape: 'Esc', Enter: 'Enter',
ArrowLeft: '←', ArrowRight: '→', ArrowUp: '↑', ArrowDown: '↓',
MetaLeft: 'Win', MetaRight: 'Win', ContextMenu: '菜单',
};
if (M[code]) return M[code];
if (code.startsWith('Key')) return code.slice(3);
if (code.startsWith('Digit')) return code.slice(5);
if (code.startsWith('Numpad')) return '小键' + code.slice(6);
if (/^F\d{1,2}$/.test(code)) return code;
return code;
}
/** 构建设置界面里的键盘映射行(点击按键后按新键重绑) */
function renderKeys() {
if (!keysBox) return;
keysBox.innerHTML = '';
// 冲突警告横幅(始终置于面板顶部,醒目)
if (conflict) {
const w = document.createElement('div');
w.className = 'kwarb';
w.textContent = `「${keyLabel(conflict.code)}」已被【${conflict.label}】占用,请换一个键(Esc 取消)`;
keysBox.appendChild(w);
}
for (const [act, label] of KEY_ACTIONS) {
const row = document.createElement('div');
row.className = 'krow';
const nm = document.createElement('span');
nm.className = 'kact'; nm.textContent = label;
const keys = document.createElement('div');
keys.className = 'kkeys';
(work.keys[act] || []).forEach((code, idx) => {
const chip = document.createElement('button');
chip.type = 'button';
const isListen = listening && listening.act === act && listening.idx === idx;
chip.className = 'kchip' + (isListen ? ' listen' : '');
chip.dataset.kact = act; chip.dataset.kidx = idx;
chip.textContent = keyLabel(code);
const rm = document.createElement('b');
rm.className = 'krm'; rm.dataset.krm = act; rm.dataset.kidx = idx; rm.textContent = '×';
chip.appendChild(rm);
keys.appendChild(chip);
});
const add = document.createElement('button');
add.type = 'button';
add.className = 'kadd'; add.dataset.kadd = act; add.textContent = '+ 添加';
keys.appendChild(add);
if (listening && listening.act === act) {
const tip = document.createElement('span');
const isClash = conflict && conflict.act === act;
tip.className = 'klisten' + (isClash ? ' bad' : '');
tip.textContent = isClash ? '该键冲突,请换一个键(Esc 取消)' : '按下一个键…(Esc 取消)';
keys.appendChild(tip);
}
row.appendChild(nm); row.appendChild(keys);
keysBox.appendChild(row);
}
}
/** 检测 code 是否已绑定到其它动作(返回冲突动作的标签,否则 null) */
function conflictInfo(code, act, idx) {
for (const [a, label] of KEY_ACTIONS) {
const arr = work.keys[a] || [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === code && !(a === act && i === idx)) return label;
}
}
// 不可重绑的系统动作也算冲突(如「菜单」用的 KeyQ)
if (BIND.menu && BIND.menu.includes(code)) return '菜单';
return null;
}
/** 重绑监听:捕获下一次按键并写入 work.keys(检测到冲突则拒绝并提示) */
function onCaptureKey(e) {
if (!listening) return;
e.preventDefault();
if (e.code === 'Escape') { listening = null; conflict = null; renderKeys(); return; }
const { act, idx } = listening;
const clash = conflictInfo(e.code, act, idx);
if (clash) { // 该键已被其它动作占用 → 拒绝并提示
conflict = { code: e.code, label: clash, act };
renderKeys();
return; // 停留在监听态,等待换键或 Esc
}
if (idx >= (work.keys[act] || []).length) (work.keys[act] = work.keys[act] || []).push(e.code);
else work.keys[act][idx] = e.code;
conflict = null;
listening = null;
renderKeys();
}
/** 给键盘映射容器绑定点击委托(重绑 / 添加 / 删除) */
let keysWired = false;
function wireKeys() {
if (!keysBox || keysWired) return;
keysWired = true;
keysBox.addEventListener('click', (e) => {
const rm = e.target.closest('.krm');
if (rm) {
const a = rm.dataset.krm, i = +rm.dataset.kidx;
work.keys[a].splice(i, 1);
if (listening && listening.act === a) listening = null;
renderKeys();
return;
}
const chip = e.target.closest('.kchip');
if (chip) { listening = { act: chip.dataset.kact, idx: +chip.dataset.kidx }; renderKeys(); return; }
const add = e.target.closest('.kadd');
if (add) { listening = { act: add.dataset.kadd, idx: 1e9 }; renderKeys(); return; }
});
}
export const Settings = {
/** isTouch:是否移动端(由 main.js 依据 ?touch 覆盖与设备检测传入) */
init(isTouch) {
pcMode = !isTouch;
wrap = document.getElementById('touch-preview');
keysBox = document.getElementById('set-keys');
work = clone(meta());
this.build();
renderKeys();
wireKeys();
showUsername();
apply();
applyBindings(meta().keys);
document.addEventListener('keydown', onCaptureKey);
},
/** 构建设置界面里的可拖拽手柄预览(克隆 #touch 的按钮形状) */
build() {
if (!wrap) return;
wrap.querySelectorAll('.tc-btn').forEach(n => n.remove());
for (const b of BUTTONS) {
const el = document.createElement('div');
el.className = 'tc-btn tc-' + b.shape;
el.innerHTML = `<span>${b.label}</span>` + (b.label2 ? `<span class="lbl">${b.label2}</span>` : '');
const h = document.createElement('div');
h.className = 'tc-rsz';
el.appendChild(h);
wrap.appendChild(el);
els[b.key] = el;
place(el, work.touch[b.key]);
wire(el, h, b.key);
}
},
/** 打开设置界面:从存档同步工作副本与输入框,并按设备切换面板 */
enter() {
const s = meta();
work = { username: s.username || '', touch: clone(s.touch), keys: clone(s.keys) };
const inp = document.getElementById('set-username');
if (inp) inp.value = work.username;
listening = null;
conflict = null;
this.build();
renderKeys();
// 按设备显示对应面板:PC→键盘映射;移动端→手柄按钮
const keysRow = document.getElementById('set-keys-row');
const touchRow = document.getElementById('set-touch-row');
if (keysRow) keysRow.classList.toggle('hidden', !pcMode);
if (touchRow) touchRow.classList.toggle('hidden', pcMode);
},
/** 确定:保存用户名 / 手柄布局 / 键位到存档,并应用,然后由调用方返回上一页 */
confirm() {
const s = meta();
const inp = document.getElementById('set-username');
work.username = (inp ? inp.value : '').trim().slice(0, 16);
s.username = work.username;
s.touch = clone(work.touch);
s.keys = clone(work.keys);
Save.flush();
showUsername();
apply();
applyBindings(s.keys);
},
/** 恢复默认:用户名/手柄布局/键位全部回到出厂值(仅影响工作副本,需点确定才落盘) */
reset() {
work = makeDefaults();
listening = null;
conflict = null;
const inp = document.getElementById('set-username');
if (inp) inp.value = '';
this.build();
renderKeys();
},
/** 供调试 / 测试使用 */
_state() { return work; },
_els() { return els; },
_pcMode() { return pcMode; },
_conflict() { return conflict; },
_listening() { return listening; },
};
/** 给单个预览按钮绑定「拖动移动」与「右下角缩放」 */
function wire(el, handle, key) {
let mode = null; // 'move' | 'resize'
let rect = null; // 预览区矩形(按下时记录)
let lastX = 0, lastY = 0; // 上一帧指针(相对位移用)
let startSize = 0, startDist = 1, cx0 = 0, cy0 = 0; // 缩放用:按下时按钮中心与指针距离
// 按下:只记录基准,不重算绝对坐标 —— 避免任何「按下即跳角」
const begin = (e, m) => {
e.preventDefault();
try { (m === 'resize' ? handle : el).setPointerCapture(e.pointerId); } catch (_) { }
mode = m;
rect = wrap.getBoundingClientRect();
const W = rect.width || 1, H = rect.height || 1;
const p = work.touch[key];
lastX = e.clientX; lastY = e.clientY;
if (m === 'resize') {
cx0 = rect.left + p.cx / 100 * W;
cy0 = rect.top + p.cy / 100 * H;
startSize = p.size;
startDist = Math.max(1, Math.hypot(e.clientX - cx0, e.clientY - cy0));
}
};
// 移动:用「相对上一帧的位移」累加,第一帧必然停在正确位置
const drag = (e) => {
if (!mode || !rect) return;
const p = work.touch[key];
if (mode === 'move') {
const W = rect.width || 1, H = rect.height || 1;
const dx = (e.clientX - lastX) / W * 100; // 像素位移 → 百分比
const dy = (e.clientY - lastY) / H * 100;
lastX = e.clientX; lastY = e.clientY;
p.cx = Math.max(3, Math.min(97, p.cx + dx));
p.cy = Math.max(3, Math.min(97, p.cy + dy));
} else {
const d = Math.max(1, Math.hypot(e.clientX - cx0, e.clientY - cy0));
p.size = Math.max(24, Math.min(160, startSize * (d / startDist)));
}
place(el, p);
};
const end = (e) => {
if (mode) { try { (mode === 'resize' ? handle : el).releasePointerCapture(e.pointerId); } catch (_) { } }
mode = null;
};
el.addEventListener('pointerdown', (e) => { if (e.target === handle) return; begin(e, 'move'); });
handle.addEventListener('pointerdown', (e) => { e.stopPropagation(); begin(e, 'resize'); });
el.addEventListener('pointermove', drag);
handle.addEventListener('pointermove', drag);
el.addEventListener('pointerup', end);
handle.addEventListener('pointerup', end);
el.addEventListener('pointercancel', end);
handle.addEventListener('pointercancel', end);
}
+364
View File
@@ -0,0 +1,364 @@
// 程序化像素绘制(无外部图片资源)
import { TILE, shade, hashNoise } from './util.js';
const C = {
stone: '#6b6b7e', stoneDark: '#3a3a48', stoneLite: '#8f8fa6',
grass: '#4f9e46', grassDark: '#2c5c2b',
brick: '#a8543c', brickDark: '#632a1d',
metal: '#5a6478', metalDark: '#333a4a',
ice: '#8fd8f0', iceDark: '#4a90b8',
water: '#2a6fd8',
spike: '#cfdde9', spikeDark: '#a8bccf',
kid: '#d94a55', kidDark: '#8e2530', skin: '#f5cfa8', hair: '#5a3a22', pant: '#2c3a7a',
save: '#b06bff', goal: '#ffc63a', gun: '#b8b8c8', apple: '#e03050',
};
/** 归一化的像素块绘制助手 */
function px(ctx, x, y, w, h, col) { ctx.fillStyle = col; ctx.fillRect(x | 0, y | 0, w | 0, h | 0); }
// ---------------- 地形 ----------------
export function drawBlock(ctx, x, y, variant = 0, lit = false) {
const s = TILE;
let base = C.stone, dark = C.stoneDark, lite = C.stoneLite;
if (variant === 1) { base = C.grass; dark = C.grassDark; lite = '#7fd06a'; }
if (variant === 2) { base = C.brick; dark = C.brickDark; lite = '#d1785c'; }
if (variant === 3) { base = C.metal; dark = C.metalDark; lite = '#8a94ad'; }
px(ctx, x, y, s, s, dark);
px(ctx, x + 1, y + 1, s - 2, s - 2, base);
// 纹理
if (variant === 2) { // 砖
px(ctx, x + 1, y + 8, s - 2, 1, dark);
px(ctx, x + 1, y + 17, s - 2, 1, dark);
px(ctx, x + 10, y + 1, 1, 7, dark);
px(ctx, x + 20, y + 9, 1, 8, dark);
px(ctx, x + 6, y + 18, 1, 7, dark);
} else if (variant === 1) { // 草
px(ctx, x + 1, y + 1, s - 2, 5, lite);
for (let i = 0; i < 4; i++) px(ctx, x + 3 + i * 7, y + 2, 1, 4, dark);
} else { // 石
const n = hashNoise(x, y);
px(ctx, x + 2, y + 2, 6, 2, lite);
if (n > 0.5) px(ctx, x + 18, y + 12, 8, 2, dark);
if (n < 0.35) px(ctx, x + 6, y + 22, 7, 2, dark);
}
// 高光/描边
px(ctx, x, y, s, 1, lite);
px(ctx, x, y, 1, s, lite);
px(ctx, x, y + s - 1, s, 1, dark);
px(ctx, x + s - 1, y, 1, s, dark);
if (lit) { ctx.fillStyle = 'rgba(255,255,255,.09)'; ctx.fillRect(x, y, s, s); }
}
export function drawIce(ctx, x, y) {
const s = TILE;
px(ctx, x, y, s, s, C.iceDark);
px(ctx, x + 1, y + 1, s - 2, s - 2, C.ice);
px(ctx, x + 2, y + 3, 10, 3, '#e6fbff');
px(ctx, x + 18, y + 16, 8, 2, 'rgba(255,255,255,.7)');
px(ctx, x, y, s, 1, '#e6fbff');
px(ctx, x, y + s - 1, s, 1, C.iceDark);
}
export function drawWater(ctx, x, y, t) {
const s = TILE;
px(ctx, x, y, s, s, 'rgba(40,110,215,.55)');
ctx.fillStyle = 'rgba(120,200,255,.35)';
const off = Math.sin(t / 260 + x * 0.09) * 3;
ctx.fillRect(x, y + 4 + off, s, 3);
ctx.fillRect(x, y + 16 - off, s, 2);
}
export function drawOneWay(ctx, x, y) {
const s = TILE;
px(ctx, x, y, s, 6, C.metalDark);
px(ctx, x, y, s, 3, '#9aa6bd');
for (let i = 0; i < 8; i++) px(ctx, x + i * 4, y + 6, 2, 3, C.metalDark);
}
// 单个三角形刺:尖端指向 dir,底边贴在相反一侧(与 level.js 的 spikeTri 顶点完全一致)。
// 外观对齐经典 I wanna 素材:冰蓝白渐变的干净大三角,占满整格。
export function drawSpike(ctx, x, y, dir, t) {
const s = TILE;
let ax, ay, bx, by, cx, cy;
if (dir === 0) { // 朝上(地面上)
ax = x + s / 2; ay = y; bx = x; by = y + s; cx = x + s; cy = y + s;
} else if (dir === 1) { // 朝下(天花板)
ax = x + s / 2; ay = y + s; bx = x; by = y; cx = x + s; cy = y;
} else if (dir === 2) { // 朝左(贴右墙)
ax = x; ay = y + s / 2; bx = x + s; by = y; cx = x + s; cy = y + s;
} else { // 朝右(贴左墙)
ax = x + s; ay = y + s / 2; bx = x; by = y; cx = x; cy = y + s;
}
// 冰蓝白渐变:尖端最亮,往底边过渡到淡蓝
let g;
if (dir === 0) { g = ctx.createLinearGradient(x, y, x, y + s); }
else if (dir === 1) { g = ctx.createLinearGradient(x, y + s, x, y); }
else if (dir === 2) { g = ctx.createLinearGradient(x, y, x + s, y); }
else { g = ctx.createLinearGradient(x + s, y, x, y); }
g.addColorStop(0, '#f4f9fd');
g.addColorStop(0.55, '#cfdde9');
g.addColorStop(1, '#a8bccf');
ctx.beginPath();
ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.lineTo(cx, cy); ctx.closePath();
ctx.fillStyle = g; ctx.fill();
// 淡蓝描边(参考图的柔和轮廓)
ctx.strokeStyle = 'rgba(150,175,200,.9)'; ctx.lineWidth = 1; ctx.stroke();
}
/** 全致死方块(美味水果外观) */
export function drawKiller(ctx, x, y, t) {
const s = TILE;
const bob = Math.sin(t / 300 + x) * 1.5;
ctx.save();
ctx.translate(x + s / 2, y + s / 2 + bob);
// 苹果
ctx.fillStyle = C.apple;
ctx.beginPath(); ctx.arc(0, 2, 11, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#ff7a90';
ctx.beginPath(); ctx.arc(-4, -2, 4, 0, Math.PI * 2); ctx.fill();
px(ctx, -1, -13, 2, 6, '#6b4423');
ctx.fillStyle = '#3ddc84';
ctx.beginPath(); ctx.ellipse(6, -11, 5, 2.6, -0.5, 0, Math.PI * 2); ctx.fill();
// 恶作剧的眼睛
px(ctx, -5, 0, 2, 2, '#000'); px(ctx, 3, 0, 2, 2, '#000');
ctx.restore();
}
export function drawVanish(ctx, x, y, state, t) {
const s = TILE;
const alpha = state === 0 ? 1 : state === 1 ? (Math.sin(t / 60) > 0 ? 0.55 : 0.9) : 0.14;
ctx.globalAlpha = alpha;
drawBlock(ctx, x, y, 3);
ctx.globalAlpha = 1;
if (state !== 2) {
ctx.strokeStyle = 'rgba(255,200,60,.55)'; ctx.lineWidth = 1;
ctx.strokeRect(x + 2.5, y + 2.5, s - 5, s - 5);
}
}
export function drawJumpRef(ctx, x, y, t) {
const s = TILE;
const b = Math.sin(t / 200 + x) * 2;
ctx.fillStyle = '#3ddc84';
ctx.beginPath();
ctx.moveTo(x + s / 2, y + 8 + b); ctx.lineTo(x + s - 6, y + s - 10 + b); ctx.lineTo(x + 6, y + s - 10 + b);
ctx.closePath(); ctx.fill();
ctx.strokeStyle = '#0d5c30'; ctx.lineWidth = 1; ctx.stroke();
}
// ---------------- 玩家 ----------------
export function drawKid(ctx, p, t) {
const x = Math.round(p.x), y = Math.round(p.y);
const w = p.w, h = p.h;
const air = !p.grounded;
// 不做任何 squash/stretch 形变:起跳与落地都保持原始体型,
// 避免身体忽高忽低被感知为"上下晃动"(2026-10-23 用户两次反馈后彻底移除)
ctx.save();
ctx.translate(x, y);
const face = p.facing; // 1 右 -1 左
// 身体(红衣)
px(ctx, 2, 7, w - 4, 7, C.kid);
px(ctx, 2, 7, w - 4, 1, shade(C.kid, 40));
// 手臂
if (air) { px(ctx, face > 0 ? w - 3 : 0, 5, 3, 5, C.skin); }
else { px(ctx, face > 0 ? w - 3 : 0, 9, 3, 5, C.skin); }
// 腿
if (air) { px(ctx, 3, 14, 4, 4, C.pant); px(ctx, w - 7, 14, 4, 3, C.pant); }
else { px(ctx, 2, 14, 4, 4, C.pant); px(ctx, w - 6, 14, 4, 4, C.pant); }
// 头
px(ctx, 1, 0, w - 2, 8, C.skin);
px(ctx, 1, 0, w - 2, 3, C.hair); // 头发
px(ctx, face > 0 ? w - 5 : 3, 1, 3, 2, C.hair);
// 眼睛
px(ctx, face > 0 ? w - 6 : 3, 4, 2, 2, '#101018');
px(ctx, face > 0 ? w - 3 : 0, 4, 1, 2, '#101018');
ctx.restore();
// 持枪
if (p.hasGun && !p.dead) {
const gx = face > 0 ? x + w - 1 : x - 7;
const gy = y + 9;
px(ctx, gx, gy, 8, 3, C.gun);
px(ctx, face > 0 ? gx + 6 : gx, gy + 1, 3, 2, '#7a7a8c');
px(ctx, gx + 1, gy + 3, 3, 3, '#6a6a7c');
}
}
// ---------------- 实体 ----------------
export function drawSave(ctx, e, t) {
const cx = e.x + e.w / 2, cy = e.y + e.h / 2;
const on = e.active;
const pulse = 1 + Math.sin(t / 180) * 0.09;
if (on) {
ctx.globalAlpha = 0.28;
ctx.fillStyle = C.save;
ctx.beginPath(); ctx.arc(cx, cy, 15 * pulse, 0, Math.PI * 2); ctx.fill();
ctx.globalAlpha = 1;
} else {
// 未激活:画一圈呼吸光环,别让玩家看不见它
const r = 13 + Math.sin(t / 26) * 2.2;
ctx.globalAlpha = 0.30 + Math.sin(t / 26) * 0.12;
ctx.strokeStyle = '#8a6ab8';
ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.stroke();
ctx.globalAlpha = 1;
}
const col = on ? C.save : '#8f74b5';
ctx.fillStyle = col;
ctx.beginPath(); ctx.arc(cx - 3, cy - 1, 4.2, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(cx + 4, cy + 1, 4.2, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(cx, cy + 5, 4.2, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(cx + 1, cy - 5, 4.2, 0, Math.PI * 2); ctx.fill();
if (on) { ctx.fillStyle = '#e5d0ff'; ctx.beginPath(); ctx.arc(cx - 1, cy - 2, 1.6, 0, Math.PI * 2); ctx.fill(); }
// 梗
px(ctx, cx + 1, cy - 9, 2, 4, '#4a8a3a');
}
export function drawGoal(ctx, e, t) {
const x = e.x, y = e.y, w = e.w, h = e.h;
// 门
px(ctx, x + 3, y + 2, w - 6, h - 2, '#2a1e3a');
px(ctx, x + 5, y + 4, w - 10, h - 6, '#140d20');
// 光柱
const g = ctx.createLinearGradient(x, y + h, x, y);
g.addColorStop(0, 'rgba(255,200,60,.55)');
g.addColorStop(1, 'rgba(255,200,60,0)');
ctx.fillStyle = g;
ctx.fillRect(x + 5, y + 4, w - 10, h - 6);
// 闪烁粒子
for (let i = 0; i < 3; i++) {
const p = ((t / 700) + i / 3) % 1;
px(ctx, x + 7 + ((i * 9) % (w - 12)), y + h - 4 - p * (h - 8), 2, 2, C.goal);
}
// 门框
px(ctx, x + 3, y + 2, w - 6, 2, C.goal);
px(ctx, x + 3, y + 2, 2, h - 2, '#c99a1e');
px(ctx, x + w - 5, y + 2, 2, h - 2, '#c99a1e');
}
export function drawGun(ctx, e, t) {
const x = e.x, y = e.y + Math.sin(t / 250) * 2;
px(ctx, x + 2, y + 6, 20, 7, '#4a4a5c'); // 枪身
px(ctx, x + 2, y + 6, 20, 2, '#8a8aa0');
px(ctx, x + 18, y + 8, 9, 3, C.gun); // 枪管
px(ctx, x + 6, y + 13, 5, 8, '#3a3a4c'); // 握把
px(ctx, x + 8, y + 19, 3, 3, '#2a2a3a');
px(ctx, x + 24, y + 7, 2, 5, '#d0d0e0');
}
export function drawApple(ctx, e, t) {
const cx = e.x + e.w / 2, cy = e.y + e.h / 2 + Math.sin(t / 320 + e.x) * 1.5;
ctx.fillStyle = C.apple;
ctx.beginPath(); ctx.arc(cx, cy, 8, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#ff8095';
ctx.beginPath(); ctx.arc(cx - 3, cy - 3, 3, 0, Math.PI * 2); ctx.fill();
px(ctx, cx - 1, cy - 11, 2, 4, '#6b4423');
ctx.fillStyle = '#3ddc84';
ctx.beginPath(); ctx.ellipse(cx + 4, cy - 9, 4, 2, -0.5, 0, Math.PI * 2); ctx.fill();
}
export function drawWarp(ctx, e, t) {
const cx = e.x + e.w / 2, cy = e.y + e.h / 2;
for (let i = 0; i < 3; i++) {
const r = 14 - i * 4;
const a = t / (300 + i * 120);
ctx.strokeStyle = `rgba(${170 - i * 30},${90 + i * 40},255,${0.85 - i * 0.2})`;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(cx, cy, r, a, a + Math.PI * 1.4);
ctx.stroke();
}
ctx.fillStyle = 'rgba(120,60,200,.35)';
ctx.beginPath(); ctx.arc(cx, cy, 5, 0, Math.PI * 2); ctx.fill();
}
/** 摄像头对象(镜头控制区标记) */
export function drawCamera(ctx, e, t) {
const x = e.x, y = e.y, w = e.w, h = e.h;
ctx.strokeStyle = `rgba(80,220,255,${0.35 + Math.sin(t / 300) * 0.15})`;
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
ctx.strokeRect(x + 1, y + 1, w - 2, h - 2);
ctx.setLineDash([]);
// 镜头图标(放中央上方)
const ix = x + w / 2 - 9, iy = y + 6;
px(ctx, ix, iy + 3, 18, 11, '#1e1e2a');
px(ctx, ix + 2, iy + 5, 14, 7, '#3a3a4c');
ctx.fillStyle = '#7ae0ff';
ctx.beginPath(); ctx.arc(ix + 9, iy + 8.5, 3.5, 0, Math.PI * 2); ctx.fill();
px(ctx, ix + 12, iy, 5, 3, '#1e1e2a');
px(ctx, ix + 13, iy - 1, 3, 2, '#ff4060');
}
export function drawSign(ctx, e, t) {
const x = e.x, y = e.y, w = e.w, h = e.h;
px(ctx, x + w / 2 - 1, y + h - 8, 3, 8, '#6b4423');
px(ctx, x, y + 2, w, h - 10, '#c9a86b');
px(ctx, x + 2, y + 4, w - 4, h - 14, '#e8d5a8');
px(ctx, x + 4, y + 8, w - 8, 2, '#8a7550');
px(ctx, x + 4, y + 13, w - 12, 2, '#8a7550');
}
export function drawTurret(ctx, e, t) {
const x = e.x, y = e.y, s = TILE;
px(ctx, x + 2, y + 6, s - 4, s - 6, '#4a4a5e');
px(ctx, x + 4, y + 8, s - 8, s - 12, '#6a6a80');
const dirx = e.dir === 'left' ? -1 : e.dir === 'right' ? 1 : 0;
const diry = e.dir === 'up' ? -1 : e.dir === 'down' ? 1 : 0;
const cx = x + s / 2, cy = y + s / 2;
px(ctx, cx + dirx * 8 - 3, cy + diry * 8 - 3, 7, 7, '#2a2a38');
const blink = (Math.floor(t / 300) % 3) === 0;
px(ctx, cx + dirx * 12 - 2, cy + diry * 12 - 2, 4, 4, blink ? '#ff4060' : '#8a2030');
}
export function drawMovingPlatform(ctx, e) {
const x = e.x, y = e.y, w = e.w, h = e.h;
px(ctx, x, y, w, h, '#3a3a4c');
px(ctx, x + 1, y + 1, w - 2, h - 2, '#6a6a84');
px(ctx, x + 1, y + 1, w - 2, 2, '#9a9ab4');
for (let i = 0; i < w; i += 8) px(ctx, x + i + 2, y + h - 4, 4, 2, '#3a3a4c');
// 轨道虚线
ctx.strokeStyle = 'rgba(255,255,255,.10)';
ctx.setLineDash([3, 5]);
ctx.beginPath();
ctx.moveTo(e.ax + e.aw / 2, e.ay + e.ah / 2);
ctx.lineTo(e.bx + e.aw / 2, e.by + e.ah / 2);
ctx.stroke();
ctx.setLineDash([]);
}
/** 掉落刺(坑向:玩家靠近触发) */
export function drawDropSpike(ctx, e, t) {
const s = TILE;
if (!e.falling) {
ctx.globalAlpha = 0.85;
px(ctx, e.x + 4, e.y + 4, s - 8, s - 8, '#4a4a5c');
px(ctx, e.x + 6, e.y + 6, s - 12, s - 12, '#6a6a80');
ctx.globalAlpha = 1;
} else {
drawSpike(ctx, e.x, e.y, 2, t);
}
}
export function drawBullet(ctx, b) {
px(ctx, b.x - 1, b.y - 1, b.w + 2, b.h + 2, 'rgba(255,240,120,.35)');
px(ctx, b.x, b.y, b.w, b.h, '#fff6a0');
px(ctx, b.x, b.y + b.h - 2, b.w, 2, '#ffb040');
}
export function drawEBullet(ctx, b, t) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
ctx.fillStyle = b.col || '#ff5c7a';
ctx.beginPath(); ctx.arc(cx, cy, b.w / 2 + 1, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#fff';
ctx.beginPath(); ctx.arc(cx - 1.5, cy - 1.5, b.w / 4, 0, Math.PI * 2); ctx.fill();
if (b.big) {
ctx.strokeStyle = 'rgba(255,255,255,.4)';
ctx.beginPath(); ctx.arc(cx, cy, b.w / 2 + 4 + Math.sin(t / 90) * 2, 0, Math.PI * 2); ctx.stroke();
}
}
export { C, px };
+98
View File
@@ -0,0 +1,98 @@
// 移动端虚拟手柄:左手方向、右手跳跃 + 道具(参考 IWBT Creator 的触屏布局)
// 左下方:← → 移动;右下方:大跳键 + 射击/下蹲 道具键 + 暂停/重生
import { setTouch, clearTouch } from './input.js';
import { Settings } from './settings.js';
// 持续按住型动作(通过 action 状态机驱动)
const HELD = ['left', 'right', 'jump', 'down'];
const api = {
pause() {},
suicide() {},
shoot() {},
};
let visible = false;
let root = null;
function q(sel) { return document.querySelector(sel); }
function bind(btn) {
const action = btn.dataset.touch;
if (!action) return;
let timer = null;
const press = (e) => {
e.preventDefault();
if (btn._pid != null) return; // 已在按住(多指防重入)
btn._pid = e.pointerId;
try { btn.setPointerCapture(e.pointerId); } catch (_) {}
btn.classList.add('on');
if (action === 'shoot') {
// 长按连发(受玩家冷却与是否持枪限制)
api.shoot();
timer = setInterval(() => api.shoot(), 140);
} else if (HELD.includes(action)) {
setTouch(action, true);
} else if (action === 'pause') {
api.pause();
} else if (action === 'suicide') {
api.suicide();
}
};
const release = (e) => {
if (btn._pid != null && e.pointerId !== btn._pid) return;
btn._pid = null;
try { btn.releasePointerCapture(e.pointerId); } catch (_) {}
btn.classList.remove('on');
if (action === 'shoot') {
if (timer) { clearInterval(timer); timer = null; }
} else if (HELD.includes(action)) {
setTouch(action, false);
}
};
btn.addEventListener('pointerdown', press);
btn.addEventListener('pointerup', release);
btn.addEventListener('pointercancel', release);
btn.addEventListener('lostpointercapture', release);
btn.addEventListener('contextmenu', (e) => e.preventDefault());
}
export const Touch = {
init(handlers) {
Object.assign(api, handlers || {});
root = q('#touch');
root.querySelectorAll('[data-touch]').forEach(bind);
// 游戏进行中禁止页面滚动/回弹
const stage = q('#stage');
if (stage) {
stage.addEventListener('touchmove', (e) => { if (visible) e.preventDefault(); }, { passive: false });
stage.addEventListener('contextmenu', (e) => { if (visible) e.preventDefault(); });
}
},
show() {
if (!root) root = q('#touch');
if (!root) return;
visible = true;
Settings.apply(); // 应用用户自定义的手柄布局
root.classList.remove('hidden');
},
hide() {
if (!root) root = q('#touch');
if (!root) return;
visible = false;
root.classList.add('hidden');
clearTouch(); // 防止按键卡住
},
/** 反映是否持有手枪:无枪时射击键置灰 */
setGun(has) {
const g = q('#tc-gun');
if (g) g.classList.toggle('off', !has);
},
};
+174
View File
@@ -0,0 +1,174 @@
// DOM 界面:菜单 / 关卡选择 / HUD / 结算
import { LEVELS, TYPE_LABEL, TYPE_CLASS } from './levels/index.js';
import { Save } from './save.js';
import { fmtTime } from './util.js';
const $ = s => document.querySelector(s);
const $$ = s => Array.from(document.querySelectorAll(s));
const SCREENS = ['scr-title', 'scr-levels', 'scr-settings', 'scr-pause', 'scr-result', 'scr-editor'];
const TABS = [
['all', '全部'], ['jump', '跳刺'], ['endur', '耐久'], ['boss', 'BOSS'], ['troll', '坑向'], ['custom', '自制'],
];
export const UI = {
H: {}, // handlers
filter: 'all',
manage: false, // 自制页「管理」态:开启后每张自制地图显示删除按钮
cur: 'scr-title',
toastTimer: 0,
init(handlers) {
this.H = handlers;
// 按钮
$$('[data-act]').forEach(btn => {
btn.addEventListener('click', () => {
const a = btn.dataset.act;
if (this.H[a]) this.H[a]();
});
});
// 分类 tabs
const tabs = $('#level-tabs');
tabs.innerHTML = '';
TABS.forEach(([k, label]) => {
const b = document.createElement('button');
b.className = 'tab' + (k === 'all' ? ' on' : '');
b.textContent = label;
b.onclick = () => {
this.filter = k;
this.setManage(false); // 切换分类时退出管理模式
$$('#level-tabs .tab').forEach(t => t.classList.remove('on'));
b.classList.add('on');
this.renderLevels();
};
tabs.appendChild(b);
});
},
show(name) {
SCREENS.forEach(s => $('#' + s).classList.toggle('hidden', s !== name));
this.cur = name;
$('#hud').classList.toggle('hidden', name !== null && name !== '');
if (name === 'scr-levels') { this.setManage(false); this.renderLevels(); }
},
showGame() {
SCREENS.forEach(s => $('#' + s).classList.add('hidden'));
this.cur = '';
$('#hud').classList.remove('hidden');
},
renderLevels() {
const grid = $('#level-grid');
grid.innerHTML = '';
const customs = Save.customs().map((l, i) => ({ ...l, index: 100 + i, no: i + 1 }));
const all = [...LEVELS, ...customs];
const list = all.filter(l => this.filter === 'all' ? true : l.type === this.filter);
// 「管理地图」按钮只在自制分类下显示
this.updateManageBtn();
if (!list.length) {
grid.innerHTML = '<div style="color:#666;padding:20px">这个分类下还没有关卡。去「自制关卡」造一个吧。</div>';
return;
}
list.forEach(l => {
const rec = Save.get(l.id);
const card = document.createElement('div');
card.className = 'lv-card' + (rec ? ' cleared' : '') + (this.manage && l.builtin === false ? ' manage' : '');
const stars = '★'.repeat(l.diff || 1) + '☆'.repeat(Math.max(0, 5 - (l.diff || 1)));
card.innerHTML = `
<div class="idx">${l.builtin === false ? 'U' + (l.no || '') : String(l.index + 1).padStart(2, '0')}</div>
<div class="nm">${escapeHtml(l.name || 'STAGE')}</div>
<div class="meta">
<span class="tag ${TYPE_CLASS[l.type] || 't-custom'}">${TYPE_LABEL[l.type] || '自制'}</span>
<span style="color:#ffc63a">${stars}</span>
</div>
<div class="st">${rec ? `✔ 死亡 ${rec.deaths} · ${fmtTime(rec.time)}` : '未通关'}</div>
${rec ? '<div class="chk">✔</div>' : ''}
`;
// 管理态下自制卡不再可进入,只保留删除按钮,避免误点开始
if (!(this.manage && l.builtin === false)) card.onclick = () => this.H.play(l);
// 管理态:自制地图显示删除按钮
if (l.builtin === false && this.manage) {
const del = document.createElement('button');
del.className = 'lv-del';
del.textContent = '✕';
del.title = '删除这张地图';
del.onclick = (e) => { e.stopPropagation(); this.delCustom(l); };
card.appendChild(del);
}
grid.appendChild(card);
});
},
/** 刷新「管理地图」按钮:仅在自制分类可见;管理态文案变「完成」并高亮 */
updateManageBtn() {
const mb = $('#manage-btn');
if (!mb) return;
mb.classList.toggle('hidden', this.filter !== 'custom');
mb.textContent = this.manage ? '完成' : '管理地图';
mb.classList.toggle('on', this.manage);
},
/** 切换自制页的管理态(显示/隐藏删除按钮) */
setManage(on) {
// 仅自制分类可进入管理态;非自制分类的开启请求按退出处理(按钮不可见,须自动复位)
if (on && this.filter !== 'custom') on = false;
this.manage = !!on;
this.updateManageBtn();
this.renderLevels();
},
/** 删除一张自制地图(从关卡选择界面管理) */
delCustom(l) {
if (typeof confirm === 'function' && !confirm('删除地图「' + (l.name || 'MY MAP') + '」?此操作不可恢复')) return;
Save.removeCustom(l.id);
this.renderLevels();
},
hud({ name, deaths, ms, apples, totalApples, hasGun, save, totalSaves }) {
$('#hud-level').textContent = name || '';
$('#hud-deaths').textContent = 'DEATH ' + deaths;
$('#hud-time').textContent = fmtTime(ms);
const ap = $('#hud-apples');
if (totalApples > 0) { ap.style.display = ''; ap.textContent = `苹果 ${apples}/${totalApples}`; }
else ap.style.display = 'none';
const sv = $('#hud-save');
if (totalSaves > 0) {
sv.style.display = '';
sv.textContent = save > 0 ? `存档 ${save}/${totalSaves}` : `存档 0/${totalSaves}`;
sv.classList.toggle('on', save > 0);
} else sv.style.display = 'none';
},
bossBar(boss) {
const bar = $('#boss-bar');
if (!boss) { bar.classList.add('hidden'); return; }
bar.classList.remove('hidden');
$('#boss-name').textContent = boss.name;
$('#boss-fill').style.width = Math.max(0, (boss.hp / boss.maxHp) * 100) + '%';
},
toast(text) {
const el = $('#toast');
if (!text) { el.classList.remove('show'); return; }
if (el.textContent !== text) el.textContent = text;
el.classList.add('show');
},
result({ name, ms, deaths, apples, totalApples, better, hasNext }) {
$('#r-name').textContent = name;
$('#r-time').textContent = fmtTime(ms);
$('#r-death').textContent = deaths;
$('#r-apple').textContent = totalApples ? `${apples}/${totalApples}` : '—';
$('#r-best').textContent = better ? '★ 新纪录!' : '';
$('#scr-result').querySelector('[data-act="next"]').style.display = hasNext ? '' : 'none';
this.show('scr-result');
},
};
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
+45
View File
@@ -0,0 +1,45 @@
// 通用工具
export const TILE = 32;
export const ROOM_W = 800;
export const ROOM_H = 608;
export const GRID_W = ROOM_W / TILE; // 25
export const GRID_H = ROOM_H / TILE; // 19
export const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
export const lerp = (a, b, t) => a + (b - a) * t;
export const sgn = v => (v < 0 ? -1 : v > 0 ? 1 : 0);
export const rand = (a, b) => a + Math.random() * (b - a);
export const randInt = (a, b) => Math.floor(a + Math.random() * (b - a + 1));
export const pick = arr => arr[Math.floor(Math.random() * arr.length)];
export 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;
}
export function pointIn(px, py, r) {
return px >= r.x && px <= r.x + r.w && py >= r.y && py <= r.y + r.h;
}
/** 浅色/深色化 hex 颜色,n>0 变亮 n<0 变暗 */
export function shade(hex, n) {
const h = hex.replace('#', '');
const v = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
let r = (v >> 16) & 255, g = (v >> 8) & 255, b = v & 255;
r = clamp(r + n, 0, 255); g = clamp(g + n, 0, 255); b = clamp(b + n, 0, 255);
return `rgb(${r},${g},${b})`;
}
/** 时间毫秒 -> m:ss.cc */
export function fmtTime(ms) {
const t = Math.max(0, ms);
const m = Math.floor(t / 60000);
const s = Math.floor((t % 60000) / 1000);
const c = Math.floor((t % 1000) / 10);
return `${m}:${String(s).padStart(2, '0')}.${String(c).padStart(2, '0')}`;
}
/** 平滑的确定性伪随机(用于装饰,不影响帧同步) */
export function hashNoise(x, y) {
let h = x * 374761393 + y * 668265263;
h = (h ^ (h >> 13)) * 1274126177;
return ((h ^ (h >> 16)) >>> 0) / 4294967295;
}