### Clone and Set Up Pokemon Showdown Server Source: https://poke-env.readthedocs.io/en/stable/_sources/getting_started.rst.txt Clone the Pokemon Showdown repository, install dependencies, and start a local server. The --no-security flag is used to disable rate limiting and authentication for AI training. ```bash git clone https://github.com/smogon/pokemon-showdown.git cd pokemon-showdown npm install cp config/config-example.js config/config.js node pokemon-showdown start --no-security ``` -------------------------------- ### Complete Example: Showdown Agent Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/connecting_to_showdown_and_challenging_humans.rst.txt A comprehensive example demonstrating agent connection, challenging, accepting challenges, ladder play, and rating retrieval. This script requires an asyncio event loop to run. ```python import asyncio from poke_env.player import RandomPlayer from poke_env import AccountConfiguration, ShowdownServerConfiguration async def main(): # We create a random player player = RandomPlayer( account_configuration=AccountConfiguration("bot_username", "bot_password"), server_configuration=ShowdownServerConfiguration, ) # Sending challenges to 'your_username' await player.send_challenges("your_username", n_challenges=1) # Accepting one challenge from any user await player.accept_challenges(None, 1) # Accepting three challenges from 'your_username' await player.accept_challenges("your_username", 3) # Playing 5 games on the ladder await player.ladder(5) # Print the rating of the player and its opponent after each battle for battle in player.battles.values(): print(battle.rating, battle.opponent_rating) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Complete Showdown Integration Example Source: https://poke-env.readthedocs.io/en/stable/examples/connecting_to_showdown_and_challenging_humans.html A full script demonstrating player initialization, challenging, accepting, and ladder play. ```python import asyncio from poke_env.player import RandomPlayer from poke_env import AccountConfiguration, ShowdownServerConfiguration async def main(): # We create a random player player = RandomPlayer( account_configuration=AccountConfiguration("bot_username", "bot_password"), server_configuration=ShowdownServerConfiguration, ) # Sending challenges to 'your_username' await player.send_challenges("your_username", n_challenges=1) # Accepting one challenge from any user await player.accept_challenges(None, 1) # Accepting three challenges from 'your_username' await player.accept_challenges("your_username", 3) # Playing 5 games on the ladder await player.ladder(5) # Print the rating of the player and its opponent after each battle for battle in player.battles.values(): print(battle.rating, battle.opponent_rating) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Instantiating PolicyPlayer for Evaluation Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/reinforcement_learning.rst.txt Example of how to instantiate the PolicyPlayer with a trained policy for evaluation against baseline opponents. ```python agent = PolicyPlayer( policy=ppo.policy, battle_format=BATTLE_FORMAT, max_concurrent_battles=10 ) ``` -------------------------------- ### Run the observation tracking example Source: https://poke-env.readthedocs.io/en/stable/examples/tracking_observations.html Execute the player against an opponent to trigger the observation recording logic. ```python async def main(): player = ObservationTrackingPlayer(battle_format="gen9randombattle") opponent = RandomPlayer(battle_format="gen9randombattle") await player.battle_against(opponent, n_battles=3) asyncio.run(main()) ``` -------------------------------- ### Run the Example with asyncio Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/tracking_observations.rst.txt Execute the battle simulation using `asyncio.run()`. This sets up the player and opponent, then initiates a specified number of battles. ```python async def main(): player = ObservationTrackingPlayer(battle_format="gen9randombattle") opponent = RandomPlayer(battle_format="gen9randombattle") await player.battle_against(opponent, n_battles=3) asyncio.run(main()) ``` -------------------------------- ### DoublesEnv Action Mapping Example Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/action_mapping_and_strict_modes.rst.txt Illustrates action to order conversion with `DoublesEnv` using `strict=False` and `fake=False`. This example shows a best-effort conversion that allows for non-legal actions during training. ```python import numpy as np from poke_env.environment import DoublesEnv mask = DoublesEnv.get_action_mask(battle) action = np.array([7, 27], dtype=np.int64) order = DoublesEnv.action_to_order(action, battle, fake=False, strict=False) recovered_action = DoublesEnv.order_to_action( order, battle, fake=False, strict=False, ) ``` -------------------------------- ### Install Poke-Env Source: https://poke-env.readthedocs.io/en/stable/_sources/getting_started.rst.txt Install the poke-env package using pip. Ensure Python 3.10 or later is installed. ```bash pip install poke-env ``` -------------------------------- ### Define team strings Source: https://poke-env.readthedocs.io/en/stable/examples/using_a_custom_teambuilder.html Example of team configurations formatted as strings for use with a Teambuilder. ```text Goodra||assaultvest|sapsipper|dragonpulse,flamethrower,sludgewave,thunderbolt|Modest|248,,,252,,8|M|,0,,,,|||]Sylveon||leftovers|pixilate|hypervoice,mysticalfire,protect,wish|Calm|248,,244,,16,|M|,0,,,,|||]Cinderace||lifeorb|blaze|pyroball,suckerpunch,uturn,highjumpkick|Jolly|,252,,,4,252|M||||]Toxtricity||throatspray|punkrock|overdrive,boomburst,shiftgear,firepunch|Rash|,4,,252,,252|M||||]Seismitoad||leftovers|waterabsorb|stealthrock,scald,earthquake,toxic|Relaxed|252,,252,,4,|M||||]Corviknight||leftovers|pressure|defog,bravebird,roost,uturn|Impish|248,,,,80,180|M|||| Goodra||assaultvest|sapsipper|dragonpulse,flamethrower,sludgewave,thunderbolt|Modest|248,,,252,,8|M|,0,,,,|||]Sylveon||leftovers|pixilate|hypervoice,mysticalfire,protect,wish|Calm|248,,244,,16,|M|,0,,,,|||]Cinderace||lifeorb|blaze|pyroball,suckerpunch,uturn,highjumpkick|Jolly|,252,,,4,252|M||||]Toxtricity||throatspray|punkrock|overdrive,boomburst,shiftgear,firepunch|Rash|,4,,252,,252|M||||]Seismitoad||leftovers|waterabsorb|stealthrock,scald,earthquake,toxic|Relaxed|252,,252,,4,|M||||]Corviknight||leftovers|pressure|defog,bravebird,roost,uturn|Impish|248,,,,80,180|M|||| Togekiss||leftovers|serenegrace|airslash,nastyplot,substitute,thunderwave|Timid|248,,,8,,252||,0,,,,|||]Galvantula||focussash|compoundeyes|stickyweb,thunderwave,thunder,energyball|Timid|,,,252,4,252||,0,,,,|||]Cloyster||leftovers|skilllink|iciclespear,rockblast,iceshard,shellsmash|Adamant|,252,,,4,252|||||]Sandaconda||focussash|sandspit|stealthrock,glare,earthquake,rocktomb|Jolly|,252,,,4,252|||||]Excadrill||focussash|sandrush|ironhead,rockslide,earthquake,rapidspin|Adamant|,252,,,4,252|||||]Cinccino||leftovers|skilllink|bulletseed,knockoff,rockblast,tailslap|Jolly|,252,4,,,252||||| Togekiss||leftovers|serenegrace|airslash,nastyplot,substitute,thunderwave|Timid|248,,,8,,252||,0,,,,|||]Galvantula||focussash|compoundeyes|stickyweb,thunderwave,thunder,energyball|Timid|,,,252,4,252||,0,,,,|||]Cloyster||leftovers|skilllink|iciclespear,rockblast,iceshard,shellsmash|Adamant|,252,,,4,252|||||]Sandaconda||focussash|sandspit|stealthrock,glare,earthquake,rocktomb|Jolly|,252,,,4,252|||||]Excadrill||focussash|sandrush|ironhead,rockslide,earthquake,rapidspin|Adamant|,252,,,4,252|||||]Cinccino||leftovers|skilllink|bulletseed,knockoff,rockblast,tailslap|Jolly|,252,4,,,252||||| Togekiss||leftovers|serenegrace|airslash,nastyplot,substitute,thunderwave|Timid|248,,,8,,252||,0,,,,|||]Galvantula||focussash|compoundeyes|stickyweb,thunderwave,thunder,energyball|Timid|,,,252,4,252||,0,,,,|||]Cloyster||leftovers|skilllink|iciclespear,rockblast,iceshard,shellsmash|Adamant|,252,,,4,252|||||]Sandaconda||focussash|sandspit|stealthrock,glare,earthquake,rocktomb|Jolly|,252,,,4,252|||||]Excadrill||focussash|sandrush|ironhead,rockslide,earthquake,rapidspin|Adamant|,252,,,4,252|||||]Cinccino||leftovers|skilllink|bulletseed,knockoff,rockblast,tailslap|Jolly|,252,4,,,252||||| ``` -------------------------------- ### Example Log Output Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html This snippet displays typical log entries generated by a RandomPlayer instance during the authentication and search update phases. ```text 2023-12-17 02:56:44,684 - RandomPlayer 7 - INFO - <<< |challstr|4|4df5324a13edbe03218bab5a290e6d64e24eadbbc4213517711beb393505ddbdc7142c71ef5a4d5cafe6e4a3407bcdc2d83e433d0c5d38eb24a046f28f99c93730aface163d8a78e05ae1cd77a1b1f085db56e72b9550e4b7c3ad487cbd59de6500a6d48b92527b279231ce93717fd795a80d6d617f73928a4826475e21c5232 2023-12-17 02:56:44,685 - RandomPlayer 7 - INFO - Bypassing authentication request 2023-12-17 02:56:44,685 - RandomPlayer 7 - INFO - >>> |/trn RandomPlayer 7,0, 2023-12-17 02:56:44,686 - RandomPlayer 7 - INFO - <<< |updatesearch|{"searching":[],"games":null} ``` -------------------------------- ### Initialize PPO Agent for Self-Play Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/self_play.rst.txt Initialize the PPO agent with a MaskedActorCriticPolicy and the vectorized environment. This setup is standard for training agents with action masking. ```python ppo = PPO( MaskedActorCriticPolicy, vec_env, ``` -------------------------------- ### Explicit Replay Export with poke-env Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/saving_replays.rst.txt This example demonstrates how to explicitly export replays from both a `Player` object and a `Battle` object after a battle has concluded. Ensure a Showdown server is running for local player battles. ```python import asyncio from poke_env.player import RandomPlayer async def main(): p1 = RandomPlayer(max_concurrent_battles=1) p2 = RandomPlayer(max_concurrent_battles=1) await p1.battle_against(p2, n_battles=1) battle_tag = next(iter(p1.battles)) # Export through Player helper p1.save_replay(battle_tag, "replays/player_export.html") # Export through Battle object p2.battles[battle_tag].save_replay("replays/battle_export.html") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### SinglesEnv Action Mapping Example Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/action_mapping_and_strict_modes.rst.txt Demonstrates converting between encoded actions and Showdown orders using `SinglesEnv` with strict mode enabled. This is useful for validating policy actions during RL training. ```python import numpy as np from poke_env.environment import SinglesEnv mask = SinglesEnv.get_action_mask(battle) # Convert action -> order order = SinglesEnv.action_to_order( np.int64(6), battle, fake=False, strict=True, ) # Convert order -> action action = SinglesEnv.order_to_action( order, battle, fake=False, strict=True, ) ``` -------------------------------- ### Run First Local Battle with Random Players Source: https://poke-env.readthedocs.io/en/stable/_sources/getting_started.rst.txt Execute a Python script to run two RandomPlayer instances against each other on a local server. This verifies your setup and demonstrates basic battle execution. ```python import asyncio from poke_env.player import RandomPlayer async def main(): player_1 = RandomPlayer(max_concurrent_battles=1) player_2 = RandomPlayer(max_concurrent_battles=1) await player_1.battle_against(player_2, n_battles=1) print(f"Finished battles: {player_1.n_finished_battles}") print(f"Player 1 wins: {player_1.n_won_battles}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initiate a Battle Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html Start a battle between two players using the asynchronous battle_against method. ```python second_player = RandomPlayer() # The battle_against method initiates a battle between two players. # Here we are using asynchronous programming (await) to start the battle. await random_player.battle_against(second_player, n_battles=1) ``` -------------------------------- ### Configure Showdown Player Accounts Source: https://poke-env.readthedocs.io/en/stable/getting_started.html Demonstrates how to initialize players with specific account configurations for authenticated or local servers. ```python from poke_env import AccountConfiguration from poke_env.player import RandomPlayer # No authentication required my_account_config = AccountConfiguration("my_username", None) player = RandomPlayer(account_configuration=my_account_config) # Authentication required my_account_config = AccountConfiguration("my_username", "super-secret-password") player = RandomPlayer( account_configuration=my_account_config, server_configuration=..., ) # Auto-generated configuration for local use player = RandomPlayer() ``` -------------------------------- ### Initialize Player with Verbose Logging Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html Sets the logging level to INFO to capture detailed client communication. ```python verbose_player = RandomPlayer(log_level=20) from asyncio import sleep await sleep(1) ``` -------------------------------- ### Run Battles Against Multiple Opponents Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/reinforcement_learning.rst.txt This snippet shows how to set up multiple opponents and run battles against them using an agent. It then calculates and prints the win rates against each opponent. ```python opponents = [ c(battle_format=BATTLE_FORMAT, max_concurrent_battles=10) for c in [RandomPlayer, MaxBasePowerPlayer, SimpleHeuristicsPlayer] ] asyncio.run(agent.battle_against(*opponents, n_battles=100)) print("--- Win rates vs bots ---") for opp in opponents: win_rate = round(100 * opp.n_lost_battles / opp.n_finished_battles) print(f"{opp.username}: {win_rate}%") ``` -------------------------------- ### Initialize a RandomPlayer for Showdown Source: https://poke-env.readthedocs.io/en/stable/examples/connecting_to_showdown_and_challenging_humans.html Configures a player with account credentials and the official Showdown server configuration. ```python from poke_env.player import RandomPlayer from poke_env import AccountConfiguration, ShowdownServerConfiguration # We create a random player player = RandomPlayer( account_configuration=AccountConfiguration("bot_username", "bot_password"), server_configuration=ShowdownServerConfiguration, ) ``` -------------------------------- ### Train an agent with PPO Source: https://poke-env.readthedocs.io/en/stable/examples/reinforcement_learning.html Uses SubprocVecEnv for parallel environment execution and initializes a PPO agent for training. ```python def train(): num_envs = 2 env = SubprocVecEnv([ExampleEnv.create_env for _ in range(num_envs)]) ppo = PPO( MaskedActorCriticPolicy, env, learning_rate=3e-4, n_steps=3072 // num_envs, batch_size=128, gamma=0.99, ent_coef=0.01, device="cpu", ) ppo.learn(98_304) env.close() ``` -------------------------------- ### Configure Player with AccountConfiguration Source: https://poke-env.readthedocs.io/en/stable/_sources/getting_started.rst.txt Instantiate a Player with an AccountConfiguration. This can be used for local servers (no authentication) or authenticated servers (with a password). ```python from poke_env import AccountConfiguration from poke_env.player import RandomPlayer # No authentication required my_account_config = AccountConfiguration("my_username", None) player = RandomPlayer(account_configuration=my_account_config) # Authentication required my_account_config = AccountConfiguration("my_username", "super-secret-password") player = RandomPlayer( account_configuration=my_account_config, server_configuration=..., ) # Auto-generated configuration for local use player = RandomPlayer() ``` -------------------------------- ### Initialize a RandomPlayer Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html Create a basic agent that selects random moves, serving as a baseline for development. ```python from poke_env import RandomPlayer from poke_env.data import GenData # The RandomPlayer is a basic agent that makes decisions randomly, # serving as a starting point for more complex agent development. random_player = RandomPlayer() ``` -------------------------------- ### Initialize a Verbose Player Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Initializes a player with detailed logging enabled. This is useful for debugging and understanding the player's actions. ```python verbose_player = RandomPlayer(log_level=20) ``` -------------------------------- ### Define and Use a Custom Teambuilder Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/using_a_custom_teambuilder.ipynb.txt Define a custom teambuilder class inheriting from Teambuilder to generate specific Pokémon teams. This example shows how to create a builder that randomly selects Pokémon from a provided pool and then uses it to generate teams for players. ```python class RandomTeamFromPool(Teambuilder): def __init__(self, pokemons): self.pokemons = [] for pokemon in pokemons: parsed_mons = self.parse_showdown_team(pokemon) self.pokemons.append(parsed_mons[0]) self.n_pokemons = len(self.pokemons) assert self.n_pokemons >= 6 def yield_team(self): idxs = np.random.choice(self.n_pokemons, 6, replace=False) team = [self.pokemons[idx] for idx in idxs] return self.join_team(team) custom_builder = RandomTeamFromPool(pokemons) for _ in range(5): print(custom_builder.yield_team()) ``` -------------------------------- ### Initialize RandomPlayer with custom team Source: https://poke-env.readthedocs.io/en/stable/examples/using_a_custom_teambuilder.html Configures a RandomPlayer instance using a custom team builder for battle simulations. ```python from poke_env.player import RandomPlayer player_1 = RandomPlayer( battle_format="gen8anythinggoes", team=custom_builder, max_concurrent_battles=10, ) player_2 = RandomPlayer( battle_format="gen8anythinggoes", team=custom_builder, max_concurrent_battles=10, ) await player_1.battle_against(player_2, n_battles=1) ``` -------------------------------- ### Initialize Player with Replay Saving Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Configure a Player object to automatically save battle replays using the 'save_replays' argument. This can be a boolean for the default 'replays' folder or a string specifying a custom directory. ```python player_with_replays = RandomPlayer(save_replays="my_folder") ``` -------------------------------- ### Singles Environment Action Mapping Source: https://poke-env.readthedocs.io/en/stable/examples/action_mapping_and_strict_modes.html Demonstrates converting actions to orders and vice versa in a Singles environment with strict validation enabled. ```python import numpy as np from poke_env.environment import SinglesEnv mask = SinglesEnv.get_action_mask(battle) # Convert action -> order order = SinglesEnv.action_to_order( np.int64(6), battle, fake=False, strict=True, ) # Convert order -> action action = SinglesEnv.order_to_action( order, battle, fake=False, strict=True, ) ``` -------------------------------- ### Train the agent with PPO Source: https://poke-env.readthedocs.io/en/stable/examples/self_play.html Initialize the PPO model with a MaskedActorCriticPolicy and train it using the vectorized environment. ```python ppo = PPO( MaskedActorCriticPolicy, vec_env, learning_rate=3e-4, n_steps=3072 // (2 * num_envs), batch_size=128, gamma=0.99, ent_coef=0.01, device="cpu", ) ppo.learn(98_304) vec_env.close() ``` -------------------------------- ### step(action) Source: https://poke-env.readthedocs.io/en/stable/modules/env.html Executes one timestep of the environment's dynamics. ```APIDOC ## step(action) ### Description Runs one timestep of the environment's dynamics. Takes an action from the main agent and automatically generates an action for the opponent. ### Parameters - **action** (ActionType) - Required - Action from the main agent. ### Returns - **observation** (Dict[str, Any]) - The new observation. - **reward** (float) - The reward obtained. - **terminated** (bool) - Whether the episode has terminated. - **truncated** (bool) - Whether the episode has been truncated. - **info** (Dict[str, Any]) - Auxiliary information. ``` -------------------------------- ### Connect Agent to Showdown Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/connecting_to_showdown_and_challenging_humans.rst.txt Use this snippet to configure and connect your agent to a Showdown server. Ensure you have a Showdown account and password. ```python from poke_env.player import RandomPlayer from poke_env import AccountConfiguration, ShowdownServerConfiguration # We create a random player player = RandomPlayer( account_configuration=AccountConfiguration("bot_username", "bot_password"), server_configuration=ShowdownServerConfiguration, ) ``` -------------------------------- ### Connect to Official Showdown Server Source: https://poke-env.readthedocs.io/en/stable/getting_started.html Requires an AccountConfiguration object with valid credentials to authenticate with the official server. ```python from poke_env import AccountConfiguration, ShowdownServerConfiguration from poke_env.player import RandomPlayer account_config = AccountConfiguration("my_username", "super-secret-password") player = RandomPlayer( server_configuration=ShowdownServerConfiguration, account_configuration=account_config, ) ``` -------------------------------- ### Connect to Custom Showdown Server Source: https://poke-env.readthedocs.io/en/stable/getting_started.html Define a custom ServerConfiguration by providing the websocket URL and authentication endpoint. ```python from poke_env import ServerConfiguration from poke_env.player import RandomPlayer custom_config = ServerConfiguration( "ws://my.custom.host:5432/showdown/websocket", "https://my.custom.host/action.php?", ) player = RandomPlayer(server_configuration=custom_config) ``` -------------------------------- ### Measure sequential battle execution time Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html Demonstrates the time taken to run 50 battles sequentially using a standard Player instance. ```python import time # Time to run 50 battles, one at a time start = time.time() await random_player.battle_against(second_player, n_battles=50) end = time.time() print(f"Time to run 50 battles, one at a time: {end - start:.2f} seconds") ``` -------------------------------- ### Connect to Custom Server Source: https://poke-env.readthedocs.io/en/stable/_sources/getting_started.rst.txt Configure a Player to connect to a custom Pokémon Showdown server using ServerConfiguration. Specify the WebSocket URL and the authentication endpoint. ```python from poke_env import ServerConfiguration from poke_env.player import RandomPlayer custom_config = ServerConfiguration( "ws://my.custom.host:5432/showdown/websocket", "https://my.custom.host/action.php?", ) player = RandomPlayer(server_configuration=custom_config) ``` -------------------------------- ### Automatic Replay Saving with poke-env Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/saving_replays.rst.txt Use `save_replays=True` to save replays to the default 'replays' folder, or provide a string path to customize the save location. ```python from poke_env.player import RandomPlayer player = RandomPlayer(save_replays=True) player_with_custom_folder = RandomPlayer(save_replays="replays") ``` -------------------------------- ### Initialize Player with Custom Logging Level Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Control the verbosity of player logs by setting the 'log_level' argument during initialization. Use logging constants like logging.INFO (20) for detailed messages or 25 for poke-env specific events. ```python import logging player_with_custom_logging = RandomPlayer(log_level=logging.INFO) ``` -------------------------------- ### Initialize player with custom builder Source: https://poke-env.readthedocs.io/en/stable/examples/using_a_custom_teambuilder.html Pass the custom Teambuilder instance to the Player constructor using the team keyword. ```python [3]: ``` ```python from poke_env.player import RandomPlayer player_1 = RandomPlayer( battle_format="gen8anythinggoes", team=custom_builder, max_concurrent_battles=10, ) player_2 = RandomPlayer( battle_format="gen8anythinggoes", team=custom_builder, max_concurrent_battles=10, ) await player_1.battle_against(player_2, n_battles=1) ``` -------------------------------- ### Initialize Player with Strict Battle Tracking Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/strict_battle_tracking.rst.txt Instantiate a `RandomPlayer` with `strict_battle_tracking` set to `True`. This option is most useful for debugging parser/state issues during live battles or integration tests. ```python from poke_env.player import RandomPlayer player = RandomPlayer( battle_format="gen9randombattle", strict_battle_tracking=True, ) ``` -------------------------------- ### Handle Battle Challenges Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Demonstrates how to handle incoming battle challenges and respond to them. This snippet shows the server's response to a challenge. ```python 2023-12-17 02:56:44,684 - RandomPlayer 7 - INFO - <<< |challstr|4|4df5324a13edbe03218bab5a290e6d64e24eadbbc4213517711beb393505ddbdc7142c71ef5a4d5cafe6e4a3407bcdc2d83e433d0c5d38eb24a046f28f99c93730aface163d8a78e05ae1cd77a1b1f085db56e72b9550e4b7c3ad487cbd59de6500a6d48b92527b279231ce93717fd795a80d6d617f73928a4826475e21c5232 ``` -------------------------------- ### Instantiate Teambuilder with Showdown Teams Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/using_a_custom_teambuilder.ipynb.txt Instantiate the custom `RandomTeamFromPool` teambuilder by providing a list of showdown formatted teams. The output shows the packed format of the first team in the list. ```python my_teams = [ "Goodra||assaultvest|sapsipper|dragonpulse,flamethrower,sludgewave,thunderbolt|Modest|248,,,252,,8|M|,0,,,,|||", "Sylveon||leftovers|pixilate|hypervoice,mysticalfire,protect,wish|Calm|248,,244,,16,|M|,0,,,,|||", "Cinderace||lifeorb|blaze|pyroball,suckerpunch,uturn,highjumpkick|Jolly|,252,,,4,252|M||||", "Toxtricity||throatspray|punkrock|overdrive,boomburst,shiftgear,firepunch|Rash|,4,,252,,252|M||||", "Seismitoad||leftovers|waterabsorb|stealthrock,scald,earthquake,toxic|Relaxed|252,,252,,4,|M||||", "Corviknight||leftovers|pressure|defog,bravebird,roost,uturn|Impish|248,,,,80,180|M||||" ] teambuilder = RandomTeamFromPool(my_teams) print(teambuilder.yield_team()) ``` -------------------------------- ### ServerConfiguration Source: https://poke-env.readthedocs.io/en/stable/modules/ps_client.html Configuration objects for defining server connection details. ```APIDOC ## ServerConfiguration ### Description Defines the connection parameters for Pokémon Showdown servers, including authentication and websocket URLs. ### Subclasses - **LocalhostServerConfiguration**: Configuration for local server instances. - **ShowdownServerConfiguration**: Configuration for official Showdown servers. ``` -------------------------------- ### Doubles Environment Action Mapping Source: https://poke-env.readthedocs.io/en/stable/examples/action_mapping_and_strict_modes.html Demonstrates converting actions to orders and vice versa in a Doubles environment with strict validation disabled for fault tolerance. ```python import numpy as np from poke_env.environment import DoublesEnv mask = DoublesEnv.get_action_mask(battle) action = np.array([7, 27], dtype=np.int64) order = DoublesEnv.action_to_order(action, battle, fake=False, strict=False) recovered_action = DoublesEnv.order_to_action( order, battle, fake=False, strict=False, ) ``` -------------------------------- ### step(actions: Dict[str, ActionType]) Source: https://poke-env.readthedocs.io/en/stable/modules/env.html Advances the environment by one step given a dictionary of actions. ```APIDOC ## step(actions: Dict[str, ActionType]) ### Description Receives a dictionary of actions keyed by the agent name and returns the observation, reward, terminated, truncated, and info dictionaries. ### Parameters - **actions** (Dict[str, ActionType]) - Required - Dictionary of actions keyed by agent name. ``` -------------------------------- ### Convert PettingZoo Env to VecEnv with SuperSuit Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/self_play.rst.txt Use SuperSuit to convert a two-agent PettingZoo ParallelEnv into an SB3-compatible VecEnv. This allows for vectorized training where both agents contribute to the learning process. ```python import supersuit as ss num_envs = 2 env = SelfPlayEnv(battle_format=BATTLE_FORMAT, log_level=40, open_timeout=None) vec_env = ss.pettingzoo_env_to_vec_env(env) vec_env = ss.concat_vec_envs_v1( vec_env, num_vec_envs=num_envs, num_cpus=num_envs, base_class="stable_baselines3", ) ``` -------------------------------- ### Training a PPO Agent with Action Masking Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/reinforcement_learning.rst.txt This function sets up and trains a PPO agent using SubprocVecEnv for parallel environments and the custom MaskedActorCriticPolicy. ```python def train(): num_envs = 2 env = SubprocVecEnv([ExampleEnv.create_env for _ in range(num_envs)]) ppo = PPO( MaskedActorCriticPolicy, env, learning_rate=3e-4, n_steps=3072 // num_envs, batch_size=128, gamma=0.99, ent_coef=0.01, device="cpu", ) ppo.learn(98_304) env.close() ``` -------------------------------- ### DoublesEnv.order_to_action Source: https://poke-env.readthedocs.io/en/stable/modules/env.html Converts a BattleOrder object into an action array. ```APIDOC ## DoublesEnv.order_to_action ### Description Converts a BattleOrder into an action array representation. ### Parameters - **order** (BattleOrder) - Required - The order to take. - **battle** (DoubleBattle) - Required - The current battle state. - **fake** (bool) - Optional - If True, return a best-effort action even if it would be illegal. - **strict** (bool) - Optional - If True, raise an error when the order is illegal; otherwise return default. ### Returns - **ndarray[int64]** - The action for the given battle order in context of the current battle. ``` -------------------------------- ### Connect to Official Showdown Server Source: https://poke-env.readthedocs.io/en/stable/_sources/getting_started.rst.txt Configure a Player to connect to the official Pokémon Showdown server. Requires an AccountConfiguration with a password and the ShowdownServerConfiguration. ```python from poke_env import AccountConfiguration, ShowdownServerConfiguration from poke_env.player import RandomPlayer account_config = AccountConfiguration("my_username", "super-secret-password") player = RandomPlayer( server_configuration=ShowdownServerConfiguration, account_configuration=account_config, ) ``` -------------------------------- ### Implement MaxDamagePlayer with Terastallization Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html Updates the player logic to prioritize terastallization when available. ```python class MaxDamagePlayer(Player): def choose_move(self, battle): if battle.available_moves: best_move = max(battle.available_moves, key=lambda move: move.base_power) if battle.can_tera: return self.create_order(best_move, terastallize=True) return self.create_order(best_move) else: return self.choose_random_move(battle) ``` -------------------------------- ### Implement PolicyPlayer for evaluation Source: https://poke-env.readthedocs.io/en/stable/examples/reinforcement_learning.html Wraps a trained policy to select actions based on battle observations and action masks. ```python class PolicyPlayer(Player): def choose_move(self, battle): if battle.wait: return DefaultBattleOrder() obs = self.embed_battle(battle) mask = np.array(SinglesEnv.get_action_mask(battle)) with torch.no_grad(): obs_dict = { "observation": torch.as_tensor( obs, device=self.policy.device ).unsqueeze(0), "action_mask": torch.as_tensor( mask, device=self.policy.device ).unsqueeze(0), } action, _, _ = self.policy.forward(obs_dict) action = action.cpu().numpy()[0] return SinglesEnv.action_to_order(action, battle) ``` -------------------------------- ### Teambuilder.join_team Source: https://poke-env.readthedocs.io/en/stable/modules/teambuilder.html Converts a list of TeambuilderPokemon objects into a packed showdown team format string. ```APIDOC ## static join_team(team: List[TeambuilderPokemon]) -> str ### Description Converts a list of TeambuilderPokemon objects into the corresponding packed showdown team format. ### Parameters - **team** (list of TeambuilderPokemon) - Required - The list of TeambuilderPokemon objects that form the team. ### Returns - **str** - The formatted team string. ``` -------------------------------- ### Define Battle Teams and Simulate Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Defines two teams for a battle simulation and initiates a battle between them. Requires teams to be defined as strings. ```python team_1 = """ Seismitoad (M) @ Leftovers Ability: Water Absorb EVs: 252 HP / 252 Def / 4 SpD Relaxed Nature - Stealth Rock - Scald - Earthquake - Toxic Corviknight (M) @ Leftovers Ability: Pressure EVs: 248 HP / 80 SpD / 180 Spe Impish Nature - Defog - Brave Bird - Roost - U-turn Galvantula @ Focus Sash Ability: Compound Eyes EVs: 252 SpA / 4 SpD / 252 Spe Timid Nature IVs: 0 Atk - Sticky Web - Thunder Wave - Thunder - Energy Ball """ team_2 = """ Togekiss @ Leftovers Ability: Serene Grace EVs: 248 HP / 8 SpA / 252 Spe Timid Nature IVs: 0 Atk - Air Slash - Nasty Plot - Substitute - Thunder Wave Galvantula @ Focus Sash Ability: Compound Eyes EVs: 252 SpA / 4 SpD / 252 Spe Timid Nature IVs: 0 Atk - Sticky Web - Thunder Wave - Thunder - Energy Ball Cloyster @ Leftovers Ability: Skill Link EVs: 252 Atk / 4 SpD / 252 Spe Adamant Nature - Icicle Spear - Rock Blast - Ice Shard - Shell Smash Sandaconda @ Focus Sash Ability: Sand Spit EVs: 252 Atk / 4 SpD / 252 Spe Jolly Nature - Stealth Rock - Glare - Earthquake - Rock Tomb Excadrill @ Focus Sash Ability: Sand Rush EVs: 252 Atk / 4 SpD / 252 Spe Adamant Nature - Iron Head - Rock Slide - Earthquake - Rapid Spin Cinccino @ Leftovers Ability: Skill Link EVs: 252 Atk / 4 Def / 252 Spe Jolly Nature - Bullet Seed - Knock Off - Rock Blast - Tail Slap """ p1 = MaxDamagePlayer(battle_format="gen8ou", team=team_1) p2 = MaxDamagePlayer(battle_format="gen8ou", team=team_2) await p1.battle_against(p2, n_battles=1) ``` -------------------------------- ### Register a Trainer Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Registers a trainer with the battle server. This command is used to create or update a trainer's profile. ```python 2023-12-17 02:56:44,685 - RandomPlayer 7 - INFO - >>> |/trn RandomPlayer 7,0, ``` -------------------------------- ### Initialize Player with Avatar Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Specify an avatar for a Player object using the 'avatar' argument. Refer to the provided link for a list of available avatar names. ```python player_with_avatar = RandomPlayer(avatar="boarder") ``` -------------------------------- ### action_to_order Source: https://poke-env.readthedocs.io/en/stable/modules/env.html Converts an integer action into a BattleOrder object based on the current battle state. ```APIDOC ## static action_to_order(action: int64, battle: Battle, fake: bool = False, strict: bool = True) -> BattleOrder ### Description 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) - Required - The action to take. - **battle** (AbstractBattle) - Required - The current battle state. - **fake** (bool) - Optional - If true, action-order converters will try to avoid returning a default output if at all possible. Defaults to False. - **strict** (bool) - Optional - If true, action-order converters will throw an error if the move is illegal. Defaults to True. ### Returns - **BattleOrder** - The battle order for the given action in context of the current battle. ``` -------------------------------- ### Prepare Pokémon pool from Showdown format Source: https://poke-env.readthedocs.io/en/stable/examples/using_a_custom_teambuilder.html Splits and cleans Pokémon team strings to create a list of individual Pokémon entries. ```python pokemons = team_1.split("\n\n") + team_2.split("\n\n") pokemons = [pokemon.strip() for pokemon in sorted(pokemons)] pokemons ``` -------------------------------- ### PSClient.accept_challenge Source: https://poke-env.readthedocs.io/en/stable/modules/ps_client.html Accepts a challenge from another user. ```APIDOC ## async accept_challenge(username: str, packed_team: str | None) ### Description Accepts a challenge from the specified username with an optional packed team. ### Parameters - **username** (str) - Required - The username of the challenger. - **packed_team** (str | None) - Optional - The packed team string to use. ``` -------------------------------- ### reset(seed: int | None = None, options: Dict[str, Any] | None = None) Source: https://poke-env.readthedocs.io/en/stable/modules/env.html Resets the environment and returns a dictionary of observations keyed by agent name. ```APIDOC ## reset(seed: int | None = None, options: Dict[str, Any] | None = None) ### Description Resets the environment and returns a dictionary of observations keyed by agent name. ### Parameters - **seed** (int | None) - Optional - Seed for the random number generator. - **options** (Dict[str, Any] | None) - Optional - Additional configuration options for the reset. ``` -------------------------------- ### Automatic Replay Saving Source: https://poke-env.readthedocs.io/en/stable/examples/saving_replays.html Configure a player to automatically save replays to a specified directory upon battle completion. ```python from poke_env.player import RandomPlayer player = RandomPlayer(save_replays=True) player_with_custom_folder = RandomPlayer(save_replays="replays") ``` -------------------------------- ### Implement a custom SinglesEnv subclass Source: https://poke-env.readthedocs.io/en/stable/examples/reinforcement_learning.html Defines the environment structure, including observation spaces, reward calculation, and integration with SingleAgentWrapper. ```python BATTLE_FORMAT = "gen9randombattle" class ExampleEnv(SinglesEnv): def __init__(self, **kwargs): super().__init__(**kwargs) self.observation_spaces = { agent: Box(-1, 4, shape=(N_FEATURES,), dtype=np.float32) for agent in self.possible_agents } @classmethod def create_env(cls) -> Monitor: env = cls(battle_format=BATTLE_FORMAT, log_level=40, open_timeout=None) opponent = SimpleHeuristicsPlayer(start_listening=False) return Monitor(SingleAgentWrapper(env, opponent)) def calc_reward(self, battle) -> float: return self.reward_computing_helper( battle, fainted_value=2.0, hp_value=1.0, status_value=0.5, victory_value=30.0, ) def embed_battle(self, battle: AbstractBattle): return PolicyPlayer.embed_battle(battle) ``` -------------------------------- ### PSClient Source: https://poke-env.readthedocs.io/en/stable/modules/ps_client.html The primary class for interacting with Pokémon Showdown servers, providing methods for authentication, game searching, and communication. ```APIDOC ## PSClient ### Description Main interface for interacting with Pokémon Showdown servers. ### Methods - **accept_challenge()**: Accepts a pending challenge. - **challenge()**: Sends a challenge to a user. - **change_avatar()**: Changes the user's avatar. - **listen()**: Starts listening to server messages. - **log_in()**: Logs into the server. - **search_ladder_game()**: Searches for a ladder game. - **send_message()**: Sends a message to a user or room. - **set_team()**: Sets the team for the client. - **stop_listening()**: Stops listening to server messages. - **wait_for_login()**: Waits for the login process to complete. ``` -------------------------------- ### Test MaxDamagePlayer Against RandomPlayer Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/quickstart.ipynb.txt Simulates 100 battles between a MaxDamagePlayer and a RandomPlayer to evaluate the MaxDamagePlayer's win rate. Requires the 'battle_against' method to be available. ```python # Creating players random_player = RandomPlayer() max_damage_player = MaxDamagePlayer() # Running battles await max_damage_player.battle_against(random_player, n_battles=100) # Displaying results print(f"Max damage player won {max_damage_player.n_won_battles} / 100 battles") ``` -------------------------------- ### PSClient.challenge Source: https://poke-env.readthedocs.io/en/stable/modules/ps_client.html Challenges a user to a battle. ```APIDOC ## async challenge(username: str, format: str, packed_team: str | None) ### Description Sends a battle challenge to a user in a specific format. ### Parameters - **username** (str) - Required - The username to challenge. - **format** (str) - Required - The battle format. - **packed_team** (str | None) - Optional - The packed team string. ``` -------------------------------- ### Enable Pokemon Showdown timer Source: https://poke-env.readthedocs.io/en/stable/examples/quickstart.html Initializes a Player with the battle timer enabled, useful for matches against human opponents. ```python impatient_player = RandomPlayer(start_timer_on_battle_start=True) ``` -------------------------------- ### Reference index Source: https://poke-env.readthedocs.io/en/stable/examples/using_a_custom_teambuilder.html A simple index reference. ```text [6]: ``` -------------------------------- ### AccountConfiguration Source: https://poke-env.readthedocs.io/en/stable/modules/ps_client.html Configuration object for managing user account credentials. ```APIDOC ## AccountConfiguration ### Description Handles account credentials for server authentication. ### Methods - **generate()**: Generates a new account configuration. ``` -------------------------------- ### Define Custom RL Environment Source: https://poke-env.readthedocs.io/en/stable/_sources/examples/reinforcement_learning.rst.txt Subclasses `SinglesEnv` to define observation spaces, rewards, and embedding for RL training. Uses `stable-baselines3`'s `Monitor` and `SingleAgentWrapper`. ```python BATTLE_FORMAT = "gen9randombattle" class ExampleEnv(SinglesEnv): def __init__(self, **kwargs): super().__init__(**kwargs) self.observation_spaces = { agent: Box(-1, 4, shape=(N_FEATURES,), dtype=np.float32) for agent in self.possible_agents } @classmethod def create_env(cls) -> Monitor: env = cls(battle_format=BATTLE_FORMAT, log_level=40, open_timeout=None) opponent = SimpleHeuristicsPlayer(start_listening=False) return Monitor(SingleAgentWrapper(env, opponent)) def calc_reward(self, battle) -> float: return self.reward_computing_helper( battle, fainted_value=2.0, ``` -------------------------------- ### DoublesEnv.action_to_order Source: https://poke-env.readthedocs.io/en/stable/modules/env.html Converts an action array into a BattleOrder object for double battles. ```APIDOC ## DoublesEnv.action_to_order ### Description Converts an action array into a BattleOrder. The action is a list in doubles, where specific integer ranges correspond to different battle actions like switching, moving, or using special mechanics. ### Parameters - **action** (ndarray[int64]) - Required - The action to take. - **battle** (DoubleBattle) - Required - The current battle state. - **fake** (bool) - Optional - If True, return a best-effort order even if it would be illegal. - **strict** (bool) - Optional - If True, raise an error when the action is illegal; otherwise return a default order. ### Returns - **BattleOrder** - The battle order for the given action in context of the current battle. ```