The env object and related subclasses
PokeEnv
This module defines a player class with the Gymnasium API on the main thread. For a black-box implementation consider using the module env_player.
- class poke_env.environment.env.PokeEnv(*, account_configuration1: AccountConfiguration | None = None, account_configuration2: AccountConfiguration | None = None, avatar: int | None = None, battle_format: str = 'gen8randombattle', log_level: int | None = None, save_replays: bool | str = False, server_configuration: ServerConfiguration | None = ('ws://localhost:8000/showdown/websocket', 'https://play.pokemonshowdown.com/action.php?'), accept_open_team_sheet: bool | None = False, start_timer_on_battle_start: bool = False, start_listening: bool = True, open_timeout: float | None = 10.0, ping_interval: float | None = 20.0, ping_timeout: float | None = 20.0, challenge_timeout: float | None = 60.0, team: str | Teambuilder | None = None, choose_on_teampreview: bool | None = None, fake: bool = False, strict: bool = True)
Bases:
ParallelEnv[str,Dict[str,Any],ActionType]Base class implementing the PettingZoo API on the main thread.
- action_space(agent: str) → Space[ActionType]
Takes in agent and returns the action space for that agent.
MUST return the same value for the same agent name
Default implementation is to return the action_spaces dict
- abstractmethod static action_to_order(action: ActionType, battle: Any, fake: bool = False, strict: bool = True) → BattleOrder
Returns the BattleOrder relative to the given action.
- Parameters:
action (ActionType) – The action to take.
battle (AbstractBattle) – The current battle state
fake (bool) – If true, action-order converters will try to avoid returning a default output if at all possible, even if the output isn’t a legal decision. Defaults to False.
strict (bool) – If true, action-order converters will throw an error if the move is illegal. Otherwise, it will return default. Defaults to True.
- Returns:
The battle order for the given action in context of the current battle.
- Return type:
- abstractmethod calc_reward(battle: AbstractBattle) → float
Returns the reward for the current battle state.
- Parameters:
battle (AbstractBattle) – The current battle state.
- Returns:
The reward for battle.
- Return type:
- static calc_term_trunc(battle: AbstractBattle)
- done(timeout: int | None = None) → bool
Returns True if the task is done or is done after the timeout, false otherwise.
- abstractmethod embed_battle(battle: AbstractBattle) → Any
Returns the embedding of the current battle state in a format compatible with the Gymnasium API.
- Parameters:
battle (AbstractBattle) – The current battle state.
- Returns:
The embedding of the current battle state.
- get_additional_info() → Dict[str, Dict[str, Any]]
Returns additional info for the reset method. Override only if you really need it.
- Returns:
Additional information as a Dict
- Return type:
Dict
- observation_space(agent: str) → Space[Dict[str, Any]]
Takes in agent and returns the observation space for that agent.
MUST return the same value for the same agent name
Default implementation is to return the observation_spaces dict
- abstractmethod static order_to_action(order: BattleOrder, battle: Any, fake: bool = False, strict: bool = True) → ActionType
Returns the action relative to the given BattleOrder.
- Parameters:
order (BattleOrder) – The order to take.
battle (AbstractBattle) – The current battle state
fake (bool) – If true, action-order converters will try to avoid returning a default output if at all possible, even if the output isn’t a legal decision. Defaults to False.
strict (bool) – If true, action-order converters will throw an error if the move is illegal. Otherwise, it will return default. Defaults to True.
- Returns:
The action for the given battle order in context of the current battle.
- Return type:
ActionType
- render(mode: str = 'human')
Displays a rendered frame from the environment, if supported.
Alternate render modes in the default environments are ‘rgb_array’ which returns a numpy array and is supported by all environments outside of classic, and ‘ansi’ which returns the strings printed (specific to classic environments).
- reset(seed: int | None = None, options: Dict[str, Any] | None = None) → Tuple[Dict[str, Dict[str, Any]], Dict[str, Dict[str, Any]]]
Resets the environment.
And returns a dictionary of observations (keyed by the agent name)
- reset_battles()
Resets the player’s inner battle tracker.
- reward_computing_helper(battle: AbstractBattle, *, fainted_value: float = 0.0, hp_value: float = 0.0, number_of_pokemons: int = 6, starting_value: float = 0.0, status_value: float = 0.0, victory_value: float = 1.0) → float
A helper function to compute rewards.
The reward is computed by computing the value of a game state, and by comparing it to the last state.
State values are computed by weighting different factor. Fainted pokemons, their remaining HP, inflicted statuses and winning are taken into account.
For instance, if the last time this function was called for battle A it had a state value of 8 and this call leads to a value of 9, the returned reward will be 9 - 8 = 1.
Consider a single battle where each player has 6 pokemons. No opponent pokemon has fainted, but our team has one fainted pokemon. Three opposing pokemons are burned. We have one pokemon missing half of its HP, and our fainted pokemon has no HP left.
The value of this state will be:
- With fainted value: 1, status value: 0.5, hp value: 1:
= - 1 (fainted) + 3 * 0.5 (status) - 1.5 (our hp) = -1
- With fainted value: 3, status value: 0, hp value: 1:
= - 3 + 3 * 0 - 1.5 = -4.5
- Parameters:
battle (AbstractBattle) – The battle for which to compute rewards.
fainted_value (float) – The reward weight for fainted pokemons. Defaults to 0.
hp_value (float) – The reward weight for hp per pokemon. Defaults to 0.
number_of_pokemons (int) – The number of pokemons per team. Defaults to 6.
starting_value (float) – The default reference value evaluation. Defaults to 0.
status_value (float) – The reward value per non-fainted status. Defaults to 0.
victory_value (float) – The reward value for winning. Defaults to 1.
- Returns:
The reward.
- Return type:
- step(actions: Dict[str, ActionType]) → Tuple[Dict[str, Dict[str, Any]], Dict[str, float], Dict[str, bool], Dict[str, bool], Dict[str, Dict[str, Any]]]
Receives a dictionary of actions keyed by the agent name.
Returns the observation dictionary, reward dictionary, terminated dictionary, truncated dictionary and info dictionary, where each dictionary is keyed by the agent.
SinglesEnv
- class poke_env.environment.singles_env.SinglesEnv(*, account_configuration1: AccountConfiguration | None = None, account_configuration2: AccountConfiguration | None = None, avatar: int | None = None, battle_format: str = 'gen8randombattle', log_level: int | None = None, save_replays: bool | str = False, server_configuration: ServerConfiguration | None = ('ws://localhost:8000/showdown/websocket', 'https://play.pokemonshowdown.com/action.php?'), accept_open_team_sheet: bool | None = False, start_timer_on_battle_start: bool = False, start_listening: bool = True, open_timeout: float | None = 10.0, ping_interval: float | None = 20.0, ping_timeout: float | None = 20.0, challenge_timeout: float | None = 60.0, team: str | Teambuilder | None = None, choose_on_teampreview: bool = True, fake: bool = False, strict: bool = True)
Bases:
PokeEnv[int64]- static action_to_order(action: int64, battle: Battle, fake: bool = False, strict: bool = True) → BattleOrder
Returns the BattleOrder relative to the given action.
The action mapping is as follows: action = -2: default action = -1: forfeit 0 <= action <= 5: switch 6 <= action <= 9: move 10 <= action <= 13: move and mega evolve 14 <= action <= 17: move and z-move 18 <= action <= 21: move and dynamax 22 <= action <= 25: move and terastallize
- Parameters:
action (int64) – The action to take.
battle (AbstractBattle) – The current battle state
fake (bool) – If true, action-order converters will try to avoid returning a default output if at all possible, even if the output isn’t a legal decision. Defaults to False.
strict (bool) – If true, action-order converters will throw an error if the move is illegal. Otherwise, it will return default. Defaults to True.
- Returns:
The battle order for the given action in context of the current battle.
- Return type:
- static order_to_action(order: BattleOrder, battle: Battle, fake: bool = False, strict: bool = True) → int64
Returns the action relative to the given BattleOrder.
- Parameters:
order (BattleOrder) – The order to take.
battle (AbstractBattle) – The current battle state
fake (bool) – If true, action-order converters will try to avoid returning a default output if at all possible, even if the output isn’t a legal decision. Defaults to False.
strict (bool) – If true, action-order converters will throw an error if the move is illegal. Otherwise, it will return default. Defaults to True.
- Returns:
The action for the given battle order in context of the current battle.
- Return type:
int64
DoublesEnv
- class poke_env.environment.doubles_env.DoublesEnv(account_configuration1: AccountConfiguration | None = None, account_configuration2: AccountConfiguration | None = None, avatar: int | None = None, battle_format: str = 'gen8randombattle', log_level: int | None = None, save_replays: bool | str = False, server_configuration: ServerConfiguration | None = ('ws://localhost:8000/showdown/websocket', 'https://play.pokemonshowdown.com/action.php?'), accept_open_team_sheet: bool | None = False, start_timer_on_battle_start: bool = False, start_listening: bool = True, open_timeout: float | None = 10.0, ping_interval: float | None = 20.0, ping_timeout: float | None = 20.0, challenge_timeout: float | None = 60.0, team: str | Teambuilder | None = None, choose_on_teampreview: bool = True, fake: bool = False, strict: bool = True)
Bases:
PokeEnv[ndarray[tuple[Any, …],dtype[int64]]]- static action_to_order(action: ndarray[tuple[Any, ...], dtype[int64]], battle: DoubleBattle, fake: bool = False, strict: bool = True) → BattleOrder
Convert an action array into a
BattleOrder.The action is a list in doubles, and the individual action mapping is as follows, where each 5-long range for a move corresponds to a different target (-2, -1, 0, 1, 2).
element = -2: default element = -1: forfeit element = 0: pass 1 <= element <= 6: switch 7 <= element <= 11: move 1 12 <= element <= 16: move 2 17 <= element <= 21: move 3 22 <= element <= 26: move 4 27 <= element <= 31: move 1 and mega evolve 32 <= element <= 36: move 2 and mega evolve 37 <= element <= 41: move 3 and mega evolve 42 <= element <= 46: move 4 and mega evolve 47 <= element <= 51: move 1 and z-move 52 <= element <= 56: move 2 and z-move 57 <= element <= 61: move 3 and z-move 62 <= element <= 66: move 4 and z-move 67 <= element <= 71: move 1 and dynamax 72 <= element <= 76: move 2 and dynamax 77 <= element <= 81: move 3 and dynamax 82 <= element <= 86: move 4 and dynamax 87 <= element <= 91: move 1 and terastallize 92 <= element <= 96: move 2 and terastallize 97 <= element <= 101: move 3 and terastallize 102 <= element <= 106: move 4 and terastallize
- Parameters:
action (ndarray[int64]) – The action to take.
battle (AbstractBattle) – The current battle state
fake (bool) – If
True, return a best-effort order even if it would be illegal.strict (bool) – If
True, raise an error when the action is illegal; otherwise return a default order.
- Returns:
The battle order for the given action in context of the current battle.
- Return type:
- static get_action_mask(battle: DoubleBattle) → list[int]
- static get_action_mask_individual(battle: DoubleBattle, pos: int) → list[int]
- static order_to_action(order: BattleOrder, battle: DoubleBattle, fake: bool = False, strict: bool = True) → ndarray[tuple[Any, ...], dtype[int64]]
Convert a
BattleOrderinto an action array.- Parameters:
order (BattleOrder) – The order to take.
battle (AbstractBattle) – The current battle state
fake (bool) – If
True, return a best-effort action even if it would be illegal.strict (bool) – If
True, raise an error when the order is illegal; otherwise return default.
- Returns:
The action for the given battle order in context of the current battle.
- Return type:
ndarray[int64]
SingleAgentWrapper
- class poke_env.environment.single_agent_wrapper.SingleAgentWrapper(env: PokeEnv[ActionType], opponent: Player)
Bases:
Env[Dict[str,Any],ActionType]- close()
After the user has finished using the environment, close contains the code necessary to “clean up” the environment.
This is critical for closing rendering windows, database or HTTP connections. Calling
closeon an already closed environment has no effect and won’t raise an error.
- render(mode='human')
Compute the render frames as specified by
render_modeduring the initialization of the environment.The environment’s
metadatarender modes (env.metadata[“render_modes”]) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through gymnasium.make which automatically applies a wrapper to collect rendered frames.- Note:
As the
render_modeis known during__init__, the objects used to render the environment state should be initialised in__init__.
By convention, if the
render_modeis:None (default): no render is computed.
“human”: The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during
step()andrender()doesn’t need to be called. ReturnsNone.“rgb_array”: Return a single frame representing the current state of the environment. A frame is a
np.ndarraywith shape(x, y, 3)representing RGB values for an x-by-y pixel image.“ansi”: Return a strings (
str) orStringIO.StringIOcontaining a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors).“rgb_array_list” and “ansi_list”: List based version of render modes are possible (except Human) through the wrapper,
gymnasium.wrappers.RenderCollectionthat is automatically applied duringgymnasium.make(..., render_mode="rgb_array_list"). The frames collected are popped afterrender()is called orreset().
- Note:
Make sure that your class’s
metadata"render_modes"key includes the list of supported modes.
Changed in version 0.25.0: The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e.,
gymnasium.make("CartPole-v1", render_mode="human")
- reset(*, seed: int | None = None, options: Dict[str, Any] | None = None) → Tuple[Dict[str, Any], Dict[str, Any]]
Resets the environment to an initial internal state, returning an initial observation and info.
This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the
seedparameter otherwise if the environment already has a random number generator andreset()is called withseed=None, the RNG is not reset.Therefore,
reset()should (in the typical use case) be called with a seed right after initialization and then never again.For Custom environments, the first line of
reset()should besuper().reset(seed=seed)which implements the seeding correctly.Changed in version v0.25: The
return_infoparameter was removed and now info is expected to be returned.- Args:
- seed (optional int): The seed that is used to initialize the environment’s PRNG (np_random) and
the read-only attribute np_random_seed. If the environment does not already have a PRNG and
seed=None(the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG andseed=Noneis passed, the PRNG will not be reset and the env’snp_random_seedwill not be altered. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer right after the environment has been initialized and then never again. Please refer to the minimal example above to see this paradigm in action.- options (optional dict): Additional information to specify how the environment is reset (optional,
depending on the specific environment)
- Returns:
- observation (ObsType): Observation of the initial state. This will be an element of
observation_space (typically a numpy array) and is analogous to the observation returned by
step().- info (dictionary): This dictionary contains auxiliary information complementing
observation. It should be analogous to the
inforeturned bystep().
- observation (ObsType): Observation of the initial state. This will be an element of