Open Route 29 and Cherrygrove City
Checks / web (push) Canceled after 0s

- Enable Route 29, its Route 46 gate, Cherrygrove City and its buildings.
- Run item balls through FindItemInBallScript and fruit trees through
  FruitTreeScript, with a native daily reset of the daily engine flags.
- Port the Pokémon Center nurse (HealParty with the PP Up clamp,
  CheckPokerus, phone-call checks) and record the whiteout spawn on
  entering a Pokémon Center, as EnterMapWarp does.
- Port standard Poké Marts with keyboard, D-pad and pointer menus.
- Add the recoil battle command (Struggle) and VAR_BOXSPACE.
- Save fruit trees, the daily reset day and the last spawn map; older
  version-3 backups migrate by absence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sébastien QUEROLandClaude Opus 5.5 committed 2026-09-23 17:25:02 +02:00
1 parent 11d1153802
commit 796fe8f6d5
24 files changed
+1549 -59

No files matched your search

+315 -14
View File
@@ -1,7 +1,9 @@
import { RomReader } from "../rom/reader";
import {
EMPTY_ROUTINES,
ENGINE_FLAGS,
NATIVE_ROUTINES,
NUM_FRUIT_TREES,
EVENTS,
RAM,
SPECIAL_ROUTINES,
@@ -50,6 +52,18 @@ export interface ScriptState {
pokedex: { seen: Set<number>; caught: Set<number> };
/** wMoney: a 24-bit amount. */
money: number;
/** wFruitTreeFlags: trees (FRUITTREE_* ids) picked since the last reset. */
fruitTrees: Set<number>;
/** Local calendar day of the last CheckDailyResetTimer reset; null until
* the first check of a new game, which resets immediately. */
dailyReset: number | null;
/** wLastSpawnMapGroup/wLastSpawnMapNumber: the outdoor map last entered
* through a Pokémon Center door (EnterMapWarp's SetSpawn), used by
* GetWhiteoutSpawn. Null before any Center has been entered. */
lastSpawnMap: string | null;
/** wSpecialPhoneCallID's low byte (checkphonecall): nonzero while a call
* is pending. No ported content ever sets it, so it is not saved. */
specialPhoneCall: number;
}
export const emptyScriptState = (): ScriptState => ({
events: new Set(),
@@ -62,6 +76,10 @@ export const emptyScriptState = (): ScriptState => ({
bag: emptyBag(),
pokedex: { seen: new Set(), caught: new Set() },
money: C.START_MONEY,
fruitTrees: new Set(),
dailyReset: null,
lastSpawnMap: null,
specialPhoneCall: 0,
});
export const copyScriptState = (state: ScriptState): ScriptState => ({
events: new Set(state.events),
@@ -77,6 +95,10 @@ export const copyScriptState = (state: ScriptState): ScriptState => ({
caught: new Set(state.pokedex.caught),
},
money: state.money,
fruitTrees: new Set(state.fruitTrees),
dailyReset: state.dailyReset,
lastSpawnMap: state.lastSpawnMap,
specialPhoneCall: state.specialPhoneCall,
});
/** Object operands keep the script's numbering: 0 is the player, 2+ are map
@@ -85,7 +107,15 @@ export const PLAYER = 0;
const LAST_TALKED = 0xfe;
/** The phone holds at most ten contacts (CONTACT_LIST_SIZE). */
const CONTACT_LIST_SIZE = 10;
const MONS_PER_BOX = 20;
/** One row of a mart's buy or sell list. `owned` is set only when selling. */
export interface MartEntry {
item: number;
name: string;
price: number;
owned?: number;
}
export type ScriptEffect =
/** Pages the player acknowledges. With holdTicks the last page instead
* stays for a fixed time, as `writetext` followed by `pause` does. */
@@ -106,6 +136,23 @@ export type ScriptEffect =
| { kind: "picture"; species: number }
/** The naming screen; answered with the name, or "" to keep `current`. */
| { kind: "name"; pages: string[]; current: string; max: number }
/** pokemart's BUY/SELL/QUIT box; answered 0/1/2. */
| { kind: "martmenu"; prompt: string; selected: number }
/** The mart's item list (buy: full stock; sell: the bag's pockets);
* answered with the chosen entry's index, or a negative number to cancel. */
| { kind: "martlist"; mode: "buy" | "sell"; entries: MartEntry[]; selected: number }
/** The 1-99 quantity stepper; answered with the chosen amount, or a
* number below 1 to cancel back to the item list. */
| {
kind: "martquantity";
mode: "buy" | "sell";
item: number;
name: string;
price: number;
max: number;
prompt: string;
selected: number;
}
/** startbattle: answered with wBattleResult. */
| { kind: "battle"; wild: { species: number; level: number } }
/** newloadmap: the world enters this map after the script ends. */
@@ -162,8 +209,14 @@ export class ScriptRun {
deferred?: number;
done = false;
private strings: Record<number, string> = {};
/** Native values for text_decimal, keyed by RAM address (wItemQuantityChange,
* hMoneyTemp): the mart's quantity and price texts. */
private numbers: Record<number, number> = {};
/** wCurItem: the item named by itemnotify and pocketisfull. */
private currentItem = 0;
/** wCurFruitTree and wCurFruit, set by fruittree and GetCurTreeFruit. */
private fruitTree = 0;
private fruit = 0;
private iterator: Generator<ScriptEffect, void, Input>;
private instructions = 0;
@@ -176,6 +229,9 @@ export class ScriptRun {
callback?: boolean;
/** The wild Pokémon chosen by the encounter check (wTempWildMonSpecies). */
wild?: { species: number; level: number };
/** wItemBallItemID/wItemBallQuantity, copied from the itemball data the
* facing object's script pointer names. */
itemBall?: { item: number; quantity: number };
} = {},
) {
this.state = copyScriptState(state);
@@ -199,6 +255,7 @@ export class ScriptRun {
return {
...this.host.text(),
strings: { ...this.host.text().strings, ...this.strings },
numbers: { ...this.host.text().numbers, ...this.numbers },
};
}
@@ -252,6 +309,14 @@ export class ScriptRun {
return effect;
};
const sceneOwner = (mapId: string) => this.host.sceneOwner(mapId);
// GetWhiteoutSpawn/IsSpawnPoint: the table index of the last recorded
// spawn map, or SPAWN_HOME when unset or no longer a listed spawn point.
const findSpawn = (mapId: string | null) => {
if (mapId)
for (let entry = SYMBOLS.spawnPoints, index = 0; r.byte(entry) !== 0xff; entry += 4, index++)
if (`${r.byte(entry)}:${r.byte(entry + 1)}` === mapId) return index;
return 0;
};
for (;;) {
if (++this.instructions > 4096)
@@ -312,9 +377,10 @@ export class ScriptRun {
const index = word();
const entry = SYMBOLS.specials + index * 3;
const routine = r.address(r.byte(entry), r.word(entry + 1));
const special = yield* this.special(routine, pages, take);
if (special === undefined)
const result = yield* this.special(routine, value, pages, take);
if (result === undefined)
throw new UnsupportedScript(offset, opcode, ` (special ${index})`);
value = result;
break;
}
case 0x11:
@@ -352,13 +418,51 @@ export class ScriptRun {
const routine = far();
if (routine === NATIVE_ROUTINES.halveMoney)
this.state.money = this.state.money >> 1;
else if (routine === NATIVE_ROUTINES.getCurTreeFruit)
this.fruit = r.byte(SYMBOLS.fruitTreeItems + this.fruitTree - 1);
else if (routine === NATIVE_ROUTINES.tryResetFruitTrees) {
// Trees regrow once per daily reset of ENGINE_ALL_FRUIT_TREES.
if (!this.state.flags.has(ENGINE_FLAGS.allFruitTrees)) {
this.state.fruitTrees.clear();
this.state.flags.add(ENGINE_FLAGS.allFruitTrees);
}
} else if (routine === NATIVE_ROUTINES.checkFruitTree)
value = Number(this.state.fruitTrees.has(this.fruitTree));
else if (routine === NATIVE_ROUTINES.pickedFruitTree)
this.state.fruitTrees.add(this.fruitTree);
else if (routine === NATIVE_ROUTINES.getWhiteoutSpawn)
// No Pokémon Center is ported, so the spawn is still SPAWN_HOME.
spawn = 0;
else if (!Object.values(EMPTY_ROUTINES).includes(routine as never))
spawn = findSpawn(this.state.lastSpawnMap);
else if (routine === NATIVE_ROUTINES.tryReceiveItem) {
// FindItemInBallScript.TryReceiveItem: give the ball's item and
// name it for FoundItemText (wStringBuffer3), matching GetItemName
// + CopyName2. wScriptVar (value) reports success for iffalse.
const ball = this.options.itemBall;
if (!ball) throw new UnsupportedScript(offset, opcode, " (no item ball)");
const name = data.itemName(ball.item);
this.strings[RAM.stringBuffer1] = name;
this.strings[RAM.stringBuffer3] = name;
this.currentItem = ball.item;
value = Number(
receiveItem(data, this.state.bag, ball.item, ball.quantity),
);
} else if (!Object.values(EMPTY_ROUTINES).includes(routine as never))
throw new UnsupportedScript(offset, opcode);
break;
}
case 0x19: {
// readmem: only the fruit a tree bears is readable so far.
if (word() !== RAM.curFruit) throw new UnsupportedScript(offset, opcode);
value = this.fruit;
break;
}
case 0x9b: {
// Script_fruittree jumps to FruitTreeScript for FRUITTREE_* id.
const tree = byte();
if (tree < 1 || tree > NUM_FRUIT_TREES) throw new Error("Invalid fruit tree.");
this.fruitTree = tree;
p = SYMBOLS.fruitTreeScript;
break;
}
case 0x5b:
break; // randomwildmon clears wBattleScriptFlags.
case 0x5f: {
@@ -386,6 +490,12 @@ export class ScriptRun {
case 0x1c:
value = this.readVar(byte(), offset);
break;
case 0x9c:
this.state.specialPhoneCall = word();
break;
case 0x9d:
value = Number(this.state.specialPhoneCall !== 0);
break;
case 0x1f:
case 0x9e: {
const item = byte(),
@@ -723,6 +833,15 @@ export class ScriptRun {
case 0x93:
yield* flush();
return;
case 0x94: {
const type = byte(),
martId = word();
if (type !== 0 /* MARTTYPE_STANDARD */)
throw new UnsupportedScript(offset, opcode, " (mart type)");
yield* flush();
yield* this.pokemart(martId, pages);
break;
}
default:
throw new UnsupportedScript(offset, opcode);
}
@@ -730,6 +849,164 @@ export class ScriptRun {
}
}
/** OpenMartDialog/MartDialog/StandardMart (engine/items/mart.asm), for
* MARTTYPE_STANDARD only. Welcome, then BUY/SELL/QUIT until the player
* quits; buying and selling loop over their own item lists until the
* player backs out, then the menu asks "anything else?" and repeats. */
private *pokemart(
martId: number,
pages: string[],
): Generator<ScriptEffect, void, Input> {
const r = this.reader;
const write = (address: number) => {
const content = readText(r, address, this.text());
if (content) pages.push(...content.split("\n\n"));
};
const take = () => pages.splice(0, pages.length);
const entry = r.near(SYMBOLS.marts + martId * 2, r.bank(SYMBOLS.marts));
let p = entry;
const count = r.byte(p++);
const stock = Array.from({ length: count }, () => r.byte(p++));
let first = true;
for (;;) {
const choice = yield {
kind: "martmenu",
prompt: readText(
r,
first ? SYMBOLS.martWelcomeText : SYMBOLS.martAskMoreText,
this.text(),
),
selected: 0,
};
first = false;
const option = typeof choice === "number" ? choice : 2;
if (option === 0) yield* this.martBuy(stock, pages);
else if (option === 1) yield* this.martSell(pages);
else {
write(SYMBOLS.martComeAgainText);
if (pages.length) yield { kind: "text", pages: take() };
return;
}
}
}
/** BuyMenu/BuyMenuLoop: pick a stocked item, a 1-99 quantity, confirm the
* price, then check funds and bag room before handing it over. */
private *martBuy(
stock: number[],
pages: string[],
): Generator<ScriptEffect, void, Input> {
const r = this.reader,
data = this.host.data;
const write = (address: number) => {
const content = readText(r, address, this.text());
if (content) pages.push(...content.split("\n\n"));
};
const take = () => pages.splice(0, pages.length);
const flush = function* (): Generator<ScriptEffect, void, Input> {
if (pages.length) yield { kind: "text", pages: take() };
};
for (;;) {
const entries: MartEntry[] = stock.map((item) => ({
item,
name: data.itemName(item),
price: data.itemPrice(item),
}));
const selection = yield { kind: "martlist", mode: "buy", entries, selected: 0 };
const item = typeof selection === "number" ? stock[selection] : undefined;
if (item === undefined) return;
const price = data.itemPrice(item);
const chosen = yield {
kind: "martquantity",
mode: "buy",
item,
name: data.itemName(item),
price,
max: 99,
prompt: readText(r, SYMBOLS.martHowManyText, this.text()),
selected: 1,
};
if (typeof chosen !== "number" || chosen < 1) continue;
const total = price * chosen;
this.strings[RAM.stringBuffer2] = data.itemName(item);
this.numbers[RAM.itemQuantityChange] = chosen;
this.numbers[RAM.moneyTemp] = total;
write(SYMBOLS.martFinalPriceText);
const confirmed = yield { kind: "yesno", pages: take() };
if (!confirmed) continue;
if (total > this.state.money) {
write(SYMBOLS.martNoMoneyText);
yield* flush();
continue;
}
if (!receiveItem(data, this.state.bag, item, chosen)) {
write(SYMBOLS.martPackFullText);
yield* flush();
continue;
}
this.state.money -= total;
write(SYMBOLS.martThanksText);
yield* flush();
}
}
/** SellMenu/DepositSellPack: pick a bag item and a quantity up to its
* stack, refuse unsellable items, then pay half price and toss it. */
private *martSell(pages: string[]): Generator<ScriptEffect, void, Input> {
const r = this.reader,
data = this.host.data;
const write = (address: number) => {
const content = readText(r, address, this.text());
if (content) pages.push(...content.split("\n\n"));
};
const take = () => pages.splice(0, pages.length);
const flush = function* (): Generator<ScriptEffect, void, Input> {
if (pages.length) yield { kind: "text", pages: take() };
};
for (;;) {
const slots = [...this.state.bag.items, ...this.state.bag.balls];
if (!slots.length) return;
const entries: MartEntry[] = slots.map((slot) => ({
item: slot.item,
name: data.itemName(slot.item),
price: data.itemPrice(slot.item),
owned: slot.quantity,
}));
const selection = yield { kind: "martlist", mode: "sell", entries, selected: 0 };
const slot = typeof selection === "number" ? slots[selection] : undefined;
if (!slot) return;
if (data.itemUnsellable(slot.item)) {
write(SYMBOLS.martCantBuyText);
yield* flush();
continue;
}
const price = data.itemPrice(slot.item);
const chosen = yield {
kind: "martquantity",
mode: "sell",
item: slot.item,
name: data.itemName(slot.item),
price,
max: slot.quantity,
prompt: readText(r, SYMBOLS.martSellHowManyText, this.text()),
selected: 1,
};
if (typeof chosen !== "number" || chosen < 1) continue;
const total = Math.floor((price * chosen) / 2);
this.strings[RAM.stringBuffer2] = data.itemName(slot.item);
this.numbers[RAM.moneyTemp] = total;
write(SYMBOLS.martSellPriceText);
const confirmed = yield { kind: "yesno", pages: take() };
if (!confirmed) continue;
tossItem(this.state.bag, slot.item, chosen);
this.state.money = Math.min(C.MAX_MONEY, this.state.money + total);
write(SYMBOLS.martBoughtText);
yield* flush();
}
}
/** readvar: the script variables that native state can answer. */
private readVar(id: number, offset: number): number {
const clock = this.host.clock();
@@ -753,6 +1030,10 @@ export class ScriptRun {
return group;
case 0x0d:
return number;
case 0x10:
// .BoxFreeSpace: MONS_PER_BOX minus sBoxCount. Nothing can be
// deposited yet (no capture or PC), so the current box is empty.
return MONS_PER_BOX;
case 0x12:
return this.host.position().x;
case 0x13:
@@ -763,18 +1044,29 @@ export class ScriptRun {
}
/** Native translations of special routines, selected by routine address.
* Returns undefined for routines that have not been translated. */
* `value` is the script's current wScriptVar, in case a routine (like
* CheckPokerus) returns a new one; routines that leave it alone return it
* unchanged. Returns undefined for routines that have not been translated. */
private *special(
routine: number,
value: number,
pages: string[],
take: () => string[],
): Generator<ScriptEffect, true | undefined, Input> {
): Generator<ScriptEffect, number | undefined, Input> {
const r = this.reader;
switch (routine) {
case SPECIAL_ROUTINES.restartMapMusic:
case SPECIAL_ROUTINES.fadeOutToWhite:
case SPECIAL_ROUTINES.warpToSpawnPoint:
return true; // Music, fades and Safari/contest flags not in use.
case SPECIAL_ROUTINES.stubbedTrainerRankingsHealings:
// Music and fades are not modeled; Safari/contest flags are unused.
// StubbedTrainerRankings_Healings begins with `ret`: the Trainer
// Rankings feature (Pokémon News) was cut, leaving a dead stub.
return value;
case SPECIAL_ROUTINES.healMachineAnim:
// Graphics, palettes and sound only: wPartyCount/wScriptVar select
// an animation sequence but nothing persists past it.
return value;
case SPECIAL_ROUTINES.healParty:
// HealPartyMon: clear status, restore HP and every move's PP.
for (const mon of this.state.party) {
@@ -784,10 +1076,19 @@ export class ScriptRun {
if (!move) return 0;
const ups = mon.pp[slot] >> 6,
base = this.host.data.move(move).pp;
return (ups << 6) | (base + Math.floor(base / 5) * ups);
// ComputeMaxPP clamps each PP Up's bonus to 7, so a 40 PP move
// maxes at 61 instead of overflowing the packed byte at 64.
return (ups << 6) | (base + Math.min(Math.floor(base / 5), 7) * ups);
}) as PartyMon["pp"];
}
return true;
return value;
case SPECIAL_ROUTINES.checkPokerus:
// _CheckPokerus: carry (here, a truthy return) if any party member's
// status nybble is infected. No ported content ever sets pokerus,
// so this is always 0 until Pokérus itself is modeled.
return Number(
this.state.party.some((mon) => (mon.pokerus & 0x0f) !== 0),
);
case SPECIAL_ROUTINES.setDayOfWeek: {
const names = Array.from({ length: 7 }, (_, day) =>
readString(
@@ -821,7 +1122,7 @@ export class ScriptRun {
if (!confirmed) continue;
this.state.clock.weekdayOffset =
(day - this.host.deviceWeekday() + 7) % 7;
return true;
return value;
}
}
case SPECIAL_ROUTINES.initialSetDst:
@@ -839,7 +1140,7 @@ export class ScriptRun {
// The box is cleared first; the following yesorno shows this page.
take();
pages.push(`${time}${text.startsWith(",") ? "" : " "}${text}`);
return true;
return value;
}
case SPECIAL_ROUTINES.toggleDecorationsVisibility:
// No decorations are placed until the native decoration system exists,
@@ -851,12 +1152,12 @@ export class ScriptRun {
EVENTS.playersHouseBigDoll,
])
this.state.events.add(event);
return true;
return value;
case SPECIAL_ROUTINES.toggleMaptileDecorations:
// Empty decoration slots leave the room blocks unchanged and clear
// the poster's conditional event.
this.state.events.delete(EVENTS.playersRoomPoster);
return true;
return value;
default:
return undefined;
}