Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions configs/game_benchmarks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ schema = "game_first_exam/benchmarks/babaisai/instance_schema.py"

[benchmarks.minihack]
schema = "game_first_exam/benchmarks/minihack/instance_schema.py"

[benchmarks.vgc]
schema = "game_first_exam/benchmarks/vgc/instance_schema.py"
25 changes: 25 additions & 0 deletions configs/game_suites/vgc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
schema_version = "game-suite/2.1"
version = "0.1.0"
tier = "smoke"
name = "games-vgc-native-smoke-v0.1.0"
files_images = ["connection-files", "game-files", "vgc-files"]

[[tasks]]
name = "vgc-vs-random-i01-standard"
benchmark = "vgc"
family = "vs-random"

[[tasks]]
name = "vgc-vs-maxbasepower-i01-standard"
benchmark = "vgc"
family = "vs-max-base-power"

[[tasks]]
name = "vgc-vs-simpleheuristics-i01-standard"
benchmark = "vgc"
family = "vs-simple-heuristics"

[[tasks]]
name = "vgc-vs-bc-i01-standard"
benchmark = "vgc"
family = "vs-bc"
26 changes: 26 additions & 0 deletions game_first_exam/benchmarks/vgc/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"benchmark": "vgc-bench",
"repository": "https://github.com/cameronangliss/vgc-bench",
"paper": "https://arxiv.org/abs/2506.10326",
"environment": {
"library": "poke-env",
"repository": "https://github.com/cameronangliss/poke-env",
"branch": "vgc-bench",
"commit": "379a04628e42b2a2c94790c0788204b652f7ae1b",
"version": "0.15.0",
"modifications": "none"
},
"simulator": {
"library": "pokemon-showdown",
"repository": "https://github.com/cameronangliss/pokemon-showdown",
"branch": "vgc-bench",
"commit": "913da3602a3aa1db79f9fdc5d5222eaf8d39569d",
"modifications": "none"
},
"team_source": {
"repository": "https://github.com/cameronangliss/vgc-bench",
"path": "teams/reg_ma",
"license_note": "Team text files are redistributed research data; verify upstream license before publication."
},
"note": "Only the native battle environment (poke-env + Pokemon Showdown) is reused. VGC-Bench RL/BC training, LLM agent and evaluation tools are not migrated."
}
304 changes: 304 additions & 0 deletions game_first_exam/benchmarks/vgc/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
"""Thin VGC adapter: one frozen battle against a fixed native opponent.

The native battle engine (poke-env fork + Pokemon Showdown) is kept unmodified. The
opponent is fixed at construction so the two-player game becomes a single-agent
episode: the agent submits one native action index at a time (one per active slot,
two per turn) and the adapter applies the opponent's reply in the same native turn.

The agent sees only the serialized observation returned by `observe()`; the native
battle object and the Showdown websocket stay inside the trusted sim.
"""
import importlib.metadata
import os
import re
import sys
import textwrap

import numpy as np
from PIL import Image, ImageDraw

from contracts import Capabilities, Transition
from encoding import state_hash

# One action per decision point: a single native action index (0-based) for the
# slot named in the observation (`slot`: 0 or 1). A full turn is two submissions.
ACTION_PATTERN = r"^\d{1,3}$"


_BENCH_DIR = os.path.dirname(os.path.abspath(__file__))


def _make_opponent(policy, *, battle_format, team, server_configuration):
from poke_env.player import MaxBasePowerPlayer, RandomPlayer, SimpleHeuristicsPlayer

common = dict(
battle_format=battle_format,
team=team,
server_configuration=server_configuration,
)
if policy == "random":
return RandomPlayer(**common)
if policy == "max_base_power":
return MaxBasePowerPlayer(**common)
if policy == "simple_heuristics":
return SimpleHeuristicsPlayer(**common)
if policy == "bc":
# Vendored vgc-bench policy code + checkpoint (see vgc_bench/ and models/).
sys.path.insert(0, _BENCH_DIR)
import torch
from stable_baselines3 import PPO

from vgc_bench.src.policy_player import PolicyPlayer

opponent = PolicyPlayer(
**common,
accept_open_team_sheet=True,
open_timeout=None,
deterministic=True,
)
checkpoint = os.path.join(_BENCH_DIR, "models", "bc_100.zip")
opponent.policy = PPO.load(checkpoint, device=torch.device("cpu")).policy
return opponent
raise ValueError(f"unknown opponent_policy: {policy}")


class Adapter:
def __init__(self, instance, assets=None):
self.instance = instance
for name, version in instance["engine_versions"].items():
if importlib.metadata.version(name) != version:
raise ValueError(f"engine version mismatch: {name}")

from gymnasium.spaces import Box
from poke_env.environment import DoublesEnv, SingleAgentWrapper
from poke_env.ps_client import ServerConfiguration

# Showdown runs in the same container on loopback; the agent cannot reach it.
server = ServerConfiguration(
"ws://127.0.0.1:7200/showdown/websocket",
"https://play.pokemonshowdown.com/action.php?",
)
env = DoublesEnv(
server_configuration=server,
battle_format=instance["battle_format"],
accept_open_team_sheet=True,
team=instance["team1"],
choose_on_teampreview=False, # random auto team-preview; the agent only decides battle turns
strict=False, # an incompatible joint order falls back to a random legal order instead of faulting the episode
open_timeout=None, # the Showdown server warms up asynchronously; do not time out the websocket open
challenge_timeout=180.0, # generous battle-setup window for the first connection
save_replays="/data/replays", # poke-env writes a self-contained HTML replay when the battle ends
)
opponent = _make_opponent(
instance["opponent_policy"],
battle_format=instance["battle_format"],
team=instance["team2"],
server_configuration=server,
)
# poke-env's SingleAgentWrapper reads the PettingZoo-style dict that
# vgc-bench's ShowdownEnv adds on top of DoublesEnv; supply a real Box
# space for each agent (the adapter serves its own JSON observation).
env.observation_spaces = {
agent: Box(0, 1, shape=(1,), dtype=np.float32)
for agent in env.possible_agents
}
self.env = SingleAgentWrapper(env, opponent)
self.obs, self.info = self.env.reset(seed=instance["seed"])
self.battle = self.env.env.battle1
self._DoublesEnv = DoublesEnv
self._slot = 0 # which active slot is being decided (0 or 1)
self._pending = [] # actions already chosen for this turn
self.return_ = 0.0
self.steps = 0
self.ended = False
# Deterministic frozen identity: the two team texts (which fully specify
# species, items, abilities, moves, EVs, natures and tera types) plus the
# frozen opponent policy and seed. The engine-parsed battle state is excluded:
# HP, status, item-reveal and team-preview selection are async and not
# reproducible from Python.
self._fingerprint = state_hash({
"team1": self.instance["team1"],
"team2": self.instance["team2"],
"opponent_policy": self.instance["opponent_policy"],
"seed": self.instance["seed"],
})
self._wait_for_battle()

def _wait_for_battle(self, timeout: float = 60.0):
# The random team preview (choose_on_teampreview=False) resolves on the
# poke-env loop asynchronously; block until the battle is past it so the
# first observation shows active Pokemon and legal actions.
import time
deadline = time.time() + timeout
while time.time() < deadline and self.battle.teampreview:
time.sleep(0.2)

def spec(self):
return {
"adapter_version": "1.0.0",
"capabilities": Capabilities(images=False, action_mode="text", native_truncation=False).to_dict(),
"action_schema": {"type": "string", "max_length": 4, "pattern": ACTION_PATTERN},
"observation": "native VGC battle state serialized as JSON; see instruction.md",
"opponent": self.instance["opponent_policy"],
"format": self.instance["battle_format"],
}

# ------------------------------------------------------------- native action surface

def _legal_actions(self):
mask = self._DoublesEnv.get_action_mask_individual(self.battle, self._slot)
return [i for i, v in enumerate(mask) if v]

def _describe_action(self, index):
try:
order = self._DoublesEnv._action_to_order_individual(
np.int64(index), self.battle, False, self._slot
)
return str(order)
except ValueError:
return f"action {index}"

def observe(self):
return {"step": self.steps, "done": self.ended, "observation": self._state()}

def step(self, action):
if self.ended:
raise ValueError("episode closed")
if not re.fullmatch(ACTION_PATTERN, action):
raise ValueError("action must be a single action index")
index = int(action)
legal = self._legal_actions()
if index not in legal:
raise ValueError(f"illegal action index {index} for slot {self._slot}")
self._pending.append(index)
if len(self._pending) < 2:
# first slot decided; ask for the second slot without advancing the game
self._slot = 1
return Transition(0.0, False, False)
joint = np.array(self._pending, dtype=np.int64)
self._pending = []
self._slot = 0
self.obs, reward, terminated, truncated, self.info = self.env.step(joint)
self.steps += 1
reward = float(reward) if reward is not None else 0.0
self.return_ += reward
self.ended = bool(terminated or truncated)
return Transition(reward, bool(terminated), bool(truncated))

def success(self):
return bool(self.battle.won)

def metrics(self):
# Called from finalize(), before Harbor collects artifacts, so the replay
# log is captured even though close() runs after the SIGTERM collection.
self._write_replay_log()
win = int(self.success())
return {
"win": win,
"completion_score": 100 * win,
"native_return": self.return_,
"native_steps": self.steps,
}

def fingerprint(self):
# Captured at construction, before the auto team preview: both teams'
# species, moves, items, abilities, types and tera types, plus
# turn/weather/fields. The Showdown engine PRNG and the opponent's random
# team-preview selection are excluded (not seedable from Python).
return self._fingerprint

def frame(self):
"""Audit-video transcript of the battle state; not an added observation."""
state = self._state()

def pkmn(p):
if p is None:
return "?"
hp = f"{p['hp_fraction'] * 100:.0f}%" if p.get("hp_fraction") is not None else "?%"
status = f" [{p['status']}]" if p.get("status") else ""
item = p.get("item") or "no item"
moves = "/".join(p.get("moves") or []) or "no moves"
return f"{p['species']} {hp}{status} | {item} | {moves}"

lines = [f"VGC | {self.instance['battle_format']} | turn {state['turn']} | step {self.steps}"]
if state.get("won") is True:
lines.append("RESULT: WON")
elif state.get("lost") is True:
lines.append("RESULT: LOST")
if state.get("weather"):
lines.append("Weather: " + ", ".join(state["weather"]))
if state.get("fields"):
lines.append("Fields: " + ", ".join(state["fields"]))
lines += ["", "== YOUR ACTIVE =="] + [pkmn(p) for p in state["active"]]
lines += ["", "== OPPONENT ACTIVE =="] + [pkmn(p) for p in state["opponent_active"]]
lines += ["", "== YOUR TEAM =="] + [pkmn(p) for p in state["team"]]
lines += ["", "== OPPONENT TEAM =="] + [pkmn(p) for p in state["opponent_team"]]

text = re.sub(r"[^\x20-\x7e\n]", "?", "\n".join(lines))
canvas = Image.new("RGB", (960, 640), (245, 246, 248))
draw = ImageDraw.Draw(canvas)
wrapped = []
for line in text.splitlines():
wrapped.extend(textwrap.wrap(line, width=130) or [""])
draw.multiline_text((20, 18), "\n".join(wrapped[:46]), fill=(20, 25, 35), spacing=3)
return np.asarray(canvas)

def close(self):
self._write_replay_log()
self.env.close()

def _write_replay_log(self):
# Best-effort evidence: the raw Showdown protocol log, which the official
# replay viewer renders as an interactive HTML battle page.
try:
from pathlib import Path
Path("/data").mkdir(parents=True, exist_ok=True)
Path("/data/replay.log").write_text(self.battle._build_replay_log() + "\n")
except Exception:
pass

# ------------------------------------------------------------------ serialization

def _pokemon(self, p):
if p is None:
return None
return {
"species": p.base_species,
"hp_fraction": round(float(p.current_hp_fraction), 4),
"status": p.status.name if p.status is not None else None,
"ability": p.ability,
"item": p.item,
"moves": sorted(m.id for m in p.moves.values()),
"types": sorted(t.name for t in p.types),
"tera_type": p.tera_type.name if p.tera_type is not None else None,
"fainted": bool(p.fainted),
}

def _team(self, team):
states = [self._pokemon(p) for p in team.values() if p is not None]
return sorted(states, key=lambda s: s["species"])

def _battle_state(self):
b = self.battle
return {
"turn": int(b.turn),
"team": self._team(b.team),
"opponent_team": self._team(b.opponent_team),
"weather": sorted(w.name for w in b.weather),
"fields": sorted(f.name for f in b.fields),
"active": [self._pokemon(p) for p in b.active_pokemon],
"opponent_active": [self._pokemon(p) for p in b.opponent_active_pokemon],
}

def _state(self):
"""Player-visible battle state plus the numbered legal actions for the
current decision slot."""
b = self.battle
state = self._battle_state()
state["won"] = b.won
state["lost"] = b.lost
state["slot"] = self._slot
state["available_actions"] = [
f"{i}: {self._describe_action(i)}" for i in self._legal_actions()
]
return state
1 change: 1 addition & 0 deletions game_first_exam/benchmarks/vgc/data/abilities.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["null", "", "noability", "adaptability", "aerilate", "aftermath", "airlock", "analytic", "angerpoint", "angershell", "anticipation", "arenatrap", "armortail", "aromaveil", "asoneglastrier", "asonespectrier", "aurabreak", "baddreams", "ballfetch", "battery", "battlearmor", "battlebond", "beadsofruin", "beastboost", "berserk", "bigpecks", "blaze", "bulletproof", "cheekpouch", "chillingneigh", "chlorophyll", "clearbody", "cloudnine", "colorchange", "comatose", "commander", "competitive", "compoundeyes", "contrary", "corrosion", "costar", "cottondown", "cudchew", "curiousmedicine", "cursedbody", "cutecharm", "damp", "dancer", "darkaura", "dauntlessshield", "dazzling", "defeatist", "defiant", "deltastream", "desolateland", "disguise", "download", "dragonize", "dragonsmaw", "drizzle", "drought", "dryskin", "earlybird", "eartheater", "eelevate", "effectspore", "electricsurge", "electromorphosis", "embodyaspectcornerstone", "embodyaspecthearthflame", "embodyaspectteal", "embodyaspectwellspring", "emergencyexit", "fairyaura", "filter", "firemane", "flamebody", "flareboost", "flashfire", "flowergift", "flowerveil", "fluffy", "forecast", "forewarn", "friendguard", "frisk", "fullmetalbody", "furcoat", "galewings", "galvanize", "gluttony", "goodasgold", "gooey", "gorillatactics", "grasspelt", "grassysurge", "grimneigh", "guarddog", "gulpmissile", "guts", "hadronengine", "harvest", "healer", "heatproof", "heavymetal", "honeygather", "hospitality", "hugepower", "hungerswitch", "hustle", "hydration", "hypercutter", "icebody", "iceface", "icescales", "illuminate", "illusion", "immunity", "imposter", "infiltrator", "innardsout", "innerfocus", "insomnia", "intimidate", "intrepidsword", "ironbarbs", "ironfist", "justified", "keeneye", "klutz", "leafguard", "levitate", "libero", "lightmetal", "lightningrod", "limber", "lingeringaroma", "liquidooze", "liquidvoice", "longreach", "magicbounce", "magicguard", "magician", "magmaarmor", "magnetpull", "marvelscale", "megalauncher", "megasol", "merciless", "mimicry", "mindseye", "minus", "mirrorarmor", "mistysurge", "moldbreaker", "moody", "motordrive", "moxie", "multiscale", "multitype", "mummy", "myceliummight", "naturalcure", "neuroforce", "neutralizinggas", "noguard", "normalize", "oblivious", "opportunist", "orichalcumpulse", "overcoat", "overgrow", "owntempo", "parentalbond", "pastelveil", "perishbody", "pickpocket", "pickup", "piercingdrill", "pixilate", "plus", "poisonheal", "poisonpoint", "poisonpuppeteer", "poisontouch", "powerconstruct", "powerofalchemy", "powerspot", "prankster", "pressure", "primordialsea", "prismarmor", "propellertail", "protean", "protosynthesis", "psychicsurge", "punkrock", "purepower", "purifyingsalt", "quarkdrive", "queenlymajesty", "quickdraw", "quickfeet", "raindish", "rattled", "receiver", "reckless", "refrigerate", "regenerator", "ripen", "rivalry", "rkssystem", "rockhead", "rockypayload", "roughskin", "runaway", "sandforce", "sandrush", "sandspit", "sandstream", "sandveil", "sapsipper", "schooling", "scrappy", "screencleaner", "seedsower", "serenegrace", "shadowshield", "shadowtag", "sharpness", "shedskin", "sheerforce", "shellarmor", "shielddust", "shieldsdown", "simple", "skilllink", "slowstart", "slushrush", "sniper", "snowcloak", "snowwarning", "solarpower", "solidrock", "soulheart", "soundproof", "speedboost", "spicyspray", "stakeout", "stall", "stalwart", "stamina", "stancechange", "static", "steadfast", "steamengine", "steelworker", "steelyspirit", "stench", "stickyhold", "stormdrain", "strongjaw", "sturdy", "suctioncups", "superluck", "supersweetsyrup", "supremeoverlord", "surgesurfer", "swarm", "sweetveil", "swiftswim", "swordofruin", "symbiosis", "synchronize", "tabletsofruin", "tangledfeet", "tanglinghair", "technician", "telepathy", "teraformzero", "terashell", "terashift", "teravolt", "thermalexchange", "thickfat", "tintedlens", "torrent", "toughclaws", "toxicboost", "toxicchain", "toxicdebris", "trace", "transistor", "triage", "truant", "turboblaze", "unaware", "unburden", "unnerve", "unseenfist", "vesselofruin", "victorystar", "vitalspirit", "voltabsorb", "wanderingspirit", "waterabsorb", "waterbubble", "watercompaction", "waterveil", "weakarmor", "wellbakedbody", "whitesmoke", "wimpout", "windpower", "windrider", "wonderguard", "wonderskin", "zenmode", "zerotohero", "mountaineer", "rebound", "persistent"]
Loading