.\PokeLLMon\poke_env\exceptions.py
"""
This module contains exceptions.
"""
class ShowdownException(Exception):
"""
This exception is raised when a non-managed message
is received from the server.
"""
pass
.\PokeLLMon\poke_env\player\baselines.py
from typing import List
import json
import os
from poke_env.environment.abstract_battle import AbstractBattle
from poke_env.environment.double_battle import DoubleBattle
from poke_env.environment.move_category import MoveCategory
from poke_env.environment.pokemon import Pokemon
from poke_env.environment.side_condition import SideCondition
from poke_env.player.player import Player
from poke_env.data.gen_data import GenData
with open("./poke_env/data/static/moves/moves_effect.json", "r") as f:
move_effect = json.load(f)
def calculate_move_type_damage_multipier(type_1, type_2, type_chart, constraint_type_list):
TYPE_list = 'BUG,DARK,DRAGON,ELECTRIC,FAIRY,FIGHTING,FIRE,FLYING,GHOST,GRASS,GROUND,ICE,NORMAL,POISON,PSYCHIC,ROCK,STEEL,WATER'.split(",")
move_type_damage_multiplier_list = []
if type_2:
for type in TYPE_list:
move_type_damage_multiplier_list.append(type_chart[type_1][type] * type_chart[type_2][type])
move_type_damage_multiplier_dict = dict(zip(TYPE_list, move_type_damage_multiplier_list))
else:
move_type_damage_multiplier_dict = type_chart[type_1]
effective_type_list = []
extreme_type_list = []
resistant_type_list = []
extreme_resistant_type_list = []
immune_type_list = []
for type, value in move_type_damage_multiplier_dict.items():
if value == 2:
effective_type_list.append(type)
elif value == 4:
extreme_type_list.append(type)
elif value == 1 / 2:
resistant_type_list.append(type)
elif value == 1 / 4:
extreme_resistant_type_list.append(type)
elif value == 0:
immune_type_list.append(type)
else:
continue
if constraint_type_list:
extreme_type_list = list(set(extreme_type_list).intersection(set(constraint_type_list)))
effective_type_list = list(set(effective_type_list).intersection(set(constraint_type_list)))
resistant_type_list = list(set(resistant_type_list).intersection(set(constraint_type_list)))
extreme_resistant_type_list = list(set(extreme_resistant_type_list).intersection(set(constraint_type_list)))
immune_type_list = list(set(immune_type_list).intersection(set(constraint_type_list)))
return extreme_type_list, effective_type_list, resistant_type_list, extreme_resistant_type_list, immune_type_list
def move_type_damage_wraper(pokemon_name, type_1, type_2, type_chart, constraint_type_list=None):
move_type_damage_prompt = ""
extreme_effective_type_list, effective_type_list, resistant_type_list, extreme_resistant_type_list, immune_type_list = calculate_move_type_damage_multipier(
type_1, type_2, type_chart, constraint_type_list)
if effective_type_list or resistant_type_list or immune_type_list:
move_type_damage_prompt = f"{pokemon_name}"
if extreme_effective_type_list:
move_type_damage_prompt = move_type_damage_prompt + " can be super-effectively attacked by " + ", ".join(
extreme_effective_type_list) + " moves"
if effective_type_list:
move_type_damage_prompt = move_type_damage_prompt + ", can be effectively attacked by " + ", ".join(
effective_type_list) + " moves"
if resistant_type_list:
move_type_damage_prompt = move_type_damage_prompt + ", is resistant to " + ", ".join(
resistant_type_list) + " moves"
if extreme_resistant_type_list:
move_type_damage_prompt = move_type_damage_prompt + ", is super-resistant to " + ", ".join(
extreme_resistant_type_list) + " moves"
if immune_type_list:
move_type_damage_prompt = move_type_damage_prompt + ", is immuned to " + ", ".join(
immune_type_list) + " moves"
return move_type_damage_prompt
class MaxBasePowerPlayer(Player):
def choose_move(self, battle: AbstractBattle):
if battle.available_moves:
best_move = max(battle.available_moves, key=lambda move: move.base_power)
return self.create_order(best_move)
return self.choose_random_move(battle)
class SimpleHeuristicsPlayer(Player):
ENTRY_HAZARDS = {
"spikes": SideCondition.SPIKES,
"stealhrock": SideCondition.STEALTH_ROCK,
"stickyweb": SideCondition.STICKY_WEB,
"toxicspikes": SideCondition.TOXIC_SPIKES,
}
ANTI_HAZARDS_MOVES = {"rapidspin", "defog"}
SPEED_TIER_COEFICIENT = 0.1
HP_FRACTION_COEFICIENT = 0.4
SWITCH_OUT_MATCHUP_THRESHOLD = -2
def _estimate_matchup(self, mon: Pokemon, opponent: Pokemon):
score = max([opponent.damage_multiplier(t) for t in mon.types if t is not None])
score -= max(
[mon.damage_multiplier(t) for t in opponent.types if t is not None]
)
if mon.base_stats["spe"] > opponent.base_stats["spe"]:
score += self.SPEED_TIER_COEFICIENT
elif opponent.base_stats["spe"] > mon.base_stats["spe"]:
score -= self.SPEED_TIER_COEFICIENT
score += mon.current_hp_fraction * self.HP_FRACTION_COEFICIENT
score -= opponent.current_hp_fraction * self.HP_FRACTION_COEFICIENT
return score
def _should_dynamax(self, battle: AbstractBattle, n_remaining_mons: int):
if battle.can_dynamax and self._dynamax_disable is False:
if (
len([m for m in battle.team.values() if m.current_hp_fraction == 1])
== 1
and battle.active_pokemon.current_hp_fraction == 1
):
return True
if (
self._estimate_matchup(
battle.active_pokemon, battle.opponent_active_pokemon
)
> 0
and battle.active_pokemon.current_hp_fraction == 1
and battle.opponent_active_pokemon.current_hp_fraction == 1
):
return True
if n_remaining_mons == 1:
return True
return False
def _should_switch_out(self, battle: AbstractBattle):
active = battle.active_pokemon
opponent = battle.opponent_active_pokemon
if [
m
for m in battle.available_switches
if self._estimate_matchup(m, opponent) > 0
]:
if active.boosts["def"] <= -3 or active.boosts["spd"] <= -3:
return True
if (
active.boosts["atk"] <= -3
and active.stats["atk"] >= active.stats["spa"]
):
return True
if (
active.boosts["spa"] <= -3
and active.stats["atk"] <= active.stats["spa"]
):
return True
if (
self._estimate_matchup(active, opponent)
< self.SWITCH_OUT_MATCHUP_THRESHOLD
):
return True
return False
def _stat_estimation(self, mon: Pokemon, stat: str):
if mon.boosts[stat] > 1:
boost = (2 + mon.boosts[stat]) / 2
else:
boost = 2 / (2 - mon.boosts[stat])
return ((2 * mon.base_stats[stat] + 31) + 5) * boost
def calc_reward(
self, current_battle: AbstractBattle
) -> float:
return self.reward_computing_helper(
current_battle, fainted_value=2.0, hp_value=1.0, victory_value=30.0
)
def boost_multiplier(self, state, level):
if state == "accuracy":
if level == 0:
return 1.0
if level == 1:
return 1.33
if level == 2:
return 1.66
if level == 3:
return 2.0
if level == 4:
return 2.5
if level == 5:
return 2.66
if level == 6:
return 3.0
if level == -1:
return 0.75
if level == -2:
return 0.6
if level == -3:
return 0.5
if level == -4:
return 0.43
if level == -5:
return 0.36
if level == -6:
return 0.33
else:
if level == 0:
return 1.0
if level == 1:
return 1.5
if level == 2:
return 2.0
if level == 3:
return 2.5
if level == 4:
return 3.0
if level == 5:
return 3.5
if level == 6:
return 4.0
if level == -1:
return 0.67
if level == -2:
return 0.5
if level == -3:
return 0.4
if level == -4:
return 0.33
if level == -5:
return 0.29
if level == -6:
return 0.25
def check_status(self, status):
if status:
if status.value == 1:
return "burnt"
elif status.value == 2:
return "fainted"
elif status.value == 3:
return "frozen"
elif status.value == 4:
return "paralyzed"
elif status.value == 5:
return "poisoned"
elif status.value == 7:
return "toxic"
elif status.value == 6:
return "sleeping"
else:
return "healthy"
.\PokeLLMon\poke_env\player\battle_order.py
from dataclasses import dataclass
from typing import Any, List, Optional, Union
@dataclass
class BattleOrder:
order: Optional[Union[Move, Pokemon]]
mega: bool = False
z_move: bool = False
dynamax: bool = False
terastallize: bool = False
move_target: int = DoubleBattle.EMPTY_TARGET_POSITION
DEFAULT_ORDER = "/choose default"
def __str__(self) -> str:
return self.message
@property
def message(self) -> str:
if isinstance(self.order, Move):
if self.order.id == "recharge":
return "/choose move 1"
message = f"/choose move {self.order.id}"
if self.mega:
message += " mega"
elif self.z_move:
message += " zmove"
elif self.dynamax:
message += " dynamax"
elif self.terastallize:
message += " terastallize"
if self.move_target != DoubleBattle.EMPTY_TARGET_POSITION:
message += f" {self.move_target}"
return message
elif isinstance(self.order, Pokemon):
return f"/choose switch {self.order.species}"
else:
return ""
class DefaultBattleOrder(BattleOrder):
def __init__(self, *args: Any, **kwargs: Any):
pass
@property
def message(self) -> str:
return self.DEFAULT_ORDER
@dataclass
class DoubleBattleOrder(BattleOrder):
def __init__(
self,
first_order: Optional[BattleOrder] = None,
second_order: Optional[BattleOrder] = None,
):
self.first_order = first_order
self.second_order = second_order
@property
def message(self) -> str:
if self.first_order and self.second_order:
return (
self.first_order.message
+ ", "
+ self.second_order.message.replace("/choose ", "")
)
elif self.first_order:
return self.first_order.message + ", default"
elif self.second_order:
return self.second_order.message + ", default"
else:
return self.DEFAULT_ORDER
@staticmethod
def join_orders(first_orders: List[BattleOrder], second_orders: List[BattleOrder]):
if first_orders and second_orders:
orders = [
DoubleBattleOrder(first_order=first_order, second_order=second_order)
for first_order in first_orders
for second_order in second_orders
if not first_order.mega or not second_order.mega
if not first_order.z_move or not second_order.z_move
if not first_order.dynamax or not second_order.dynamax
if not first_order.terastallize or not second_order.terastallize
if first_order.order != second_order.order
]
if orders:
return orders
elif first_orders:
return [DoubleBattleOrder(first_order=order) for order in first_orders]
elif second_orders:
return [DoubleBattleOrder(first_order=order) for order in second_orders]
return [DefaultBattleOrder()]
class ForfeitBattleOrder(BattleOrder):
def __init__(self, *args: Any, **kwargs: Any):
pass
@property
def message(self) -> str:
return "/forfeit"
.\PokeLLMon\poke_env\player\gpt_player.py
import json
import os
import random
from typing import List
from poke_env.environment.abstract_battle import AbstractBattle
from poke_env.environment.double_battle import DoubleBattle
from poke_env.environment.move_category import MoveCategory
from poke_env.environment.pokemon import Pokemon
from poke_env.environment.side_condition import SideCondition
from poke_env.player.player import Player, BattleOrder
from typing import Dict, List, Optional, Union
from poke_env.environment.move import Move
import time
import json
from openai import OpenAI
from poke_env.data.gen_data import GenData
def calculate_move_type_damage_multipier(type_1, type_2, type_chart, constraint_type_list):
TYPE_list = 'BUG,DARK,DRAGON,ELECTRIC,FAIRY,FIGHTING,FIRE,FLYING,GHOST,GRASS,GROUND,ICE,NORMAL,POISON,PSYCHIC,ROCK,STEEL,WATER'.split(",")
move_type_damage_multiplier_list = []
if type_2:
for type in TYPE_list:
move_type_damage_multiplier_list.append(type_chart[type_1][type] * type_chart[type_2][type])
move_type_damage_multiplier_dict = dict(zip(TYPE_list, move_type_damage_multiplier_list))
else:
move_type_damage_multiplier_dict = type_chart[type_1]
effective_type_list = []
extreme_type_list = []
resistant_type_list = []
extreme_resistant_type_list = []
immune_type_list = []
for type, value in move_type_damage_multiplier_dict.items():
if value == 2:
effective_type_list.append(type)
elif value == 4:
extreme_type_list.append(type)
elif value == 1 / 2:
resistant_type_list.append(type)
elif value == 1 / 4:
extreme_resistant_type_list.append(type)
elif value == 0:
immune_type_list.append(type)
else:
continue
if constraint_type_list:
extreme_type_list = list(set(extreme_type_list).intersection(set(constraint_type_list)))
effective_type_list = list(set(effective_type_list).intersection(set(constraint_type_list)))
resistant_type_list = list(set(resistant_type_list).intersection(set(constraint_type_list)))
extreme_resistant_type_list = list(set(extreme_resistant_type_list).intersection(set(constraint_type_list)))
immune_type_list = list(set(immune_type_list).intersection(set(constraint_type_list)))
return (list(map(lambda x: x.capitalize(), extreme_type_list)),
list(map(lambda x: x.capitalize(), effective_type_list)),
list(map(lambda x: x.capitalize(), resistant_type_list)),
list(map(lambda x: x.capitalize(), extreme_resistant_type_list)),
list(map(lambda x: x.capitalize(), immune_type_list)))
def move_type_damage_wraper(pokemon, type_chart, constraint_type_list=None):
type_1 = None
type_2 = None
if pokemon.type_1:
type_1 = pokemon.type_1.name
if pokemon.type_2:
type_2 = pokemon.type_2.name
move_type_damage_prompt = ""
extreme_effective_type_list, effective_type_list, resistant_type_list, extreme_resistant_type_list, immune_type_list = calculate_move_type_damage_multipier(
type_1, type_2, type_chart, constraint_type_list)
if extreme_effective_type_list:
move_type_damage_prompt = (move_type_damage_prompt + " " + ", ".join(extreme_effective_type_list) +
f"-type attack is extremely-effective (4x damage) to {pokemon.species}.")
if effective_type_list:
move_type_damage_prompt = (move_type_damage_prompt + " " + ", ".join(effective_type_list) +
f"-type attack is super-effective (2x damage) to {pokemon.species}.")
if resistant_type_list:
move_type_damage_prompt = (move_type_damage_prompt + " " + ", ".join(resistant_type_list) +
f"-type attack is ineffective (0.5x damage) to {pokemon.species}.")
if extreme_resistant_type_list:
move_type_damage_prompt = (move_type_damage_prompt + " " + ", ".join(extreme_resistant_type_list) +
f"-type attack is highly ineffective (0.25x damage) to {pokemon.species}.")
if immune_type_list:
move_type_damage_prompt = (move_type_damage_prompt + " " + ", ".join(immune_type_list) +
f"-type attack is zero effect (0x damage) to {pokemon.species}.")
return move_type_damage_prompt
class LLMPlayer(Player):
def chatgpt(self, system_prompt, user_prompt, model, temperature=0.7, json_format=False, seed=None, stop=[], max_tokens=200) -> str:
client = OpenAI(api_key=self.api_key)
if json_format:
response = client.chat.completions.create(
response_format={"type": "json_object"},
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=temperature,
stream=False,
stop=stop,
max_tokens=max_tokens
)
else:
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=temperature,
stream=False,
max_tokens=max_tokens,
stop=stop
)
outputs = response.choices[0].message.content
self.completion_tokens += response.usage.completion_tokens
self.prompt_tokens += response.usage.prompt_tokens
return outputs
def _estimate_matchup(self, mon: Pokemon, opponent: Pokemon):
score = max([opponent.damage_multiplier(t) for t in mon.types if t is not None])
score -= max(
[mon.damage_multiplier(t) for t in opponent.types if t is not None]
)
if mon.base_stats["spe"] > opponent.base_stats["spe"]:
score += self.SPEED_TIER_COEFICIENT
elif opponent.base_stats["spe"] > mon.base_stats["spe"]:
score -= self.SPEED_TIER_COEFICIENT
score += mon.current_hp_fraction * self.HP_FRACTION_COEFICIENT
score -= opponent.current_hp_fraction * self.HP_FRACTION_COEFICIENT
return score
def _should_dynamax(self, battle: AbstractBattle):
n_remaining_mons = len(
[m for m in battle.team.values() if m.fainted is False]
)
if battle.can_dynamax and self._dynamax_disable is False:
if (
len([m for m in battle.team.values() if m.current_hp_fraction == 1])
== 1
and battle.active_pokemon.current_hp_fraction == 1
):
return True
if (
self._estimate_matchup(
battle.active_pokemon, battle.opponent_active_pokemon
)
> 0
and battle.active_pokemon.current_hp_fraction == 1
and battle.opponent_active_pokemon.current_hp_fraction == 1
):
return True
if n_remaining_mons == 1:
return True
return False
json_start = llm_output.find('{')
json_end = llm_output.rfind('}') + 1
json_content = llm_output[json_start:json_end]
llm_action_json = json.loads(json_content)
next_action = None
if "move" in llm_action_json.keys():
llm_move_id = llm_action_json["move"]
llm_move_id = llm_move_id.replace(" ","").replace("-", "")
for i, move in enumerate(battle.available_moves):
if move.id.lower() == llm_move_id.lower():
next_action = self.create_order(move, dynamax=self._should_dynamax(battle))
elif "switch" in llm_action_json.keys():
llm_switch_species = llm_action_json["switch"]
for i, pokemon in enumerate(battle.available_switches):
if pokemon.species.lower() == llm_switch_species.lower():
next_action = self.create_order(pokemon)
if next_action is None:
raise ValueError("Value Error")
return next_action
json_start = llm_output.find('{')
json_end = llm_output.rfind('}') + 1
json_content = llm_output[json_start:json_end]
llm_action_json = json.loads(json_content)
next_action = None
action = llm_action_json["decision"]["action"]
target = llm_action_json["decision"]["target"]
target = target.replace(" ", "").replace("_", "")
if action.lower() == "move":
for i, move in enumerate(battle.available_moves):
if move.id.lower() == target.lower():
next_action = self.create_order(move, dynamax=self._should_dynamax(battle))
elif action.lower() == "switch":
for i, pokemon in enumerate(battle.available_switches):
if pokemon.species.lower() == target.lower():
next_action = self.create_order(pokemon)
if next_action is None:
raise ValueError("Value Error")
return next_action
def check_status(self, status):
if status:
if status.value == 1:
return "burnt"
elif status.value == 2:
return "fainted"
elif status.value == 3:
return "frozen"
elif status.value == 4:
return "paralyzed"
elif status.value == 5:
return "poisoned"
elif status.value == 7:
return "toxic"
elif status.value == 6:
return "sleeping"
else:
return ""
def boost_multiplier(self, state, level):
if state == "accuracy":
if level == 0:
return 1.0
if level == 1:
return 1.33
if level == 2:
return 1.66
if level == 3:
return 2.0
if level == 4:
return 2.5
if level == 5:
return 2.66
if level == 6:
return 3.0
if level == -1:
return 0.75
if level == -2:
return 0.6
if level == -3:
return 0.5
if level == -4:
return 0.43
if level == -5:
return 0.36
if level == -6:
return 0.33
else:
if level == 0:
return 1.0
if level == 1:
return 1.5
if level == 2:
return 2.0
if level == 3:
return 2.5
if level == 4:
return 3.0
if level == 5:
return 3.5
if level == 6:
return 4.0
if level == -1:
return 0.67
if level == -2:
return 0.5
if level == -3:
return 0.4
if level == -4:
return 0.33
if level == -5:
return 0.29
if level == -6:
return 0.25
def battle_summary(self):
beat_list = []
remain_list = []
win_list = []
tag_list = []
for tag, battle in self.battles.items():
beat_score = 0
for mon in battle.opponent_team.values():
beat_score += (1-mon.current_hp_fraction)
beat_list.append(beat_score)
remain_score = 0
for mon in battle.team.values():
remain_score += mon.current_hp_fraction
remain_list.append(remain_score)
if battle.won:
win_list.append(1)
tag_list.append(tag)
return beat_list, remain_list, win_list, tag_list
def reward_computing_helper(
self,
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."""
if battle not in self._reward_buffer:
self._reward_buffer[battle] = starting_value
current_value = 0
for mon in battle.team.values():
current_value += mon.current_hp_fraction * hp_value
if mon.fainted:
current_value -= fainted_value
elif mon.status is not None:
current_value -= status_value
current_value += (number_of_pokemons - len(battle.team)) * hp_value
for mon in battle.opponent_team.values():
current_value -= mon.current_hp_fraction * hp_value
if mon.fainted:
current_value += fainted_value
elif mon.status is not None:
current_value += status_value
current_value -= (number_of_pokemons - len(battle.opponent_team)) * hp_value
if battle.won:
current_value += victory_value
elif battle.lost:
current_value -= victory_value
to_return = current_value - self._reward_buffer[battle]
self._reward_buffer[battle] = current_value
return to_return
def choose_max_damage_move(self, battle: AbstractBattle):
if battle.available_moves:
best_move = max(battle.available_moves, key=lambda move: move.base_power)
return self.create_order(best_move)
return self.choose_random_move(battle)
.\PokeLLMon\poke_env\player\llama_player.py
from poke_env.player.gpt_player import LLMPlayer
from poke_env.environment.abstract_battle import AbstractBattle
import json
from peft import PeftModel
import transformers
import torch
from poke_env.player.player import BattleOrder
my_token = ""
IGNORE_INDEX = -100
DEFAULT_PAD_TOKEN = "[PAD]"
DEFAULT_EOS_TOKEN = "</s>"
DEFAULT_BOS_TOKEN = "<s>"
DEFAULT_UNK_TOKEN = "<unk>"
class LLAMAPlayer(LLMPlayer):
def __init__(self, battle_format,
model_name_or_path: str = "",
lora_weights: str = "",
model_max_length: int = 2048,
w_reason = False,
log_dir = "",
account_configuration=None,
server_configuration=None,
):
super().__init__(battle_format=battle_format,
account_configuration=account_configuration,
server_configuration=server_configuration)
self.except_cnt = 0
self.total_cnt = 0
self.log_dir = log_dir
self.w_reason = w_reason
self.last_output = None
self.last_state_prompt = None
assert (model_name_or_path), "Please specify the model path"
self.tokenizer = transformers.AutoTokenizer.from_pretrained(
model_name_or_path,
model_max_length=model_max_length,
padding_side="right",
use_fast=False,
use_auth_token=my_token
)
self.model = transformers.AutoModelForCausalLM.from_pretrained(
model_name_or_path,
load_in_8bit=False,
torch_dtype=torch.float16,
device_map="auto",
use_auth_token=my_token
)
if lora_weights:
print("Recover LoRA weights..")
self.model = PeftModel.from_pretrained(
self.model,
lora_weights,
torch_dtype=torch.float16,
)
print("Loading finished...")
self.model.eval()
.\PokeLLMon\poke_env\player\openai_api.py
"""This module defines a player class with the OpenAI API on the main thread.
For a black-box implementation consider using the module env_player.
"""
from __future__ import annotations
import asyncio
import copy
import random
import time
from abc import ABC, abstractmethod
from logging import Logger
from typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, Tuple, Union
from gymnasium.core import ActType, Env, ObsType
from gymnasium.spaces import Discrete, Space
from poke_env.concurrency import POKE_LOOP, create_in_poke_loop
from poke_env.environment.abstract_battle import AbstractBattle
from poke_env.player.battle_order import BattleOrder, ForfeitBattleOrder
from poke_env.player.player import Player
from poke_env.ps_client import AccountConfiguration
from poke_env.ps_client.server_configuration import (
LocalhostServerConfiguration,
ServerConfiguration,
)
from poke_env.teambuilder.teambuilder import Teambuilder
class _AsyncQueue:
def __init__(self, queue: asyncio.Queue[Any]):
self.queue = queue
async def async_get(self):
return await self.queue.get()
def get(self):
res = asyncio.run_coroutine_threadsafe(self.queue.get(), POKE_LOOP)
return res.result()
async def async_put(self, item: Any):
await self.queue.put(item)
def put(self, item: Any):
task = asyncio.run_coroutine_threadsafe(self.queue.put(item), POKE_LOOP)
task.result()
def empty(self):
return self.queue.empty()
def join(self):
task = asyncio.run_coroutine_threadsafe(self.queue.join(), POKE_LOOP)
task.result()
async def async_join(self):
await self.queue.join()
class _AsyncPlayer(Generic[ObsType, ActType], Player):
actions: _AsyncQueue
observations: _AsyncQueue
def __init__(
self,
user_funcs: OpenAIGymEnv[ObsType, ActType],
username: str,
**kwargs: Any,
):
self.__class__.__name__ = username
super().__init__(**kwargs)
self.__class__.__name__ = "_AsyncPlayer"
self.observations = _AsyncQueue(create_in_poke_loop(asyncio.Queue, 1))
self.actions = _AsyncQueue(create_in_poke_loop(asyncio.Queue, 1))
self.current_battle: Optional[AbstractBattle] = None
def choose_move(self, battle: AbstractBattle) -> Awaitable[BattleOrder]:
return self._env_move(battle)
async def _env_move(self, battle: AbstractBattle) -> BattleOrder:
if not self.current_battle or self.current_battle.finished:
self.current_battle = battle
if not self.current_battle == battle:
raise RuntimeError("Using different battles for queues")
battle_to_send = self._user_funcs.embed_battle(battle)
await self.observations.async_put(battle_to_send)
action = await self.actions.async_get()
if action == -1:
return ForfeitBattleOrder()
return self._user_funcs.action_to_move(action, battle)
def _battle_finished_callback(self, battle: AbstractBattle):
to_put = self._user_funcs.embed_battle(battle)
asyncio.run_coroutine_threadsafe(self.observations.async_put(to_put), POKE_LOOP)
class _ABCMetaclass(type(ABC)):
pass
class _EnvMetaclass(type(Env)):
pass
class _OpenAIGymEnvMetaclass(_EnvMetaclass, _ABCMetaclass):
pass
class OpenAIGymEnv(
Env[ObsType, ActType],
ABC,
metaclass=_OpenAIGymEnvMetaclass,
):
"""
Base class implementing the OpenAI Gym API on the main thread.
"""
_INIT_RETRIES = 100
_TIME_BETWEEN_RETRIES = 0.5
_SWITCH_CHALLENGE_TASK_RETRIES = 30
_TIME_BETWEEN_SWITCH_RETIRES = 1
def __init__(
self,
account_configuration: Optional[AccountConfiguration] = None,
*,
avatar: Optional[int] = None,
battle_format: str = "gen8randombattle",
log_level: Optional[int] = None,
save_replays: Union[bool, str] = False,
server_configuration: Optional[
ServerConfiguration
] = LocalhostServerConfiguration,
start_timer_on_battle_start: bool = False,
start_listening: bool = True,
ping_interval: Optional[float] = 20.0,
ping_timeout: Optional[float] = 20.0,
team: Optional[Union[str, Teambuilder]] = None,
start_challenging: bool = False,
@abstractmethod
def calc_reward(
self, last_battle: AbstractBattle, current_battle: AbstractBattle
) -> float:
"""
Returns the reward for the current battle state. The battle state in the previous
turn is given as well and can be used for comparisons.
:param last_battle: The battle state in the previous turn.
:type last_battle: AbstractBattle
:param current_battle: The current battle state.
:type current_battle: AbstractBattle
:return: The reward for current_battle.
:rtype: float
"""
pass
@abstractmethod
def action_to_move(self, action: int, battle: AbstractBattle) -> BattleOrder:
"""
Returns the BattleOrder relative to the given action.
:param action: The action to take.
:type action: int
:param battle: The current battle state
:type battle: AbstractBattle
:return: The battle order for the given action in context of the current battle.
:rtype: BattleOrder
"""
pass
@abstractmethod
def embed_battle(self, battle: AbstractBattle) -> ObsType:
"""
Returns the embedding of the current battle state in a format compatible with
the OpenAI gym API.
:param battle: The current battle state.
:type battle: AbstractBattle
:return: The embedding of the current battle state.
"""
pass
@abstractmethod
def describe_embedding(self) -> Space[ObsType]:
"""
Returns the description of the embedding. It must return a Space specifying
low bounds and high bounds.
:return: The description of the embedding.
:rtype: Space
"""
pass
@abstractmethod
def action_space_size(self) -> int:
"""
Returns the size of the action space. Given size x, the action space goes
from 0 to x - 1.
:return: The action space size.
:rtype: int
"""
pass
@abstractmethod
def get_opponent(
self,
) -> Union[Player, str, List[Player], List[str]]:
"""
Returns the opponent (or list of opponents) that will be challenged
on the next iteration of the challenge loop. If a list is returned,
a random element will be chosen at random during the challenge loop.
:return: The opponent (or list of opponents).
:rtype: Player or str or list(Player) or list(str)
"""
pass
def _get_opponent(self) -> Union[Player, str]:
opponent = self.get_opponent()
random_opponent = (
random.choice(opponent) if isinstance(opponent, list) else opponent
)
return random_opponent
def reset(
self,
*,
seed: Optional[int] = None,
options: Optional[Dict[str, Any]] = None,
) -> Tuple[ObsType, Dict[str, Any]]:
if seed is not None:
super().reset(seed=seed)
self._seed_initialized = True
elif not self._seed_initialized:
super().reset(seed=int(time.time()))
self._seed_initialized = True
if not self.agent.current_battle:
count = self._INIT_RETRIES
while not self.agent.current_battle:
if count == 0:
raise RuntimeError("Agent is not challenging")
count -= 1
time.sleep(self._TIME_BETWEEN_RETRIES)
if self.current_battle and not self.current_battle.finished:
if self.current_battle == self.agent.current_battle:
self._actions.put(-1)
self._observations.get()
else:
raise RuntimeError(
"Environment and agent aren't synchronized. Try to restart"
)
while self.current_battle == self.agent.current_battle:
time.sleep(0.01)
self.current_battle = self.agent.current_battle
battle = copy.copy(self.current_battle)
battle.logger = None
self.last_battle = copy.deepcopy(battle)
return self._observations.get(), self.get_additional_info()
def get_additional_info(self) -> Dict[str, Any]:
"""
Returns additional info for the reset method.
Override only if you really need it.
:return: Additional information as a Dict
:rtype: Dict
"""
return {}
def step(
self, action: ActType
) -> Tuple[ObsType, float, bool, bool, Dict[str, Any]]:
"""
Execute the specified action in the environment.
:param ActType action: The action to be executed.
:return: A tuple containing the new observation, reward, termination flag, truncation flag, and info dictionary.
:rtype: Tuple[ObsType, float, bool, bool, Dict[str, Any]]
"""
if not self.current_battle:
obs, info = self.reset()
return obs, 0.0, False, False, info
if self.current_battle.finished:
raise RuntimeError("Battle is already finished, call reset")
battle = copy.copy(self.current_battle)
battle.logger = None
self.last_battle = copy.deepcopy(battle)
self._actions.put(action)
observation = self._observations.get()
reward = self.calc_reward(self.last_battle, self.current_battle)
terminated = False
truncated = False
if self.current_battle.finished:
size = self.current_battle.team_size
remaining_mons = size - len(
[mon for mon in self.current_battle.team.values() if mon.fainted]
)
remaining_opponent_mons = size - len(
[
mon
for mon in self.current_battle.opponent_team.values()
if mon.fainted
]
)
if (remaining_mons == 0) != (remaining_opponent_mons == 0):
terminated = True
else:
truncated = True
return observation, reward, terminated, truncated, self.get_additional_info()
def render(self, mode: str = "human"):
if self.current_battle is not None:
print(
" Turn %4d. | [%s][%3d/%3dhp] %10.10s - %10.10s [%3d%%hp][%s]"
% (
self.current_battle.turn,
"".join(
[
"⦻" if mon.fainted else "●"
for mon in self.current_battle.team.values()
]
),
self.current_battle.active_pokemon.current_hp or 0,
self.current_battle.active_pokemon.max_hp or 0,
self.current_battle.active_pokemon.species,
self.current_battle.opponent_active_pokemon.species,
self.current_battle.opponent_active_pokemon.current_hp or 0,
"".join(
[
"⦻" if mon.fainted else "●"
for mon in self.current_battle.opponent_team.values()
]
),
),
end="\n" if self.current_battle.finished else "\r",
)
def close(self, purge: bool = True):
if self.current_battle is None or self.current_battle.finished:
time.sleep(1)
if self.current_battle != self.agent.current_battle:
self.current_battle = self.agent.current_battle
closing_task = asyncio.run_coroutine_threadsafe(
self._stop_challenge_loop(purge=purge), POKE_LOOP
)
closing_task.result()
def background_send_challenge(self, username: str):
"""
Sends a single challenge to a specified player asynchronously. The function immediately returns
to allow use of the OpenAI gym API.
:param username: The username of the player to challenge.
:type username: str
"""
if self._challenge_task and not self._challenge_task.done():
raise RuntimeError(
"Agent is already challenging opponents with the challenging loop. "
"Try to specify 'start_challenging=True' during instantiation or call "
"'await agent.stop_challenge_loop()' to clear the task."
)
self._challenge_task = asyncio.run_coroutine_threadsafe(
self.agent.send_challenges(username, 1), POKE_LOOP
)
def background_accept_challenge(self, username: str):
"""
Accepts a single challenge from a specified player asynchronously. The function immediately returns
to allow use of the OpenAI gym API.
:param username: The username of the player to challenge.
:type username: str
"""
if self._challenge_task and not self._challenge_task.done():
raise RuntimeError(
"Agent is already challenging opponents with the challenging loop. "
"Try to specify 'start_challenging=True' during instantiation or call "
"'await agent.stop_challenge_loop()' to clear the task."
)
self._challenge_task = asyncio.run_coroutine_threadsafe(
self.agent.accept_challenges(username, 1, self.agent.next_team), POKE_LOOP
)
async def _challenge_loop(
self,
n_challenges: Optional[int] = None,
callback: Optional[Callable[[AbstractBattle], None]] = None,
):
if not n_challenges:
while self._keep_challenging:
opponent = self._get_opponent()
if isinstance(opponent, Player):
await self.agent.battle_against(opponent, 1)
else:
await self.agent.send_challenges(opponent, 1)
if callback and self.current_battle is not None:
callback(copy.deepcopy(self.current_battle))
elif n_challenges > 0:
for _ in range(n_challenges):
opponent = self._get_opponent()
if isinstance(opponent, Player):
await self.agent.battle_against(opponent, 1)
else:
await self.agent.send_challenges(opponent, 1)
if callback and self.current_battle is not None:
callback(copy.deepcopy(self.current_battle))
else:
raise ValueError(f"Number of challenges must be > 0. Got {n_challenges}")
def start_challenging(
self,
n_challenges: Optional[int] = None,
callback: Optional[Callable[[AbstractBattle], None]] = None,
):
"""
Starts the challenge loop.
:param n_challenges: The number of challenges to send. If empty it will run until
stopped.
:type n_challenges: int, optional
:param callback: The function to callback after each challenge with a copy of
the final battle state.
:type callback: Callable[[AbstractBattle], None], optional
"""
if self._challenge_task and not self._challenge_task.done():
count = self._SWITCH_CHALLENGE_TASK_RETRIES
while not self._challenge_task.done():
if count == 0:
raise RuntimeError("Agent is already challenging")
count -= 1
time.sleep(self._TIME_BETWEEN_SWITCH_RETIRES)
if not n_challenges:
self._keep_challenging = True
self._challenge_task = asyncio.run_coroutine_threadsafe(
self._challenge_loop(n_challenges, callback), POKE_LOOP
)
async def _ladder_loop(
self,
n_challenges: Optional[int] = None,
callback: Optional[Callable[[AbstractBattle], None]] = None,
):
if n_challenges:
if n_challenges <= 0:
raise ValueError(
f"Number of challenges must be > 0. Got {n_challenges}"
)
for _ in range(n_challenges):
await self.agent.ladder(1)
if callback and self.current_battle is not None:
callback(copy.deepcopy(self.current_battle))
else:
while self._keep_challenging:
await self.agent.ladder(1)
if callback and self.current_battle is not None:
callback(copy.deepcopy(self.current_battle))
def start_laddering(
self,
n_challenges: Optional[int] = None,
callback: Optional[Callable[[AbstractBattle], None]] = None,
):
"""
Starts the laddering loop.
:param n_challenges: The number of ladder games to play. If empty it
will run until stopped.
:type n_challenges: int, optional
:param callback: The function to callback after each challenge with a
copy of the final battle state.
:type callback: Callable[[AbstractBattle], None], optional
"""
if self._challenge_task and not self._challenge_task.done():
count = self._SWITCH_CHALLENGE_TASK_RETRIES
while not self._challenge_task.done():
if count == 0:
raise RuntimeError("Agent is already challenging")
count -= 1
time.sleep(self._TIME_BETWEEN_SWITCH_RETIRES)
if not n_challenges:
self._keep_challenging = True
self._challenge_task = asyncio.run_coroutine_threadsafe(
self._ladder_loop(n_challenges, callback), POKE_LOOP
)
async def _stop_challenge_loop(
self, force: bool = True, wait: bool = True, purge: bool = False
):
self._keep_challenging = False
if force:
if self.current_battle and not self.current_battle.finished:
if not self._actions.empty():
await asyncio.sleep(2)
if not self._actions.empty():
raise RuntimeError(
"The agent is still sending actions. "
"Use this method only when training or "
"evaluation are over."
)
if not self._observations.empty():
await self._observations.async_get()
await self._actions.async_put(-1)
if wait and self._challenge_task:
while not self._challenge_task.done():
await asyncio.sleep(1)
self._challenge_task.result()
self._challenge_task = None
self.current_battle = None
self.agent.current_battle = None
while not self._actions.empty():
await self._actions.async_get()
while not self._observations.empty():
await self._observations.async_get()
if purge:
self.agent.reset_battles()
def reset_battles(self):
"""Resets the player's inner battle tracker."""
self.agent.reset_battles()
def done(self, timeout: Optional[int] = None) -> bool:
"""
Returns True if the task is done or is done after the timeout, false otherwise.
:param timeout: The amount of time to wait for if the task is not already done.
If empty it will wait until the task is done.
:type timeout: int, optional
:return: True if the task is done or if the task gets completed after the
timeout.
:rtype: bool
"""
if self._challenge_task is None:
return True
if timeout is None:
self._challenge_task.result()
return True
if self._challenge_task.done():
return True
time.sleep(timeout)
return self._challenge_task.done()
@property
def battles(self) -> Dict[str, AbstractBattle]:
return self.agent.battles
@property
def format(self) -> str:
return self.agent.format
@property
def format_is_doubles(self) -> bool:
return self.agent.format_is_doubles
@property
def n_finished_battles(self) -> int:
return self.agent.n_finished_battles
@property
def n_lost_battles(self) -> int:
return self.agent.n_lost_battles
@property
def n_tied_battles(self) -> int:
return self.agent.n_tied_battles
@property
def n_won_battles(self) -> int:
return self.agent.n_won_battles
@property
def win_rate(self) -> float:
return self.agent.win_rate
@property
def logged_in(self) -> asyncio.Event:
"""Event object associated with user login.
:return: The logged-in event
:rtype: Event
"""
return self.agent.ps_client.logged_in
@property
def logger(self) -> Logger:
"""Logger associated with the player.
:return: The logger.
:rtype: Logger
"""
return self.agent.logger
@property
def username(self) -> str:
"""The player's username.
:return: The player's username.
:rtype: str
"""
return self.agent.username
@property
def websocket_url(self) -> str:
"""The websocket url.
It is derived from the server url.
:return: The websocket url.
:rtype: str
"""
return self.agent.ps_client.websocket_url
def __getattr__(self, item: str):
return getattr(self.agent, item)