Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions src/Ankimon/functions/LegendaryCatchingFunction.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,3 @@ def get_catchable_pokemon(self, caught_pokemon):
if self.can_catch(caught_pokemon, pokemon):
catchable.add(pokemon)
return catchable


# Example usage
caught = {151, 243, 244, 245} # Already caught Mew, Raikou, Entei, Suicune
catching = LegendaryCatching()

print("Catchable Pokémon:", catching.get_catchable_pokemon(caught))
7 changes: 4 additions & 3 deletions src/Ankimon/functions/battle_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from ..poke_engine import constants
from ..resources import move_names_file_path
from ..pyobj.error_handler import show_warning_with_traceback
from aqt import mw

with open(move_names_file_path, "r", encoding="utf-8") as f:
MOVE_NAME_LOOKUP = json.load(f)
Expand Down Expand Up @@ -117,7 +118,7 @@ def update_pokemon_battle_status(battle_info: dict, enemy_pokemon, main_pokemon)
from ..pyobj.error_handler import show_warning_with_traceback
show_warning_with_traceback(e, "Failed to update pokemon battle status")
except ImportError:
print(f"ERROR in update_pokemon_battle_status: {e}")
mw.logger.log("error", f"ERROR in update_pokemon_battle_status: {e}")
return False, False


Expand Down Expand Up @@ -154,7 +155,7 @@ def safe_translate(key: str, **kwargs) -> str:
if result and result.strip():
return result
except (KeyError, AttributeError, Exception) as e:
print(f"Translation error for key '{key}': {e}")
mw.logger.log("error", f"Translation error for key '{key}': {e}")

if 'pokemon_name' in kwargs and 'status_name' in kwargs:
if 'apply' in key or 'still' in key:
Expand Down Expand Up @@ -486,7 +487,7 @@ def check_persistent_effects():
effect_messages.append(message)

except Exception as e:
print(f"Error processing state change {change}: {e}")
mw.logger.log("error", f"Error processing state change {change}: {e}")
effect_messages.append(f"Battle effect occurred (processing error)")
continue

Expand Down
4 changes: 2 additions & 2 deletions src/Ankimon/functions/pokedex_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,9 +563,9 @@ def check_key_in_table(column_name, value, file_path):
break # Exit the loop once the matching row is found

except FileNotFoundError:
print(f"Error: The file {file_path} does not exist.")
mw.logger.log("error", f"Error: The file {file_path} does not exist.")
except Exception as e:
print(f"Error: {e}")
mw.logger.log("error", f"Error: {e}")

# Return the matching row or None if no match is found
return matching_row
Expand Down
3 changes: 2 additions & 1 deletion src/Ankimon/functions/sprite_functions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from ..resources import pkmnimgfolder
import os
from aqt import mw

def get_sprite_path(side: str, sprite_type: str, id: int=132, shiny: bool=False, gender: str="M"):
"""Return the path to the sprite of the Pokémon with robust fallbacks."""
Expand Down Expand Up @@ -30,5 +31,5 @@ def get_sprite_path(side: str, sprite_type: str, id: int=132, shiny: bool=False,
return path

# 5. Fallback to the generic substitute image
print(f"Unable to find sprite for ID {id} (Shiny: {shiny}, Gender: {gender}). Returning substitute.")
mw.logger.log("warning", f"Unable to find sprite for ID {id} (Shiny: {shiny}, Gender: {gender}). Returning substitute.")
return default_path
3 changes: 2 additions & 1 deletion src/Ankimon/functions/trainer_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .pokemon_functions import find_experience_for_level
from .pokedex_functions import check_evolution_for_pokemon, return_name_for_id
from aqt.utils import showInfo, showWarning
from aqt import mw

def find_trainer_rank(highest_level, trainer_level):
"""
Expand Down Expand Up @@ -59,7 +60,7 @@ def find_trainer_rank(highest_level, trainer_level):
return rank

except FileNotFoundError:
print("Error: One of the files (Pokedex or MyPokemon) could not be found.")
mw.logger.log("error", "Error: One of the files (Pokedex or MyPokemon) could not be found.")
return "Unknown Rank"

def xp_share_gain_exp(logger, settings_obj, evo_window, main_pokemon_id, exp, xp_share_individual_id):
Expand Down
5 changes: 3 additions & 2 deletions src/Ankimon/poke_engine/ankimon_hooks_to_poke_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from .helpers import normalize_name
from .find_state_instructions import get_all_state_instructions
from ..pyobj.error_handler import show_warning_with_traceback
from aqt import mw

def reset_stat_boosts(pokemon: Pokemon) -> Pokemon:
"""
Expand Down Expand Up @@ -302,7 +303,7 @@ def simulate_battle_with_poke_engine(
'state': new_state
}

print(f"{unlucky_life * 100}% chance: {battle_effects}")
mw.logger.log("info", f"{unlucky_life * 100}% chance: {battle_effects}")
return battle_info, new_state, dmg_from_enemy_move, dmg_from_user_move, mutator_full_reset, battle_info_changes

except Exception as e:
Expand Down Expand Up @@ -443,5 +444,5 @@ def print_state_changes(changes):
key = change['key']
before = change['before']
after = change['after']
print(f"{key}: {before} -> {after}")
mw.logger.log("info", f"{key}: {before} -> {after}")

5 changes: 4 additions & 1 deletion src/Ankimon/poke_engine/data/scripts/update_moves.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import json
import copy
import subprocess
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


"""
Expand Down Expand Up @@ -39,7 +42,7 @@

# exit if stderr is not empty
if stderr:
print("Something went wrong? stderr: {}".format(stderr))
logging.error("Something went wrong? stderr: {}".format(stderr))

# add a console log to the .js file. This will error if the file doesn't exist
with open("/tmp/moves.js", "a") as f:
Expand Down
17 changes: 5 additions & 12 deletions src/Ankimon/pokedex/pokedex_obj.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,9 @@ def __init__(self, addon_dir, ankimon_tracker):
def load_html(self):
self.ankimon_tracker.get_ids_in_collection()
self.owned_pokemon_ids = self.ankimon_tracker.owned_pokemon_ids
#print("POKEDEX_DEBUG: Caught Pokémon IDs:", self.owned_pokemon_ids)

# Convert caught IDs to string
str_owned_pokemon_ids = ",".join(map(str, self.owned_pokemon_ids)) if self.owned_pokemon_ids else ""
#print("POKEDEX_DEBUG: Caught IDs string:", str_owned_pokemon_ids)

# Calculate defeated Pokémon count
defeated_count = 0
Expand All @@ -63,36 +61,31 @@ def load_html(self):
try:
with open(mypokemon_path, "r", encoding="utf-8") as file:
pokemon_list = json.load(file)
print("POKEDEX_DEBUG: Loaded pokemon_list!")
mw.logger.log("info", "POKEDEX_DEBUG: Loaded pokemon_list!")

except json.JSONDecodeError:
print("POKEDEX_DEBUG: Invalid JSON in mypokemon.json at", mypokemon_path)
mw.logger.log("error", f"POKEDEX_DEBUG: Invalid JSON in mypokemon.json at {mypokemon_path}")
except Exception as e:
print("POKEDEX_DEBUG: Error reading mypokemon.json at", mypokemon_path, ":", str(e))
mw.logger.log("error", f"POKEDEX_DEBUG: Error reading mypokemon.json at {mypokemon_path}: {str(e)}")

if pokemon_list:
for pokemon in pokemon_list:
defeated = pokemon.get("pokemon_defeated", 0)
try:
defeated_num = int(float(str(defeated))) # Handle int, float, string
defeated_count += defeated_num
#print(f"POKEDEX_DEBUG: Pokemon ID {pokemon.get('id', 'unknown')}: pokemon_defeated = {defeated_num}")
except (TypeError, ValueError):
print(f"POKEDEX_DEBUG: Invalid pokemon_defeated for ID {pokemon.get('id', 'unknown')}: {defeated}")
mw.logger.log("warning", f"POKEDEX_DEBUG: Invalid pokemon_defeated for ID {pokemon.get('id', 'unknown')}: {defeated}")
else:
print("POKEDEX_DEBUG: No valid mypokemon.json found")

#print("POKEDEX_DEBUG: Total defeated_count =", defeated_count)
mw.logger.log("warning", "POKEDEX_DEBUG: No valid mypokemon.json found")

file_path = os.path.join(self.addon_dir, "pokedex", "pokedex.html").replace("\\", "/")
#print("POKEDEX_DEBUG: Loading HTML from:", file_path)
url = QUrl.fromLocalFile(file_path)

query = QUrlQuery()
query.addQueryItem("numbers", str_owned_pokemon_ids)
query.addQueryItem("defeated", str(defeated_count))
url.setQuery(query)
#print("POKEDEX_DEBUG: Final URL:", url.toString())

self.webview.setUrl(url)

Expand Down
6 changes: 3 additions & 3 deletions src/Ankimon/pyobj/collection_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ def PokemonTradeIn(number_code, old_pokemon_name, position):
"growth_rate": growth_rate,
}
trade_pokemon(f"{old_pokemon_name}", pokemon_trade, position)
logger.log_and_showinfo("info",f"You have sucessfully traded your {old_pokemon_name} for {name} ")
mw.logger.log_and_showinfo("info",f"You have sucessfully traded your {old_pokemon_name} for {name} ")
else:
showWarning("Please enter a valid Code !")

Expand All @@ -602,10 +602,10 @@ def trade_pokemon(old_pokemon_name, pokemon_trade, position):
with open(mypokemon_path, "r", encoding="utf-8") as file:
pokemon_list = json.load(file)
except FileNotFoundError:
print("The Pokemon file was not found. Please check the file path.")
mw.logger.log_and_showinfo("error", "The Pokemon file was not found. Please check the file path.")
return
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
mw.logger.log_and_showinfo("error", f"Error decoding JSON: {e}")
return

# Find and replace the specific Pokemon's information
Expand Down
9 changes: 5 additions & 4 deletions src/Ankimon/pyobj/data_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
}

class DataHandler:
def __init__(self):
def __init__(self, logger):
self.logger = logger
self.new_values = new_values
self.path = user_path # Store the provided path
self.data = {} # Store any potential errors or file read issues
Expand Down Expand Up @@ -59,7 +60,7 @@ def read_files(self):
if isinstance(entry, dict):
valid_content.append(entry)
else:
print(f"Skipping invalid entry in {file}: {entry}")
self.logger.log("warning", f"Skipping invalid entry in {file}: {entry}")
setattr(self, attr_name, valid_content)
else:
setattr(self, attr_name, content)
Expand All @@ -78,7 +79,7 @@ def assign_unique_ids(self, pokemon_list):
unique_ids = set()
for idx, entry in enumerate(pokemon_list):
if not isinstance(entry, dict):
print(f"Skipping invalid entry at index {idx} - not a dictionary")
self.logger.log("warning", f"Skipping invalid entry at index {idx} - not a dictionary")
continue
try:
unique_ids = set(pokemon.get("individual_id") for pokemon in pokemon_list if "individual_id" in pokemon)
Expand All @@ -97,7 +98,7 @@ def assign_unique_ids(self, pokemon_list):
unique_ids.add(new_id)
break
except:
print("Unique ID assignment failed")
self.logger.log("error", "Unique ID assignment failed")

def assign_new_variables(self, pokemon_list):
"""
Expand Down
11 changes: 6 additions & 5 deletions src/Ankimon/pyobj/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@
}

class Settings:
def __init__(self):
def __init__(self, logger):
self.logger = logger
self.config = self.load_config()
self.compute_gui_config()

Expand All @@ -94,7 +95,7 @@ def load_config(self):
with open(items_path, 'w', encoding='utf-8') as f:
json.dump(config["items"], f, indent=4)
except Exception as e:
print(f"Ankimon: Error migrating 'items' data during load_config: {e}")
self.logger.log("error", f"Ankimon: Error migrating 'items' data during load_config: {e}")
del config["items"]

if "trainer.team" in config:
Expand All @@ -113,10 +114,10 @@ def load_config(self):
try:
config[key] = int(config[key])
except ValueError:
print(f"Ankimon: Warning: Could not convert '{config[key]}' for key '{key}' to int. Keeping as string.")
self.logger.log("warning", f"Ankimon: Warning: Could not convert '{config[key]}' for key '{key}' to int. Keeping as string.")

except Exception as e:
print(f"Ankimon: Error loading config from config.obf: {e}. Falling back to default config.")
self.logger.log("error", f"Ankimon: Error loading config from config.obf: {e}. Falling back to default config.")
config = {} # Fallback to default if error occurs

modified = False
Expand All @@ -143,7 +144,7 @@ def save_config(self, config):
with open(obfuscated_config_path, 'w', encoding='utf-8') as f:
f.write(file_content)
except Exception as e:
print(f"Ankimon: Could not save obfuscated config: {e}")
self.logger.log("error", f"Ankimon: Could not save obfuscated config: {e}")

def get(self, key):
return self.config.get(key)
Expand Down
10 changes: 5 additions & 5 deletions src/Ankimon/pyobj/trainer_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ def get_highest_level_pokemon(self):
highest_pokemon = max(pokemon_data, key=lambda p: p.get("level", 0))
return f"{highest_pokemon.get('name', 'None')} (Level {highest_pokemon.get('level', 0)})"
except FileNotFoundError:
showInfo(f"File not found: {mypokemon_path}")
self.logger.log_and_showinfo("error", f"File not found: {mypokemon_path}")
return "None"
except json.JSONDecodeError:
showInfo(f"Error decoding JSON from file: {mypokemon_path}")
self.logger.log_and_showinfo("error", f"Error decoding JSON from file: {mypokemon_path}")
return "None"

def highest_pokemon_level(self):
Expand All @@ -96,10 +96,10 @@ def highest_pokemon_level(self):
highest_pokemon = max(pokemon_data, key=lambda p: p.get("level", 0))
return int(highest_pokemon.get('level', 0))
except FileNotFoundError:
showInfo(f"File not found: {mypokemon_path}")
self.logger.log_and_showinfo("error", f"File not found: {mypokemon_path}")
return int(0)
except json.JSONDecodeError:
showInfo(f"Error decoding JSON from file: {mypokemon_path}")
self.logger.log_and_showinfo("error", f"Error decoding JSON from file: {mypokemon_path}")
return int(0)

def add_achievement(self, achievement):
Expand Down Expand Up @@ -140,7 +140,7 @@ def gain_xp(self, tier, allow_to_choose_move=False):
if allow_to_choose_move is True:
xp_gained = xp_gained * 0.5
self.xp += xp_gained
print(f"Gained {xp_gained} XP from defeating a {tier} Pokémon!")
self.logger.log("info", f"Gained {xp_gained} XP from defeating a {tier} Pokémon!")
self.check_level_up()

def check_level_up(self):
Expand Down
4 changes: 2 additions & 2 deletions src/Ankimon/singletons.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
logger = ShowInfoLogger()

# Create the Settings object
settings_obj = Settings()
settings_obj = Settings(logger)

# Pass the correct attributes to SettingsWindow
settings_window = SettingsWindow(
Expand Down Expand Up @@ -151,7 +151,7 @@

achievement_bag = AchievementWindow()

data_handler_obj = DataHandler()
data_handler_obj = DataHandler(logger)
data_handler_window = DataHandlerWindow(data_handler = data_handler_obj)

# Initialize the Pokémon Shop Manager
Expand Down
4 changes: 2 additions & 2 deletions src/Ankimon/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ def count_items_and_rewrite(file_path):
with open(file_path, "w", encoding="utf-8") as f:
json.dump(updated_items, f, indent=4, ensure_ascii=False)

print("items.json has been updated with aggregated quantities!")
mw.logger.log("info", "items.json has been updated with aggregated quantities!")

except Exception as e:
show_warning_with_traceback(exception=e, message=f"An unexpected error occurred: {e}")
Expand Down Expand Up @@ -586,7 +586,7 @@ def get_all_sprites(directory):
]
return sprite_names
except FileNotFoundError:
print(f"Error: The directory '{directory}' does not exist.")
mw.logger.log("error", f"Error: The directory '{directory}' does not exist.")
return []

def play_effect_sound(settings_obj, sound_type):
Expand Down
Loading