Finish the opening milestone's switching, items and acceptance run

- Decode evolution lists from the ROM; all 251 match the pinned PRET source.
- Compare CalcMonStats and CalcExpAtLevel against the original routines in
  the reference emulator.
- Add a continuous opening playthrough from the intro to the catching
  tutorial, reloading a JSON save after every stage.
- Port player switching in battle: the PKMN menu, forced choices after a
  faint, Shift mode's offer and double faints, with the original texts.
- Port HP and status healing items in battle through the ROM's ItemEffects,
  HealingHPAmounts and StatusHealingActions tables.
- Add the battle party menu and the Items pocket to the UI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sébastien QUEROLandClaude Opus 5.5 committed 2026-09-30 11:04:11 +02:00
1 parent eb03a20d8f
commit f8e0f9c65a
20 files changed
+1902 -96

No files matched your search

+143 -27
View File
@@ -1,23 +1,41 @@
import { test, expect } from "@playwright/test";
import { test, expect, type Page } from "@playwright/test";
import { existsSync, readFileSync } from "node:fs";
import { CrystalAssets } from "../src/game/rom/assets";
import { BattleData } from "../src/game/battle/data";
import { applyTypeMatchups, calculateDamage } from "../src/game/battle/battle";
import { C } from "../src/game/battle/constants";
import { NATIVE_MAPS } from "../src/game/rom/profile";
import { calcStat } from "../src/game/party/pokemon";
import { resolve } from "node:path";
const romPath = resolve(
process.env.CRYSTAL_ROM_PATH ??
"Pokemon - Crystal Version (UE) (V1.1) [C][!].gbc",
);
const symbolsPath = ".reference/pokecrystal/pokecrystal11.sym";
test("native decompression matches original GB assembly executing in the reference emulator", async ({
page,
}) => {
test.skip(!existsSync(romPath), "Requires the local user ROM.");
/** Banked addresses from the private PRET rebuild's symbol file. */
function loadSymbols() {
const symbols = new Map(
readFileSync(symbolsPath, "utf8")
.split("\n")
.flatMap((line) => {
const match = /^([0-9a-f]{2}):([0-9a-f]{4}) (\S+)$/.exec(line);
return match
? [[match[3], { bank: parseInt(match[1], 16), address: parseInt(match[2], 16) }] as const]
: [];
}),
);
return {
at: (name: string) => symbols.get(name)!.address,
routine: (name: string) => symbols.get(name)!,
};
}
/** Open the reference page and hand it the ROM through an isolated file
* input, without an HTTP ROM endpoint. */
async function openReference(page: Page) {
await page.goto("/reference.html");
// File chooser supplies bytes to an isolated test input, without an HTTP ROM endpoint.
await page.evaluate(() => {
const input = document.createElement("input");
input.type = "file";
@@ -25,6 +43,13 @@ test("native decompression matches original GB assembly executing in the referen
document.body.append(input);
});
await page.locator("#reference-fixture").setInputFiles(romPath);
}
test("native decompression matches original GB assembly executing in the reference emulator", async ({
page,
}) => {
test.skip(!existsSync(romPath), "Requires the local user ROM.");
await openReference(page);
const result = await page.evaluate(async () => {
const { BinjgbEmulator } = await import("/src/emulator/binjgb.ts");
const { CrystalAssets } = await import("/src/game/rom/assets.ts");
@@ -113,23 +138,11 @@ test("native decompression matches original GB assembly executing in the referen
test("native damage and type effectiveness match the original battle routines", async ({
page,
}) => {
const symbolsPath = ".reference/pokecrystal/pokecrystal11.sym";
test.skip(
!existsSync(romPath) || !existsSync(symbolsPath),
"Requires the local user ROM and the private PRET rebuild.",
);
const symbols = new Map(
readFileSync(symbolsPath, "utf8")
.split("\n")
.flatMap((line) => {
const match = /^([0-9a-f]{2}):([0-9a-f]{4}) (\S+)$/.exec(line);
return match
? [[match[3], { bank: parseInt(match[1], 16), address: parseInt(match[2], 16) }] as const]
: [];
}),
);
const at = (name: string) => symbols.get(name)!.address;
const routine = (name: string) => symbols.get(name)!;
const { at, routine } = loadSymbols();
const bytes = new Uint8Array(readFileSync(romPath));
const assets = new CrystalAssets(bytes);
const data = new BattleData(assets.reader);
@@ -164,14 +177,7 @@ test("native damage and type effectiveness match the original battle routines",
identified: next(4) === 0,
damage: next(1000),
}));
await page.goto("/reference.html");
await page.evaluate(() => {
const input = document.createElement("input");
input.type = "file";
input.id = "reference-fixture";
document.body.append(input);
});
await page.locator("#reference-fixture").setInputFiles(romPath);
await openReference(page);
const addresses = {
curDamage: at("wCurDamage"),
critical: at("wCriticalHit"),
@@ -294,3 +300,113 @@ test("native damage and type effectiveness match the original battle routines",
).toEqual([original.damage, original.modifier, original.missed]);
});
});
test("native stats and experience curves match the original routines", async ({ page }) => {
test.skip(
!existsSync(romPath) || !existsSync(symbolsPath),
"Requires the local user ROM and the private PRET rebuild.",
);
const { at, routine } = loadSymbols();
const pokemon = new CrystalAssets(new Uint8Array(readFileSync(romPath))).pokemon;
let seed = 0x5eed;
const next = (limit: number) => {
seed = (seed * 1103515245 + 12345) >>> 0;
return (seed >>> 8) % limit;
};
// Legal stats stay below 999; levels above 100 reach the MAX_STAT_VALUE cap.
const statCases = Array.from({ length: 300 }, () => ({
base: Array.from({ length: 6 }, () => (next(4) === 0 ? 200 + next(56) : 1 + next(255))),
level: next(6) === 0 ? 101 + next(155) : next(5) === 0 ? 100 : 1 + next(100),
dvs: next(0x10000),
statExp: Array.from({ length: 5 }, () => (next(3) === 0 ? 0xffff - next(256) : next(0x10000))),
useStatExp: next(4) !== 0,
}));
await openReference(page);
const addresses = {
baseStats: at("wBaseStats"),
level: at("wCurPartyLevel"),
growthRate: at("wBaseGrowthRate"),
product: at("hProduct"),
calcMonStats: routine("CalcMonStats"),
calcExpAtLevel: routine("CalcExpAtLevel"),
};
const results = await page.evaluate(
async ({ addresses, statCases }) => {
const { BinjgbEmulator } = await import("/src/emulator/binjgb.ts");
const file = (document.querySelector("#reference-fixture") as HTMLInputElement).files![0];
const reference = new BinjgbEmulator();
await reference.load(new Uint8Array(await file.arrayBuffer()), document.createElement("canvas"));
const write = (address: number, value: number) => reference.writeMemory(address, value & 0xff);
const read = (address: number, length: number) =>
Array.from({ length }, (_, i) => reference.readMemory(address + i));
// Trampoline: DI; SP=$c7fe; switch to the routine's bank; set BC, DE
// and HL; CALL the original routine; write a sentinel; loop.
const call = (
target: { bank: number; address: number },
bc: number,
de: number,
hl: number,
frames = 2,
) => {
const program = [
0xf3, 0x31, 0xfe, 0xc7, 0x3e, target.bank, 0xe0, 0x9d, 0xea, 0x00, 0x20,
0x01, bc & 0xff, bc >> 8, 0x11, de & 0xff, de >> 8, 0x21, hl & 0xff, hl >> 8,
0xcd, target.address & 0xff, target.address >> 8,
0x3e, 0x42, 0xea, 0xff, 0xc6, 0x18, 0xfe,
];
write(0xc6ff, 0);
program.forEach((value, index) => write(0xc000 + index, value));
reference.setProgramCounter(0xc000);
reference.advanceFrames(frames);
return reference.readMemory(0xc6ff) === 0x42;
};
write(0xff70, 1); // WRAM bank 1 holds the base data and party level
// A party struct at $c100 (stat experience at +11, DVs at +21) and
// the six computed stats at $c140.
const mon = 0xc100,
out = 0xc140;
const stats = statCases.map((input) => {
input.base.forEach((value, i) => write(addresses.baseStats + i, value));
write(addresses.level, input.level);
input.statExp.forEach((value, i) => {
write(mon + 11 + i * 2, value >> 8);
write(mon + 12 + i * 2, value);
});
write(mon + 21, input.dvs >> 8);
write(mon + 22, input.dvs);
// B = stat experience flag; HL = MON_STAT_EXP - 1; DE = output.
// GetSquareRoot counts up to 255 per stat, so allow more frames.
const returned = call(addresses.calcMonStats, Number(input.useStatExp) << 8, out, mon + 10, 8);
const bytes = read(out, 12);
return { returned, stats: Array.from({ length: 6 }, (_, i) => (bytes[i * 2] << 8) | bytes[i * 2 + 1]) };
});
const experience: { returned: boolean; exp: number }[] = [];
for (let growth = 0; growth < 6; growth++)
for (let level = 1; level <= 100; level++) {
write(addresses.growthRate, growth);
// D = level
const returned = call(addresses.calcExpAtLevel, 0, level << 8, 0);
const [high, middle, low] = read(addresses.product + 1, 3);
experience.push({ returned, exp: (high << 16) | (middle << 8) | low });
}
reference.dispose();
return { stats, experience };
},
{ addresses, statCases },
);
statCases.forEach((input, index) => {
const original = results.stats[index];
expect(original.returned, `stat case ${index} returned`).toBe(true);
const native = input.base.map((base, stat) =>
calcStat(base, input.dvs, stat, input.level, input.useStatExp ? input.statExp : undefined),
);
expect(native, `stat case ${index}: ${JSON.stringify(input)}`).toEqual(original.stats);
});
expect(results.stats.some(({ stats }) => stats.includes(999))).toBe(true);
results.experience.forEach((original, index) => {
const growth = Math.floor(index / 100),
level = (index % 100) + 1;
expect(original.returned, `experience ${growth}/${level} returned`).toBe(true);
expect(pokemon.expAtLevel(growth, level), `experience ${growth}/${level}`).toBe(original.exp);
});
});