|
| 1 | +"""Gymnasium interface for a policy controlling one seat.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import copy |
| 5 | +import json |
| 6 | +from collections.abc import Callable |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +import gymnasium as gym |
| 10 | +import numpy as np |
| 11 | +from gymnasium import spaces |
| 12 | +from gymnasium.error import ResetNeeded |
| 13 | + |
| 14 | +from ._native import NativeEnv |
| 15 | + |
| 16 | +Policy = Callable[[np.ndarray, dict[str, Any]], int] |
| 17 | + |
| 18 | + |
| 19 | +class GameEnv(gym.Env): |
| 20 | + """One learner seat against random opponents or a caller-supplied policy. |
| 21 | +
|
| 22 | + A callable opponent receives only its own observation and info (including |
| 23 | + the legal mask). Its external model state remains the caller's responsibility. |
| 24 | + """ |
| 25 | + |
| 26 | + metadata = {"render_modes": ["ansi"]} |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + game: str, |
| 31 | + *, |
| 32 | + config: dict[str, Any] | None = None, |
| 33 | + seat: int = 0, |
| 34 | + opponent: str | Policy = "random", |
| 35 | + render_mode: str | None = None, |
| 36 | + ) -> None: |
| 37 | + if render_mode not in (None, "ansi"): |
| 38 | + raise ValueError("render_mode must be None or 'ansi'") |
| 39 | + if opponent != "random" and not callable(opponent): |
| 40 | + raise ValueError("opponent must be 'random' or a Python policy callable") |
| 41 | + self.native = NativeEnv(game, json.dumps(config or {})) |
| 42 | + if isinstance(seat, bool) or not isinstance(seat, int) or not 0 <= seat < self.native.num_players: |
| 43 | + raise ValueError("seat is outside this game's player range") |
| 44 | + self.seat = seat |
| 45 | + self.opponent = opponent |
| 46 | + self.render_mode = render_mode |
| 47 | + frame = self.native.frame(seat) |
| 48 | + self.action_space = spaces.Discrete(self.native.action_space_size) |
| 49 | + self.observation_space = spaces.Box( |
| 50 | + -np.inf, np.inf, shape=frame["observation"].shape, dtype=np.float32 |
| 51 | + ) |
| 52 | + self._needs_reset = True |
| 53 | + |
| 54 | + def _frame(self, seat: int) -> tuple[np.ndarray, dict[str, Any]]: |
| 55 | + frame = self.native.frame(seat) |
| 56 | + terminated, truncated = self.native.flags() |
| 57 | + info = { |
| 58 | + "action_mask": frame["action_mask"], |
| 59 | + "text": frame["text"], |
| 60 | + "board": json.loads(frame["board_json"]), |
| 61 | + "seat": seat, |
| 62 | + "to_act": self.native.current_players(), |
| 63 | + "terminated": terminated, |
| 64 | + "truncated": truncated, |
| 65 | + } |
| 66 | + return frame["observation"], info |
| 67 | + |
| 68 | + def _opponents(self) -> float: |
| 69 | + reward = 0.0 |
| 70 | + while actors := self.native.current_players(): |
| 71 | + if len(actors) != 1: |
| 72 | + raise ValueError("Gym single-seat play requires sequential turns; use a multi-agent interface") |
| 73 | + seat = actors[0] |
| 74 | + if seat == self.seat: |
| 75 | + break |
| 76 | + observation, info = self._frame(seat) |
| 77 | + if callable(self.opponent): |
| 78 | + action = self.opponent(observation, info) |
| 79 | + if isinstance(action, (bool, np.bool_)) or not isinstance(action, (int, np.integer)): |
| 80 | + raise ValueError("opponent policy must return an integer action index") |
| 81 | + action = int(action) |
| 82 | + else: |
| 83 | + legal = np.flatnonzero(info["action_mask"]) |
| 84 | + if not legal.size: |
| 85 | + raise ValueError("active opponent has no legal action") |
| 86 | + action = int(self.np_random.choice(legal)) |
| 87 | + rewards, _, _ = self.native.step(seat, action) |
| 88 | + reward += rewards[self.seat] |
| 89 | + return reward |
| 90 | + |
| 91 | + def reset( |
| 92 | + self, *, seed: int | None = None, options: dict[str, Any] | None = None |
| 93 | + ) -> tuple[np.ndarray, dict[str, Any]]: |
| 94 | + options = options or {} |
| 95 | + if set(options) - {"position"}: |
| 96 | + raise ValueError("supported reset option: position") |
| 97 | + position = options.get("position") |
| 98 | + if position is not None and not isinstance(position, str): |
| 99 | + raise ValueError("position must be a notation string") |
| 100 | + super().reset(seed=seed) |
| 101 | + native_seed = int(self.np_random.integers(0, 2**64, dtype=np.uint64)) if seed is None else seed |
| 102 | + self.native.reset(native_seed, position) |
| 103 | + self._opponents() |
| 104 | + self._needs_reset = any(self.native.flags()) |
| 105 | + return self._frame(self.seat) |
| 106 | + |
| 107 | + def step(self, action: int) -> tuple[np.ndarray, float, bool, bool, dict[str, Any]]: |
| 108 | + if self._needs_reset: |
| 109 | + raise ResetNeeded("Call reset before stepping this episode") |
| 110 | + if isinstance(action, (bool, np.bool_)) or not isinstance(action, (int, np.integer)): |
| 111 | + raise ValueError("action must be an integer index") |
| 112 | + # Roll back the entire learner/opponent exchange if a custom policy fails. |
| 113 | + saved = self.native.clone() |
| 114 | + random_state = copy.deepcopy(self.np_random.bit_generator.state) |
| 115 | + try: |
| 116 | + rewards, _, _ = self.native.step(self.seat, int(action)) |
| 117 | + reward = rewards[self.seat] + self._opponents() |
| 118 | + except Exception: |
| 119 | + self.native = saved |
| 120 | + self.np_random.bit_generator.state = random_state |
| 121 | + raise |
| 122 | + terminated, truncated = self.native.flags() |
| 123 | + self._needs_reset = terminated or truncated |
| 124 | + observation, info = self._frame(self.seat) |
| 125 | + return observation, float(reward), terminated, truncated, info |
| 126 | + |
| 127 | + def render(self) -> str: |
| 128 | + return self.native.frame(self.seat)["text"] |
| 129 | + |
| 130 | + def close(self) -> None: |
| 131 | + pass |
| 132 | + |
| 133 | + def clone(self) -> GameEnv: |
| 134 | + """Clone engine and RNG state; an external policy callable is shared.""" |
| 135 | + result = copy.copy(self) |
| 136 | + result.native = self.native.clone() |
| 137 | + result._np_random = copy.deepcopy(self.np_random) |
| 138 | + result._np_random_seed = self.np_random_seed |
| 139 | + result.action_space = copy.deepcopy(self.action_space) |
| 140 | + result.observation_space = copy.deepcopy(self.observation_space) |
| 141 | + return result |
| 142 | + |
| 143 | + def get_state(self) -> dict[str, Any]: |
| 144 | + """Trusted checkpoint containing private engine state and environment RNG.""" |
| 145 | + return { |
| 146 | + "version": 1, |
| 147 | + "seat": self.seat, |
| 148 | + "native": json.loads(self.native.get_state()), |
| 149 | + "rng": copy.deepcopy(self.np_random.bit_generator.state), |
| 150 | + "rng_seed": self.np_random_seed, |
| 151 | + "needs_reset": self._needs_reset, |
| 152 | + } |
| 153 | + |
| 154 | + def set_state(self, state: dict[str, Any]) -> None: |
| 155 | + """Atomically restore this wrapper; external policy state is not included.""" |
| 156 | + required = {"version", "seat", "native", "rng", "rng_seed", "needs_reset"} |
| 157 | + if set(state) != required or state["version"] != 1 or state["seat"] != self.seat: |
| 158 | + raise ValueError("incompatible environment checkpoint") |
| 159 | + if not isinstance(state["needs_reset"], bool): |
| 160 | + raise ValueError("invalid checkpoint episode flag") |
| 161 | + candidate = self.native.clone() |
| 162 | + candidate.set_state(json.dumps(state["native"])) |
| 163 | + if any(candidate.flags()) and not state["needs_reset"]: |
| 164 | + raise ValueError("finished checkpoint cannot be marked active") |
| 165 | + generator = np.random.default_rng() |
| 166 | + generator.bit_generator.state = copy.deepcopy(state["rng"]) |
| 167 | + self.native = candidate |
| 168 | + self._np_random = generator |
| 169 | + self._np_random_seed = state["rng_seed"] |
| 170 | + self._needs_reset = state["needs_reset"] |
| 171 | + |
| 172 | + |
| 173 | +def make(game: str, **kwargs: Any) -> GameEnv: |
| 174 | + """Create a Gymnasium environment for one model's seat.""" |
| 175 | + return GameEnv(game, **kwargs) |
0 commit comments