Skip to content

Commit

Permalink
Run Black code formatter over project
Browse files Browse the repository at this point in the history
  • Loading branch information
40Cakes committed Dec 10, 2023
1 parent 38b0b7f commit 92b72e3
Show file tree
Hide file tree
Showing 13 changed files with 131 additions and 78 deletions.
2 changes: 1 addition & 1 deletion modules/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ def log_encounter_to_csv(total_stats: dict, pokemon_dict: dict, stats_dir_path:
pd_pokemon.to_csv(csv_file, mode="a", encoding="utf-8", index=False, header=header)
return True
except:
return False
return False
4 changes: 3 additions & 1 deletion modules/data/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,9 @@ def extract_moves(english_rom: ROM, localised_roms: dict[str, ROM], types_list:
localised_file.seek(get_address("gMoveDescriptionPointers"))
for i in range(1, 355):
description_pointer = int.from_bytes(localised_file.read(4), byteorder="little") - 0x0800_0000
moves_list[i]["localised_descriptions"][language_code] = read_string(localised_file, description_pointer)
moves_list[i]["localised_descriptions"][language_code] = read_string(
localised_file, description_pointer
)

return moves_list

Expand Down
4 changes: 3 additions & 1 deletion modules/encounter.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ def encounter_pokemon(pokemon: Pokemon) -> None:
context.message = message
console.print(message)
else:
message = f"Saved {pokemon.species.name} to PC box {import_result[0] + 1} ('{import_result[1]}')!"
message = (
f"Saved {pokemon.species.name} to PC box {import_result[0] + 1} ('{import_result[1]}')!"
)
context.message = message
console.print(message)

Expand Down
68 changes: 50 additions & 18 deletions modules/gui/create_profile_screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ def disable(self) -> None:
self.frame.destroy()

def _show_return_button(self, row: int = 0) -> None:
button = ttk.Button(self.frame, text="Back to Profile Selection", command=self.enable_profile_selection_screen,
cursor="hand2")
button = ttk.Button(
self.frame, text="Back to Profile Selection", command=self.enable_profile_selection_screen, cursor="hand2"
)
button.grid(sticky="NE", row=row)

def _show_welcome_message(self, row: int = 0) -> None:
Expand All @@ -72,8 +73,12 @@ def _show_welcome_message(self, row: int = 0) -> None:
icon.img1 = birch_image
icon.img2 = flipped_birch_image
# Very important.
icon.bind("<Button-1>", lambda *_: icon.config(
image=(flipped_birch_image if icon.cget("image")[0] == str(birch_image) else birch_image)))
icon.bind(
"<Button-1>",
lambda *_: icon.config(
image=(flipped_birch_image if icon.cget("image")[0] == str(birch_image) else birch_image)
),
)

text = ttk.Label(container, text=welcome_text, wraplength=360)
text.grid(sticky="N", row=0, column=1)
Expand All @@ -90,8 +95,8 @@ def _add_form(self, row: int = 1) -> None:
name_pattern = re.compile("^[-_a-zA-Z0-9 ]+$")

def select_all(widget: ttk.Entry):
widget.select_range(0, 'end')
widget.icursor('end')
widget.select_range(0, "end")
widget.icursor("end")

def handle_name_input_change(name, index, mode, sv=sv_name):
value = sv.get()
Expand Down Expand Up @@ -128,7 +133,7 @@ def handle_name_input_change(name, index, mode, sv=sv_name):

entry = ttk.Entry(container, textvariable=sv_name)
entry.grid(column=1, row=0, sticky="EW")
entry.bind('<Control-a>', lambda e: self.window.after(50, select_all, e.widget))
entry.bind("<Control-a>", lambda e: self.window.after(50, select_all, e.widget))

available_roms = list_available_roms()
rom_names = []
Expand Down Expand Up @@ -172,23 +177,48 @@ def handle_selected_file(selection: list[str]) -> None:
message_label.grid(row=3, column=0, columnspan=2)

plyer.filechooser.open_file(
filters=[["Save Games", "*.ss0", "*.ss1", "*.ss2", "*.ss3", "*.ss4", "*.ss5", "*.ss6", "*.ss7", "*.ss8",
"*.ss9"]],
filters=[
[
"Save Games",
"*.ss0",
"*.ss1",
"*.ss2",
"*.ss3",
"*.ss4",
"*.ss5",
"*.ss6",
"*.ss7",
"*.ss8",
"*.ss9",
]
],
title="Load Existing Save",
on_selection=handle_selected_file)
on_selection=handle_selected_file,
)

button_container = ttk.Frame(container, padding=(0, 15, 0, 5))
button_container.grid(row=2, column=0, columnspan=2)
button_container.columnconfigure(0, weight=1)
button_container.columnconfigure(1, minsize=10)
button_container.columnconfigure(2, weight=1)

new_game_button = ttk.Button(button_container, text="Start New Game", cursor="hand2", state="disabled",
command=handle_create_new_game_press, style="Accent.TButton")
new_game_button = ttk.Button(
button_container,
text="Start New Game",
cursor="hand2",
state="disabled",
command=handle_create_new_game_press,
style="Accent.TButton",
)
new_game_button.grid(column=0, row=0)

load_save_button = ttk.Button(button_container, text="Load Existing Save", cursor="hand2", state="disabled",
command=handle_load_save_press)
load_save_button = ttk.Button(
button_container,
text="Load Existing Save",
cursor="hand2",
state="disabled",
command=handle_load_save_press,
)
load_save_button.grid(column=2, row=0)

message_label = ttk.Label(container, text="", wraplength=340, padding=(0, 15, 0, 0))
Expand All @@ -197,10 +227,12 @@ def _show_missing_roms_screen(self) -> None:
group = ttk.Frame(self.frame)
group.grid()

error_message = ("There don't seem to be any Pokémon ROMs in the 'roms/' folder. "
"Please add some and retry.\n\n"
"Note that only the original ROMs for Pokémon Ruby, Sapphire, Emerald, FireRed and LeafGreen "
"are supported by this bot. Any modified ROM will not be detected.")
error_message = (
"There don't seem to be any Pokémon ROMs in the 'roms/' folder. "
"Please add some and retry.\n\n"
"Note that only the original ROMs for Pokémon Ruby, Sapphire, Emerald, FireRed and LeafGreen "
"are supported by this bot. Any modified ROM will not be detected."
)
message = ttk.Label(group, text=error_message, wraplength=300, foreground="red", padding=(0, 0, 0, 25))
message.grid(row=0, column=0, sticky="S")

Expand Down
46 changes: 29 additions & 17 deletions modules/gui/debug_tabs.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@

class FancyTreeview:
def __init__(
self,
root: ttk.Widget,
height=22,
row=0,
column=0,
columnspan=1,
additional_context_actions: Optional[dict[str, callable]] = None,
on_highlight: Optional[callable] = None,
self,
root: ttk.Widget,
height=22,
row=0,
column=0,
columnspan=1,
additional_context_actions: Optional[dict[str, callable]] = None,
on_highlight: Optional[callable] = None,
):
if additional_context_actions is None:
additional_context_actions = {}
Expand Down Expand Up @@ -78,6 +78,7 @@ def __init__(
self._tv.bind("<Right>", lambda _: root.focus_set())

if on_highlight is not None:

def handle_selection(e):
selected_item = self._tv.focus()
on_highlight(self._tv.item(selected_item)["text"])
Expand Down Expand Up @@ -533,7 +534,7 @@ def update(self, emulator: "LibmgbaEmulator"):
n = int.from_bytes(value, byteorder="little")
binary_string = bin(n).removeprefix("0b").rjust(length * 8, "0")
chunk_size = 4
chunks = [binary_string[i: i + chunk_size] for i in range(0, len(binary_string), chunk_size)]
chunks = [binary_string[i : i + chunk_size] for i in range(0, len(binary_string), chunk_size)]
data[symbol] = " ".join(chunks)
else:
data[symbol] = value.hex(" ", 1)
Expand Down Expand Up @@ -636,9 +637,20 @@ def _get_data(self):
"TMs and HMs": {"__value": f"{len(item_bag.tms_hms)}/{item_bag.tms_hms_size} Slots"},
"Berries": {"__value": f"{len(item_bag.berries)}/{item_bag.berries_size} Slots"},
}
total_slots = item_bag.items_size + item_bag.key_items_size + item_bag.poke_balls_size + item_bag.tms_hms_size + item_bag.berries_size
used_slots = len(item_bag.items) + len(item_bag.key_items) + len(item_bag.poke_balls) + len(
item_bag.tms_hms) + len(item_bag.berries)
total_slots = (
item_bag.items_size
+ item_bag.key_items_size
+ item_bag.poke_balls_size
+ item_bag.tms_hms_size
+ item_bag.berries_size
)
used_slots = (
len(item_bag.items)
+ len(item_bag.key_items)
+ len(item_bag.poke_balls)
+ len(item_bag.tms_hms)
+ len(item_bag.berries)
)
bag_data["__value"] = f"{used_slots}/{total_slots} Slots"
n = 0
for slot in item_bag.items:
Expand Down Expand Up @@ -857,11 +869,11 @@ def on_video_output_click(self, click_location: tuple[int, int], scale: int):
actual_x = current_map_data.local_position[0] + (tile_x - 7)
actual_y = current_map_data.local_position[1] + (tile_y - 5)
if (
self._selected_tile == (actual_x, actual_y)
or actual_x < 0
or actual_x >= current_map_data.map_size[0]
or actual_y < 0
or actual_y >= current_map_data.map_size[1]
self._selected_tile == (actual_x, actual_y)
or actual_x < 0
or actual_x >= current_map_data.map_size[0]
or actual_y < 0
or actual_y >= current_map_data.map_size[1]
):
self._selected_tile = None
self._selected_map = None
Expand Down
14 changes: 10 additions & 4 deletions modules/gui/select_profile_screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,13 @@ def _add_header_and_controls(self, row: int = 0) -> None:
label = ttk.Label(header, text="Select a profile to run:")
label.grid(column=0, row=0, sticky="W")

new_profile_button = ttk.Button(header, text="+ New profile", command=self.enable_profile_creation_screen,
style="Accent.TButton", cursor="hand2")
new_profile_button = ttk.Button(
header,
text="+ New profile",
command=self.enable_profile_creation_screen,
style="Accent.TButton",
cursor="hand2",
)
new_profile_button.grid(column=1, row=0, sticky="E")

def _add_profile_list(self, available_profiles: list[Profile], row: int = 1) -> None:
Expand All @@ -51,8 +56,9 @@ def _add_profile_list(self, available_profiles: list[Profile], row: int = 1) ->
container.rowconfigure(0, weight=1)
container.grid(row=row, sticky="NSEW")

treeview = ttk.Treeview(container, columns=("profile_name", "game", "last_played"), show="headings",
selectmode="browse")
treeview = ttk.Treeview(
container, columns=("profile_name", "game", "last_played"), show="headings", selectmode="browse"
)
treeview.column("profile_name", width=200)
treeview.heading("profile_name", text="Profile Name")
treeview.column("game", width=150)
Expand Down
12 changes: 7 additions & 5 deletions modules/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,14 @@ def http_get_bag():
if cached_storage.age_in_seconds > 1:
work_queue.put_nowait(get_item_storage)
while cached_bag.age_in_seconds > 1 or cached_storage.age_in_seconds > 1:
time.sleep(0.05)
time.sleep(0.05)

return jsonify({
"bag": cached_bag.value.to_dict(),
"storage": cached_storage.value.to_list(),
})
return jsonify(
{
"bag": cached_bag.value.to_dict(),
"storage": cached_storage.value.to_list(),
}
)

@server.route("/map", methods=["GET"])
def http_get_map():
Expand Down
1 change: 0 additions & 1 deletion modules/http_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@ def run_watcher():
previous_game_state["pokedex"] = state_cache.pokedex.frame
send_message(DataSubscription.Pokedex, data=state_cache.pokedex.value.to_dict(), event_type="Pokedex")


if subscriptions["Opponent"] > 0:
if current_game_state == GameState.BATTLE:
if state_cache.opponent.age_in_frames >= 60:
Expand Down
27 changes: 18 additions & 9 deletions modules/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,16 @@ def to_dict(self) -> dict:


class ItemBag:
def __init__(self, data: bytes, items_count: int, key_items_count: int, poke_balls_count: int, tms_hms_count: int,
berries_count: int, encryption_key: bytes):
def __init__(
self,
data: bytes,
items_count: int,
key_items_count: int,
poke_balls_count: int,
tms_hms_count: int,
berries_count: int,
encryption_key: bytes,
):
self._data = data
self._encryption_key = encryption_key
self.items_size = items_count
Expand All @@ -108,8 +116,8 @@ def _get_pocket(self, slot_offset: int, number_of_slots: int) -> list[ItemSlot]:
result = []
for index in range(number_of_slots):
offset = (slot_offset + index) * 4
item_index = unpack_uint16(self._data[offset:offset + 2])
quantity = unpack_uint16(self._data[offset + 2:offset + 4]) ^ unpack_uint16(self._encryption_key[0:2])
item_index = unpack_uint16(self._data[offset : offset + 2])
quantity = unpack_uint16(self._data[offset + 2 : offset + 4]) ^ unpack_uint16(self._encryption_key[0:2])
if item_index != 0 and quantity > 0:
item = get_item_by_index(item_index)
result.append(ItemSlot(item, quantity))
Expand Down Expand Up @@ -223,8 +231,8 @@ def items(self) -> list[ItemSlot]:
result = []
for index in range(self.number_of_slots):
offset = index * 4
item_index = unpack_uint16(self._data[offset:offset + 2])
quantity = unpack_uint16(self._data[offset + 2:offset + 4])
item_index = unpack_uint16(self._data[offset : offset + 2])
quantity = unpack_uint16(self._data[offset + 2 : offset + 4])
if item_index != 0 and quantity > 0:
item = get_item_by_index(item_index)
result.append(ItemSlot(item, quantity))
Expand Down Expand Up @@ -302,13 +310,14 @@ def get_item_bag() -> ItemBag:
tms_hms_count = 64
berries_count = 46
offset = 0x560
encryption_key = b'\x00\x00\x00\x00'
encryption_key = b"\x00\x00\x00\x00"

data_size = 4 * (items_count + key_items_count + poke_balls_count + tms_hms_count + berries_count)
data = get_save_block(1, offset=offset, size=data_size)

item_bag = ItemBag(data, items_count, key_items_count, poke_balls_count, tms_hms_count, berries_count,
encryption_key)
item_bag = ItemBag(
data, items_count, key_items_count, poke_balls_count, tms_hms_count, berries_count, encryption_key
)
state_cache.item_bag = item_bag
return item_bag

Expand Down
16 changes: 4 additions & 12 deletions modules/pokedex.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,13 @@ def __init__(self, data, seen1, seen2):

def __eq__(self, other):
if isinstance(other, Pokedex):
return other._data == self._data and \
other._seen1 == self._seen1 and \
other._seen2 == self._seen2
return other._data == self._data and other._seen1 == self._seen1 and other._seen2 == self._seen2
else:
return NotImplemented

def __ne__(self, other):
if isinstance(other, Pokedex):
return other._data != self._data or \
other._seen1 != self._seen1 or \
other._seen2 != self._seen2
return other._data != self._data or other._seen1 != self._seen1 or other._seen2 != self._seen2
else:
return NotImplemented

Expand All @@ -40,9 +36,7 @@ def seen_species(self) -> list[Species]:
mask = 1 << (index % 8)

is_seen = self._data[0x44 + offset] & mask
if is_seen and \
(self._seen1[offset] & mask) == is_seen and \
(self._seen2[offset] & mask) == is_seen:
if is_seen and (self._seen1[offset] & mask) == is_seen and (self._seen2[offset] & mask) == is_seen:
result.append(get_species_by_national_dex(index + 1))
return result

Expand All @@ -54,9 +48,7 @@ def owned_species(self) -> list[Species]:
mask = 1 << (index % 8)

is_seen = self._data[0x10 + offset] & mask
if is_seen and \
(self._seen1[offset] & mask) == is_seen and \
(self._seen2[offset] & mask) == is_seen:
if is_seen and (self._seen1[offset] & mask) == is_seen and (self._seen2[offset] & mask) == is_seen:
result.append(get_species_by_national_dex(index + 1))
return result

Expand Down
Loading

0 comments on commit 92b72e3

Please sign in to comment.