|
| 1 | +"""PettingZoo AEC interface for independent policies and self-play.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import copy |
| 5 | +import json |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +from gymnasium import spaces |
| 10 | +from gymnasium.utils import seeding |
| 11 | +from pettingzoo import AECEnv |
| 12 | + |
| 13 | +from ._native import NativeEnv |
| 14 | + |
| 15 | + |
| 16 | +class AECGameEnv(AECEnv): |
| 17 | + """Sequential game turns with a separate information set for each agent.""" |
| 18 | + |
| 19 | + metadata = {"render_modes": ["ansi"], "name": "gamesforai_v0", "is_parallelizable": False} |
| 20 | + |
| 21 | + def __init__( |
| 22 | + self, game: str, *, config: dict[str, Any] | None = None, render_mode: str | None = None |
| 23 | + ) -> None: |
| 24 | + if render_mode not in (None, "ansi"): |
| 25 | + raise ValueError("render_mode must be None or 'ansi'") |
| 26 | + self.native = NativeEnv(game, json.dumps(config or {})) |
| 27 | + self.render_mode = render_mode |
| 28 | + self.possible_agents = [f"player_{seat}" for seat in range(self.native.num_players)] |
| 29 | + self._seats = {agent: seat for seat, agent in enumerate(self.possible_agents)} |
| 30 | + self._actions = {agent: spaces.Discrete(self.native.action_space_size) for agent in self.possible_agents} |
| 31 | + self._observations = {} |
| 32 | + for agent, seat in self._seats.items(): |
| 33 | + shape = self.native.frame(seat)["observation"].shape |
| 34 | + self._observations[agent] = spaces.Dict({ |
| 35 | + "observation": spaces.Box(-np.inf, np.inf, shape=shape, dtype=np.float32), |
| 36 | + "action_mask": spaces.MultiBinary(self.native.action_space_size), |
| 37 | + }) |
| 38 | + self.agents = [] |
| 39 | + self._rng, _ = seeding.np_random(None) |
| 40 | + |
| 41 | + def observation_space(self, agent): |
| 42 | + return self._observations[agent] |
| 43 | + |
| 44 | + def action_space(self, agent): |
| 45 | + return self._actions[agent] |
| 46 | + |
| 47 | + def observe(self, agent): |
| 48 | + frame = self.native.frame(self._seats[agent]) |
| 49 | + return {"observation": frame["observation"], "action_mask": frame["action_mask"]} |
| 50 | + |
| 51 | + def _refresh_infos(self): |
| 52 | + self.infos = { |
| 53 | + agent: {"seat": self._seats[agent], "text": self.native.frame(self._seats[agent])["text"]} |
| 54 | + for agent in self.agents |
| 55 | + } |
| 56 | + |
| 57 | + def reset(self, seed=None, options=None): |
| 58 | + options = options or {} |
| 59 | + # PettingZoo callers may pass options intended for other wrappers. |
| 60 | + position = options.get("position") |
| 61 | + if position is not None and not isinstance(position, str): |
| 62 | + raise ValueError("position must be a notation string") |
| 63 | + if seed is not None: |
| 64 | + self._rng, _ = seeding.np_random(seed) |
| 65 | + native_seed = int(self._rng.integers(0, 2**64, dtype=np.uint64)) if seed is None else seed |
| 66 | + self.native.reset(native_seed, position) |
| 67 | + actors = self.native.current_players() |
| 68 | + if len(actors) > 1: |
| 69 | + raise ValueError("AEC adapter currently requires sequential turns") |
| 70 | + self.agents = self.possible_agents[:] |
| 71 | + self.rewards = {agent: 0.0 for agent in self.agents} |
| 72 | + self._cumulative_rewards = self.rewards.copy() |
| 73 | + terminated, truncated = self.native.flags() |
| 74 | + self.terminations = {agent: terminated for agent in self.agents} |
| 75 | + self.truncations = {agent: truncated for agent in self.agents} |
| 76 | + self.agent_selection = self.possible_agents[actors[0]] if actors else self.agents[0] |
| 77 | + self._skip_agent_selection = None |
| 78 | + self._refresh_infos() |
| 79 | + |
| 80 | + def step(self, action): |
| 81 | + if not self.agents: |
| 82 | + raise ValueError("reset before stepping an empty AEC episode") |
| 83 | + agent = self.agent_selection |
| 84 | + if self.terminations[agent] or self.truncations[agent]: |
| 85 | + self._was_dead_step(action) |
| 86 | + return |
| 87 | + if isinstance(action, (bool, np.bool_)) or not isinstance(action, (int, np.integer)): |
| 88 | + raise ValueError("a live agent must choose an integer action index") |
| 89 | + # Do not change bookkeeping until the native engine accepts the action. |
| 90 | + rewards, terminated, truncated = self.native.step(self._seats[agent], int(action)) |
| 91 | + self._cumulative_rewards[agent] = 0.0 |
| 92 | + self.rewards = {name: float(rewards[self._seats[name]]) for name in self.agents} |
| 93 | + self.terminations = {name: terminated for name in self.agents} |
| 94 | + self.truncations = {name: truncated for name in self.agents} |
| 95 | + actors = self.native.current_players() |
| 96 | + if actors: |
| 97 | + self.agent_selection = self.possible_agents[actors[0]] |
| 98 | + self._refresh_infos() |
| 99 | + self._accumulate_rewards() |
| 100 | + self._deads_step_first() |
| 101 | + |
| 102 | + def render(self): |
| 103 | + return self.native.public_text() |
| 104 | + |
| 105 | + def close(self): |
| 106 | + pass |
| 107 | + |
| 108 | + def clone(self): |
| 109 | + """Independent native and AEC bookkeeping state for trusted local search.""" |
| 110 | + result = copy.copy(self) |
| 111 | + result.native = self.native.clone() |
| 112 | + for name in ( |
| 113 | + "agents", "rewards", "_cumulative_rewards", "terminations", "truncations", |
| 114 | + "infos", "_actions", "_observations", "_rng", |
| 115 | + ): |
| 116 | + if hasattr(self, name): |
| 117 | + setattr(result, name, copy.deepcopy(getattr(self, name))) |
| 118 | + return result |
| 119 | + |
| 120 | + |
| 121 | +def aec(game: str, **kwargs: Any) -> AECGameEnv: |
| 122 | + """Create a PettingZoo AEC environment with one policy per game seat.""" |
| 123 | + return AECGameEnv(game, **kwargs) |
0 commit comments