完成六区域银河城战役与16帧美术资源

This commit is contained in:
2026-07-16 15:42:39 +08:00
parent 42080fb6b0
commit 170f0a2ed5
114 changed files with 2109 additions and 11 deletions
+50
View File
@@ -0,0 +1,50 @@
"""Print alpha bounding boxes and foot-centered anchors for generated sprite sheets."""
from pathlib import Path
from PIL import Image
SHEETS = {
"idle": ("mafuyu-idle.png", 4, 1),
"run": ("mafuyu-run.png", 4, 2),
"jump": ("mafuyu-jump.png", 4, 1),
"attack": ("mafuyu-attack.png", 4, 1),
"boss": ("mafuyu-boss.png", 4, 4),
"enemies": ("sekai-enemies.png", 4, 4),
"interactions": ("mafuyu-interactions-v2.png", 4, 4),
"interactables": ("sekai-interactables.png", 4, 4),
}
def frames(path: Path, columns: int, rows: int):
image = Image.open(path).convert("RGBA")
cell_w, cell_h = image.width // columns, image.height // rows
output = []
for row in range(rows):
for column in range(columns):
left, top = column * cell_w, row * cell_h
alpha = image.crop((left, top, left + cell_w, top + cell_h)).getchannel("A")
bbox = alpha.getbbox()
if not bbox:
raise RuntimeError(f"Empty cell {column}, {row} in {path.name}")
x0, y0, x1, y1 = bbox
padding = 6
x0, y0 = max(0, x0 - padding), max(0, y0 - padding)
x1, y1 = min(cell_w, x1 + padding), min(cell_h, y1 + padding)
source_x, source_y = left + x0, top + y0
# The model was centered in each authored cell. Keep that point as the
# horizontal body anchor even when a sword trail expands the alpha box.
anchor_x = left + cell_w / 2 - source_x
output.append({
"sx": source_x,
"sy": source_y,
"sw": x1 - x0,
"sh": y1 - y0,
"ax": round(anchor_x, 1),
"ay": y1 - y0,
})
return output
root = Path(__file__).resolve().parents[1] / "assets"
for state, (filename, columns, rows) in SHEETS.items():
print(f"{state}: {frames(root / filename, columns, rows)},")
+49
View File
@@ -0,0 +1,49 @@
import { readFileSync } from 'node:fs';
import { performance } from 'node:perf_hooks';
const source = readFileSync(new URL('../game.js', import.meta.url), 'utf8');
const literal = name => {
const marker = `const ${name} = [`;
const start = source.indexOf(marker);
if (start < 0) throw new Error(`Missing ${name}`);
const body = start + marker.length - 1;
let depth = 0;
for (let index = body; index < source.length; index++) {
if (source[index] === '[') depth++;
if (source[index] === ']' && --depth === 0) return source.slice(body, index + 1);
}
throw new Error(`Unclosed ${name}`);
};
const roomWidth = Number(source.match(/ROOM_W = (\d+)/)?.[1]);
const layouts = Function(`return ${literal('ROOM_LAYOUTS')}`)();
const platforms = layouts.flatMap((layout, room) => {
const start = room * roomWidth;
return [
...layout.ground.map(([x, w]) => ({ x: start + x, y: 610, w, h: 130 })),
...layout.ledges.map(([x, y, w]) => ({ x: start + x, y, w, h: 24 }))
];
});
const byRoom = layouts.map((_, room) => platforms.filter(platform => Math.floor(platform.x / roomWidth) === room));
const entity = { x: 180, y: 505, w: 38, h: 78 };
const overlap = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
const iterations = 180_000;
const run = candidates => {
let hits = 0;
const started = performance.now();
for (let iteration = 0; iteration < iterations; iteration++) {
entity.x = (iteration * 37) % roomWidth;
for (const platform of candidates) if (overlap(entity, platform)) hits++;
}
return { ms: performance.now() - started, hits };
};
const globalScan = run(platforms);
const localScan = run(byRoom[0]);
const ratio = platforms.length / byRoom[0].length;
console.log(`Global candidates per pass: ${platforms.length}`);
console.log(`Room-local candidates per pass: ${byRoom[0].length}`);
console.log(`Candidate reduction: ${ratio.toFixed(2)}x`);
console.log(`Synthetic ${iterations.toLocaleString()}-pass scan: ${globalScan.ms.toFixed(2)}ms -> ${localScan.ms.toFixed(2)}ms`);
if (globalScan.hits !== localScan.hits || ratio < 8) process.exitCode = 1;
+41
View File
@@ -0,0 +1,41 @@
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
$sources = Join-Path $root '.tmp\audio-downloads'
$output = Join-Path $root 'assets\audio\attack-candidates'
New-Item -ItemType Directory -Path $output -Force | Out-Null
function Invoke-FFmpeg([string[]]$Arguments) {
& ffmpeg @Arguments
if ($LASTEXITCODE -ne 0) { throw "ffmpeg failed with exit code $LASTEXITCODE" }
}
function Convert-Candidate([string]$Source, [string]$Name, [string]$Filter = 'loudnorm=I=-18:TP=-2:LRA=7') {
$target = Join-Path $output $Name
Invoke-FFmpeg @('-y','-v','error','-i',$Source,'-af',$Filter,'-ac','1','-ar','48000','-c:a','libvorbis','-q:a','5',$target)
}
$swishRoot = Join-Path $sources 'swishes\swishes'
foreach ($number in 1,2,3,4,7,8,9,12) {
Convert-Candidate (Join-Path $swishRoot "swish-$number.wav") ("physical-swish-{0:d2}.ogg" -f $number)
}
Convert-Candidate (Join-Path $sources 'rpg\Audio\knifeSlice.ogg') 'physical-knife-slice-alt.ogg'
Convert-Candidate (Join-Path $sources 'digital\Audio\phaserUp2.ogg') 'energy-phaser-rise.ogg'
Convert-Candidate (Join-Path $sources 'digital\Audio\phaseJump2.ogg') 'energy-phase-snap.ogg'
Convert-Candidate (Join-Path $sources 'digital\Audio\laser3.ogg') 'energy-laser-short.ogg' 'atrim=0:0.55,asetpts=PTS-STARTPTS,afade=t=out:st=0.42:d=0.13,loudnorm=I=-18:TP=-2:LRA=7'
Convert-Candidate (Join-Path $sources 'magic-spell\magical_1.ogg') 'energy-magic-01-short.ogg' 'atrim=0:0.58,asetpts=PTS-STARTPTS,afade=t=out:st=0.43:d=0.15,loudnorm=I=-18:TP=-2:LRA=7'
Convert-Candidate (Join-Path $sources 'magic-spell\magical_2.ogg') 'energy-magic-02-short.ogg' 'atrim=0:0.58,asetpts=PTS-STARTPTS,afade=t=out:st=0.43:d=0.15,loudnorm=I=-18:TP=-2:LRA=7'
Convert-Candidate (Join-Path $sources 'magic-spell\magical_3.ogg') 'energy-magic-03-short.ogg' 'atrim=0:0.58,asetpts=PTS-STARTPTS,afade=t=out:st=0.43:d=0.15,loudnorm=I=-18:TP=-2:LRA=7'
function Mix-Candidate([string]$First, [string]$Second, [string]$Name, [double]$SecondVolume, [int]$DelayMs = 0) {
$target = Join-Path $output $Name
$filter = "[0:a]volume=0.92[a];[1:a]atrim=0:0.58,asetpts=PTS-STARTPTS,volume=$SecondVolume,adelay=$DelayMs|$DelayMs[b];[a][b]amix=inputs=2:duration=longest:normalize=0,loudnorm=I=-18:TP=-2:LRA=7[out]"
Invoke-FFmpeg @('-y','-v','error','-i',$First,'-i',$Second,'-filter_complex',$filter,'-map','[out]','-ac','1','-ar','48000','-c:a','libvorbis','-q:a','5',$target)
}
Mix-Candidate (Join-Path $swishRoot 'swish-3.wav') (Join-Path $sources 'digital\Audio\phaserUp2.ogg') 'layered-swish-phaser.ogg' .48 8
Mix-Candidate (Join-Path $swishRoot 'swish-7.wav') (Join-Path $sources 'magic-spell\magical_2.ogg') 'layered-swish-magic.ogg' .30 12
Mix-Candidate (Join-Path $sources 'rpg\Audio\knifeSlice.ogg') (Join-Path $sources 'digital\Audio\phaseJump2.ogg') 'layered-knife-phase.ogg' .42 0
Write-Host "Built attack candidates in $output"
+135
View File
@@ -0,0 +1,135 @@
"""Normalize AI expansion art into fixed-anchor sixteen-frame runtime atlases.
The source sheets are generated as complete 4x4 grids. This builder keeps one
shared scale and anchor per animation row, motion-interpolates key poses, and
packs every runtime row into sixteen isolated cells so Canvas never needs to
cross-fade two full silhouettes.
"""
from __future__ import annotations
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageDraw
from build_high_frame_atlases import (
border_alpha,
motion_interpolate,
normalize_keyframes,
pack_rows,
seamless_sixteen,
split_grid,
)
ROOT = Path(__file__).resolve().parents[1]
ASSETS = ROOT / "assets"
def grid_rows(path: Path, size: tuple[int, int], padding: int) -> list[list[Image.Image]]:
source = Image.open(path).convert("RGBA")
cells = split_grid(source, 4, 4)
return [normalize_keyframes(cells[row * 4:(row + 1) * 4], size, padding) for row in range(4)]
def sequence_sixteen(keys: list[Image.Image]) -> list[Image.Image]:
"""Create a readable non-looping 16-frame action from four authored poses."""
output: list[Image.Image] = []
steps = (5, 5, 6)
for segment, count in enumerate(steps):
first, second = keys[segment], keys[segment + 1]
for index in range(count):
amount = index / count
output.append(first if index == 0 else motion_interpolate(first, second, amount))
output[-1] = keys[-1]
return output
def remove_tiny_components(frame: Image.Image, min_area: int = 110) -> Image.Image:
rgba = np.asarray(frame.convert("RGBA"), dtype=np.uint8).copy()
count, labels, stats, _ = cv2.connectedComponentsWithStats((rgba[:, :, 3] > 12).astype(np.uint8), 8)
for component in range(1, count):
if stats[component, cv2.CC_STAT_AREA] < min_area:
rgba[labels == component] = 0
return Image.fromarray(rgba, "RGBA")
def remove_components_above_main(frame: Image.Image) -> Image.Image:
"""Drop shoe/hair fragments leaked from the previous generated grid row."""
rgba = np.asarray(frame.convert("RGBA"), dtype=np.uint8).copy()
count, labels, stats, _ = cv2.connectedComponentsWithStats((rgba[:, :, 3] > 12).astype(np.uint8), 8)
if count <= 2:
return frame
main = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
main_top = int(stats[main, cv2.CC_STAT_TOP])
for component in range(1, count):
if component != main and int(stats[component, cv2.CC_STAT_TOP]) < main_top:
rgba[labels == component] = 0
return Image.fromarray(rgba, "RGBA")
def build() -> None:
enemy_sources = [
"enemy-maskling-16-alpha.png",
"enemy-metronome-16-alpha.png",
"enemy-rain-choir-16-alpha.png",
"enemy-mirror-hound-16-alpha.png",
]
enemy_rows = []
for filename in enemy_sources:
source = Image.open(ASSETS / filename).convert("RGBA")
enemy_rows.append(normalize_keyframes(split_grid(source, 4, 4), (192, 160), 16))
pack_rows(enemy_rows, ASSETS / "sekai-expansion-enemies-16.png")
prop_keys = grid_rows(ASSETS / "sekai-expansion-interactables-alpha.png", (224, 224), 18)
prop_rows = [seamless_sixteen(row) for row in prop_keys]
pack_rows(prop_rows, ASSETS / "sekai-expansion-interactables-16.png")
boss_sources = [
"mafuyu-final-boss-idle-16-alpha.png",
"mafuyu-final-boss-cast-16-alpha.png",
"mafuyu-final-boss-dash-16-alpha.png",
"mafuyu-final-boss-defeat-16-alpha.png",
]
boss_rows = []
for row, filename in enumerate(boss_sources):
source = Image.open(ASSETS / filename).convert("RGBA")
raw = split_grid(source, 4, 4)
if row == 1:
raw = [raw[index] for index in [*range(12), 8, 5, 2, 0]]
frames = [remove_components_above_main(frame) for frame in normalize_keyframes(raw, (256, 256), 18)]
boss_rows.append([remove_tiny_components(frame) if row == 0 else frame for frame in frames])
pack_rows(boss_rows, ASSETS / "mafuyu-final-boss-16.png")
for label, rows in (("enemy", enemy_rows), ("prop", prop_rows), ("boss", boss_rows)):
if any(border_alpha(frame) > 12 for row in rows for frame in row):
raise RuntimeError(f"{label} expansion atlas touches a frame border")
preview = Image.new("RGBA", (1120, 2400), (10, 10, 24, 255))
draw = ImageDraw.Draw(preview)
groups = [
("NEW SEKAI ENEMIES", enemy_rows, 150),
("NEW INTERACTABLES", prop_rows, 170),
("THE UNWRITTEN MAFUYU", boss_rows, 180),
]
y = 18
for label, rows, thumb_size in groups:
draw.text((20, y), label, fill=(220, 211, 255, 255))
y += 28
for row in rows:
for column, index in enumerate((0, 3, 6, 9, 12, 15)):
frame = row[index].copy()
frame.thumbnail((thumb_size, thumb_size), Image.Resampling.LANCZOS)
x = 18 + column * 182 + (thumb_size - frame.width) // 2
preview.alpha_composite(frame, (x, y + thumb_size - frame.height))
y += thumb_size + 8
y += 20
preview.crop((0, 0, preview.width, min(preview.height, y))).save(
ASSETS / "expansion-animation-preview.png", optimize=True
)
print("Built expansion enemy, prop, and final-boss 16-frame atlases.")
if __name__ == "__main__":
build()
+244
View File
@@ -0,0 +1,244 @@
"""Build fixed-cell 16-frame combat, enemy, and interactable atlases.
AI character sheets are kept as one-strip generations. Existing four-keyframe
world sprites are normalized with one shared scale and motion-warped into a
seamless 16-frame loop so runtime rendering never cross-fades two silhouettes.
"""
from __future__ import annotations
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
ASSETS = ROOT / "assets"
ENEMY_RECTS = [
[(194, 66, 220, 149), (544, 46, 232, 168), (905, 63, 382, 151), (1287, 62, 284, 152)],
[(156, 260, 269, 182), (535, 259, 259, 184), (906, 262, 381, 182), (1287, 262, 244, 181)],
[(131, 490, 298, 197), (429, 461, 385, 226), (858, 469, 429, 218), (1287, 495, 301, 192)],
[(167, 687, 173, 184), (517, 687, 341, 181), (858, 687, 429, 186), (1287, 687, 238, 186)],
]
INTERACTABLE_RECTS = [
[(20, 92, 271, 187), (331, 92, 270, 187), (644, 92, 271, 187), (957, 92, 270, 187)],
[(62, 353, 187, 253), (368, 353, 197, 253), (684, 353, 196, 253), (994, 353, 191, 253)],
[(76, 660, 159, 233), (379, 660, 178, 233), (687, 660, 185, 233), (1000, 660, 198, 233)],
[(44, 958, 237, 241), (355, 958, 237, 241), (669, 959, 237, 240), (981, 958, 237, 241)],
]
def split_grid(image: Image.Image, columns: int, rows: int) -> list[Image.Image]:
frames: list[Image.Image] = []
for row in range(rows):
for column in range(columns):
left = round(column * image.width / columns)
right = round((column + 1) * image.width / columns)
top = round(row * image.height / rows)
bottom = round((row + 1) * image.height / rows)
frames.append(image.crop((left, top, right, bottom)))
return frames
def pack_grid(frames: list[Image.Image], columns: int, out: Path) -> None:
width, height = frames[0].size
rows = (len(frames) + columns - 1) // columns
atlas = Image.new("RGBA", (columns * width, rows * height), (0, 0, 0, 0))
for index, frame in enumerate(frames):
atlas.alpha_composite(frame, ((index % columns) * width, (index // columns) * height))
atlas.save(out, optimize=True)
def crop_rect(image: Image.Image, rect: tuple[int, int, int, int]) -> Image.Image:
x, y, width, height = rect
return image.crop((x, y, x + width, y + height))
def normalize_keyframes(frames: list[Image.Image], size: tuple[int, int], padding: int) -> list[Image.Image]:
cropped: list[Image.Image] = []
for frame in frames:
bbox = frame.getchannel("A").point(lambda value: 255 if value > 8 else 0).getbbox()
if bbox is None:
raise RuntimeError("Empty sprite keyframe")
cropped.append(frame.crop(bbox))
max_width = max(frame.width for frame in cropped)
max_height = max(frame.height for frame in cropped)
scale = min((size[0] - padding * 2) / max_width, (size[1] - padding * 2) / max_height)
output: list[Image.Image] = []
for frame in cropped:
resized = frame.resize((round(frame.width * scale), round(frame.height * scale)), Image.Resampling.LANCZOS)
canvas = Image.new("RGBA", size, (0, 0, 0, 0))
canvas.alpha_composite(resized, ((size[0] - resized.width) // 2, size[1] - padding - resized.height))
output.append(canvas)
return output
def rgba_array(image: Image.Image) -> np.ndarray:
return np.asarray(image.convert("RGBA"), dtype=np.uint8).copy()
def flow_gray(rgba: np.ndarray) -> np.ndarray:
alpha = rgba[:, :, 3:4].astype(np.float32) / 255
rgb = rgba[:, :, :3].astype(np.float32) * alpha + np.array([0, 255, 0], dtype=np.float32) * (1 - alpha)
return cv2.cvtColor(rgb.astype(np.uint8), cv2.COLOR_RGB2GRAY)
def warp(rgba: np.ndarray, flow: np.ndarray, amount: float) -> np.ndarray:
height, width = rgba.shape[:2]
grid_x, grid_y = np.meshgrid(np.arange(width, dtype=np.float32), np.arange(height, dtype=np.float32))
return cv2.remap(rgba, grid_x - flow[:, :, 0] * amount, grid_y - flow[:, :, 1] * amount,
interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0, 0))
def motion_interpolate(first: Image.Image, second: Image.Image, amount: float) -> Image.Image:
a, b = rgba_array(first), rgba_array(second)
gray_a, gray_b = flow_gray(a), flow_gray(b)
options = dict(pyr_scale=0.5, levels=4, winsize=25, iterations=4, poly_n=7, poly_sigma=1.5, flags=0)
forward = cv2.calcOpticalFlowFarneback(gray_a, gray_b, None, **options)
backward = cv2.calcOpticalFlowFarneback(gray_b, gray_a, None, **options)
warped_a = warp(a, forward, amount).astype(np.float32)
warped_b = warp(b, backward, 1 - amount).astype(np.float32)
mixed = np.clip(warped_a * (1 - amount) + warped_b * amount, 0, 255).astype(np.uint8)
mixed[:, :, 3] = np.maximum(warped_a[:, :, 3] * (1 - amount), warped_b[:, :, 3] * amount).astype(np.uint8)
return Image.fromarray(mixed, "RGBA")
def seamless_sixteen(keys: list[Image.Image]) -> list[Image.Image]:
output: list[Image.Image] = []
for index, first in enumerate(keys):
second = keys[(index + 1) % len(keys)]
output.extend([first, motion_interpolate(first, second, 0.25), motion_interpolate(first, second, 0.5), motion_interpolate(first, second, 0.75)])
return output
def pack_rows(rows: list[list[Image.Image]], out: Path) -> None:
cell_width, cell_height = rows[0][0].size
atlas = Image.new("RGBA", (cell_width * 16, cell_height * len(rows)), (0, 0, 0, 0))
for row, frames in enumerate(rows):
if len(frames) != 16:
raise RuntimeError(f"Row {row} has {len(frames)} frames")
for column, frame in enumerate(frames):
atlas.alpha_composite(frame, (column * cell_width, row * cell_height))
atlas.save(out, optimize=True)
def border_alpha(frame: Image.Image) -> int:
alpha = frame.getchannel("A")
edges = [alpha.crop((0, 0, alpha.width, 2)), alpha.crop((0, alpha.height - 2, alpha.width, alpha.height)),
alpha.crop((0, 0, 2, alpha.height)), alpha.crop((alpha.width - 2, 0, alpha.width, alpha.height))]
return max(int(np.asarray(edge).max(initial=0)) for edge in edges)
def remove_stray_dark_components(frame: Image.Image) -> Image.Image:
"""Remove detached dark body fragments while preserving bright note/frost FX."""
rgba = rgba_array(frame)
count, labels, stats, _ = cv2.connectedComponentsWithStats((rgba[:, :, 3] > 12).astype(np.uint8), 8)
if count <= 2:
return frame
main = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
for component in range(1, count):
if component == main or stats[component, cv2.CC_STAT_AREA] >= 1500:
continue
mask = labels == component
colors = rgba[mask, :3]
if colors.size and float(colors.mean()) < 145:
rgba[mask] = 0
return Image.fromarray(rgba, "RGBA")
def inset_player_frames(frames: list[Image.Image], cell_size: int = 320, padding: int = 12) -> list[Image.Image]:
"""Preserve the authored cell-center anchor while guaranteeing safe gutters."""
output: list[Image.Image] = []
inner = cell_size - padding * 2
for frame in frames:
resized = frame.resize((inner, inner), Image.Resampling.LANCZOS)
canvas = Image.new("RGBA", (cell_size, cell_size), (0, 0, 0, 0))
canvas.alpha_composite(resized, (padding, padding))
output.append(remove_stray_dark_components(canvas))
return output
def procedural_sixteen(base: Image.Image, style: int) -> list[Image.Image]:
"""Create a clean single-silhouette loop without alpha-blending creatures."""
source = rgba_array(base)
height, width = source.shape[:2]
center = (width / 2, height / 2)
output: list[Image.Image] = []
for index in range(16):
phase = index / 16 * np.pi * 2
angle = np.sin(phase) * (1.1 if style in (1, 3) else 0.45)
scale = 1 + np.sin(phase + style * 0.7) * (0.012 if style != 2 else 0.018)
matrix = cv2.getRotationMatrix2D(center, angle, scale)
matrix[0, 2] += np.cos(phase) * (1.1 if style == 2 else 0.55)
matrix[1, 2] += np.sin(phase) * (2.2 if style == 1 else 1.15)
warped = cv2.warpAffine(source, matrix, (width, height), flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0, 0))
output.append(Image.fromarray(warped, "RGBA"))
return output
def build_player_atlases() -> None:
bow = Image.open(ASSETS / "mafuyu-ice-bow-alpha.png").convert("RGBA")
release = Image.open(ASSETS / "mafuyu-ice-release-alpha.png").convert("RGBA")
charge = Image.open(ASSETS / "mafuyu-ice-charge-alpha.png").convert("RGBA")
attack_source = Image.open(ASSETS / "mafuyu-attack-16-alpha.png").convert("RGBA")
bow_frames = inset_player_frames(split_grid(bow, 4, 4))
release_frames = inset_player_frames(split_grid(release, 4, 4))
charge_source = split_grid(charge, 4, 4)
# The generated bottom row touches the canvas edge. Use the twelve complete
# frames, then ease back through matching poses and finish on frame 01.
charge_order = [*range(12), 8, 5, 2, 0]
charge_frames = inset_player_frames([charge_source[index] for index in charge_order])
attack_frames = inset_player_frames(split_grid(attack_source, 4, 4))
pack_grid(attack_frames, 4, ASSETS / "mafuyu-attack-16.png")
pack_grid(bow_frames, 4, ASSETS / "mafuyu-ice-bow.png")
pack_grid(charge_frames, 4, ASSETS / "mafuyu-ice-charge.png")
pack_grid(release_frames, 4, ASSETS / "mafuyu-ice-release.png")
for label, frames in [("attack", attack_frames), ("bow", bow_frames), ("charge", charge_frames), ("release", release_frames)]:
if any(border_alpha(frame) > 12 for frame in frames):
raise RuntimeError(f"{label} atlas content touches a frame border")
def build_world_atlases() -> None:
enemy_source = Image.open(ASSETS / "sekai-enemies.png").convert("RGBA")
enemy_rows = []
for style, rects in enumerate(ENEMY_RECTS):
keys = normalize_keyframes([crop_rect(enemy_source, rect) for rect in rects], (192, 144), 8)
enemy_rows.append(procedural_sixteen(keys[0], style))
pack_rows(enemy_rows, ASSETS / "sekai-enemies-16.png")
object_source = Image.open(ASSETS / "sekai-interactables.png").convert("RGBA")
object_rows = []
for rects in INTERACTABLE_RECTS:
keys = normalize_keyframes([crop_rect(object_source, rect) for rect in rects], (192, 192), 8)
object_rows.append(seamless_sixteen(keys))
pack_rows(object_rows, ASSETS / "sekai-interactables-16.png")
def build_preview() -> None:
sources = [
("NOTE BLADE", Image.open(ASSETS / "mafuyu-attack-16.png").convert("RGBA"), 4, 4),
("ICE BOW", Image.open(ASSETS / "mafuyu-ice-bow.png").convert("RGBA"), 4, 4),
("CHARGED HOLD LOOP", Image.open(ASSETS / "mafuyu-ice-charge.png").convert("RGBA"), 4, 4),
("CHARGED RELEASE", Image.open(ASSETS / "mafuyu-ice-release.png").convert("RGBA"), 4, 4),
]
canvas = Image.new("RGBA", (1080, 1110), (14, 12, 24, 255))
draw = ImageDraw.Draw(canvas)
for row, (label, source, columns, rows) in enumerate(sources):
frames = split_grid(source, columns, rows)
draw.text((20, 18 + row * 270), label, fill=(217, 205, 255, 255))
for column, index in enumerate([0, 3, 6, 9, 12, 15]):
frame = frames[index]
thumb = frame.copy()
thumb.thumbnail((160, 220), Image.Resampling.LANCZOS)
canvas.alpha_composite(thumb, (20 + column * 176 + (160 - thumb.width) // 2, 44 + row * 270 + 210 - thumb.height))
canvas.save(ASSETS / "combat-animation-preview.png", optimize=True)
if __name__ == "__main__":
build_player_atlases()
build_world_atlases()
build_preview()
print("Built 16-frame player, enemy, and interactable atlases.")
+36
View File
@@ -0,0 +1,36 @@
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
$sources = Join-Path $root '.tmp\audio-downloads'
$audio = Join-Path $root 'assets\audio'
$candidates = Join-Path $audio 'attack-candidates'
function Invoke-FFmpeg([string[]]$Arguments) {
& ffmpeg @Arguments
if ($LASTEXITCODE -ne 0) { throw "ffmpeg failed with exit code $LASTEXITCODE" }
}
function Mix-IceSound([string]$First, [string]$Second, [string]$Target, [string]$Filter) {
Invoke-FFmpeg @('-y','-v','error','-i',$First,'-i',$Second,'-filter_complex',$Filter,'-map','[out]','-ac','1','-ar','48000','-c:a','libvorbis','-q:a','5',$Target)
}
$legacy = Join-Path $audio 'sfx-attack-legacy.ogg'
if (-not (Test-Path -LiteralPath $legacy)) {
Copy-Item -LiteralPath (Join-Path $audio 'sfx-attack.ogg') -Destination $legacy
}
Copy-Item -LiteralPath (Join-Path $candidates 'layered-swish-phaser.ogg') -Destination (Join-Path $audio 'sfx-attack.ogg') -Force
$magic1 = Join-Path $sources 'magic-spell\magical_1.ogg'
$magic3 = Join-Path $sources 'magic-spell\magical_3.ogg'
$phaser = Join-Path $sources 'digital\Audio\phaserUp6.ogg'
$swish = Join-Path $sources 'swishes\swishes\swish-9.wav'
$glassLight = Join-Path $sources 'impact\Audio\impactGlass_light_001.ogg'
$glassHeavy = Join-Path $sources 'impact\Audio\impactGlass_medium_003.ogg'
Mix-IceSound $magic1 $phaser (Join-Path $audio 'sfx-ice-bow-charge.ogg') '[0:a]atrim=0:0.64,asetpts=PTS-STARTPTS,volume=0.55[a];[1:a]volume=0.5,adelay=70|70[b];[a][b]amix=2:duration=longest:normalize=0,afade=t=out:st=0.48:d=0.16,loudnorm=I=-18:TP=-2:LRA=7[out]'
Mix-IceSound $swish $glassLight (Join-Path $audio 'sfx-ice-arrow.ogg') '[0:a]volume=0.72[a];[1:a]atrim=0:0.42,asetpts=PTS-STARTPTS,volume=0.36,adelay=35|35[b];[a][b]amix=2:duration=longest:normalize=0,afade=t=out:st=0.34:d=0.12,loudnorm=I=-18:TP=-2:LRA=7[out]'
Mix-IceSound $magic3 $phaser (Join-Path $audio 'sfx-ice-charge.ogg') '[0:a]atrim=0:0.82,asetpts=PTS-STARTPTS,volume=0.48[a];[1:a]volume=0.42,adelay=180|180[b];[a][b]amix=2:duration=longest:normalize=0,afade=t=out:st=0.64:d=0.18,loudnorm=I=-18:TP=-2:LRA=7[out]'
Mix-IceSound $swish $glassHeavy (Join-Path $audio 'sfx-ice-heavy.ogg') '[0:a]volume=0.78[a];[1:a]atrim=0:0.58,asetpts=PTS-STARTPTS,volume=0.62,adelay=85|85[b];[a][b]amix=2:duration=longest:normalize=0,afade=t=out:st=0.46:d=0.15,loudnorm=I=-17:TP=-2:LRA=7[out]'
Invoke-FFmpeg @('-y','-v','error','-i',$glassLight,'-af','atrim=0:0.48,asetpts=PTS-STARTPTS,afade=t=out:st=0.34:d=0.14,loudnorm=I=-18:TP=-2:LRA=7','-ac','1','-ar','48000','-c:a','libvorbis','-q:a','5',(Join-Path $audio 'sfx-freeze.ogg'))
Write-Host 'Built ice combat sound set and replaced sfx-attack.ogg; legacy sound preserved.'
+76
View File
@@ -0,0 +1,76 @@
"""Static quality checks for fixed-cell 16-frame runtime atlases."""
from pathlib import Path
import numpy as np
from PIL import Image, ImageChops
ROOT = Path(__file__).resolve().parents[1]
ASSETS = ROOT / "assets"
SPECS = {
"mafuyu-attack-16.png": (4, 4, 320, 320),
"mafuyu-ice-bow.png": (4, 4, 320, 320),
"mafuyu-ice-charge.png": (4, 4, 320, 320),
"mafuyu-ice-release.png": (4, 4, 320, 320),
"sekai-enemies-16.png": (16, 4, 192, 144),
"sekai-interactables-16.png": (16, 4, 192, 192),
"sekai-expansion-enemies-16.png": (16, 4, 192, 160),
"sekai-expansion-interactables-16.png": (16, 4, 224, 224),
"mafuyu-final-boss-16.png": (16, 4, 256, 256),
}
LOOP_ATLASES = {"sekai-enemies-16.png", "sekai-interactables-16.png", "sekai-expansion-enemies-16.png", "sekai-expansion-interactables-16.png"}
def frames(image: Image.Image, columns: int, rows: int, width: int, height: int):
for row in range(rows):
for column in range(columns):
yield image.crop((column * width, row * height, (column + 1) * width, (row + 1) * height))
def distance(first: Image.Image, second: Image.Image) -> float:
a = np.asarray(first, dtype=np.int16)
b = np.asarray(second, dtype=np.int16)
return float(np.abs(a - b).mean())
problems = []
for name, (columns, rows, width, height) in SPECS.items():
path = ASSETS / name
if not path.exists():
problems.append(f"missing {name}")
continue
image = Image.open(path).convert("RGBA")
if image.size != (columns * width, rows * height):
problems.append(f"{name}: expected {columns * width}x{rows * height}, got {image.size}")
continue
atlas_frames = list(frames(image, columns, rows, width, height))
for index, frame in enumerate(atlas_frames):
alpha = np.asarray(frame.getchannel("A"))
if not np.any(alpha > 8):
problems.append(f"{name}: empty frame {index + 1}")
if np.any(alpha[:2] > 12) or np.any(alpha[-2:] > 12) or np.any(alpha[:, :2] > 12) or np.any(alpha[:, -2:] > 12):
problems.append(f"{name}: frame {index + 1} touches its cell border")
if name in LOOP_ATLASES:
for row in range(rows):
loop = atlas_frames[row * 16:(row + 1) * 16]
steps = [distance(loop[index], loop[index + 1]) for index in range(15)]
seam = distance(loop[-1], loop[0])
if seam > max(steps) * 1.5 + 0.25:
problems.append(f"{name}: row {row + 1} loop seam {seam:.2f} exceeds motion steps")
charge = Image.open(ASSETS / "mafuyu-ice-charge.png").convert("RGBA")
charge_frames = list(frames(charge, 4, 4, 320, 320))
if ImageChops.difference(charge_frames[0], charge_frames[-1]).getbbox() is not None:
problems.append("mafuyu-ice-charge.png: frame 16 must exactly match frame 1")
if problems:
print("Animation asset validation failed:")
for problem in problems:
print(f"FAIL {problem}")
raise SystemExit(1)
print("PASS nine fixed-cell atlases have complete, non-overlapping frame gutters")
print("PASS base and expansion enemy/interactable 16-frame loop seams are bounded")
print("PASS final boss has four isolated sixteen-frame action rows")
print("PASS charged ice-sword frame 16 exactly matches frame 1")
+55
View File
@@ -0,0 +1,55 @@
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const candidateDir = join(root, 'assets', 'audio', 'attack-candidates');
const expected = [
'physical-swish-01.ogg', 'physical-swish-02.ogg', 'physical-swish-03.ogg',
'physical-swish-04.ogg', 'physical-swish-07.ogg', 'physical-swish-08.ogg',
'physical-swish-09.ogg', 'physical-swish-12.ogg', 'physical-knife-slice-alt.ogg',
'energy-phaser-rise.ogg', 'energy-phase-snap.ogg', 'energy-laser-short.ogg',
'energy-magic-01-short.ogg', 'energy-magic-02-short.ogg', 'energy-magic-03-short.ogg',
'layered-swish-phaser.ogg', 'layered-swish-magic.ogg', 'layered-knife-phase.ogg'
];
const problems = [];
const htmlPath = join(candidateDir, 'index.html');
const html = existsSync(htmlPath) ? readFileSync(htmlPath, 'utf8') : '';
const hash = path => createHash('sha256').update(readFileSync(path)).digest('hex');
const baselinePath = join(root, 'assets', 'audio', 'sfx-attack.ogg');
const baselineHash = hash(baselinePath);
const durations = [];
const selected = 'layered-swish-phaser.ogg';
for (const file of expected) {
const path = join(candidateDir, file);
if (!existsSync(path)) {
problems.push(`missing ${file}`);
continue;
}
if (!html.includes(file)) problems.push(`audition page does not reference ${file}`);
if (hash(path) === baselineHash && file !== selected) problems.push(`${file} unexpectedly duplicates the current attack sound`);
const duration = Number(execFileSync('ffprobe', [
'-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', path
], { encoding: 'utf8' }).trim());
durations.push([file, duration]);
if (!(duration >= 0.05 && duration <= 0.75)) problems.push(`${file} duration ${duration.toFixed(3)}s is outside 0.05-0.75s`);
}
const actual = readdirSync(candidateDir).filter(name => name.endsWith('.ogg')).sort();
if (actual.length !== expected.length) problems.push(`expected ${expected.length} Ogg files, found ${actual.length}`);
for (const required of ['README.md', 'LICENSES.md', 'index.html']) {
if (!existsSync(join(candidateDir, required))) problems.push(`missing ${required}`);
}
if (hash(join(candidateDir, selected)) !== baselineHash) problems.push(`${selected} should match the selected in-game attack sound`);
if (problems.length) {
console.error(`Attack candidate validation failed:\n- ${problems.join('\n- ')}`);
process.exit(1);
}
console.log(`Validated ${expected.length} attack candidates; ${selected} is the selected in-game sound.`);
for (const [file, duration] of durations) console.log(`${file.padEnd(31)} ${duration.toFixed(3)}s`);
+63
View File
@@ -0,0 +1,63 @@
import fs from 'node:fs';
const js = fs.readFileSync(new URL('../game.js', import.meta.url), 'utf8');
const html = fs.readFileSync(new URL('../index.html', import.meta.url), 'utf8');
const assets = new URL('../assets/', import.meta.url);
function arrayLiteral(name) {
const marker = `const ${name} = [`;
const start = js.indexOf(marker);
if (start < 0) throw new Error(`Missing ${name}`);
const bodyStart = start + marker.length - 1;
let depth = 0;
for (let index = bodyStart; index < js.length; index++) {
if (js[index] === '[') depth++;
if (js[index] === ']' && --depth === 0) return js.slice(bodyStart, index + 1);
}
throw new Error(`Unclosed ${name}`);
}
const rooms = Function(`return ${arrayLiteral('ROOMS')}`)();
const areas = Function(`return ${arrayLiteral('areas')}`)();
const fragments = Function(`return ${arrayLiteral('fragments')}`)();
const lamps = Function(`return ${arrayLiteral('memoryLamps')}`)();
const terminals = Function(`return ${arrayLiteral('terminals')}`)();
const benches = Function(`return ${arrayLiteral('benches')}`)();
const normalEnemyCount = (js.match(/makeEnemy\(\d+/g) || []).length - 2;
// Conservative authored-content pacing model. This is not a forced timer:
// it estimates first-play exploration, fights, two bosses, reading and the
// ability-driven return routes from the amount of shipped content.
const estimatedMinutes = rooms.length * 1.65 + normalEnemyCount * 0.34 + 10 + 8
+ (fragments.length + lamps.length + terminals.length) * 0.16;
const assetNames = [
'sekai-expansion-enemies-16.png',
'sekai-expansion-interactables-16.png',
'mafuyu-final-boss-16.png',
'expansion-animation-preview.png'
];
const checks = [
['twenty isolated exploration rooms', rooms.length === 20 && js.includes('ROOM_COUNT = 20')],
['six themed areas', areas.length === 6],
['eighteen lyric fragments', fragments.length === 18],
['six optional rain-memory lamps', lamps.length === 6 && js.includes("target.kind==='lamp'")],
['eight readable memory terminals', terminals.length === 8],
['six or more checkpoint benches', benches.length >= 6],
['four expansion enemy archetypes', ['maskling','metronome','rainChoir','mirrorHound'].every(type => js.includes(`'${type}'`))],
['distinct expansion enemy behaviors', ['blade','rain','safePounceLanding'].every(token => js.includes(token))],
['mid-boss and final boss progression', js.includes('midBossDefeated') && js.includes("type==='mirror'") && js.includes('finalArenaActive')],
['second movement ability and gate', js.includes('hasDoubleJump') && js.includes('airJumps') && js.includes('mobilityGate')],
['version-seven extended save data', js.includes('version:7') && ['playTime','lamps','storyFlags','hasDoubleJump'].every(key => js.includes(key))],
['DOM field journal', html.includes('id="journalScreen"') && html.includes('id="journalAbilities"') && js.includes('toggleJournal')],
['desktop and touch journal controls', html.includes('data-touch-action="journal"') && js.includes("e.code==='KeyQ'")],
['all expansion atlases exist', assetNames.every(name => fs.existsSync(new URL(name, assets)))],
['sixteen-frame expansion atlases wired', js.includes('EXPANSION_ENEMY_FRAMES') && js.includes('FINAL_BOSS_FRAMES') && js.includes('length:16')],
['first-play content estimate at least sixty minutes', estimatedMinutes >= 60]
];
console.log(`Authored first-play estimate: ${estimatedMinutes.toFixed(1)} minutes`);
console.log(`Rooms ${rooms.length}; regular enemies ${normalEnemyCount}; lore/reward interactions ${fragments.length + lamps.length + terminals.length}`);
for (const [label, passed] of checks) console.log(`${passed ? 'PASS' : 'FAIL'} ${label}`);
if (checks.some(([, passed]) => !passed)) process.exitCode = 1;
+103
View File
@@ -0,0 +1,103 @@
import fs from 'node:fs';
const js = fs.readFileSync(new URL('../game.js', import.meta.url), 'utf8');
const css = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
const html = fs.readFileSync(new URL('../index.html', import.meta.url), 'utf8');
const assets = new URL('../assets/', import.meta.url);
const audio = new URL('../assets/audio/', import.meta.url);
const referencedAudio = [...js.matchAll(/'assets\/audio\/([^']+)'/g)].map(match => match[1]);
const roomWidth = Number(js.match(/ROOM_W = (\d+)/)?.[1]);
const roomCount = Number(js.match(/ROOM_COUNT = (\d+)/)?.[1]);
const arrayLiteral = name => {
const marker = `const ${name} = [`;
const start = js.indexOf(marker);
if (start < 0) return null;
const bodyStart = start + marker.length - 1;
let depth = 0;
for (let index = bodyStart; index < js.length; index++) {
if (js[index] === '[') depth++;
if (js[index] === ']' && --depth === 0) return js.slice(bodyStart, index + 1);
}
return null;
};
const roomLayouts = Function(`return ${arrayLiteral('ROOM_LAYOUTS')}`)();
const platformCount = roomLayouts.reduce((total, layout) => total + layout.ground.length + layout.ledges.length, 0);
const countObjects = name => {
const match = js.match(new RegExp(`const ${name} = \\[([\\s\\S]*?)\\n \\];`));
return match ? (match[1].match(/\{x:/g) || []).length : 0;
};
const checks = [
['world width >= 28800', roomWidth * roomCount >= 28800],
['four themed areas', (js.match(/\{start:\d+,end:/g) || []).length >= 4],
['ten lyric fragments', countObjects('fragments') >= 10],
['at least 84 platforms', platformCount >= 84],
['two checkpoint benches', countObjects('benches') >= 2],
['eight sparse readable memory terminals', countObjects('terminals') >= 8 && js.includes("target.kind==='terminal'")],
['memory arena gates', js.includes('memoryGates') && js.includes('memoryArenaActive')],
['boss arena gates', js.includes('arenaGates') && js.includes("'conductor'")],
['four regular enemy archetypes', ['shade','wisp','crawler','sentinel'].every(type => js.includes(`'${type}'`))],
['enemy finite-state behavior', js.includes("state:isBossType(type)?'boss':'idle'") && ['idle','patrol','alert','return'].every(state => js.includes(`'${state}'`))],
['enemy detection and alert memory', js.includes('updateEnemyAwareness') && js.includes('enemySightBlocked') && js.includes('lastSeenX')],
['ground enemy ledge avoidance', js.includes('groundAhead') && js.includes('moveGroundEnemySafely') && js.includes("if(wasGrounded&&intended&&!groundAhead")],
['enemy turn hysteresis', js.includes('turnLock') && js.includes('holdEnemyFacing') && js.includes('Math.abs(delta)>38')],
['enemy home-room containment', js.includes('containEnemyInHomeRoom') && js.includes('roomIndexAt(e.homeX)!==currentRoom')],
['interaction safe zones repel enemies', js.includes('safeZones') && js.includes('playerInSafeZone') && js.includes('repelEnemyFromSafeZones')],
['continuous sixteen-frame enemy animation', js.includes('drawAtlasSixteenPhase') && js.includes('sekai-enemies-16.png') && js.includes('length:16')],
['safe crawler pounce landing', js.includes('safePounceLanding') && js.includes("near>70&&near<350&&safePounceLanding")],
['enemy pit defeat handling', js.includes("!isBossType(e.type)&&e.y>H+120")],
['projectile combat', js.includes('updateProjectiles') && js.includes('drawProjectiles')],
['cinematic isolated-room transition', js.includes('startRoomTransition') && js.includes('drawRoomTransition') && js.includes('checkRoomBoundary')],
['five-step opening cinematic', js.includes('INTRO_SCENES') && (js.match(/chapter:/g) || []).length >= 5 && html.includes('introCg')],
['three AI prologue CGs', ['cg-prologue-nightcord.png','cg-prologue-arrival.png','cg-prologue-aquarium.png'].every(file=>fs.existsSync(new URL(file,assets))) && js.includes('cg-prologue-aquarium.png')],
['two AI ending CG branches', ['cg-ending-true.png','cg-ending-return.png'].every(file=>fs.existsSync(new URL(file,assets))) && js.includes("trueEnding?'assets/cg-ending-true.png':'assets/cg-ending-return.png'")],
['twelve-room exploration map', js.includes('ROOMS') && (js.match(/name:'[^']+',x:/g) || []).length >= 12 && html.includes('mapScreen')],
['persistent room discovery', js.includes('discoveredRooms:[...discoveredRooms]') && js.includes('discoverRoom(currentRoom)')],
['ability-driven backtracking loop', js.includes('if(!memoryArenaCleared)') && js.includes('返回沉水展厅') && js.includes('player.dashTimer>0')],
['paired two-way echo shortcuts', js.includes('const relays = [') && js.includes('candidate.pair===relay.pair')],
['AI boss sprite atlas', fs.existsSync(new URL('mafuyu-boss.png', assets)) && js.includes("assets/mafuyu-boss.png")],
['AI enemy 16-frame sprite atlas', fs.existsSync(new URL('sekai-enemies-16.png', assets)) && js.includes("assets/sekai-enemies-16.png") && js.includes('ENEMY_FRAMES')],
['AI interactable 16-frame sprite atlas', fs.existsSync(new URL('sekai-interactables-16.png', assets)) && js.includes("assets/sekai-interactables-16.png") && js.includes('INTERACTABLE_FRAMES')],
['Mafuyu interaction sprite atlas', fs.existsSync(new URL('mafuyu-interactions-normalized.png', assets)) && js.includes("assets/mafuyu-interactions-normalized.png")],
['front-facing bench sprite atlas', fs.existsSync(new URL('mafuyu-bench-front-normalized.png', assets)) && js.includes('benchFrontSprite') && js.includes('benchFrames(2)')],
['sixteen-frame Mafuyu ice-bow atlas', fs.existsSync(new URL('mafuyu-ice-bow.png', assets)) && js.includes('iceBow:{image:iceBowSprite') && js.includes('gridFrames16')],
['sixteen-frame Mafuyu normal attack atlas', fs.existsSync(new URL('mafuyu-attack-16.png', assets)) && js.includes("attack:{image:loadSprite('assets/mafuyu-attack-16.png')")],
['sixteen-frame charged ice-sword atlases', ['mafuyu-ice-charge.png','mafuyu-ice-release.png'].every(file=>fs.existsSync(new URL(file,assets))) && js.includes('CHARGE_FULL_TIME') && js.includes('updateChargedRelease')],
['PERFECT-powered freezing ice bow', js.includes('player.energy+25') && js.includes('function rangedAttack') && js.includes('freezeChance:FREEZE_CHANCE') && js.includes('cost=25')],
['four-frame short interactions', js.includes('interact:{image:interactionSprite,frames:normalizedFrames(0)}') && js.includes('sit:{image:benchFrontSprite,frames:benchFrames(0)}')],
['eight-frame front-facing rest loop', js.includes('rest:{image:benchFrontSprite,frames:[...benchFrames(1),...benchFrames(2)]}') && js.includes('%8')],
['room-local runtime caches', ['platformsByRoom','spikesByRoom','safeZonesByRoom','fragmentsByRoom'].every(name=>js.includes(name)) && !js.includes('const solids=[...platforms]')],
['bounded transient effects', ['MAX_PARTICLES','MAX_PROJECTILES','MAX_RESONANCE_SHOTS'].every(name=>js.includes(name))],
['forgiving platform input windows', js.includes('COYOTE_TIME = .14') && js.includes('JUMP_BUFFER_TIME = .15') && js.includes('ATTACK_BUFFER_TIME = .13')],
['player-only one-way thin platforms', js.includes('oneWay&&e===player') && js.includes('standingOnOneWay') && js.includes('player.dropTimer')],
['rhythm-safe hit stop and camera lookahead', js.includes('advanceRhythmClock(dt)') && js.includes('hitStop') && js.includes('cameraLookahead')],
['non-blocking tutorial room', html.includes('id="tutorialGuide"') && js.includes('TUTORIAL_LESSONS') && js.includes('trainingDummy') && js.includes('tutorial.flags.perfect')],
['dynamic Mafuyu portrait', fs.existsSync(new URL('mafuyu-portrait-normalized.png', assets)) && html.includes('id="characterPortrait"') && js.includes('updatePortrait') && css.includes('.character-portrait')],
['animated bench checkpoint flow', js.includes("beginPlayerAction('bench',bench,3.4)") && js.includes("player.action==='bench'") && js.includes('SEKAI 记忆已同步 · 生命完全恢复')],
['procedural enemies are fallback only', js.includes('drawEnemyFallback') && js.includes('if(!drawn)drawEnemyFallback(e)')],
['five local BGM tracks', ['bgm-empty.mp3','bgm-aquarium.mp3','bgm-corridor.mp3','bgm-stage.mp3','bgm-ending.mp3'].every(file => fs.existsSync(new URL(file, audio)))],
['gameplay SFX library', ['sfx-attack.ogg','sfx-hit.ogg','sfx-hurt.ogg','sfx-jump.ogg','sfx-dash.ogg','sfx-collect.ogg','sfx-boss-cast.ogg'].every(file => fs.existsSync(new URL(file, audio)))],
['crossfade audio system', js.includes('musicChannels') && js.includes('musicFade') && js.includes('updateAudio')],
['BGM playback failure can retry', js.includes("musicKey='';musicFade=null") && js.includes('ensureMusicPlaying') && !js.includes("pointerdown',()=>{unlockAudio();if(!running)playMusic('empty',.35);},{once:true}")],
['separate music and SFX volume', js.includes('musicVolumeInput') && js.includes('sfxVolumeInput')],
['main-menu settings surface', html.includes('id="settingsButton"') && html.includes('id="settingsScreen"') && html.includes('id="pauseSettingsButton"')],
['fullscreen settings control', html.includes('id="fullscreenButton"') && js.includes('requestFullscreen') && js.includes('fullscreenchange')],
['persistent control modes', html.includes('<option value="auto">') && html.includes('<option value="keyboard">') && html.includes('<option value="touch">') && js.includes('silent-sekai-control-mode')],
['automatic touch-device detection', js.includes("matchMedia('(pointer: coarse)')") && js.includes('navigator.maxTouchPoints') && js.includes('resolvedControlMode')],
['mobile joystick input', html.includes('id="touchJoystick"') && html.includes('id="joystickKnob"') && js.includes('updateJoystickFromPointer') && js.includes('touchAxis')],
['mobile gameplay action buttons', ['jump','attack','ranged','dash','interact','map','pause'].every(action=>html.includes(`data-touch-action="${action}"`)) && js.includes("ranged:'KeyL'")],
['multi-touch pointer capture', js.includes('setPointerCapture') && js.includes('pointercancel') && css.includes('touch-action:none')],
['mobile controls protect playfield center', css.includes('.touch-joystick') && css.includes('.mobile-action-controls') && css.includes('.mobile-utility-controls')],
['animated menu and room atmosphere', css.includes('titleRain') && css.includes('titleOrb') && js.includes('drawAmbientWorld') && js.includes('drawAtmosphereForeground')],
['missing volume values use audible defaults', js.includes("if(raw===null||raw==='')return fallback")],
['interactive audio test', js.includes("'#audioTestButton'") && js.includes('audioStatus')],
['all referenced audio exists', referencedAudio.length >= 22 && referencedAudio.every(file => fs.existsSync(new URL(file, audio)))],
['safe storage fallback', js.includes('storageGet') && js.includes('storageRemove')],
['menu decoration ignores clicks', /\.title-screen::after[^}]*pointer-events:none/.test(css)],
['new game explicit button', /<button type="button" id="newGameButton"/.test(html)]
];
for (const [label, passed] of checks) console.log(`${passed ? 'PASS' : 'FAIL'} ${label}`);
if (checks.some(([, passed]) => !passed)) process.exitCode = 1;
+75
View File
@@ -0,0 +1,75 @@
import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('../game.js', import.meta.url), 'utf8');
function arrayLiteral(name) {
const marker = `const ${name} = [`;
const start = source.indexOf(marker);
if (start < 0) throw new Error(`Missing ${name}`);
const bodyStart = start + marker.length - 1;
let depth = 0;
for (let index = bodyStart; index < source.length; index++) {
if (source[index] === '[') depth++;
if (source[index] === ']' && --depth === 0) return source.slice(bodyStart, index + 1);
}
throw new Error(`Unclosed ${name}`);
}
const roomLayouts = Function(`return ${arrayLiteral('ROOM_LAYOUTS')}`)();
const roomWidth = Number(source.match(/ROOM_W = (\d+)/)?.[1]);
const platforms = roomLayouts.flatMap((layout, index) => {
const start = index * roomWidth;
return [
...layout.ground.map(([x, w]) => ({ x: start + x, y: 610, w, h: 130 })),
...layout.ledges.map(([x, y, w]) => ({ x: start + x, y, w, h: 24 }))
];
});
const safeZones = Function(`return ${arrayLiteral('safeZones')}`)();
const sizes = { shade: { w: 46, h: 55, speed: 112 }, crawler: { w: 54, h: 34, speed: 178 } };
const spawns = [...source.matchAll(/makeEnemy\((\d+),(\d+),'(shade|crawler)'\)/g)].map(match => ({
x: Number(match[1]), y: Number(match[2]), type: match[3], ...sizes[match[3]]
}));
const supportBelow = enemy => platforms
.filter(platform => enemy.x + enemy.w / 2 >= platform.x && enemy.x + enemy.w / 2 <= platform.x + platform.w && platform.y >= enemy.y + enemy.h - 8)
.sort((a, b) => a.y - b.y)[0];
function groundAhead(enemy, direction, distance = 28, drop = 72) {
const foot = enemy.y + enemy.h;
const probeX = direction > 0 ? enemy.x + enemy.w + distance : enemy.x - distance;
const roomStart = Math.floor(enemy.x / roomWidth) * roomWidth;
if (probeX <= roomStart + 28 || probeX >= roomStart + roomWidth - 28) return false;
if (safeZones.some(zone => probeX >= zone.x && probeX <= zone.x + zone.w && foot >= zone.y)) return false;
return platforms.some(platform => probeX >= platform.x + 3 && probeX <= platform.x + platform.w - 3 && platform.y >= foot - 10 && platform.y <= foot + drop);
}
function hasFooting(enemy) {
const center = enemy.x + enemy.w / 2;
const foot = enemy.y + enemy.h;
return platforms.some(platform => center >= platform.x && center <= platform.x + platform.w && platform.y >= foot - 10 && platform.y <= foot + 72);
}
const failures = [];
for (const spawn of spawns) {
if (safeZones.some(zone => spawn.x + spawn.w > zone.x && spawn.x < zone.x + zone.w)) {
failures.push(`${spawn.type}@${spawn.x}: spawned inside safe zone`);
continue;
}
const support = supportBelow(spawn);
if (!support) { failures.push(`${spawn.type}@${spawn.x}: no spawn support`); continue; }
const enemy = { ...spawn, y: support.y - spawn.h };
let direction = 1;
for (let frame = 0; frame < 900; frame++) {
if (!groundAhead(enemy, direction)) direction *= -1;
enemy.x += direction * enemy.speed / 60;
if (!hasFooting(enemy)) { failures.push(`${spawn.type}@${spawn.x}: left safe ground on frame ${frame}`); break; }
}
}
console.log(`Ground enemies simulated: ${spawns.length}`);
console.log(`Patrol frames simulated: ${spawns.length * 900}`);
console.log(`Unsafe ledge exits: ${failures.length}`);
if (failures.length) {
failures.forEach(failure => console.error(failure));
process.exitCode = 1;
}
+73
View File
@@ -0,0 +1,73 @@
import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('../game.js', import.meta.url), 'utf8');
const number = name => {
const raw = source.match(new RegExp(`\\b${name}\\s*=\\s*(\\.?\\d+(?:\\.\\d+)?)`))?.[1];
if (!raw) throw new Error(`Missing numeric constant: ${name}`);
return Number(raw);
};
const approach = (value, target, amount) => value < target ? Math.min(target, value + amount) : Math.max(target, value - amount);
const RUN_SPEED = number('RUN_SPEED');
const GROUND_ACCEL = number('GROUND_ACCEL');
const TURN_ACCEL = number('TURN_ACCEL');
const GROUND_DECEL = number('GROUND_DECEL');
const JUMP_SPEED = number('JUMP_SPEED');
const GRAVITY = number('GRAVITY');
const APEX_GRAVITY_SCALE = number('APEX_GRAVITY_SCALE');
const FALL_GRAVITY_SCALE = number('FALL_GRAVITY_SCALE');
const JUMP_CUT_GRAVITY_SCALE = number('JUMP_CUT_GRAVITY_SCALE');
const COYOTE_TIME = number('COYOTE_TIME');
const JUMP_BUFFER_TIME = number('JUMP_BUFFER_TIME');
const ATTACK_BUFFER_TIME = number('ATTACK_BUFFER_TIME');
const dt = 1 / 240;
const timeTo = (initial, target, acceleration, threshold) => {
let value = initial, time = 0;
while (time < 2 && Math.abs(value - target) > threshold) {
value = approach(value, target, acceleration * dt);
time += dt;
}
return time;
};
const simulateJump = releaseAt => {
let y = 0, velocity = -JUMP_SPEED, time = 0, highest = 0;
while (time < 2) {
const held = time < releaseAt;
let scale = 1;
if (velocity < 0 && !held) scale = JUMP_CUT_GRAVITY_SCALE;
else if (Math.abs(velocity) < 95) scale = APEX_GRAVITY_SCALE;
else if (velocity > 0) scale = FALL_GRAVITY_SCALE;
velocity = Math.min(980, velocity + GRAVITY * scale * dt);
y += velocity * dt;
highest = Math.min(highest, y);
time += dt;
if (time > .1 && y >= 0 && velocity > 0) break;
}
return { height: -highest, airtime: time };
};
const run90 = timeTo(0, RUN_SPEED, GROUND_ACCEL, RUN_SPEED * .1);
const stop = timeTo(RUN_SPEED, 0, GROUND_DECEL, 1);
const reverse90 = timeTo(RUN_SPEED, -RUN_SPEED, TURN_ACCEL, RUN_SPEED * .1);
const fullJump = simulateJump(Infinity);
const shortJump = simulateJump(.09);
const checks = [
['90% run speed reached in 70–130ms', run90 >= .07 && run90 <= .13],
['ground stop completes within 100ms', stop <= .1],
['full reverse completes within 150ms', reverse90 <= .15],
['full jump remains compatible with authored 92px rises', fullJump.height >= 108 && fullJump.height <= 130],
['short jump is meaningfully lower', shortJump.height < fullJump.height * .78 && shortJump.height >= 48],
['coyote and jump buffers are forgiving but bounded', COYOTE_TIME >= .1 && COYOTE_TIME <= .16 && JUMP_BUFFER_TIME >= .1 && JUMP_BUFFER_TIME <= .18],
['combat buffer stays below one eighth-note window', ATTACK_BUFFER_TIME > 0 && ATTACK_BUFFER_TIME < .18],
['thin platforms use player-only one-way collision', source.includes("oneWay&&e===player") && source.includes('standingOnOneWay') && source.includes('player.dropTimer')],
['hit stop preserves rhythm clock', source.includes('advanceRhythmClock(dt)') && source.includes('if(hitStop>0)')],
['camera uses smoothed directional lookahead', source.includes('desiredLookahead') && source.includes('cameraLookahead')],
['touch joystick preserves analog magnitude outside a deadzone', source.includes('const normalized=x/max,deadzone=.18') && source.includes('player.dir=direction')]
];
console.log(`Run 90%: ${(run90 * 1000).toFixed(1)}ms; stop: ${(stop * 1000).toFixed(1)}ms; reverse 90%: ${(reverse90 * 1000).toFixed(1)}ms`);
console.log(`Full jump: ${fullJump.height.toFixed(1)}px / ${fullJump.airtime.toFixed(3)}s; short jump: ${shortJump.height.toFixed(1)}px / ${shortJump.airtime.toFixed(3)}s`);
for (const [label, passed] of checks) console.log(`${passed ? 'PASS' : 'FAIL'} ${label}`);
if (checks.some(([, passed]) => !passed)) process.exitCode = 1;
+34
View File
@@ -0,0 +1,34 @@
import fs from 'node:fs';
const root = new URL('../', import.meta.url);
const source = fs.readFileSync(new URL('game.js', root), 'utf8');
const requiredAssets = [
'assets/mafuyu-ice-bow.png',
'assets/mafuyu-attack-16.png',
'assets/mafuyu-ice-charge.png',
'assets/mafuyu-ice-release.png',
'assets/sekai-enemies-16.png',
'assets/sekai-interactables-16.png',
'assets/audio/sfx-ice-bow-charge.ogg',
'assets/audio/sfx-ice-arrow.ogg',
'assets/audio/sfx-ice-charge.ogg',
'assets/audio/sfx-ice-heavy.ogg',
'assets/audio/sfx-freeze.ogg'
];
const checks = [
['all ice combat assets exist', requiredAssets.every(path => fs.existsSync(new URL(path, root)))],
['all revised player attacks use 16 frames', ['attack','iceBow','iceCharge','iceRelease'].every(state => source.includes(`${state}:{image:`)) && source.includes('Array.from({length:16}')],
['ranged shot costs energy and carries freeze chance', source.includes('const cost=25') && source.includes('freezeChance:FREEZE_CHANCE')],
['normal enemies freeze longer than boss', source.includes('enemy.frozen=boss?.62:2.15')],
['charge is mobile and free', source.includes('moveSpeed=RUN_SPEED*(player.chargeActive?.68:1)') && !/chargeActive[^\n]{0,120}energy\s*-=/.test(source)],
['charge releases only after full state', source.includes('if(charged)releaseChargedAttack()') && source.includes('player.chargeTimer>=CHARGE_FULL_TIME')],
['heavy hit is short-range and three damage', source.includes('w:138,h:86') && source.includes('damage:3,heavy:true')],
['new high-frame actions avoid alpha cross-fade', source.includes('highFrame||reducedMotion?0')],
['interactables render one of sixteen fixed frames', source.includes('phase%16') && source.includes('sekai-interactables-16.png')],
['first-area enemies use a fixed 16-frame atlas', source.includes('drawAtlasSixteenPhase') && source.includes('sekai-enemies-16.png')],
['full-screen flash replaced by restrained radial glow', source.includes("Math.min(.13,flash*.16)") && !source.includes('flash*.45')]
];
for (const [label, passed] of checks) console.log(`${passed ? 'PASS' : 'FAIL'} ${label}`);
if (checks.some(([, passed]) => !passed)) process.exitCode = 1;
+128
View File
@@ -0,0 +1,128 @@
import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('../game.js', import.meta.url), 'utf8');
function arrayLiteral(name) {
const marker = `const ${name} = [`;
const start = source.indexOf(marker);
if (start < 0) throw new Error(`Missing ${name}`);
const bodyStart = start + marker.length - 1;
let depth = 0;
for (let i = bodyStart; i < source.length; i++) {
if (source[i] === '[') depth++;
if (source[i] === ']' && --depth === 0) return source.slice(bodyStart, i + 1);
}
throw new Error(`Unclosed ${name}`);
}
const roomLayouts = Function(`return ${arrayLiteral('ROOM_LAYOUTS')}`)();
const fragments = Function(`return ${arrayLiteral('fragments')}`)();
const relays = Function(`return ${arrayLiteral('relays')}`)();
const benches = Function(`return ${arrayLiteral('benches')}`)();
const terminals = Function(`return ${arrayLiteral('terminals')}`)();
const shrine = Function(`return ${source.match(/const shrine = (\{[^;]+\});/)?.[1]}`)();
const airShrine = Function(`return ${source.match(/const airShrine = (\{[^;]+\});/)?.[1]}`)();
const door = Function(`return ${source.match(/const door = (\{[^;]+\});/)?.[1]}`)();
const mobilityGate = Function(`return ${source.match(/const mobilityGate = (\{[^;]+\});/)?.[1]}`)();
const maxRise = Number(source.match(/const MAX_SAFE_RISE = (\d+)/)?.[1]);
const maxGap = Number(source.match(/MAX_SAFE_GAP = (\d+)/)?.[1]);
const jumpSpeed = Number(source.match(/JUMP_SPEED = (\d+)/)?.[1]);
const gravity = Number(source.match(/GRAVITY = (\d+)/)?.[1]);
const roomWidth = Number(source.match(/ROOM_W = (\d+)/)?.[1]);
const platforms = roomLayouts.flatMap((layout, index) => {
const start = index * roomWidth;
return [
...layout.ground.map(([x, w]) => ({ x: start + x, y: 610, w, h: 130 })),
...layout.ledges.map(([x, y, w]) => ({ x: start + x, y, w, h: 24 }))
];
});
const spikes = Function(`return ${arrayLiteral('spikes')}`)();
const safeZones = Function(`return ${arrayLiteral('safeZones')}`)();
const theoreticalRise = jumpSpeed ** 2 / (2 * gravity);
const horizontalGap = (a, b) => Math.max(0,
Math.max(a.x, b.x) - Math.min(a.x + a.w, b.x + b.w)
);
const jumpReach = rise => {
const discriminant = jumpSpeed ** 2 - 2 * gravity * Math.max(0, rise);
if (discriminant < 0) return 0;
const airTime = (jumpSpeed + Math.sqrt(discriminant)) / gravity;
return 260 * airTime + 38;
};
const reachable = new Set([0]);
const queue = [0];
while (queue.length) {
const from = platforms[queue.shift()];
platforms.forEach((to, index) => {
if (reachable.has(index)) return;
const rise = from.y - to.y;
const gap = horizontalGap(from, to);
if (rise <= maxRise && gap <= maxGap && gap <= jumpReach(rise)) {
reachable.add(index);
queue.push(index);
}
});
}
const unreachable = platforms.map((_, index) => index).filter(index => !reachable.has(index));
const missedFragments = fragments.filter(fragment => !platforms.some(platform =>
fragment.x >= platform.x && fragment.x <= platform.x + platform.w &&
Math.abs(fragment.y - (platform.y - 39)) <= 62
));
const unsupportedRelays = relays.filter(relay => !platforms.some(platform =>
relay.x + relay.w >= platform.x && relay.x <= platform.x + platform.w &&
Math.abs(relay.y + relay.h - platform.y) <= 5
));
const unsupportedProps = [...benches, ...terminals].filter(prop => !platforms.some(platform =>
prop.x + prop.w >= platform.x && prop.x <= platform.x + platform.w &&
Math.abs(prop.y + prop.h - platform.y) <= 5
));
const shrineSupported = platforms.some(platform =>
shrine.x + shrine.w >= platform.x && shrine.x <= platform.x + platform.w &&
Math.abs(shrine.y + shrine.h - platform.y) <= 5
);
const airShrineSupported = platforms.some(platform =>
airShrine.x + airShrine.w >= platform.x && airShrine.x <= platform.x + platform.w &&
Math.abs(airShrine.y + airShrine.h - platform.y) <= 5
);
const backtrackingOrder = Math.floor(shrine.x / roomWidth) === 4 && Math.floor(door.x / roomWidth) === 6
&& Math.floor(airShrine.x / roomWidth) === 14 && Math.floor(mobilityGate.x / roomWidth) === 16;
const unsupportedSpikes = spikes.filter(spike => !platforms.some(platform =>
spike.x >= platform.x && spike.x + spike.w <= platform.x + platform.w && Math.abs(spike.y + 18 - platform.y) <= 2
));
const badRoomGround = roomLayouts.flatMap((layout, room) => {
const sorted = [...layout.ground].sort((a, b) => a[0] - b[0]);
const failures = [];
if (sorted[0][0] !== 0 || sorted.at(-1)[0] + sorted.at(-1)[1] !== roomWidth) failures.push(`room ${room}: entry/exit floor missing`);
for (let index = 1; index < sorted.length; index++) {
const gap = sorted[index][0] - (sorted[index - 1][0] + sorted[index - 1][1]);
if (gap > maxGap) failures.push(`room ${room}: ground gap ${gap}px`);
}
return failures;
});
const unsafeProps = [...benches, ...terminals].filter(prop => !safeZones.some(zone =>
prop.x >= zone.x && prop.x + prop.w <= zone.x + zone.w && prop.y + prop.h <= zone.y + zone.h
));
console.log(`Theoretical jump rise: ${theoreticalRise.toFixed(1)}px; authored safe rise: ${maxRise}px`);
console.log(`Reachable platforms: ${reachable.size}/${platforms.length}`);
console.log(`Reachable lyric fragments: ${fragments.length - missedFragments.length}/${fragments.length}`);
console.log(`Supported echo relays: ${relays.length - unsupportedRelays.length}/${relays.length}`);
console.log(`Supported interactive props: ${benches.length + terminals.length - unsupportedProps.length}/${benches.length + terminals.length}`);
console.log(`Safe interactive props: ${benches.length + terminals.length - unsafeProps.length}/${benches.length + terminals.length}`);
console.log(`Metroidvania route order: ${backtrackingOrder && shrineSupported ? 'valid' : 'invalid'}`);
if (unreachable.length || missedFragments.length || unsupportedRelays.length || unsupportedProps.length || unsupportedSpikes.length || badRoomGround.length || unsafeProps.length || !shrineSupported || !airShrineSupported || !backtrackingOrder) {
if (unreachable.length) console.error('Unreachable platform indices:', unreachable);
if (missedFragments.length) console.error('Unreachable fragments:', missedFragments);
if (unsupportedRelays.length) console.error('Unsupported relays:', unsupportedRelays);
if (unsupportedProps.length) console.error('Unsupported interactive props:', unsupportedProps);
if (unsupportedSpikes.length) console.error('Unsupported spikes:', unsupportedSpikes);
if (badRoomGround.length) console.error('Unsafe room ground:', badRoomGround);
if (unsafeProps.length) console.error('Interactive props outside safe zones:', unsafeProps);
if (!shrineSupported) console.error('Ability shrine is not supported by a platform');
if (!airShrineSupported) console.error('Air-echo shrine is not supported by a platform');
if (!backtrackingOrder) console.error('Each ability shrine must precede its matching traversal gate');
process.exitCode = 1;
}
+62
View File
@@ -0,0 +1,62 @@
import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('../game.js', import.meta.url), 'utf8');
function arrayLiteral(name) {
const marker = `const ${name} = [`;
const start = source.indexOf(marker);
if (start < 0) throw new Error(`Missing ${name}`);
const bodyStart = start + marker.length - 1;
let depth = 0;
for (let index = bodyStart; index < source.length; index++) {
if (source[index] === '[') depth++;
if (source[index] === ']' && --depth === 0) return source.slice(bodyStart, index + 1);
}
throw new Error(`Unclosed ${name}`);
}
const rooms = Function(`return ${arrayLiteral('ROOMS')}`)();
const benches = Function(`return ${arrayLiteral('benches')}`)();
const relays = Function(`return ${arrayLiteral('relays')}`)();
const terminals = Function(`return ${arrayLiteral('terminals')}`)();
const safeZones = Function(`return ${arrayLiteral('safeZones')}`)();
const lamps = Function(`return ${arrayLiteral('memoryLamps')}`)();
const layouts = Function(`return ${arrayLiteral('ROOM_LAYOUTS')}`)();
const shrine = Function(`return ${source.match(/const shrine = (\{[^;]+\});/)?.[1]}`)();
const airShrine = Function(`return ${source.match(/const airShrine = (\{[^;]+\});/)?.[1]}`)();
const roomWidth = Number(source.match(/ROOM_W = (\d+)/)?.[1]);
const roomCount = Number(source.match(/ROOM_COUNT = (\d+)/)?.[1]);
const canvasWidth = Number(source.match(/const W = canvas\.width, H = canvas\.height/) ? 1280 : 0);
const roomGeometryValid = rooms.length === roomCount && rooms.every((room, index) =>
room.start === index * roomWidth && room.end === (index + 1) * roomWidth && room.end - room.start >= canvasWidth
);
const interactions = [...benches, ...relays, ...terminals, ...lamps, shrine, airShrine];
const density = rooms.map(room => interactions.filter(item => item.x >= room.start && item.x < room.end).length);
const sparseInteractions = Math.max(...density) <= 3;
const richRooms = layouts.every(layout => layout.ground.length + layout.ledges.length >= 5);
const safeInteractions = [...benches, ...terminals].every(item => safeZones.some(zone =>
item.x >= zone.x && item.x + item.w <= zone.x + zone.w && item.y + item.h <= zone.y + zone.h
));
const boundariesClear = interactions.every(item => {
const room = rooms[Math.floor(item.x / roomWidth)];
return item.x - room.start >= 80 && room.end - (item.x + item.w) >= 80;
});
const isolatedRendering = source.includes('ctx.rect(room.start,-120,room.end-room.start,H+240)') && source.includes('ctx.clip()');
const boundaryTransitions = source.includes('checkRoomBoundary') && source.includes('startRoomTransition(currentRoom+1,1)') && source.includes('startRoomTransition(currentRoom-1,-1)');
const roomCameraLock = source.includes('roomCameraTarget') && source.includes('Math.min(room.end-W');
const checks = [
[`${rooms.length} contiguous rooms at least one screen wide`, roomGeometryValid],
['at most three well-spaced interactions per 2400px room', sparseInteractions],
['every room has layered traversal content', richRooms],
['benches and terminals are inside safe zones', safeInteractions],
['interactions stay away from transition edges', boundariesClear],
['world rendering clipped to current room', isolatedRendering],
['both room-boundary directions transition', boundaryTransitions],
['camera clamped inside current room', roomCameraLock]
];
console.log(`Room width: ${roomWidth}px; interaction density: ${density.join('/')}`);
for (const [label, passed] of checks) console.log(`${passed ? 'PASS' : 'FAIL'} ${label}`);
if (checks.some(([, passed]) => !passed)) process.exitCode = 1;
+24
View File
@@ -0,0 +1,24 @@
import { readFileSync } from 'node:fs';
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
const js = readFileSync(new URL('../game.js', import.meta.url), 'utf8');
const ids = new Set([...html.matchAll(/\bid="([^"]+)"/g)].map(match => match[1]));
const queried = [...js.matchAll(/querySelector\(['"]#([^'"]+)['"]\)/g)].map(match => match[1]);
const missing = [...new Set(queried)].filter(id => !ids.has(id));
const requiredActions = [
'newGameButton','continueButton','controlsButton','settingsButton','muteButton','closeControlsButton',
'closeSettingsButton','fullscreenButton','controlMode','resumeButton','retryButton','pauseSettingsButton','pauseMuteButton','mainMenuButton','restartButton','endingMenuButton',
'audioTestButton','introNextButton','introSkipButton','mapCloseButton'
];
const unwired = requiredActions.filter(id => !js.includes(`'#${id}'`) && !js.includes(`"#${id}"`));
console.log(`DOM ids: ${ids.size}`);
console.log(`Queried ids resolved: ${new Set(queried).size - missing.length}/${new Set(queried).size}`);
console.log(`Required menu actions present: ${requiredActions.length - unwired.length}/${requiredActions.length}`);
if (missing.length || unwired.length) {
if (missing.length) console.error('Missing DOM ids:', missing);
if (unwired.length) console.error('Unwired menu actions:', unwired);
process.exitCode = 1;
}
+69
View File
@@ -0,0 +1,69 @@
"""Extract and repack the generated 4x3 front-facing bench animation."""
from __future__ import annotations
import argparse
from pathlib import Path
from PIL import Image
def bounds(length: int, index: int, count: int) -> tuple[int, int]:
return round(index * length / count), round((index + 1) * length / count)
def make_strip(source: Image.Image, rows: list[int], output: Path) -> None:
cell_width = round(source.width / 4)
cell_height = round(source.height / 3)
slots: list[Image.Image] = []
for row in rows:
top, bottom = bounds(source.height, row, 3)
for column in range(4):
left, right = bounds(source.width, column, 4)
slot = source.crop((left, top, right, bottom))
canvas = Image.new("RGBA", (cell_width, cell_height), (0, 0, 0, 0))
canvas.alpha_composite(slot, ((cell_width - slot.width) // 2, cell_height - slot.height))
slots.append(canvas)
strip = Image.new("RGBA", (cell_width * len(slots), cell_height), (0, 0, 0, 0))
for index, slot in enumerate(slots):
strip.alpha_composite(slot, (index * cell_width, 0))
output.parent.mkdir(parents=True, exist_ok=True)
strip.save(output)
def extract(source_path: Path, output_dir: Path) -> None:
source = Image.open(source_path).convert("RGBA")
make_strip(source, [0], output_dir / "sit-front-strip.png")
make_strip(source, [1, 2], output_dir / "rest-front-strip.png")
def pack(frames_root: Path, output: Path, frame_size: int) -> None:
atlas = Image.new("RGBA", (frame_size * 4, frame_size * 3), (0, 0, 0, 0))
rows = [("sit-front", range(1, 5)), ("rest-front", range(1, 5)), ("rest-front", range(5, 9))]
for row, (folder, indices) in enumerate(rows):
for column, index in enumerate(indices):
frame = Image.open(frames_root / folder / f"{index:02d}.png").convert("RGBA")
atlas.alpha_composite(frame, (column * frame_size, row * frame_size))
output.parent.mkdir(parents=True, exist_ok=True)
atlas.save(output)
def main() -> None:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command", required=True)
extract_parser = subparsers.add_parser("extract")
extract_parser.add_argument("--source", type=Path, required=True)
extract_parser.add_argument("--out-dir", type=Path, required=True)
pack_parser = subparsers.add_parser("pack")
pack_parser.add_argument("--frames-root", type=Path, required=True)
pack_parser.add_argument("--output", type=Path, required=True)
pack_parser.add_argument("--frame-size", type=int, default=256)
args = parser.parse_args()
if args.command == "extract":
extract(args.source, args.out_dir)
else:
pack(args.frames_root, args.output, args.frame_size)
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
"""Prepare and repack Mafuyu's generated interaction animation atlas.
The generator authored a 4x4 presentation sheet whose row spacing is not
perfectly uniform. This helper extracts clean horizontal action strips before
the Game Studio normalizer aligns every frame to a shared bottom-center anchor.
"""
from __future__ import annotations
import argparse
from pathlib import Path
from PIL import Image
def frame_x_bounds(width: int, column: int) -> tuple[int, int]:
return round(column * width / 4), round((column + 1) * width / 4)
def make_strip(source: Image.Image, rows: list[tuple[int, int]], output: Path) -> None:
slots: list[Image.Image] = []
slot_width = round(source.width / 4)
strip_height = max(bottom - top for top, bottom in rows)
for top, bottom in rows:
for column in range(4):
left, right = frame_x_bounds(source.width, column)
slot = source.crop((left, top, right, bottom))
canvas = Image.new("RGBA", (slot_width, strip_height), (0, 0, 0, 0))
canvas.alpha_composite(slot, ((slot_width - slot.width) // 2, strip_height - slot.height))
slots.append(canvas)
strip = Image.new("RGBA", (slot_width * len(slots), strip_height), (0, 0, 0, 0))
for index, slot in enumerate(slots):
strip.alpha_composite(slot, (index * slot_width, 0))
output.parent.mkdir(parents=True, exist_ok=True)
strip.save(output)
def extract(source_path: Path, output_dir: Path) -> None:
source = Image.open(source_path).convert("RGBA")
make_strip(source, [(0, 330)], output_dir / "interact-strip.png")
make_strip(source, [(330, 660)], output_dir / "sit-strip.png")
make_strip(source, [(660, 940), (940, source.height)], output_dir / "rest-strip.png")
def pack(frames_root: Path, output: Path, frame_size: int) -> None:
atlas = Image.new("RGBA", (frame_size * 4, frame_size * 4), (0, 0, 0, 0))
rows = [
("interact", range(1, 5)),
("sit", range(1, 5)),
("rest", range(1, 5)),
("rest", range(5, 9)),
]
for row, (folder, indices) in enumerate(rows):
for column, index in enumerate(indices):
frame = Image.open(frames_root / folder / f"{index:02d}.png").convert("RGBA")
atlas.alpha_composite(frame, (column * frame_size, row * frame_size))
output.parent.mkdir(parents=True, exist_ok=True)
atlas.save(output)
def main() -> None:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command", required=True)
extract_parser = subparsers.add_parser("extract")
extract_parser.add_argument("--source", type=Path, required=True)
extract_parser.add_argument("--out-dir", type=Path, required=True)
pack_parser = subparsers.add_parser("pack")
pack_parser.add_argument("--frames-root", type=Path, required=True)
pack_parser.add_argument("--output", type=Path, required=True)
pack_parser.add_argument("--frame-size", type=int, default=256)
args = parser.parse_args()
if args.command == "extract":
extract(args.source, args.out_dir)
else:
pack(args.frames_root, args.output, args.frame_size)
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
"""Remove chroma green and normalize a generated 4x2 dialogue portrait atlas."""
from __future__ import annotations
import argparse
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw
def bounds(length: int, index: int, count: int) -> tuple[int, int]:
return round(index * length / count), round((index + 1) * length / count)
def remove_green(image: Image.Image) -> Image.Image:
rgba = image.convert("RGBA")
pixels = []
for red, green, blue, _ in rgba.get_flattened_data():
dominance = green - max(red, blue)
alpha = max(0, min(255, round((150 - dominance) * 255 / 105)))
if alpha < 250:
green = min(green, max(red, blue) + 12)
pixels.append((red, green, blue, alpha))
rgba.putdata(pixels)
return rgba
def normalize_cell(cell: Image.Image, size: int) -> Image.Image:
alpha = cell.getchannel("A")
box = alpha.getbbox()
output = Image.new("RGBA", (size, size), (0, 0, 0, 0))
if not box:
return output
subject = cell.crop(box)
max_width, max_height = round(size * 0.94), round(size * 0.96)
scale = min(max_width / subject.width, max_height / subject.height)
subject = subject.resize(
(max(1, round(subject.width * scale)), max(1, round(subject.height * scale))),
Image.Resampling.LANCZOS,
)
x = (size - subject.width) // 2
y = size - subject.height - round(size * 0.015)
output.alpha_composite(subject, (x, y))
return output
def make_preview(atlas: Image.Image, output: Path, size: int) -> None:
tile = 24
preview = Image.new("RGBA", atlas.size, (23, 25, 39, 255))
draw = ImageDraw.Draw(preview)
for y in range(0, preview.height, tile):
for x in range(0, preview.width, tile):
if (x // tile + y // tile) % 2:
draw.rectangle((x, y, x + tile - 1, y + tile - 1), fill=(36, 39, 57, 255))
preview.alpha_composite(atlas)
preview = preview.resize((size * 2, size), Image.Resampling.LANCZOS)
output.parent.mkdir(parents=True, exist_ok=True)
preview.save(output, optimize=True, compress_level=9)
def prepare(source_path: Path, output: Path, preview: Path, frame_size: int) -> None:
source = Image.open(source_path).convert("RGBA")
atlas = Image.new("RGBA", (frame_size * 4, frame_size * 2), (0, 0, 0, 0))
for row in range(2):
top, bottom = bounds(source.height, row, 2)
for column in range(4):
left, right = bounds(source.width, column, 4)
cell = remove_green(source.crop((left, top, right, bottom)))
atlas.alpha_composite(normalize_cell(cell, frame_size), (column * frame_size, row * frame_size))
output.parent.mkdir(parents=True, exist_ok=True)
atlas.save(output, optimize=True, compress_level=9)
make_preview(atlas, preview, frame_size)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--preview", type=Path, required=True)
parser.add_argument("--frame-size", type=int, default=320)
args = parser.parse_args()
prepare(args.source, args.output, args.preview, args.frame_size)
if __name__ == "__main__":
main()