Skip to content

Instantly share code, notes, and snippets.

@easierbycode
Last active November 5, 2026 19:04
Show Gist options
  • Select an option

  • Save easierbycode/88f00e70925ad38b102cbc7d8a320ed4 to your computer and use it in GitHub Desktop.

Select an option

Save easierbycode/88f00e70925ad38b102cbc7d8a320ed4 to your computer and use it in GitHub Desktop.
deza .sav -> game.json/atlas in RTDB
claude/shmupx-game-lists-redesign-7e0ac1
// Decode a cart (.sav / .bcr) and dump what the writer put in it.
// deno run -A inspect-cart.ts <file> <out-prefix>
import * as deza from "/home/easierbycode/CODE/shmupX.github.io/packages/shmup-engine/mod.js";
import { SEC5_REGIONS } from "/home/easierbycode/CODE/shmupX.github.io/packages/shmup-engine/src/decode/decode-stage.js";
import { encodePng, newRaster } from "/home/easierbycode/CODE/shmupX.github.io/lib/ps2/png.ts";
// deno-lint-ignore no-explicit-any
const engine = deza as any;
const [file, outPrefix] = Deno.args;
let bytes = await Deno.readFile(file);
const norm = await engine.normalize(bytes);
console.log("normalize kind:", norm.kind, "logical", norm.data.length);
let data = norm.data;
if (data.length === 0x80000) {
// bare cart partition (Mednafen .bcr) — prepend an empty internal partition so parse() sees both
const full = new Uint8Array(0x8000 + 0x80000);
full.set(engine.formatPartition ? engine.formatPartition(0x8000, 64) : new Uint8Array(0x8000), 0);
full.set(data, 0x8000);
data = full;
}
const saves = engine.parse(data);
for (const s of saves) console.log("entry:", s.filename, JSON.stringify(s.comment), "datasize", s.datasize, "err", s.payloadError);
const games = saves.filter((s: { filename: string }) => engine.isGameSave(s));
const dec = engine.decodeSave(games[0].payload.buffer);
console.log("stages:", dec.stageCount, "sprites:", dec.sprites.length, "enemies:", dec.enemies.length, "bosses:", dec.bosses.length);
console.log("sprite keys:", dec.sprites.map((s: { key: string; w: number; h: number }) => `${s.key}(${s.w}x${s.h})`).join(" "));
for (const e of dec.enemies) {
const b = e.bytes as Uint8Array;
console.log(`enemy ${e.name} stage ${e.stage} rec ${e.record} bytes ${[...b].map((x) => x.toString(16).padStart(2, "0")).join(" ")} bulletType ${b[4] & 3} geom ${b[5] & 15} aimed ${(b[5] >> 4) & 1} rate ${(b[4] >> 4) & 7} sprites ${JSON.stringify(e.spriteKeys)}`);
}
for (const b of dec.bosses) console.log("boss", JSON.stringify({ ...b, spriteKeys: b.spriteKeys }));
const sec5 = dec.sections[5].decompressed as Uint8Array;
const gb = SEC5_REGIONS.spriteBank.offset;
const words: number[] = [];
for (let i = 0; i < 232; i++) words.push((sec5[gb + i * 2] << 8) | sec5[gb + i * 2 + 1]);
const painted = (a: number, b: number) => words.slice(a, b + 1).filter((w) => w !== 0xffff).length;
console.log("global bank painted refs: ship0-23", painted(0, 23), "p2 24-47", painted(24, 47), "weapons 48-93", painted(48, 93), "items 94-101", painted(94, 101), "blastA 102-107", painted(102, 107), "blastB 108-131", painted(108, 131), "bullets 132-143", painted(132, 143), "title1 144-175", painted(144, 175), "title2 176-207", painted(176, 207), "credits 208-231", painted(208, 231));
console.log("bullets words:", words.slice(132, 144).map((w) => w.toString(16)).join(" "));
console.log("title1 words:", words.slice(144, 176).map((w) => w.toString(16)).join(" "));
console.log("title2 words:", words.slice(176, 208).map((w) => w.toString(16)).join(" "));
const st = SEC5_REGIONS.settings.offset;
const settings = sec5.subarray(st, st + SEC5_REGIONS.settings.stride);
console.log("settings:", [...settings].map((x) => x.toString(16).padStart(2, "0")).join(" "));
console.log("title roles:", JSON.stringify(dec.titleRoles || dec.title || null));
console.log("global roles:", JSON.stringify(dec.globalRoles || dec.globalArt || null));
console.log("decoded keys:", Object.keys(dec).join(","));
// contact sheet: sprites in order, wrapped at 1024 px
const sprites = dec.sprites as { key: string; w: number; h: number; rgba: Uint8ClampedArray }[];
const MW = 1024, P = 2;
let cx = P, cy = P, rh = 0;
const pos: { x: number; y: number }[] = [];
for (const s of sprites) {
if (cx + s.w + P > MW) { cy += rh + P; cx = P; rh = 0; }
pos.push({ x: cx, y: cy });
cx += s.w + P;
rh = Math.max(rh, s.h);
}
const H = cy + rh + P;
const sheet = newRaster(MW, H);
// grey backdrop so transparent sprites read
for (let i = 0; i < sheet.data.length; i += 4) { sheet.data[i] = 40; sheet.data[i + 1] = 40; sheet.data[i + 2] = 60; sheet.data[i + 3] = 255; }
sprites.forEach((s, i) => {
const p = pos[i];
for (let y = 0; y < s.h; y++) {
for (let x = 0; x < s.w; x++) {
const si = (y * s.w + x) * 4;
if (!s.rgba[si + 3]) continue;
const di = ((p.y + y) * MW + p.x + x) * 4;
sheet.data[di] = s.rgba[si]; sheet.data[di + 1] = s.rgba[si + 1]; sheet.data[di + 2] = s.rgba[si + 2]; sheet.data[di + 3] = 255;
}
}
});
await Deno.writeFile(`${outPrefix}-sheet.png`, await encodePng(sheet));
console.log("wrote", `${outPrefix}-sheet.png`, MW, "x", H);
"""Compare a Saturn survey with a web survey from the parity testdrive.
usage: python compare-survey.py <out-dir> (build/testdrive/parity/<slug>)
Reads panes/saturn.survey.json, panes/web.survey.json and rush.json, and
prints: the roster (placement id -> letter), each side's enemy births by
placement id with the scroll position they came on at, each side's bullet
kinds with what fired them, and a side-by-side timeline by scroll position.
"""
import json
import sys
import os
import collections
out = sys.argv[1]
rush = json.load(open(os.path.join(out, "rush.json"), encoding="utf-8"))
ed = rush["enemyData"]
pid_to_letter = {}
letter_info = {}
for k, d in ed.items():
dz = d.get("dezaemon") or {}
if dz.get("stage") != 0:
continue
L = k[len("enemy"):]
pid_to_letter[dz.get("placementId")] = L
b = dz.get("behavior") or {}
f = b.get("fire") or {}
letter_info[L] = dict(rec=dz.get("record"), pid=dz.get("placementId"), name=d.get("name"),
fire=f.get("enabled"), type=f.get("mode"), geom=f.get("geometry"),
aimed=f.get("aimed"), ivl=f.get("interval"), hp=b.get("hp"),
app=b.get("appearance"), move=(b.get("move") or {}).get("mode"))
def load(name):
p = os.path.join(out, "panes", name)
if not os.path.exists(p):
return None
return json.load(open(p, encoding="utf-8"))
sat = load("saturn.survey.json")
web = load("web.survey.json")
SPR_BULLET = {55: 0, 59: 1, 63: 2}
if sat:
print("=== SATURN ===")
print("samples", sat["n"], "births", len(sat["births"]), "maxObjs", sat["maxObjs"], "err", sat["err"])
kept = sat.get("kept") or []
print("kept spans", len(kept), "deaths", sat.get("deaths"))
s0 = sat["samples"][0] if sat["samples"] else None
sN = sat["samples"][-1] if sat["samples"] else None
if s0 and sN:
print("scroll from", s0["scroll"], "to", sN["scroll"], "over", (sN["t"] - s0["t"]) / 1000, "s; rank", s0["rank"], "->", sN["rank"], "lives", s0["lives"], "->", sN["lives"])
# births by slot band and sprite
by_spr = collections.defaultdict(list)
for b in sat["births"]:
by_spr[b["spr"]].append(b)
print("\nsprite index -> births (count, slots range, first t, first scroll, keys seen):")
for spr, bs in sorted(by_spr.items(), key=lambda kv: -len(kv[1])):
slots = sorted(set(b["slot"] for b in bs))
keys = collections.Counter(b["key"] for b in bs)
print(f" spr {spr:4} n={len(bs):4} slots {slots[0]}-{slots[-1]} first t={bs[0]['t']/1000:.1f}s scroll={bs[0]['scroll']} keys={dict(keys.most_common(6))} hp0={bs[0]['hp']} attr={bs[0]['attr']} atk={bs[0]['atk']}")
# enemy births = slots 99..248 with key in 0x80..0xE3 ; use rewinds-insensitive: first by (key)
print("\nenemies by placement id (first seen):")
first_by_key = {}
count_by_key = collections.Counter()
for b in sat["births"]:
if 99 <= b["slot"] <= 248 and 0x80 <= b["key"] <= 0xEF:
count_by_key[b["key"]] += 1
if b["key"] not in first_by_key:
first_by_key[b["key"]] = b
for key, b in sorted(first_by_key.items(), key=lambda kv: kv[1]["t"]):
L = pid_to_letter.get(key, "?")
info = letter_info.get(L, {})
print(f" pid {key:3} ({key:#04x}) {L:3} rec {info.get('rec')} n={count_by_key[key]:3} first t={b['t']/1000:5.1f}s scroll={b['scroll']:5} spr={b['spr']} at ({b['x']:.0f},{b['y']:.0f}) hp={b['hp']} attr={b['attr']}")
# bullets: births whose spr is in SPR_BULLET
print("\nbullet births by type (spr 55/59/63), with the nearest enemy at birth:")
# build a per-sample enemy list for attribution: find the sample at that wall
samples = sat["samples"]
idx = 0
bullets = [b for b in sat["births"] if b["spr"] in SPR_BULLET]
attrib = collections.Counter()
for b in bullets:
# the sample with the same wall
s = None
for smp in samples:
if smp["wall"] == b["wall"]:
s = smp
break
best, bd = None, 1e12
if s:
for o in s["objs"]:
slot, spr, x, y, hp, key, attr, atk, st, md = o
if 99 <= slot <= 248 and 0x80 <= key <= 0xEF:
d = (x - b["x"]) ** 2 + (y - b["y"]) ** 2
if d < bd:
bd, best = d, (key, slot)
attrib[(SPR_BULLET[b["spr"]], pid_to_letter.get(best[0], "?") if best else "?")] += 1
for (t, L), n in sorted(attrib.items(), key=lambda kv: -kv[1]):
print(f" type {t} from {L:3} ({letter_info.get(L, {}).get('name')}): {n}")
print(" total bullets", len(bullets), "by type", collections.Counter(SPR_BULLET[b['spr']] for b in bullets))
if web:
print("\n=== WEB ===")
print("samples", web["n"], "births", len(web["births"]), "maxObjs", web["maxObjs"], "err", web["err"], "ended", web.get("ended"))
s0 = web["samples"][0] if web["samples"] else None
sN = web["samples"][-1] if web["samples"] else None
if s0 and sN:
print("scroll from", s0["scroll"], "to", sN["scroll"], "step", s0["step"], "->", sN["step"], "over", (sN["t"] - s0["t"]) / 1000, "s; score", s0["score"], "->", sN["score"], "shot", s0["player"] and s0["player"]["shot"], "->", sN["player"] and sN["player"]["shot"])
print("\nkinds (bullet frames):", json.dumps(web["kinds"]))
print("\nenemies by key (first seen):")
first = {}
cnt = collections.Counter()
for b in web["births"]:
if b["kind"] in ("enemy", "boss", "part"):
k = b.get("key") or b.get("name")
cnt[k] += 1
first.setdefault(k, b)
for k, b in sorted(first.items(), key=lambda kv: kv[1]["t"]):
L = (k or "").replace("enemy", "")
info = letter_info.get(L, {})
print(f" {k:10} {b['kind']:5} deza={b.get('deza')} rec {info.get('rec')} n={cnt[k]:3} first t={b['t']/1000:5.1f}s scroll={b['scroll']} step={b['step']} at ({b['x']:.0f},{b['y']:.0f}) hp={b.get('hp')} frame={b.get('frame')} proj={b.get('proj')}")
print("\nbullet births by frame and shooter:")
attrib = collections.Counter()
for b in web["births"]:
if b["kind"] == "bullet":
fr = b.get("frame")
if b.get("tex") and b["tex"] != "game_asset":
fr = f"{b['tex']}:{fr}"
frm = b.get("from") or {}
attrib[(fr, (frm.get("key") or frm.get("name") or "?"), frm.get("kind"))] += 1
for (fr, k, kind), n in sorted(attrib.items(), key=lambda kv: -kv[1]):
L = (k or "").replace("enemy", "")
print(f" {fr:28} from {k:10} {kind or '':6} ({letter_info.get(L, {}).get('name')}) type={letter_info.get(L, {}).get('type')} geom={letter_info.get(L, {}).get('geom')}: {n}")
if sat and web:
print("\n=== TIMELINE by scroll (first appearance of each placement id) ===")
rows = []
sat_first = {}
for b in sat["births"]:
if 99 <= b["slot"] <= 248 and 0x80 <= b["key"] <= 0xEF and b["key"] not in sat_first:
sat_first[b["key"]] = b
web_first = {}
for b in web["births"]:
if b["kind"] == "enemy" and b.get("deza") is not None and b["deza"] not in web_first:
web_first[b["deza"]] = b
keys = sorted(set(sat_first) | set(web_first), key=lambda k: min(
sat_first[k]["scroll"] if k in sat_first else 1e9, web_first[k]["scroll"] if (k in web_first and web_first[k]["scroll"] is not None) else 1e9))
print(f"{'pid':>4} {'L':3} {'rec':>3} | {'sat scroll':>10} {'sat t':>6} {'sat y':>6} | {'web scroll':>10} {'web t':>6} {'web y':>6} | d.scroll")
for k in keys:
L = pid_to_letter.get(k, "?")
info = letter_info.get(L, {})
s = sat_first.get(k)
w = web_first.get(k)
ds = (w["scroll"] - s["scroll"]) if (s and w and w["scroll"] is not None) else None
print(f"{k:4} {L:3} {str(info.get('rec')):>3} | {s['scroll'] if s else '-':>10} {s['t']/1000 if s else '-':>6} {s['y'] if s else '-':>6} | {w['scroll'] if w else '-':>10} {w['t']/1000 if w else '-':>6} {w['y'] if w else '-':>6} | {ds}")
bash -lc "for i in 1 2 3; do n=\$(curl -s 'https://evil-invaders-default-rtdb.firebasei o.com/dezaemon/index.json?shallow=true' | tr ',' '\n' | wc -l); echo \"index entries: \$n\"; sleep 45; done" index entries: 257
const g = window.__PHASER_GAME__;
function slot(note, bass) {
const b = new Uint8Array(4228); b.set([0, 1, 0, 31], 0);
for (let m = 0; m < 32; m++) b.set([0, 0, 0x80, 3], 4 + m * 132);
for (let k = 0; k < 8; k++) { const step = k * 4; for (let s = step; s < step + 3; s++) { const m = Math.floor(s / 16), st = s % 16; const base = 4 + m * 132 + 4; b[base + st] = s === step ? 16 : 0x80; b[base + 16 + st] = note; } }
for (let s = 0; s < 32; s++) { const m = Math.floor(s / 16), st = s % 16; const base = 4 + m * 132 + 4 + 32; b[base + st] = s === 0 ? 18 : 0x80; b[base + 16 + st] = bass; }
let str = ""; for (const x of b) str += String.fromCharCode(x); return btoa(str);
}
window.__synthBgm = { sfxSet: 1, special: [0, 3, 3, 2], stages: [[0, 1], [0, 1], [1, 2], [1, 2], [2, 2]], songs: { 0: slot(25, 1), 1: slot(37, 2), 2: slot(49, 3) }, sequence: [0, 1, 2] };
g.scene.start("PhaserGameScene"); g.scene.stop("PhaserTitleScene");
await new Promise(r => setTimeout(r, 400));
const sc = g.scene.getScene("PhaserGameScene");
sc.recipe.dezaemonBgm = window.__synthBgm;
sc.stopAllSounds();
sc.playBossBgm(0);
const ctx = sc.sound.context;
const samples = [];
for (let i = 0; i < 17; i++) {
const st = sc._dezaBgm;
samples.push(st ? { t: +(ctx.currentTime - st.startTime).toFixed(2), seqIndex: st.seqIndex, songIndex: st.songIndex, scheduled: st.scheduled, stepSec: st.stepSeconds, loopEnd: st.song.loopEndStep } : null);
await new Promise(r => setTimeout(r, 500));
}
({ fps: Math.round(g.loop.actualFps), stageBgmName: sc.stageBgmName, hasSeq: !!(sc._dezaBgm && sc._dezaBgm.seq), samples })
// http://localhost:5173/games/2028-ai/?level=foo&god=1
// {
// "fps": 61,
// "hasSeq": true,
// "samples": [
// {
// "loopEnd": 32,
// "scheduled": 3,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": -0.04
// },
// {
// "loopEnd": 32,
// "scheduled": 4,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": 0.46
// },
// {
// "loopEnd": 32,
// "scheduled": 6,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": 0.96
// },
// {
// "loopEnd": 32,
// "scheduled": 7,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": 1.46
// },
// {
// "loopEnd": 32,
// "scheduled": 9,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": 1.97
// },
// {
// "loopEnd": 32,
// "scheduled": 12,
// "seqIndex": 1,
// "songIndex": 1,
// "stepSec": 0.075,
// "t": 0.07
// },
// {
// "loopEnd": 32,
// "scheduled": 14,
// "seqIndex": 1,
// "songIndex": 1,
// "stepSec": 0.075,
// "t": 0.57
// },
// {
// "loopEnd": 32,
// "scheduled": 15,
// "seqIndex": 1,
// "songIndex": 1,
// "stepSec": 0.075,
// "t": 1.07
// },
// {
// "loopEnd": 32,
// "scheduled": 17,
// "seqIndex": 1,
// "songIndex": 1,
// "stepSec": 0.075,
// "t": 1.57
// },
// {
// "loopEnd": 32,
// "scheduled": 18,
// "seqIndex": 1,
// "songIndex": 1,
// "stepSec": 0.075,
// "t": 2.07
// },
// {
// "loopEnd": 32,
// "scheduled": 21,
// "seqIndex": 2,
// "songIndex": 2,
// "stepSec": 0.075,
// "t": 0.17
// },
// {
// "loopEnd": 32,
// "scheduled": 23,
// "seqIndex": 2,
// "songIndex": 2,
// "stepSec": 0.075,
// "t": 0.68
// },
// {
// "loopEnd": 32,
// "scheduled": 24,
// "seqIndex": 2,
// "songIndex": 2,
// "stepSec": 0.075,
// "t": 1.18
// },
// {
// "loopEnd": 32,
// "scheduled": 26,
// "seqIndex": 2,
// "songIndex": 2,
// "stepSec": 0.075,
// "t": 1.68
// },
// {
// "loopEnd": 32,
// "scheduled": 29,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": -0.22
// },
// {
// "loopEnd": 32,
// "scheduled": 31,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": 0.28
// },
// {
// "loopEnd": 32,
// "scheduled": 32,
// "seqIndex": 0,
// "songIndex": 0,
// "stepSec": 0.075,
// "t": 0.78
// }
// ],
// "stageBgmName": "__dezaemon__"
// }
const g = window.__PHASER_GAME__;
let sc = g.scene.getScene("PhaserGameScene");
const ctx = sc.sound.context;
for (let i = 0; i < 60; i++) { const st = sc._dezaBgm; const t = st ? ctx.currentTime - st.startTime : 9; if (st && t > 0.2 && t < 0.5) break; await new Promise(r => setTimeout(r, 50)); }
const st0 = sc._dezaBgm;
const paused = { index: st0.seqIndex, step: Math.floor((ctx.currentTime - st0.startTime) / st0.stepSeconds) };
sc.stageClear();
await new Promise(r => setTimeout(r, 3200));
const advSounds = g.sound.sounds.filter(s => s.isPlaying).map(s => s.key);
g.scene.stop("PhaserAdvScene"); g.scene.start("PhaserGameScene");
await new Promise(r => setTimeout(r, 150));
sc = g.scene.getScene("PhaserGameScene");
const st2 = sc._dezaBgm;
const resumed = { index: st2.seqIndex, stepNow: +((ctx.currentTime - st2.startTime) / st2.stepSeconds).toFixed(1), cursors: st2.cursor.slice(0, 2) };
// the boss keeps the piece going
const before = sc._dezaBgm;
let bossErr = null;
try { sc.bossAdd(); } catch (e) { bossErr = String(e); }
await new Promise(r => setTimeout(r, 100));
// {
// "advSoundsPlaying": [],
// "afterClear": {
// "dezaBgmNull": true,
// "stageCleared": true
// },
// "bossStageId": 1,
// "paused": {
// "index": 1,
// "step": 26
// },
// "resumed": {
// "cursors": [
// 1,
// 1,
// 0,
// 0
// ],
// "index": 2,
// "seq": true,
// "songIndex": 2,
// "stepNow": 0.1
// },
// "scenesMid": [
// "PhaserAdvScene"
// ],
// "stageBgmName": "__dezaemon__"
// }
// Drive the real game to gameplay, then fly each traced sub / charge loadout
// and report what actually reaches the screen.
import { chromium } from 'playwright-core';
const PORT = process.env.PORT || 8137;
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM, args: ['--no-sandbox'] });
const page = await browser.newPage({ viewport: { width: 900, height: 700 } });
const errors = [];
page.on('pageerror', e => { const m = String(e.message || e); if (!/reading 'duration'/.test(m)) errors.push(m); });
await page.goto(`http://localhost:${PORT}/games/2028-ai`, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => document.querySelector('#phaser-canvas canvas') && window.__PHASER_4_GAME__, null, { timeout: 40000 });
await page.waitForTimeout(2500);
const rect = await page.evaluate(() => {
const c = document.querySelector('#phaser-canvas canvas');
const r = Element.prototype.getBoundingClientRect.call(c);
return { x: r.left, y: r.top, w: r.width, h: r.height };
});
const keys = () => page.evaluate(() => window.__PHASER_4_GAME__.scene.getScenes(true).map(s => s.scene.key));
// Boot -> title -> adv -> game. Each step needs poking until it takes.
for (let i = 0; i < 60; i++) {
const k = await keys();
if (k.some(x => /GameScene/.test(x))) break;
if (k.every(x => x === 'BootScene')) {
await page.mouse.click(rect.x + rect.w / 2, rect.y + rect.h / 2);
} else {
await page.evaluate(() => {
for (const s of window.__PHASER_4_GAME__.scene.getScenes(true)) {
if (s.playerBullets) return;
if (s.titleStart) { s.titleStart(); return; }
if (s.goToNextScene) { s.goToNextScene(); return; }
}
});
}
await page.waitForTimeout(1000);
if (i % 5 === 0) console.log(' boot step', i, (await keys()).join(','));
}
await page.waitForTimeout(2000);
console.log('scenes now:', await keys());
const ok = await page.evaluate(() => !!window.__PHASER_4_GAME__.scene.getScenes(true).find(s => s.playerBullets));
if (!ok) { console.log('NEVER REACHED GAMEPLAY'); await browser.close(); process.exit(2); }
async function fly(sub, charge, holdCharge) {
return await page.evaluate(async ([sub, charge, holdCharge]) => {
const scene = window.__PHASER_4_GAME__.scene.getScenes(true).find(s => s.playerBullets);
scene.recipe = scene.recipe || {};
scene.recipe.meta = scene.recipe.meta || {};
scene.recipe.meta.dezaemonSettings = {
loadouts: [{ main: 1, sub, charge, bomb: 0, bombVariant: 0 }],
startLoadout: [0, 0], ships: [{ initialPower: 4, maxPower: 4 }, { initialPower: 4, maxPower: 4 }],
shotDamage: 5120
};
const p = scene.players[0];
p.dezaLoadoutIndex = 0; p.dezaPower = 4; p.dezaWeapons = null;
scene.playerBullets.length = 0; scene.dezaColumns = null;
const probe = window.__updateDezaWeaponsProbe;
let maxBullets = 0, maxCols = 0, spawns = 0, seen = new Set();
for (let t = 0; t < 240; t++) { // 240 ticks = 120 engine frames
probe(scene, p, holdCharge && t < 200);
for (const b of scene.playerBullets) { if (!seen.has(b)) { seen.add(b); spawns++; } }
maxBullets = Math.max(maxBullets, scene.playerBullets.length);
maxCols = Math.max(maxCols, (scene.dezaColumns || []).length);
await new Promise(r => setTimeout(r, 0));
}
return { spawns, maxBullets, maxCols };
}, [sub, charge, holdCharge]);
}
console.log('\nsub spawns live columns');
for (const s of [1, 2, 3, 4, 5, 6, 7]) {
const r = await fly(s, 0, false);
console.log(String(s).padEnd(5), String(r.spawns).padEnd(7), String(r.maxBullets).padEnd(5), r.maxCols);
}
console.log('\ncharge spawns live columns');
for (const c of [1, 2, 3]) {
const r = await fly(0, c, true);
console.log(String(c).padEnd(8), String(r.spawns).padEnd(7), String(r.maxBullets).padEnd(5), r.maxCols);
}
await page.screenshot({ path: '/tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/wt/shot.png' });
console.log('\npage errors:', errors.length ? errors.slice(0, 5) : 'none');
await browser.close();
mkdir -p /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/deza && cat > /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/deza/extract.py <<'PY'
import os, struct, sys
DISC = "/mnt/c/Users/phatm/Downloads/Dezaemon 2 (Japan)/Dezaemon 2 (Japan) (Track 1).bin"
OUT = os.path.dirname(os.path.abspath(__file__))
def read_userdata():
raw = open(DISC, 'rb').read()
sec = 2352
n = len(raw)//sec
out = bytearray()
for i in range(n):
out += raw[i*sec+16 : i*sec+16+2048]
return bytes(out)
def iso_files(ud):
# PVD at logical sector 16
pvd = ud[16*2048:17*2048]
assert pvd[1:6] == b'CD001', pvd[:16]
root = pvd[156:156+34]
root_lba = struct.unpack('<I', root[2:6])[0]
root_len = struct.unpack('<I', root[10:14])[0]
files = {}
def walk(lba, length, prefix=""):
data = ud[lba*2048: lba*2048+length]
i = 0
while i < len(data):
l = data[i]
if l == 0:
# advance to next sector boundary
i = (i//2048 + 1)*2048
if i >= len(data): break
continue
rec = data[i:i+l]
ext_lba = struct.unpack('<I', rec[2:6])[0]
ext_len = struct.unpack('<I', rec[10:14])[0]
flags = rec[25]
nlen = rec[32]
name = rec[33:33+nlen]
i += l
if nlen == 1 and name in (b'\x00', b'\x01'):
continue
nm = name.decode('ascii', 'replace')
if flags & 2:
walk(ext_lba, ext_len, prefix + nm + "/")
else:
files[prefix + nm.split(';')[0]] = (ext_lba, ext_len)
walk(root_lba, root_len)
return files
RING=0x1000; MASK=RING-1
def lzss(inp):
out = bytearray(); ring = bytearray(RING); rpos = 0xFEE
i=0; flags=0; fc=0
while i < len(inp):
if fc == 0:
flags = inp[i]; i+=1; fc=8
if i >= len(inp): break
lit = flags & 1; flags >>= 1; fc -= 1
if lit:
if i >= len(inp): break
b = inp[i]; i+=1
out.append(b); ring[rpos]=b; rpos=(rpos+1)&MASK
else:
if i+1 >= len(inp): break
b1=inp[i]; b2=inp[i+1]; i+=2
off = b1 | ((b2 & 0xF0) << 4); ln = (b2 & 0x0F)+3
for k in range(ln):
b = ring[(off+k)&MASK]
out.append(b); ring[rpos]=b; rpos=(rpos+1)&MASK
return bytes(out)
if __name__ == '__main__':
ud = read_userdata()
files = iso_files(ud)
for k in sorted(files): print(k, files[k])
for name in ('GAME.CMP','0KERNEL.BIN','KUMITATE.CMP'):
for k,(lba,ln) in files.items():
if k.upper().endswith(name):
data = ud[lba*2048: lba*2048+ln]
if name.endswith('.CMP'):
size = struct.unpack('<I', data[:4])[0]
dec = lzss(data[4:])
print(name, 'hdr size', hex(size), 'got', hex(len(dec)))
open(os.path.join(OUT, name.replace('.CMP','.BIN')), 'wb').write(dec)
else:
open(os.path.join(OUT, name), 'wb').write(data)
print(name, 'raw', hex(len(data)))
PY
cd /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/deza && python3 extract.py 2>&1 | tail -60
M_DATA47.BIN (3017, 4228)
M_DATA48.BIN (3020, 4228)
M_DATA49.BIN (3023, 4228)
M_DATA50.BIN (3026, 4228)
M_DATA51.BIN (3029, 4228)
M_DATA52.BIN (3032, 4228)
M_DATA53.BIN (3035, 4228)
M_DATA54.BIN (3038, 4228)
M_DATA55.BIN (3041, 4228)
M_DATA56.BIN (3044, 4228)
M_DATA57.BIN (3047, 4228)
M_DATA58.BIN (3050, 4228)
M_DATA59.BIN (3053, 4228)
M_DATA60.BIN (3056, 4228)
M_DATA61.BIN (3059, 4228)
M_DATA62.BIN (3062, 4228)
M_DATA63.BIN (3065, 4228)
M_DATA64.BIN (3068, 4228)
M_DATA65.BIN (3071, 4228)
M_DATA66.BIN (3074, 4228)
M_DATA67.BIN (3077, 4228)
M_DATA68.BIN (3080, 4228)
M_DATA69.BIN (3083, 4228)
M_DATA70.BIN (3086, 4228)
M_DATA71.BIN (3089, 4228)
M_DATA72.BIN (3092, 4228)
M_DATA73.BIN (3095, 4228)
NOWLOAD.BM (453, 73728)
OPTION.CMP (756, 20044)
ORE.BM (2266, 73728)
POLYBTN.CMP (1989, 21461)
POLYHELP.CMP (2020, 20606)
POLYKITI.CMP (1966, 45301)
POLY_LF.CMP (2000, 20196)
POLY_RI.CMP (2010, 20264)
SGM_DAIO.CMP (1712, 127399)
SGM_ELFI.CMP (1843, 151045)
SGM_GUST.CMP (1548, 166670)
SGM_INIT.CMP (1416, 166670)
SGM_MIYA.CMP (1775, 138847)
SGM_RAMS.CMP (1630, 167362)
SMP_BGM.BIN (339, 101472)
SNDPAC.BIN (92, 505774)
SPR_ANIM.CMP (2343, 20281)
SPR_OPT.CMP (827, 3221)
SPR_OPTI.CMP (766, 61865)
SPR_PAI.CMP (2256, 18698)
SPR_REG.CMP (2325, 9401)
SPR_SND.CMP (2863, 30945)
SYS_PIC.BIN (2506, 11689)
S_ANIM.CMP (2333, 19611)
S_EDIT.CMP (2831, 38331)
S_OPT.CMP (744, 24156)
S_PAINT.CMP (2238, 35206)
S_REGIST.CMP (2315, 19794)
ZAKK_PIC.BIN (2671, 133680)
ZAKO_PIC.BIN (2580, 65140)
GAME.CMP hdr size 0x1883e got 0x286fc
0KERNEL.BIN raw 0x20484
KUMITATE.CMP hdr size 0x15d74 got 0x2f278
Shell cwd was reset to /home/easierbycode/CODE/shmupX.github.io
// mkdir -p /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/wt && cat > /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/wt/harness.js <<'JS'
// Pull the shipped Dezaemon weapons block straight out of the bundle and run it
// against stubs, so the assertions below test the real code, not a copy.
const fs = require('fs');
const SRC = '/home/easierbycode/CODE/shmupX.github.io/static/games/2028-ai/game.bundle.js';
const src = fs.readFileSync(SRC, 'utf8');
const a = src.indexOf(' // ---- Dezaemon CHARGE and SUB weapons');
const b = src.indexOf(' // A plain player projectile');
if (a < 0 || b < 0 || b < a) throw new Error('markers not found');
const block = src.slice(a, b);
const SATURN_TICKS_PER_FRAME = 2;
const DEZA_BOMB_UNIT = 5120;
let LOADOUT = { sub: 0, charge: 0 };
function dezaLoadout(scene, p) { return LOADOUT; }
function mkSprite(x, y, vx, vy, damage) {
const d = { dezaVx: vx, dezaVy: vy, damage };
return {
x, y, active: true, scale: 1, alpha: 1, rot: 0,
setData(k, v) { d[k] = v; return this; },
getData(k) { return d[k]; },
setScale(s) { this.scale = s; return this; },
setAlpha(v) { this.alpha = v; return this; },
setRotation(r) { this.rot = r; return this; },
destroy() { this.active = false; },
_d: d
};
}
let SPAWNED = [];
function spawnDezaPlayerShot(scene, p, x, y, vx, vy, damage) {
const s = mkSprite(x, y, vx, vy, damage);
SPAWNED.push(s);
scene.playerBullets.push(s);
return s;
}
const gfxCalls = [];
function mkScene() {
return {
enemies: [], players: [], playerBullets: [], dezaColumns: null, dezaBeamGfx: null,
recipe: { meta: { dezaemonSettings: { shotDamage: 5120 } } },
playSound() {},
add: { graphics: () => ({ setDepth() { return this; }, fillStyle(...x) { gfxCalls.push(['fs', ...x]); }, fillRect(...x) { gfxCalls.push(['fr', ...x]); }, fillCircle(...x) { gfxCalls.push(['fc', ...x]); }, clear() {} }) },
enemyDie() {}, bossDie() {}
};
}
function mkPlayer(i) {
return { index: i, dead: false, dezaPower: 0, sprite: { x: 100, y: 400 } };
}
const mod = {};
eval(block + '\nmodule.exports = { updateDezaWeapons, fireDezaSub, fireDezaCharge, dezaStepShot, updateDezaColumns, drawDezaTrails, DEZA_SUB2_MUZZLES, DEZA_SUB3_SHOTS, DEZA_SUB4_SHOTS, DEZA_CHARGE1_SHOTS, DEZA_CHARGE_BUSY, DEZA_SUB_INTERVAL, dezaPx, dezaVel };');
module.exports = { api: module.exports, block };
JS
cat > /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/wt/run.js <<'JS'
const fs = require('fs');
const SRC = '/home/easierbycode/CODE/shmupX.github.io/static/games/2028-ai/game.bundle.js';
const src = fs.readFileSync(SRC, 'utf8');
const a = src.indexOf(' // ---- Dezaemon CHARGE and SUB weapons');
const b = src.indexOf(' // A plain player projectile');
const block = src.slice(a, b);
const SATURN_TICKS_PER_FRAME = 2;
const DEZA_BOMB_UNIT = 5120;
let LOADOUT = { sub: 0, charge: 0 };
function dezaLoadout() { return LOADOUT; }
let SPAWNED = [];
function mkSprite(x, y, vx, vy, damage) {
const d = { dezaVx: vx, dezaVy: vy, damage };
return { x, y, active: true, scale: 1, alpha: 1, rot: 0,
setData(k, v) { d[k] = v; return this; }, getData(k) { return d[k]; },
setScale(s) { this.scale = s; return this; }, setAlpha(v) { this.alpha = v; return this; },
setRotation(r) { this.rot = r; return this; }, destroy() { this.active = false; }, _d: d };
}
function spawnDezaPlayerShot(scene, p, x, y, vx, vy, damage) {
const s = mkSprite(x, y, vx, vy, damage); SPAWNED.push(s); scene.playerBullets.push(s); return s;
}
const G = { setDepth() { return G; }, fillStyle() {}, fillRect() {}, fillCircle() {}, clear() {} };
function mkScene() {
return { enemies: [], players: [], playerBullets: [], dezaColumns: null, dezaBeamGfx: G,
recipe: { meta: { dezaemonSettings: { shotDamage: 5120 } } },
playSound() {}, add: { graphics: () => G }, enemyDie() {}, bossDie() {} };
}
function mkPlayer(i) { return { index: i || 0, dead: false, dezaPower: 0, sprite: { x: 100, y: 400 } }; }
let API;
eval(block + '\nAPI = { updateDezaWeapons, fireDezaSub, fireDezaCharge, dezaStepShot, updateDezaColumns, drawDezaTrails, DEZA_SUB_INTERVAL, DEZA_CHARGE_BUSY, dezaPx, dezaVel };');
let fails = 0, checks = 0;
function eq(name, got, want, tol) {
checks++;
const ok = tol == null ? JSON.stringify(got) === JSON.stringify(want) : Math.abs(got - want) <= tol;
if (!ok) { fails++; console.log('FAIL', name, '\n got ', JSON.stringify(got), '\n want', JSON.stringify(want)); }
}
// --- unit conversions -------------------------------------------------------
eq('128 units = 1 px', API.dezaPx(1280), 10);
eq('units -> px/tick', API.dezaVel(1280), 5);
// --- SUB 2: one volley per level -------------------------------------------
const want2 = [
[[0, -10]],
[[6, -10], [-6, -10]],
[[0, -10], [-8, 4], [8, 4]],
[[6, -10], [-6, -10], [12, 4], [-12, 4]],
[[8, 4], [-8, 4], [0, -10], [16, 18], [-16, 18]]
];
for (let L = 0; L < 5; L++) {
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 2, L, {});
eq('sub2 L' + L + ' offsets', SPAWNED.map(s => [s.x - 100, s.y - 400]), want2[L]);
eq('sub2 L' + L + ' all straight up', SPAWNED.every(s => s._d.dezaVx === 0 && s._d.dezaVy === -5), true);
eq('sub2 L' + L + ' damage', SPAWNED[0]._d.damage, [6656, 5632, 4608, 3584, 2560][L] / 5120, 1e-9);
}
// --- SUB 3: lobbed grenades, launch DOWN then accelerate up -----------------
{
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 3, 2, {});
eq('sub3 L2 count', SPAWNED.length, 3);
eq('sub3 L2 launches downward', SPAWNED.every(s => s._d.dezaVy > 0), true);
eq('sub3 L2 lateral drifts', SPAWNED.map(s => s._d.dezaVx), [0.125, 0, -0.125]);
// 256 units of downward launch, +40/frame: crosses zero after 6.4 frames.
const g = SPAWNED[1];
let flips = 0, ticks = 0;
for (let t = 0; t < 40 && flips === 0; t++) { API.dezaStepShot(sc, g); ticks++; if (g._d.dezaVy <= 0) flips = 1; }
eq('sub3 apex near frame 6.4', ticks / SATURN_TICKS_PER_FRAME, 6.4, 0.6);
}
// --- SUB 4: homing chains ---------------------------------------------------
{
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 4, 4, {});
eq('sub4 L4 chains', SPAWNED.length, 5);
eq('sub4 L4 headings', SPAWNED.map(s => s._d.dezaHome.heading), [0, 6, -6, 12, -12]);
eq('sub4 L4 links', SPAWNED.map(s => s._d.dezaHome.links), [3, 3, 3, 3, 3]);
eq('sub4 pierces', SPAWNED.every(s => s._d.dezaPerFrame === true), true);
eq('sub4 launch speed 6.5 px/tick', Math.hypot(SPAWNED[0]._d.dezaVx, SPAWNED[0]._d.dezaVy), 6.5, 1e-9);
// A head with a target inside the box turns toward it, capped at 12 units/tick.
const head = SPAWNED[0];
sc.enemies.push({ active: true, x: head.x + 60, y: head.y - 20, width: 16, getData: () => 5, setData() {} });
API.dezaStepShot(sc, head);
eq('sub4 turns toward the target', head._d.dezaHome.heading > 0 && head._d.dezaHome.heading <= 12, true);
}
// --- SUB 5: anchored columns, per-level lifetime ----------------------------
{
const want = [10, 14, 19, 23, 28];
for (let L = 0; L < 5; L++) {
const sc = mkScene(), p = mkPlayer();
API.fireDezaSub(sc, p, 5, L, {});
eq('sub5 L' + L + ' life frames', sc.dezaColumns[0].life, want[L]);
eq('sub5 L' + L + ' anchored', sc.dezaColumns[0].follow, false);
}
// It stays where it was fired even as the ship moves, and retires on time.
const sc = mkScene(), p = mkPlayer(); sc.players = [p];
API.fireDezaSub(sc, p, 5, 0, {});
const x0 = sc.dezaColumns[0].x;
p.sprite.x += 40;
for (let t = 0; t < 19; t++) API.updateDezaColumns(sc);
eq('sub5 column does not follow', sc.dezaColumns.length && sc.dezaColumns[0].x, x0);
API.updateDezaColumns(sc); API.updateDezaColumns(sc);
eq('sub5 column expires at 10 frames', sc.dezaColumns.length, 0);
}
// --- SUB 6: one growing indestructible ball --------------------------------
{
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 6, 4, {});
eq('sub6 count', SPAWNED.length, 1);
eq('sub6 speed 4.5 px/tick up', SPAWNED[0]._d.dezaVy, -4.5);
eq('sub6 pierces', SPAWNED[0]._d.dezaPerFrame, true);
for (let t = 0; t < 12; t++) API.dezaStepShot(sc, SPAWNED[0]);
eq('sub6 L4 grows to 2.125x', SPAWNED[0].scale, 8704 / 4096, 1e-9);
}
// --- CHARGE cadence: the whole state machine, gated to Saturn frames -------
function runCharge(ctype, holdFrames) {
const sc = mkScene(), p = mkPlayer(); sc.players = [p];
LOADOUT = { sub: 0, charge: ctype };
SPAWNED = [];
let volleys = 0;
const spawnBefore = () => SPAWNED.length + (sc.dezaColumns ? sc.dezaColumns.length : 0);
let prev = 0;
// Two ticks per Saturn frame, held then released.
for (let f = 0; f < holdFrames; f++) { API.updateDezaWeapons(sc, p, true); API.updateDezaWeapons(sc, p, true); }
for (let f = 0; f < 400; f++) {
API.updateDezaWeapons(sc, p, false); API.updateDezaWeapons(sc, p, false);
const n = spawnBefore();
if (n > prev) { volleys++; prev = n; }
}
return { sc, p, volleys, spawned: SPAWNED.length, columns: sc.dezaColumns ? sc.dezaColumns.length : 0 };
}
{
// gauge +1/frame, cap 320, level = gauge/64 - 1: 64 frames of hold = level 0.
const lvl0 = runCharge(1, 64);
eq('charge1 fires at gauge 64', lvl0.spawned, 1);
const lvl4 = runCharge(1, 320);
eq('charge1 L4 fires 5 orbs', lvl4.spawned, 5);
eq('charge1 is a ONE-SHOT volley', lvl4.volleys, 1);
const below = runCharge(1, 60);
eq('charge1 below 64 does nothing', below.spawned, 0);
}
{
// Types 2 and 3 fire again on every odd count of their busy window.
const c2 = runCharge(2, 320);
eq('charge2 segments per attack', c2.volleys, 1 + API.DEZA_CHARGE_BUSY[2] / 2);
const c3 = runCharge(3, 320);
eq('charge3 orbs per attack', c3.volleys, 1 + API.DEZA_CHARGE_BUSY[3] / 2);
}
{
// Charge 1's packed descriptors: L3 is two mirrored pairs, the wide one held
// back 2 frames, and the weave amplitudes are 3 and 9 px/frame.
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaCharge(sc, p, 1, 3, { busy: 16 });
eq('charge1 L3 count', SPAWNED.length, 4);
eq('charge1 L3 phases', SPAWNED.map(s => s._d.dezaWeave.phase), [0x40, 0xC0, 0x40, 0xC0]);
eq('charge1 L3 amplitudes', SPAWNED.map(s => s._d.dezaWeave.amp), [768, 768, 2304, 2304]);
eq('charge1 L3 delays', SPAWNED.map(s => s._d.dezaWeave.delay), [0, 0, 2, 2]);
eq('charge1 pierces by pool', SPAWNED.every(s => s._d.dezaPool > 0), true);
// The delayed pair hangs at the muzzle for 2 frames, then climbs at 3 px/tick.
const wide = SPAWNED[2];
API.dezaStepShot(sc, wide);
eq('charge1 delayed orb hovers', wide._d.dezaVy, 0);
for (let t = 0; t < 4; t++) API.dezaStepShot(sc, wide);
eq('charge1 orb climbs at 3 px/tick', wide._d.dezaVy, -3, 1e-9);
// The mirrored pair weaves in antiphase.
const l = SPAWNED[0], r = SPAWNED[1];
for (let t = 0; t < 20; t++) { API.dezaStepShot(sc, l); API.dezaStepShot(sc, r); }
eq('charge1 pair weaves in antiphase', Math.sign(l._d.dezaVx) === -Math.sign(r._d.dezaVx) && l._d.dezaVx !== 0, true);
}
{
// Charge 2's column tracks the ship sideways; charge 3's orb leans WITH drift.
const sc = mkScene(), p = mkPlayer(); sc.players = [p];
API.fireDezaCharge(sc, p, 2, 2, { busy: 96 });
p.dezaWeapons = { busy: 96 };
p.sprite.x = 180;
API.updateDezaColumns(sc);
eq('charge2 column re-locks to the ship', sc.dezaColumns[0].x, 180);
eq('charge2 L2 half-width 10 px', sc.dezaColumns[0].halfW, 10);
const sc3 = mkScene(), p3 = mkPlayer(); SPAWNED = [];
API.fireDezaCharge(sc3, p3, 3, 0, { busy: 160, aim: 96 }); // aim 96 = full left
eq('charge3 aim 96 leans LEFT', SPAWNED[0]._d.dezaVx < 0, true);
SPAWNED = [];
API.fireDezaCharge(sc3, p3, 3, 0, { busy: 160, aim: 32 }); // aim 32 = full right
eq('charge3 aim 32 leans RIGHT', SPAWNED[0]._d.dezaVx > 0, true);
}
// --- sub cadence: the traced reload intervals, gated to Saturn frames -------
{
for (const st of [2, 3, 4, 5, 6]) {
LOADOUT = { sub: st, charge: 0 };
const sc = mkScene(), p = mkPlayer(); sc.players = [p]; SPAWNED = [];
let volleys = 0, prev = 0;
for (let f = 0; f < 60; f++) {
API.updateDezaWeapons(sc, p, false); API.updateDezaWeapons(sc, p, false);
const n = SPAWNED.length + (sc.dezaColumns ? sc.dezaColumns.length : 0);
if (n > prev) { volleys++; prev = n; }
}
const iv = API.DEZA_SUB_INTERVAL[st];
eq('sub' + st + ' volleys in 60 frames (interval ' + iv + ')', volleys, Math.ceil(60 / (iv + 1)), 1);
}
}
console.log(fails ? `\n${fails}/${checks} checks FAILED` : `\nall ${checks} checks passed`);
process.exit(fails ? 1 : 0);
// JS
// ~/.local/bin/node /tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/wt/run.js
// Exit code 1
// FAIL sub4 launch speed 6.5 px/tick
// got 13
// want 6.5
// FAIL sub2 volleys in 60 frames (interval 5)
// got 12
// want 10
// FAIL sub4 volleys in 60 frames (interval 1)
// got 60
// want 30
// FAIL sub5 volleys in 60 frames (interval 3)
// got 20
// want 15
// 4/66 checks FAILED
S=/tmp/claude-0/-home-user-shmupX-github-io/098c1003-d888-5154-89df-9119998b02a6/scratchpad && cd $S/apply && DB=https://evil-invaders-default-rtdb.firebaseio.com/shmupX/levels/gs && curl -sS "$DB/storyData/customImages/stage1_part1.json" -o now_part1.json && cmp now_part1.json body.json && echo "stage1_part1 now holds the bunny pin PNG exactly ($(wc -c < now_part1.json) bytes)" && for k in stage0_part0 stage0_part1 stage1_part0; do curl -sS "$DB/storyData/customImages/$k.json" -o now_$k.json; cmp now_$k.json $S/current/$k.txt && echo "$k unchanged"; done && echo "savedAt=$(curl -sS "$DB/savedAt.json")" && echo "customImages keys: $(curl -sS "$DB/storyData/customImages.json?shallow=true")" && echo "stage1 words: $(curl -sS "$DB/storyData/stage1.json")"
S=/tmp/claude-0/-home-user-shmupX-github-io/89ec543c-2181-5fcc-9006-596d81fb428e/scratchpad; python3 -I $S/srv/serve.py $S/ma/record.json 8823 > $S/srv.log 2>&1
# alt port
S=/tmp/claude-0/-home-user-shmupX-github-io/89ec543c-2181-5fcc-9006-596d81fb428e/scratchpad; python3 -I $S/srv/serve.py /home/user/shmupX.github.io/static/games/2028-ai/foo.json 8824 > $S/srv2.log 2>&1
S=/tmp/claude-0/-home-user-shmupX-github-io/89ec543c-2181-5fcc-9006-596d81fb428e/scratchpad; cd /home/user/shmupX.github.io && node --check static/games/2028-ai/game.bundle.js && cd $S/pw && timeout 150 node crash2.js "http://127.0.0.1:8823/games/2028-ai/?version=mod" $S/fixed3 stage 2>&1 | grep "ctx events\|sample" | cut -c1-300 && python3 -I -c "
from PIL import Image
a=Image.open('$S/fixed3_before.png');b=Image.open('$S/fixed3_after.png')
o=Image.new('RGB',(a.width*2+10,a.height),(255,0,255));o.paste(a,(0,0));o.paste(b,(a.width+10,0));o.save('$S/fixed3_cmp.png')"
import zlib, struct
def read_png(path):
data = open(path,'rb').read()
assert data[:8] == b'\x89PNG\r\n\x1a\n'
pos = 8; idat = b''; w=h=None; bitdepth=colortype=None; plte=None; trns=None
while pos < len(data):
ln, typ = struct.unpack('>I4s', data[pos:pos+8]); pos += 8
chunk = data[pos:pos+ln]; pos += ln + 4
if typ == b'IHDR':
w,h,bitdepth,colortype = struct.unpack('>IIBB', chunk[:10])
elif typ == b'IDAT': idat += chunk
elif typ == b'PLTE': plte = chunk
elif typ == b'tRNS': trns = chunk
raw = zlib.decompress(idat)
ch = {0:1,2:3,3:1,4:2,6:4}[colortype]
assert bitdepth == 8, f'bitdepth {bitdepth}'
stride = w*ch
out = bytearray(h*stride)
prev = bytearray(stride)
p = 0
for y in range(h):
f = raw[p]; p += 1
line = bytearray(raw[p:p+stride]); p += stride
if f == 1:
for i in range(ch, stride): line[i] = (line[i] + line[i-ch]) & 255
elif f == 2:
for i in range(stride): line[i] = (line[i] + prev[i]) & 255
elif f == 3:
for i in range(stride):
a = line[i-ch] if i >= ch else 0
line[i] = (line[i] + ((a + prev[i])>>1)) & 255
elif f == 4:
for i in range(stride):
a = line[i-ch] if i >= ch else 0
b = prev[i]; c = prev[i-ch] if i >= ch else 0
pa, pb, pc = abs(b-c), abs(a-c), abs(a+b-2*c)
pr = a if (pa<=pb and pa<=pc) else (b if pb<=pc else c)
line[i] = (line[i] + pr) & 255
out[y*stride:(y+1)*stride] = line
prev = line
# normalize to RGBA
if colortype == 6:
rgba = bytes(out)
elif colortype == 2:
rgba = bytearray()
for i in range(0, len(out), 3): rgba += out[i:i+3] + b'\xff'
rgba = bytes(rgba)
elif colortype == 3:
rgba = bytearray()
for i in out:
r,g,b = plte[i*3:i*3+3]
a = trns[i] if trns and i < len(trns) else 255
rgba += bytes((r,g,b,a))
rgba = bytes(rgba)
else: raise ValueError(f'colortype {colortype}')
return w, h, rgba
def crop(w,h,rgba,x0,y0,cw,ch_):
out = bytearray()
for y in range(y0, y0+ch_):
out += rgba[(y*w+x0)*4:(y*w+x0+cw)*4]
return cw, ch_, bytes(out)
def scale(w,h,rgba,f):
out = bytearray()
for y in range(h):
row = bytearray()
for x in range(w):
row += rgba[(y*w+x)*4:(y*w+x)*4+4]*f
out += row*f
return w*f, h*f, bytes(out)
def write_png(path,w,h,rgba):
raw = b''.join(b'\x00' + rgba[y*w*4:(y+1)*w*4] for y in range(h))
def chunk(typ, data):
return struct.pack('>I',len(data)) + typ + data + struct.pack('>I', zlib.crc32(typ+data) & 0xffffffff)
png = b'\x89PNG\r\n\x1a\n'
png += chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0))
png += chunk(b'IDAT', zlib.compress(raw))
png += chunk(b'IEND', b'')
open(path,'wb').write(png)
$ SP=/private/tmp/claude-501/-Volumes-SANDISK-USB-CODE-shmupX-github-io/d60a3485-901a-4c3e-acf9-2f430886ac93/scratchpad; P='[["hello world &?=_","M",3]]'; deno run --allow-read "$SP/dumpmask.js" "$P" > "$SP/a.json"; "$SP/venv/bin/python" "$SP/refmask.py" "$P" > "$SP/b.json"; "$SP/venv/bin/python" -c "
import json
SP='$SP'
a=json.load(open(SP+'/a.json'))[0]; b=json.load(open(SP+'/b.json'))[0]
for r1,r2 in zip(a['rows'],b['rows']):
print(r1.replace('0','.').replace('1','#'),' ',r2.replace('0','.').replace('1','#'),' ',''.join('X' if x!=y else '.' for x,y in zip(r1,r2)))
"
#######.#.#.#..##.####### #######.#....#.#..####### ..........X.XX..X........
#.....#.#.##..##..#.....# #.....#.#.#.##....#.....# ...........XXXXX.........
#.###.#...##.###..#.###.# #.###.#..#.##...#.#.###.# .........XX.XXXXX........
#.###.#.#.#.#.....#.###.# #.###.#.##.##.##..#.###.# .........XXX..XX.........
#.###.#..##.##....#.###.# #.###.#..##.#.#...#.###.# .............XX..........
#.....#..###..#...#.....# #.....#..#.#.#....#.....# ..........X..XX..........
#######.#.#.#.#.#.####### #######.#.#.#.#.#.####### .........................
........####.####........ ........#.##...##........ .........X...XX..........
#.##.###...#.###..#..#.## #.##.###..##.#.#..#..#.## ..........X...X..........
##.....##..##..##..#..#.. .#.###....#..####..#..#.. X..XXX.XX.XXXXX..........
..###.#..##.#.#.#.#...... ###.####..#..#..#.#...... XX.X.X.X.X..XXX..........
.##......###.##....#.###. #.#.##...#.#.......#.###. XX..XX....X..XX..........
###.#.###.##....######### #.#..##.#...#.#.######### .X..XX.X..XXX.X..........
.#..##.#..##.#.#.######## .###.#.##..##.##.######## ..XXX...X.X.XXX..........
.##..###....#.#..#..#.##. .#.#.##..###.#...#..#.##. ..XX...X.XXXXXX..........
#..###....#.##..#.###...# #..##..#.#.#..#.#.###...# .....X.X.XXXXXX..........
....#.#.####...######.### ..#####.##..#.#######.### ..XX.X....XXX.X..........
........##..##.##...##..# ........##....###...##..# ............XXX..........
#######.#####...#.#.#.### #######.#.#..##.#.#.#.### .........X.XXXX..........
#.....#.##..#...#...#..#. #.....#.##.#.##.#...#..#. ...........XXXX..........
#.###.#...####..#####.... #.###.#..##..##.#####.... .........X.XX.X..........
#.###.#.###.#####.#.##.## #.###.#.#.#....##.#.##.## .........X..XXX..........
#.###.#.#..###.#.####..#. #.###.#.###...##.####..#. .........XXXXXX..........
#.....#...#.........###.. #.....#..#.####.....###.. .........XXXXXX..........
#######.#...#.##..##..### #######.#.##...#..##..### ..........XXX.X..........
cd /Users/danieljohnson/CODE/shmupX.github.io && cat > /private/tmp/claude-501/-Users-danieljohnson-CODE-shmupX-github-io/91fe123b-4bae-40f0-8582-d561924aaddc/scratchpad/fix-foo.ts <<'EOF'
import { normalizeLegacyGame } from "@shmupx/shmup-engine/legacy-names";
const path = "static/games/2028-ai/foo.json";
const text = await Deno.readTextFile(path);
const game = JSON.parse(text);
// The file is written with sorted keys and two-space indent (a Firebase
// export); keep that shape so the diff is only the renamed keys.
const sorted = (v: unknown): unknown =>
Array.isArray(v)
? v.map(sorted)
: v && typeof v === "object"
? Object.fromEntries(
Object.keys(v as object).sort().map((k) => [k, sorted((v as Record<string, unknown>)[k])]),
)
: v;
const isSorted = JSON.stringify(sorted(game), null, 2) + "\n" === text;
const isPlain = JSON.stringify(game, null, 2) + "\n" === text;
console.log({ isSorted, isPlain, endsWithNewline: text.endsWith("\n") });
const report = normalizeLegacyGame(game);
console.log(`${report.frames.length} frame(s), ${report.fields.length} field(s)`);
const out = JSON.stringify(isSorted ? sorted(game) : game, null, 2) + (text.endsWith("\n") ? "\n" : "");
await Deno.writeTextFile(path, out);
EOF
deno run -A /private/tmp/claude-501/-Users-danieljohnson-CODE-shmupX-github-io/91fe123b-4bae-40f0-8582-d561924aaddc/scratchpad/fix-foo.ts && git diff --stat static/games/2028-ai/foo.json && git diff static/games/2028-ai/foo.json | /usr/bin/grep -E '^[-+] ' | sort | uniq -c | sort -rn | head -6 && /usr/bin/grep -c 'cagage' static/games/2028-ai/foo.json
const fs = require('fs');
const SRC = '/home/easierbycode/CODE/shmupX.github.io/static/games/2028-ai/game.bundle.js';
const src = fs.readFileSync(SRC, 'utf8');
const a = src.indexOf(' // ---- Dezaemon CHARGE and SUB weapons');
const b = src.indexOf(' // A plain player projectile');
const block = src.slice(a, b);
const SATURN_TICKS_PER_FRAME = 2;
const DEZA_BOMB_UNIT = 5120;
let LOADOUT = { sub: 0, charge: 0 };
function dezaLoadout() { return LOADOUT; }
let SPAWNED = [];
function mkSprite(x, y, vx, vy, damage) {
const d = { dezaVx: vx, dezaVy: vy, damage };
return { x, y, active: true, scale: 1, alpha: 1, rot: 0,
setData(k, v) { d[k] = v; return this; }, getData(k) { return d[k]; },
setScale(s) { this.scale = s; return this; }, setAlpha(v) { this.alpha = v; return this; },
setRotation(r) { this.rot = r; return this; }, destroy() { this.active = false; }, _d: d };
}
function spawnDezaPlayerShot(scene, p, x, y, vx, vy, damage) {
const s = mkSprite(x, y, vx, vy, damage); SPAWNED.push(s); scene.playerBullets.push(s); return s;
}
const G = { setDepth() { return G; }, fillStyle() {}, fillRect() {}, fillCircle() {}, clear() {} };
function mkScene() {
return { enemies: [], players: [], playerBullets: [], dezaColumns: null, dezaBeamGfx: G,
recipe: { meta: { dezaemonSettings: { shotDamage: 5120 } } },
playSound() {}, add: { graphics: () => G }, enemyDie() {}, bossDie() {} };
}
function mkPlayer(i) { return { index: i || 0, dead: false, dezaPower: 0, sprite: { x: 100, y: 400 } }; }
let API;
eval(block + '\nAPI = { updateDezaWeapons, fireDezaSub, fireDezaCharge, dezaStepShot, updateDezaColumns, drawDezaTrails, DEZA_SUB_INTERVAL, DEZA_CHARGE_BUSY, dezaPx, dezaVel };');
let fails = 0, checks = 0;
function eq(name, got, want, tol) {
checks++;
const ok = tol == null ? JSON.stringify(got) === JSON.stringify(want) : Math.abs(got - want) <= tol;
if (!ok) { fails++; console.log('FAIL', name, '\n got ', JSON.stringify(got), '\n want', JSON.stringify(want)); }
}
// --- unit conversions -------------------------------------------------------
eq('128 units = 1 px', API.dezaPx(1280), 10);
eq('units -> px/tick', API.dezaVel(1280), 5);
// --- SUB 2: one volley per level -------------------------------------------
const want2 = [
[[0, -10]],
[[6, -10], [-6, -10]],
[[0, -10], [-8, 4], [8, 4]],
[[6, -10], [-6, -10], [12, 4], [-12, 4]],
[[8, 4], [-8, 4], [0, -10], [16, 18], [-16, 18]]
];
for (let L = 0; L < 5; L++) {
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 2, L, {});
eq('sub2 L' + L + ' offsets', SPAWNED.map(s => [s.x - 100, s.y - 400]), want2[L]);
eq('sub2 L' + L + ' all straight up', SPAWNED.every(s => s._d.dezaVx === 0 && s._d.dezaVy === -5), true);
eq('sub2 L' + L + ' damage', SPAWNED[0]._d.damage, [6656, 5632, 4608, 3584, 2560][L] / 5120, 1e-9);
}
// --- SUB 3: lobbed grenades, launch DOWN then accelerate up -----------------
{
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 3, 2, {});
eq('sub3 L2 count', SPAWNED.length, 3);
eq('sub3 L2 launches downward', SPAWNED.every(s => s._d.dezaVy > 0), true);
eq('sub3 L2 lateral drifts', SPAWNED.map(s => s._d.dezaVx), [0.125, 0, -0.125]);
// 256 units of downward launch, +40/frame: crosses zero after 6.4 frames.
const g = SPAWNED[1];
let flips = 0, ticks = 0;
for (let t = 0; t < 40 && flips === 0; t++) { API.dezaStepShot(sc, g); ticks++; if (g._d.dezaVy <= 0) flips = 1; }
eq('sub3 apex near frame 6.4', ticks / SATURN_TICKS_PER_FRAME, 6.4, 0.6);
}
// --- SUB 4: homing chains ---------------------------------------------------
{
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 4, 4, {});
eq('sub4 L4 chains', SPAWNED.length, 5);
eq('sub4 L4 headings', SPAWNED.map(s => s._d.dezaHome.heading), [0, 6, -6, 12, -12]);
eq('sub4 L4 links', SPAWNED.map(s => s._d.dezaHome.links), [3, 3, 3, 3, 3]);
eq('sub4 pierces', SPAWNED.every(s => s._d.dezaPerFrame === true), true);
eq('sub4 launch speed 6.5 px/tick', Math.hypot(SPAWNED[0]._d.dezaVx, SPAWNED[0]._d.dezaVy), 6.5, 1e-9);
// A head with a target inside the box turns toward it, capped at 12 units/tick.
const head = SPAWNED[0];
sc.enemies.push({ active: true, x: head.x + 60, y: head.y - 20, width: 16, getData: () => 5, setData() {} });
API.dezaStepShot(sc, head);
eq('sub4 turns toward the target', head._d.dezaHome.heading > 0 && head._d.dezaHome.heading <= 12, true);
}
// --- SUB 5: anchored columns, per-level lifetime ----------------------------
{
const want = [10, 14, 19, 23, 28];
for (let L = 0; L < 5; L++) {
const sc = mkScene(), p = mkPlayer();
API.fireDezaSub(sc, p, 5, L, {});
eq('sub5 L' + L + ' life frames', sc.dezaColumns[0].life, want[L]);
eq('sub5 L' + L + ' anchored', sc.dezaColumns[0].follow, false);
}
// It stays where it was fired even as the ship moves, and retires on time.
const sc = mkScene(), p = mkPlayer(); sc.players = [p];
API.fireDezaSub(sc, p, 5, 0, {});
const x0 = sc.dezaColumns[0].x;
p.sprite.x += 40;
for (let t = 0; t < 19; t++) API.updateDezaColumns(sc);
eq('sub5 column does not follow', sc.dezaColumns.length && sc.dezaColumns[0].x, x0);
API.updateDezaColumns(sc); API.updateDezaColumns(sc);
eq('sub5 column expires at 10 frames', sc.dezaColumns.length, 0);
}
// --- SUB 6: one growing indestructible ball --------------------------------
{
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaSub(sc, p, 6, 4, {});
eq('sub6 count', SPAWNED.length, 1);
eq('sub6 speed 4.5 px/tick up', SPAWNED[0]._d.dezaVy, -4.5);
eq('sub6 pierces', SPAWNED[0]._d.dezaPerFrame, true);
for (let t = 0; t < 12; t++) API.dezaStepShot(sc, SPAWNED[0]);
eq('sub6 L4 grows to 2.125x', SPAWNED[0].scale, 8704 / 4096, 1e-9);
}
// --- CHARGE cadence: the whole state machine, gated to Saturn frames -------
function runCharge(ctype, holdFrames) {
const sc = mkScene(), p = mkPlayer(); sc.players = [p];
LOADOUT = { sub: 0, charge: ctype };
SPAWNED = [];
// Count every distinct object the attack emits, columns included, so a list
// cap or a retirement cannot hide a spawn.
const seenCols = new Set();
const sweep = () => {
if (sc.dezaColumns) for (const c of sc.dezaColumns) seenCols.add(c);
};
let prev = 0, volleys = 0;
for (let f = 0; f < holdFrames; f++) { API.updateDezaWeapons(sc, p, true); API.updateDezaWeapons(sc, p, true); sweep(); }
for (let f = 0; f < 400; f++) {
API.updateDezaWeapons(sc, p, false); sweep();
API.updateDezaWeapons(sc, p, false); sweep();
API.updateDezaColumns(sc);
const n = SPAWNED.length + seenCols.size;
if (n > prev) { volleys++; prev = n; }
}
return { sc, p, volleys, spawned: SPAWNED.length, columns: seenCols.size };
}
{
// gauge +1/frame, cap 320, level = gauge/64 - 1: 64 frames of hold = level 0.
const lvl0 = runCharge(1, 64);
eq('charge1 fires at gauge 64', lvl0.spawned, 1);
const lvl4 = runCharge(1, 320);
eq('charge1 L4 fires 5 orbs', lvl4.spawned, 5);
eq('charge1 is a ONE-SHOT volley', lvl4.volleys, 1);
const below = runCharge(1, 60);
eq('charge1 below 64 does nothing', below.spawned, 0);
}
{
// Types 2 and 3 fire again on every odd count of their busy window.
const c2 = runCharge(2, 320);
eq('charge2 segments per attack', c2.volleys, 1 + API.DEZA_CHARGE_BUSY[2] / 2);
const c3 = runCharge(3, 320);
eq('charge3 orbs per attack', c3.volleys, 1 + API.DEZA_CHARGE_BUSY[3] / 2);
}
{
// Charge 1's packed descriptors: L3 is two mirrored pairs, the wide one held
// back 2 frames, and the weave amplitudes are 3 and 9 px/frame.
const sc = mkScene(), p = mkPlayer(); SPAWNED = [];
API.fireDezaCharge(sc, p, 1, 3, { busy: 16 });
eq('charge1 L3 count', SPAWNED.length, 4);
eq('charge1 L3 phases', SPAWNED.map(s => s._d.dezaWeave.phase), [0x40, 0xC0, 0x40, 0xC0]);
eq('charge1 L3 amplitudes', SPAWNED.map(s => s._d.dezaWeave.amp), [768, 768, 2304, 2304]);
eq('charge1 L3 delays', SPAWNED.map(s => s._d.dezaWeave.delay), [0, 0, 2, 2]);
eq('charge1 pierces by pool', SPAWNED.every(s => s._d.dezaPool > 0), true);
// The delayed pair hangs at the muzzle for 2 frames, then climbs at 3 px/tick.
const wide = SPAWNED[2];
API.dezaStepShot(sc, wide);
eq('charge1 delayed orb hovers', wide._d.dezaVy, 0);
for (let t = 0; t < 4; t++) API.dezaStepShot(sc, wide);
eq('charge1 orb climbs at 3 px/tick', wide._d.dezaVy, -3, 1e-9);
// The mirrored pair weaves in antiphase.
const l = SPAWNED[0], r = SPAWNED[1];
for (let t = 0; t < 20; t++) { API.dezaStepShot(sc, l); API.dezaStepShot(sc, r); }
eq('charge1 pair weaves in antiphase', Math.sign(l._d.dezaVx) === -Math.sign(r._d.dezaVx) && l._d.dezaVx !== 0, true);
}
{
// Charge 2's column tracks the ship sideways; charge 3's orb leans WITH drift.
const sc = mkScene(), p = mkPlayer(); sc.players = [p];
API.fireDezaCharge(sc, p, 2, 2, { busy: 96 });
p.dezaWeapons = { busy: 96 };
p.sprite.x = 180;
API.updateDezaColumns(sc);
eq('charge2 column re-locks to the ship', sc.dezaColumns[0].x, 180);
eq('charge2 L2 half-width 10 px', sc.dezaColumns[0].halfW, 10);
const sc3 = mkScene(), p3 = mkPlayer(); SPAWNED = [];
API.fireDezaCharge(sc3, p3, 3, 0, { busy: 160, aim: 96 }); // aim 96 = full left
eq('charge3 aim 96 leans LEFT', SPAWNED[0]._d.dezaVx < 0, true);
SPAWNED = [];
API.fireDezaCharge(sc3, p3, 3, 0, { busy: 160, aim: 32 }); // aim 32 = full right
eq('charge3 aim 32 leans RIGHT', SPAWNED[0]._d.dezaVx > 0, true);
}
// --- sub cadence: the traced reload intervals, gated to Saturn frames -------
{
for (const st of [2, 3, 4, 5, 6]) {
LOADOUT = { sub: st, charge: 0 };
const sc = mkScene(), p = mkPlayer(); sc.players = [p]; SPAWNED = [];
let volleys = 0, prev = 0;
for (let f = 0; f < 60; f++) {
API.updateDezaWeapons(sc, p, false); API.updateDezaWeapons(sc, p, false);
const n = SPAWNED.length + (sc.dezaColumns ? sc.dezaColumns.length : 0);
if (n > prev) { volleys++; prev = n; }
}
const iv = API.DEZA_SUB_INTERVAL[st];
eq("sub" + st + " volleys in 60 frames (interval " + iv + ")", volleys, Math.ceil(60 / iv), 1);
}
}
console.log(fails ? `\n${fails}/${checks} checks FAILED` : `\nall ${checks} checks passed`);
process.exit(fails ? 1 : 0);
import { chromium } from 'playwright-core';
const PORT = process.env.PORT || 8137;
const OUT = '/tmp/claude-1000/-home-easierbycode-CODE-shmupX-github-io/e5802725-7876-4150-8e6d-695d4ccecfba/scratchpad/wt';
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM, args: ['--no-sandbox'] });
const page = await browser.newPage({ viewport: { width: 900, height: 700 } });
page.on('pageerror', () => {});
await page.goto(`http://localhost:${PORT}/games/2028-ai`, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => document.querySelector('#phaser-canvas canvas') && window.__PHASER_4_GAME__, null, { timeout: 40000 });
await page.waitForTimeout(2500);
const rect = await page.evaluate(() => {
const c = document.querySelector('#phaser-canvas canvas');
const r = Element.prototype.getBoundingClientRect.call(c);
return { x: r.left, y: r.top, w: r.width, h: r.height };
});
const keys = () => page.evaluate(() => window.__PHASER_4_GAME__.scene.getScenes(true).map(s => s.scene.key));
for (let i = 0; i < 60; i++) {
const k = await keys();
if (k.some(x => /GameScene/.test(x))) break;
if (k.every(x => x === 'BootScene')) await page.mouse.click(rect.x + rect.w / 2, rect.y + rect.h / 2);
else await page.evaluate(() => { for (const s of window.__PHASER_4_GAME__.scene.getScenes(true)) { if (s.playerBullets) return; if (s.titleStart) { s.titleStart(); return; } if (s.goToNextScene) { s.goToNextScene(); return; } } });
await page.waitForTimeout(900);
}
await page.waitForTimeout(1500);
async function shoot(name, sub, charge, holdCharge, ticks) {
await page.evaluate(([sub, charge, holdCharge, ticks]) => {
const scene = window.__PHASER_4_GAME__.scene.getScenes(true).find(s => s.playerBullets);
scene.recipe = scene.recipe || {}; scene.recipe.meta = scene.recipe.meta || {};
scene.recipe.meta.dezaemonSettings = { loadouts: [{ main: 1, sub, charge, bomb: 0 }], startLoadout: [0, 0],
ships: [{ initialPower: 4, maxPower: 4 }, { initialPower: 4, maxPower: 4 }], shotDamage: 5120 };
const p = scene.players[0];
p.dezaLoadoutIndex = 0; p.dezaPower = 4; p.dezaWeapons = null;
for (const b of scene.playerBullets.slice()) b.destroy();
scene.playerBullets.length = 0; scene.dezaColumns = null;
window.__driveSub = { sub, charge, holdCharge, left: ticks };
}, [sub, charge, holdCharge, ticks]);
// Let the game's OWN loop drive it; just supply the charge input.
await page.evaluate(() => {
const scene = window.__PHASER_4_GAME__.scene.getScenes(true).find(s => s.playerBullets);
const p = scene.players[0];
if (!p.keys) p.keys = {};
p.keys.charge = { isDown: window.__driveSub.holdCharge };
});
await page.waitForTimeout(1400);
if (holdCharge) {
await page.evaluate(() => {
const scene = window.__PHASER_4_GAME__.scene.getScenes(true).find(s => s.playerBullets);
scene.players[0].keys.charge.isDown = false;
});
await page.waitForTimeout(700);
}
const n = await page.evaluate(() => {
const s = window.__PHASER_4_GAME__.scene.getScenes(true).find(x => x.playerBullets);
return { bullets: s.playerBullets.length, cols: (s.dezaColumns || []).length };
});
await page.screenshot({ path: `${OUT}/${name}.png`, clip: { x: rect.x, y: rect.y, width: rect.w, height: rect.h } });
console.log(name, JSON.stringify(n));
}
await shoot('sub2-L4', 2, 0, false, 200);
await shoot('sub3-L4', 3, 0, false, 200);
await shoot('sub4-L4', 4, 0, false, 200);
await shoot('sub5-L4', 5, 0, false, 200);
await shoot('sub6-L4', 6, 0, false, 200);
await shoot('charge1-L4', 0, 1, true, 200);
await shoot('charge2-L4', 0, 2, true, 200);
await shoot('charge3-L4', 0, 3, true, 200);
await browser.close();
cat /tmp/claude-1000/-var-home-easierbycode-CODE-shmupX-github-io/f399e0ff-1fc2-4f86-9bf1-a30d46d2da4e/tasks/bxpz7pomt.output | cut -c1-1800; ls -la /var/home/easierbycode/CODE/shmupX.github.io/build/ogmod/*.png | awk '{print $6,$7,$8,$9}'; curl -s -m 5 http://127.0.0.1:9333/json/list | grep '"url"' | head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment