Skip to content

Commit

Permalink
Code formatting/linting
Browse files Browse the repository at this point in the history
  • Loading branch information
40Cakes committed Nov 19, 2023
1 parent f40e3ce commit afaa223
Show file tree
Hide file tree
Showing 19 changed files with 322 additions and 297 deletions.
34 changes: 18 additions & 16 deletions modules/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@

# Defines which class attributes of the Config class are meant to hold required configuration data.
CONFIG_ATTRS = {
'catch_block',
'cheats',
'discord',
'general',
'keys',
'logging',
'obs',
"catch_block",
"cheats",
"discord",
"general",
"keys",
"logging",
"obs",
}


Expand All @@ -34,17 +34,19 @@ def __init__(self, config_dir: str | Path | None = None, is_profile: bool = Fals
:param is_profile: Whether profile files are expected in this directory.
:param strict: Whether to allow files to be missing.
"""
self.config_dir = get_base_path() / 'profiles' if not config_dir else Path(config_dir)
self.config_dir = get_base_path() / "profiles" if not config_dir else Path(config_dir)

self.catch_block: CatchBlock = CatchBlock()
self.cheats: Cheats = Cheats()
self.discord: Discord = Discord()
self.general: General = General()
self.is_profile = is_profile
self.keys: Keys = Keys()
self.loaded = False
self.logging: Logging = Logging()
self.metadata: ProfileMetadata | None = None
self.obs: OBS = OBS()

self.is_profile = is_profile
self.loaded = False
self.metadata: ProfileMetadata | None = None
self.load(strict=strict)

def load(self, config_dir: str | Path | None = None, strict: bool = True):
Expand Down Expand Up @@ -75,7 +77,7 @@ def save(self, config_dir: str | Path | None = None, strict: bool = True):
for attr in CONFIG_ATTRS:
self.save_file(attr, strict=strict)
if self.is_profile:
self.save_file('metadata', strict=strict)
self.save_file("metadata", strict=strict)

def reload_file(self, attr: str, strict: bool = False) -> None:
"""Reload a specific configuration file, using the same source.
Expand All @@ -86,7 +88,7 @@ def reload_file(self, attr: str, strict: bool = False) -> None:

config_inst = getattr(self, attr, None)
if not isinstance(config_inst, BaseConfig):
raise exceptions.PrettyValueError(f'Config.{attr} is not a valid configuration to load.')
raise exceptions.PrettyValueError(f"Config.{attr} is not a valid configuration to load.")
file_path = self.config_dir / config_inst.filename
config_inst = load_config_file(file_path, config_inst.__class__, strict=strict)
if config_inst:
Expand All @@ -101,7 +103,7 @@ def save_file(self, attr: str, strict: bool = False) -> None:

config_inst = getattr(self, attr, None)
if not isinstance(config_inst, BaseConfig):
raise exceptions.PrettyValueError(f'Config.{attr} is not a valid configuration to save.')
raise exceptions.PrettyValueError(f"Config.{attr} is not a valid configuration to save.")
save_config_file(self.config_dir, config_inst, strict=strict)


Expand Down Expand Up @@ -134,10 +136,10 @@ def save_config_file(config_dir: Path, config_inst: BaseConfig, strict: bool = F
raise exceptions.CriticalDirectoryMissing(config_dir)
config_dir.mkdir()
if not isinstance(config_inst, BaseConfig):
raise exceptions.PrettyValueError(f'The provided config is not a valid config instance.')
raise exceptions.PrettyValueError(f"The provided config is not a valid config instance.")
config_file = config_dir / config_inst.filename
if strict and config_file.is_file():
raise exceptions.PrettyValueError(f'The file {config_file} already exists. Refusing to overwrite it.')
raise exceptions.PrettyValueError(f"The file {config_file} already exists. Refusing to overwrite it.")
yaml = YAML()
yaml.allow_unicode = False
yaml.dump(config_inst.model_dump(), config_dir / config_inst.filename)
96 changes: 48 additions & 48 deletions modules/config/schemas_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,26 @@ class Starters(Enum):
class CatchBlock(BaseConfig):
"""Schema for the catch_block configuration."""

filename: ClassVar = 'catch_block.yml'
filename: ClassVar = "catch_block.yml"
block_list: list[str] = []


class Cheats(BaseConfig):
"""Schema for the cheat configuration."""

filename: ClassVar = 'cheats.yml'
filename: ClassVar = "cheats.yml"
starters: bool = False
starters_rng: bool = False


class Discord(BaseConfig):
"""Schema for the discord configuration."""

filename: ClassVar = 'discord.yml'
filename: ClassVar = "discord.yml"
rich_presence: bool = False
iv_format: Literal["basic", "formatted"] = 'formatted'
bot_id: str = 'PokéBot'
global_webhook_url: str = ''
iv_format: Literal["basic", "formatted"] = "formatted"
bot_id: str = "PokéBot"
global_webhook_url: str = ""
shiny_pokemon_encounter: DiscordWebhook = Field(default_factory=lambda: DiscordWebhook())
pokemon_encounter_milestones: DiscordWebhook = Field(default_factory=lambda: DiscordWebhook(interval=10000))
shiny_pokemon_encounter_milestones: DiscordWebhook = Field(default_factory=lambda: DiscordWebhook(interval=5))
Expand All @@ -62,64 +62,64 @@ class DiscordWebhook(BaseConfig):
first_interval: PositiveInt | None = 8192 # Only used by phase_summary.
consequent_interval: PositiveInt | None = 5000 # Only used by phase_summary.
interval: PositiveInt = 5
ping_mode: Literal['user', 'role', None] = None
ping_mode: Literal["user", "role", None] = None
ping_id: str | None = None


class General(BaseConfig):
"""Schema for the general configuration."""

filename: ClassVar = 'general.yml'
filename: ClassVar = "general.yml"
starter: Starters = Starters.MUDKIP


class Keys(BaseConfig):
"""Schema for the keys configuration."""

filename: ClassVar = 'keys.yml'
filename: ClassVar = "keys.yml"
gba: KeysGBA = Field(default_factory=lambda: KeysGBA())
emulator: KeysEmulator = Field(default_factory=lambda: KeysEmulator())


class KeysEmulator(BaseConfig):
"""Schema for the emulator keys section in the Keys config."""

zoom_in: str = 'plus'
zoom_out: str = 'minus'
toggle_manual: str = 'Tab'
toggle_video: str = 'v'
toggle_audio: str = 'b'
set_speed_1x: str = '1'
set_speed_2x: str = '2'
set_speed_3x: str = '3'
set_speed_4x: str = '4'
set_speed_unthrottled: str = '0'
reset: str = 'Ctrl+R'
reload_config: str = 'Ctrl+C'
exit: str = 'Ctrl+Q'
save_state: str = 'Ctrl+S'
toggle_stepping_mode: str = 'Ctrl+L'
zoom_in: str = "plus"
zoom_out: str = "minus"
toggle_manual: str = "Tab"
toggle_video: str = "v"
toggle_audio: str = "b"
set_speed_1x: str = "1"
set_speed_2x: str = "2"
set_speed_3x: str = "3"
set_speed_4x: str = "4"
set_speed_unthrottled: str = "0"
reset: str = "Ctrl+R"
reload_config: str = "Ctrl+C"
exit: str = "Ctrl+Q"
save_state: str = "Ctrl+S"
toggle_stepping_mode: str = "Ctrl+L"


class KeysGBA(BaseConfig):
"""Schema for the GBA keys section in the Keys config."""

Up: str = 'Up'
Down: str = 'Down'
Left: str = 'Left'
Right: str = 'Right'
A: str = 'x'
B: str = 'z'
L: str = 'a'
R: str = 's'
Start: str = 'Return'
Select: str = 'BackSpace'
Up: str = "Up"
Down: str = "Down"
Left: str = "Left"
Right: str = "Right"
A: str = "x"
B: str = "z"
L: str = "a"
R: str = "s"
Start: str = "Return"
Select: str = "BackSpace"


class Logging(BaseConfig):
"""Schema for the logging configuration."""

filename: ClassVar = 'logging.yml'
filename: ClassVar = "logging.yml"
console: LoggingConsole = Field(default_factory=lambda: LoggingConsole())
save_pk3: LoggingSavePK3 = Field(default_factory=lambda: LoggingSavePK3())
import_pk3: bool = False
Expand All @@ -129,10 +129,10 @@ class Logging(BaseConfig):
class LoggingConsole(BaseConfig):
"""Schema for the console section in the Logging config."""

encounter_data: Literal["verbose", "basic", "disable"] = 'verbose'
encounter_ivs: Literal["verbose", "basic", "disable"] = 'verbose'
encounter_moves: Literal["verbose", "basic", "disable"] = 'disable'
statistics: Literal["verbose", "basic", "disable"] = 'verbose'
encounter_data: Literal["verbose", "basic", "disable"] = "verbose"
encounter_ivs: Literal["verbose", "basic", "disable"] = "verbose"
encounter_moves: Literal["verbose", "basic", "disable"] = "disable"
statistics: Literal["verbose", "basic", "disable"] = "verbose"


class LoggingSavePK3(BaseConfig):
Expand All @@ -146,7 +146,7 @@ class LoggingSavePK3(BaseConfig):
class OBS(BaseConfig):
"""Schema for the OBS configuration."""

filename: ClassVar = 'obs.yml'
filename: ClassVar = "obs.yml"
discord_delay: NonNegativeInt = 0
discord_webhook_url: str | None = None
replay_dir: Path = "./stream/replays/"
Expand All @@ -157,7 +157,7 @@ class OBS(BaseConfig):
obs_websocket: OBSWebsocket = Field(default_factory=lambda: OBSWebsocket())
http_server: OBSHTTPServer = Field(default_factory=lambda: OBSHTTPServer())

@field_validator('replay_dir')
@field_validator("replay_dir")
def validate_dir(cls, value: str | Path, **kwargs) -> Path:
"""Ensure the replay_dir field returns a path."""
if isinstance(value, str):
Expand All @@ -170,31 +170,31 @@ def validate_dir(cls, value: str | Path, **kwargs) -> Path:
class OBSWebsocket(BaseConfig):
"""Schema for the obs_websocket section in the OBS config."""

host: str = '127.0.0.1'
password: str = 'password'
host: str = "127.0.0.1"
password: str = "password"
port: Annotated[int, Field(gt=0, lt=65536)] = 4455


class OBSHTTPServer(BaseConfig):
"""Schema for the http_server section in the OBS config."""

enable: bool = False
ip: str = '127.0.0.1'
ip: str = "127.0.0.1"
port: Annotated[int, Field(gt=0, lt=65536)] = 8888


class ProfileMetadata(BaseConfig):
"""Schema for the metadata configuration file part of profiles."""

filename: ClassVar = 'metadata.yml'
filename: ClassVar = "metadata.yml"
version: PositiveInt = 1
rom: ProfileMetadataROM = Field(default_factory=lambda: ProfileMetadataROM())


class ProfileMetadataROM(BaseConfig):
"""Schema for the rom section of the metadata config."""

file_name: str = ''
game_code: str = ''
file_name: str = ""
game_code: str = ""
revision: NonNegativeInt = 0
language: Literal['E', 'F', 'D', 'I', 'J', 'S'] = ''
language: Literal["E", "F", "D", "I", "J", "S"] = ""
36 changes: 23 additions & 13 deletions modules/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ def sv_colour(value: int) -> str:


def print_stats(total_stats: dict, pokemon: Pokemon, session_pokemon: list, encounter_rate: int) -> None:

type_colour = pokemon.species.types[0].name.lower()
rich_name = f"[{type_colour}]{pokemon.species.name}[/]"
console.print("\n")
Expand Down Expand Up @@ -182,8 +181,10 @@ def print_stats(total_stats: dict, pokemon: Pokemon, session_pokemon: list, enco
for p in sorted(set(session_pokemon)):
stats_table.add_row(
p,
f"[red]{total_stats['pokemon'][p].get('phase_lowest_iv_sum', -1)}[/] / [green]{total_stats['pokemon'][p].get('phase_highest_iv_sum', -1)}",
f"[green]{total_stats['pokemon'][p].get('phase_lowest_sv', -1):,}[/] / [{sv_colour(total_stats['pokemon'][p].get('phase_highest_sv', -1))}]{total_stats['pokemon'][p].get('phase_highest_sv', -1):,}",
f"[red]{total_stats['pokemon'][p].get('phase_lowest_iv_sum', -1)}[/] /"
f" [green]{total_stats['pokemon'][p].get('phase_highest_iv_sum', -1)}",
f"[green]{total_stats['pokemon'][p].get('phase_lowest_sv', -1):,}[/] /"
f" [{sv_colour(total_stats['pokemon'][p].get('phase_highest_sv', -1))}]{total_stats['pokemon'][p].get('phase_highest_sv', -1):,}",
f"{total_stats['pokemon'][p].get('phase_encounters', 0):,}",
f"{(total_stats['pokemon'][p].get('phase_encounters', 0) / total_stats['totals'].get('phase_encounters', 0)) * 100:0.2f}%",
f"{total_stats['pokemon'][p].get('shiny_encounters', 0):,}",
Expand All @@ -192,8 +193,10 @@ def print_stats(total_stats: dict, pokemon: Pokemon, session_pokemon: list, enco
)
stats_table.add_row(
"[bold yellow]Total",
f"[red]{total_stats['totals'].get('phase_lowest_iv_sum', -1)}[/] / [green]{total_stats['totals'].get('phase_highest_iv_sum', -1)}",
f"[green]{total_stats['totals'].get('phase_lowest_sv', -1):,}[/] / [{sv_colour(total_stats['totals'].get('phase_highest_sv', -1))}]{total_stats['totals'].get('phase_highest_sv', -1):,}",
f"[red]{total_stats['totals'].get('phase_lowest_iv_sum', -1)}[/] /"
f" [green]{total_stats['totals'].get('phase_highest_iv_sum', -1)}",
f"[green]{total_stats['totals'].get('phase_lowest_sv', -1):,}[/] /"
f" [{sv_colour(total_stats['totals'].get('phase_highest_sv', -1))}]{total_stats['totals'].get('phase_highest_sv', -1):,}",
f"[bold yellow]{total_stats['totals'].get('phase_encounters', 0):,}",
"[bold yellow]100%",
f"[bold yellow]{total_stats['totals'].get('shiny_encounters', 0):,}",
Expand All @@ -203,19 +206,26 @@ def print_stats(total_stats: dict, pokemon: Pokemon, session_pokemon: list, enco
console.print(stats_table)
case "basic":
console.print(
f"{rich_name} Phase Encounters: {total_stats['pokemon'][pokemon.species.name].get('phase_encounters', 0):,} | "
f"{rich_name} Total Encounters: {total_stats['pokemon'][pokemon.species.name].get('encounters', 0):,} | "
f"{rich_name} Shiny Encounters: {total_stats['pokemon'][pokemon.species.name].get('shiny_encounters', 0):,}"
f"{rich_name} Phase Encounters:"
f" {total_stats['pokemon'][pokemon.species.name].get('phase_encounters', 0):,} | {rich_name} Total"
f" Encounters: {total_stats['pokemon'][pokemon.species.name].get('encounters', 0):,} |"
f" {rich_name} Shiny Encounters:"
f" {total_stats['pokemon'][pokemon.species.name].get('shiny_encounters', 0):,}"
)
console.print(
f"{rich_name} Phase IV Records [red]{total_stats['pokemon'][pokemon.species.name].get('phase_lowest_iv_sum', -1)}[/]/[green]{total_stats['pokemon'][pokemon.species.name].get('phase_highest_iv_sum', -1)}[/] | "
f"{rich_name} Phase SV Records [green]{total_stats['pokemon'][pokemon.species.name].get('phase_lowest_sv', -1):,}[/]/[{sv_colour(total_stats['pokemon'][pokemon.species.name].get('phase_highest_sv', -1))}]{total_stats['pokemon'][pokemon.species.name].get('phase_highest_sv', -1):,}[/] | "
f"{rich_name} Shiny Average: {total_stats['pokemon'][pokemon.species.name].get('shiny_average', 'N/A')}"
f"{rich_name} Phase IV Records"
f" [red]{total_stats['pokemon'][pokemon.species.name].get('phase_lowest_iv_sum', -1)}[/]/[green]{total_stats['pokemon'][pokemon.species.name].get('phase_highest_iv_sum', -1)}[/]"
f" | {rich_name} Phase SV Records"
f" [green]{total_stats['pokemon'][pokemon.species.name].get('phase_lowest_sv', -1):,}[/]/[{sv_colour(total_stats['pokemon'][pokemon.species.name].get('phase_highest_sv', -1))}]{total_stats['pokemon'][pokemon.species.name].get('phase_highest_sv', -1):,}[/]"
f" | {rich_name} Shiny Average:"
f" {total_stats['pokemon'][pokemon.species.name].get('shiny_average', 'N/A')}"
)
console.print(
f"Phase Encounters: {total_stats['totals'].get('phase_encounters', 0):,} | "
f"Phase IV Records [red]{total_stats['totals'].get('phase_lowest_iv_sum', -1)}[/]/[green]{total_stats['totals'].get('phase_highest_iv_sum', -1)}[/] | "
f"Phase SV Records [green]{total_stats['totals'].get('phase_lowest_sv', -1):,}[/]/[{sv_colour(total_stats['totals'].get('phase_highest_sv', -1))}]{total_stats['totals'].get('phase_highest_sv', -1):,}[/]"
"Phase IV Records"
f" [red]{total_stats['totals'].get('phase_lowest_iv_sum', -1)}[/]/[green]{total_stats['totals'].get('phase_highest_iv_sum', -1)}[/] | "
"Phase SV Records"
f" [green]{total_stats['totals'].get('phase_lowest_sv', -1):,}[/]/[{sv_colour(total_stats['totals'].get('phase_highest_sv', -1))}]{total_stats['totals'].get('phase_highest_sv', -1):,}[/]"
)
console.print(
f"Total Shinies: {total_stats['totals'].get('shiny_encounters', 0):,} | "
Expand Down
14 changes: 7 additions & 7 deletions modules/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@


class BotContext:
def __init__(self, initial_bot_mode: str = 'Manual'):
def __init__(self, initial_bot_mode: str = "Manual"):
self.config = Config()

self.emulator: Optional["LibmgbaEmulator"] = None
self.gui: Optional["PokebotGui"] = None
self.profile: Optional["Profile"] = None
self.debug: bool = False

self._current_message: str = ''
self._current_message: str = ""

self._current_bot_mode: str = initial_bot_mode
self._previous_bot_mode: str = 'Manual'
self._previous_bot_mode: str = "Manual"

def reload_config(self) -> str:
"""Triggers a config reload, reload the global config then specific profile config.
Expand All @@ -32,14 +32,14 @@ def reload_config(self) -> str:
new_config = Config()
new_config.load(self.config.config_dir, strict=False)
self.config = new_config
message = '[cyan]Profile settings loaded.[/]'
message = "[cyan]Profile settings loaded.[/]"
except Exception as error:
if self.debug:
raise error
message = (
'[bold red]The configuration could not be loaded, no changes have been made.[/]\n'
'[bold yellow]This is Probably due to a malformed file.'
'For more information run the bot with the --debug flag.[/]'
"[bold red]The configuration could not be loaded, no changes have been made.[/]\n"
"[bold yellow]This is Probably due to a malformed file."
"For more information run the bot with the --debug flag.[/]"
)
return message

Expand Down
Loading

0 comments on commit afaa223

Please sign in to comment.