From 4e131cd5e47dc90a0ccf4ae1a964a66f0d918dc7 Mon Sep 17 00:00:00 2001 From: morgan Date: Fri, 31 Oct 2025 21:24:07 -0600 Subject: [PATCH] Grinch Refactor --- worlds/grinch/Client.py | 161 ++++++++++-------------------------- worlds/grinch/Items.py | 16 ++-- worlds/grinch/Locations.py | 89 +++++++++++++++----- worlds/grinch/RamHandler.py | 50 ++++++++--- worlds/grinch/Regions.py | 22 +++-- worlds/grinch/Rules.py | 21 ++--- worlds/grinch/__init__.py | 40 +++++---- 7 files changed, 202 insertions(+), 197 deletions(-) diff --git a/worlds/grinch/Client.py b/worlds/grinch/Client.py index ac6ccf6f..239a01db 100644 --- a/worlds/grinch/Client.py +++ b/worlds/grinch/Client.py @@ -66,34 +66,24 @@ class GrinchClient(BizHawkClient): try: bytes_actual: bytes = ( - await bizhawk.read( - ctx.bizhawk_ctx, [(grinch_identifier_ram_address, 11, "MainRAM")] - ) + await bizhawk.read(ctx.bizhawk_ctx, [(grinch_identifier_ram_address, 11, "MainRAM")]) )[0] psx_rom_name = bytes_actual.decode("ascii") if psx_rom_name != "SLUS_011.97": bios_bytes_check: bytes = ( - await bizhawk.read( - ctx.bizhawk_ctx, [(bios_identifier_ram_address, 24, "MainRAM")] - ) + await bizhawk.read(ctx.bizhawk_ctx, [(bios_identifier_ram_address, 24, "MainRAM")]) )[0] if "System ROM Version" in bios_bytes_check.decode("ascii"): if not self.loading_bios_msg: self.loading_bios_msg = True - logger.error( - "BIOS is currently loading. Will wait up to 5 seconds before retrying." - ) + logger.error("BIOS is currently loading. Will wait up to 5 seconds before retrying.") return False - logger.error( - "Invalid rom detected. You are not playing Grinch USA Version." - ) - raise Exception( - "Invalid rom detected. You are not playing Grinch USA Version." - ) + logger.error("Invalid rom detected. You are not playing Grinch USA Version.") + raise Exception("Invalid rom detected. You are not playing Grinch USA Version.") ctx.command_processor.commands["ringlink"] = _cmd_ringlink @@ -147,9 +137,7 @@ class GrinchClient(BizHawkClient): and "RingLink" in args["tags"] and args["data"]["source"] != self.unique_client_id ): - Utils.async_start( - self.ring_link_input(args["data"]["amount"], ctx), "SyncEggs" - ) + Utils.async_start(self.ring_link_input(args["data"]["amount"], ctx), "SyncEggs") async def set_auth(self, ctx: "BizHawkClientContext") -> None: await ctx.get_username() @@ -165,9 +153,7 @@ class GrinchClient(BizHawkClient): if not await self.ingame_checker(ctx): return - if not any( - task.get_name() == "Grinch EggLink" for task in asyncio.all_tasks() - ): + if not any(task.get_name() == "Grinch EggLink" for task in asyncio.all_tasks()): print("EggLink") self.send_ring_link = True Utils.async_start(self.ring_link_output(ctx), name="Grinch EggLink") @@ -180,18 +166,12 @@ class GrinchClient(BizHawkClient): except bizhawk.RequestFailedError as ex: # The connector didn't respond. Exit handler and return to main loop to reconnect - logger.error( - "Failure to connect / authenticate the grinch. Error details: " - + str(ex) - ) + logger.error("Failure to connect / authenticate the grinch. Error details: " + str(ex)) pass except Exception as genericEx: # For all other errors, catch this and let the client gracefully disconnect - logger.error( - "Unknown error occurred while playing the grinch. Error details: " - + str(genericEx) - ) + logger.error("Unknown error occurred while playing the grinch. Error details: " + str(genericEx)) await ctx.disconnect(False) pass @@ -208,14 +188,12 @@ class GrinchClient(BizHawkClient): grinch_loc_name = ctx.location_names.lookup_in_game(missing_location) grinch_loc_ram_data = grinch_locations[grinch_loc_name] missing_addr_list: list[tuple[int, int, str]] = [ - (read_addr.ram_address, read_addr.byte_size, "MainRAM") + (read_addr.ram_address, read_addr.byte_size, read_addr.ram_area) for read_addr in grinch_loc_ram_data.update_ram_addr ] addr_list_to_read = [*addr_list_to_read, *missing_addr_list] - returned_bytes: list[bytes] = await bizhawk.read( - ctx.bizhawk_ctx, addr_list_to_read - ) + returned_bytes: list[bytes] = await bizhawk.read(ctx.bizhawk_ctx, addr_list_to_read) # Now loop through everything again and this time get the byte value from the above read, convert to int, # and check to see if that ram address has our expected value. @@ -234,31 +212,20 @@ class GrinchClient(BizHawkClient): orig_index: int = addr_list_to_read.index( (addr_to_update.ram_address, addr_to_update.byte_size, "MainRAM") ) - value_read_from_bizhawk: int = int.from_bytes( - returned_bytes[orig_index], "little" - ) + value_read_from_bizhawk: int = int.from_bytes(returned_bytes[orig_index], "little") if is_binary: - ram_checked_list.append( - (value_read_from_bizhawk & (1 << addr_to_update.binary_bit_pos)) - > 0 - ) + ram_checked_list.append((value_read_from_bizhawk & (1 << addr_to_update.binary_bit_pos)) > 0) else: expected_int_value = addr_to_update.value - ram_checked_list.append( - expected_int_value == value_read_from_bizhawk - ) + ram_checked_list.append(expected_int_value == value_read_from_bizhawk) if all(ram_checked_list): - local_locations_checked.append( - GrinchLocation.get_apid(grinch_loc_ram_data.id) - ) + local_locations_checked.append(GrinchLocation.get_apid(grinch_loc_ram_data.id)) # Update the AP server with the locally checked list of locations (In other words, locations I found in Grinch) - locations_sent_to_ap: set[int] = await ctx.check_locations( - local_locations_checked - ) + locations_sent_to_ap: set[int] = await ctx.check_locations(local_locations_checked) if len(locations_sent_to_ap) > 0: await self.remove_physical_items(ctx) @@ -271,11 +238,7 @@ class GrinchClient(BizHawkClient): # Otherwise, we will get the new items and give them to the player. self.last_received_index = int.from_bytes( - ( - await bizhawk.read( - ctx.bizhawk_ctx, [(RECV_ITEM_ADDR, RECV_ITEM_BITSIZE, "MainRAM")] - ) - )[0], + (await bizhawk.read(ctx.bizhawk_ctx, [(RECV_ITEM_ADDR, RECV_ITEM_BITSIZE, "MainRAM")]))[0], "little", ) @@ -294,9 +257,7 @@ class GrinchClient(BizHawkClient): is_binary = True if not addr_to_update.binary_bit_pos is None else False if addr_to_update.ram_address in ram_addr_dict.keys(): - current_ram_address_value = ram_addr_dict[ - addr_to_update.ram_address - ][0] + current_ram_address_value = ram_addr_dict[addr_to_update.ram_address][0] else: current_ram_address_value = int.from_bytes( ( @@ -306,25 +267,21 @@ class GrinchClient(BizHawkClient): ( addr_to_update.ram_address, addr_to_update.byte_size, - "MainRAM", + addr_to_update.ram_area, ) ], ) )[0], - "little", + addr_to_update.endian, ) if is_binary: - current_ram_address_value = current_ram_address_value | ( - 1 << addr_to_update.binary_bit_pos - ) + current_ram_address_value = current_ram_address_value | (1 << addr_to_update.binary_bit_pos) elif addr_to_update.update_existing_value: # Grabs minimum value of a list of numbers and makes sure it does not go above max count possible current_ram_address_value += addr_to_update.value - current_ram_address_value = min( - current_ram_address_value, addr_to_update.max_count - ) + current_ram_address_value = min(current_ram_address_value, addr_to_update.max_count) else: current_ram_address_value = addr_to_update.value @@ -340,9 +297,7 @@ class GrinchClient(BizHawkClient): # Update the latest received item index to ram as well. ram_addr_dict[RECV_ITEM_ADDR] = [self.last_received_index, RECV_ITEM_BITSIZE] - await bizhawk.write( - ctx.bizhawk_ctx, self.convert_dict_to_ram_list(ram_addr_dict) - ) + await bizhawk.write(ctx.bizhawk_ctx, self.convert_dict_to_ram_list(ram_addr_dict)) async def goal_checker(self, ctx: "BizHawkClientContext"): if not ctx.finished_game: @@ -356,12 +311,12 @@ class GrinchClient(BizHawkClient): ( goal_ram_address.ram_address, goal_ram_address.byte_size, - "MainRAM", + goal_ram_address.ram_area, ) ], ) )[0], - "little", + goal_ram_address.endian, ) if (current_ram_address_value & (1 << goal_ram_address.binary_bit_pos)) > 0: @@ -381,12 +336,8 @@ class GrinchClient(BizHawkClient): ram_addr_dict: dict[int, list[int]] = {} list_recv_itemids: list[int] = [netItem.item for netItem in ctx.items_received] - items_to_check: dict[str, GrinchItemData] = { - **GADGETS_TABLE - } # , **SLEIGH_PARTS_TABLE - heart_count = len( - list(item_id for item_id in list_recv_itemids if item_id == 42570) - ) + items_to_check: dict[str, GrinchItemData] = {**GADGETS_TABLE} # , **SLEIGH_PARTS_TABLE + heart_count = len(list(item_id for item_id in list_recv_itemids if item_id == 42570)) heart_item_data = ALL_ITEMS_TABLE["Heart of Stone"] ram_addr_dict[heart_item_data.update_ram_addr[0].ram_address] = [ min(heart_count, 4), @@ -398,10 +349,7 @@ class GrinchClient(BizHawkClient): for item_name, item_data in items_to_check.items(): # If item is an event or already been received, ignore. - if ( - item_data.id is None - or GrinchLocation.get_apid(item_data.id) in list_recv_itemids - ): + if item_data.id is None or GrinchLocation.get_apid(item_data.id) in list_recv_itemids: continue # This assumes we don't have the item so we must set all the data to 0 @@ -421,12 +369,12 @@ class GrinchClient(BizHawkClient): ( addr_to_update.ram_address, addr_to_update.byte_size, - "MainRAM", + addr_to_update.ram_area, ) ], ) )[0], - "little", + addr_to_update.endian, ) current_bin_value &= ~(1 << addr_to_update.binary_bit_pos) ram_addr_dict[addr_to_update.ram_address] = [current_bin_value, 1] @@ -437,19 +385,13 @@ class GrinchClient(BizHawkClient): addr_to_update.byte_size, ] - await bizhawk.write( - ctx.bizhawk_ctx, self.convert_dict_to_ram_list(ram_addr_dict) - ) + await bizhawk.write(ctx.bizhawk_ctx, self.convert_dict_to_ram_list(ram_addr_dict)) - def convert_dict_to_ram_list( - self, addr_dict: dict[int, list[int]] - ) -> list[tuple[int, Sequence[int], str]]: + def convert_dict_to_ram_list(self, addr_dict: dict[int, list[int]]) -> list[tuple[int, Sequence[int], str]]: addr_list_to_update: list[tuple[int, Sequence[int], str]] = [] for key, val in addr_dict.items(): - addr_list_to_update.append( - (key, val[0].to_bytes(val[1], "little"), "MainRAM") - ) + addr_list_to_update.append((key, val[0].to_bytes(val[1], "little"), "MainRAM")) return addr_list_to_update @@ -465,9 +407,7 @@ class GrinchClient(BizHawkClient): for item_name, item_data in items_to_check.items(): # If item is an event or already been received, ignore. - if ( - item_data.id is None - ): # or GrinchLocation.get_apid(item_data.id) in list_recv_itemids: + if item_data.id is None: # or GrinchLocation.get_apid(item_data.id) in list_recv_itemids: continue # This will either constantly update the item to ensure you still have it or take it away if you don't deserve it @@ -487,12 +427,12 @@ class GrinchClient(BizHawkClient): ( addr_to_update.ram_address, addr_to_update.byte_size, - "MainRAM", + addr_to_update.ram_area, ) ], ) )[0], - "little", + addr_to_update.endian, ) if GrinchLocation.get_apid(item_data.id) in list_recv_itemids: @@ -516,9 +456,7 @@ class GrinchClient(BizHawkClient): addr_to_update.byte_size, ] - await bizhawk.write( - ctx.bizhawk_ctx, self.convert_dict_to_ram_list(ram_addr_dict) - ) + await bizhawk.write(ctx.bizhawk_ctx, self.convert_dict_to_ram_list(ram_addr_dict)) async def ingame_checker(self, ctx: "BizHawkClientContext"): from CommonClient import logger @@ -575,14 +513,13 @@ class GrinchClient(BizHawkClient): if self.loc_unlimited_eggs: await bizhawk.write( ctx.bizhawk_ctx, - [(EGG_COUNT_ADDR, MAX_EGGS.to_bytes(2, "little"), "MainRAM")], + [(EGG_COUNT_ADDR, MAX_EGGS.to_bytes(EGG_ADDR_BYTESIZE, "little"), "MainRAM")], ) async def ring_link_output(self, ctx: "BizHawkClientContext"): from CommonClient import logger while self.send_ring_link and ctx.slot: - try: current_egg_count = int.from_bytes( ( @@ -604,6 +541,7 @@ class GrinchClient(BizHawkClient): }, "tags": ["RingLink"], } + await ctx.send_msgs([msg]) self.previous_egg_count = current_egg_count # logger.info(f"RingLink: You sent {str(current_egg_count - self.previous_egg_count)} rotten eggs.") @@ -611,31 +549,20 @@ class GrinchClient(BizHawkClient): await asyncio.sleep(0.1) except Exception as ex: - logger.error( - "While monitoring grinch's egg count ingame, an error occurred. Details:" - + str(ex) - ) + logger.error("While monitoring grinch's egg count ingame, an error occurred. Details:" + str(ex)) self.send_ring_link = False if not ctx.slot: - logger.info( - "You must be connected to the multi-world in order for RingLink to work properly." - ) + logger.info("You must be connected to the multi-world in order for RingLink to work properly.") async def ring_link_input(self, egg_amount: int, ctx: "BizHawkClientContext"): from CommonClient import logger game_egg_count = int.from_bytes( - ( - await bizhawk.read( - ctx.bizhawk_ctx, [(EGG_COUNT_ADDR, EGG_ADDR_BYTESIZE, "MainRAM")] - ) - )[0], + (await bizhawk.read(ctx.bizhawk_ctx, [(EGG_COUNT_ADDR, EGG_ADDR_BYTESIZE, "MainRAM")]))[0], "little", ) - non_neg_eggs = ( - game_egg_count + egg_amount if game_egg_count + egg_amount > 0 else 0 - ) + non_neg_eggs = game_egg_count + egg_amount if game_egg_count + egg_amount > 0 else 0 current_egg_count = min(non_neg_eggs, MAX_EGGS) await bizhawk.write( @@ -657,6 +584,7 @@ class GrinchClient(BizHawkClient): uid: int = 0 for char in string_id: uid += ord(char) + return uid @@ -677,7 +605,6 @@ async def _update_ring_link(ctx: "BizHawkClientContext", ring_link: bool): if ring_link: ctx.tags.add("RingLink") - else: ctx.tags -= {"RingLink"} diff --git a/worlds/grinch/Items.py b/worlds/grinch/Items.py index 402800b7..0be049ba 100644 --- a/worlds/grinch/Items.py +++ b/worlds/grinch/Items.py @@ -8,9 +8,7 @@ from BaseClasses import ( class GrinchItemData(NamedTuple): - item_group: list[ - str - ] # arbituary that can be whatever it can be, basically the field/property for item groups + item_group: list[str] # arbituary that can be whatever it can be, basically the field/property for item groups id: Optional[int] classification: IC update_ram_addr: list[GrinchRamData] @@ -27,9 +25,7 @@ class GrinchItem(Item): return base_id + id if id is not None else None def __init__(self, name: str, player: int, data: GrinchItemData): - super(GrinchItem, self).__init__( - name, data.classification, GrinchItem.get_apid(data.id), player - ) + super(GrinchItem, self).__init__(name, data.classification, GrinchItem.get_apid(data.id), player) self.type = data.item_group self.item_id = data.id @@ -75,13 +71,13 @@ class grinch_items: WV_WHO_CLOAK: str = "Who Cloak" WV_PAINT_BUCKET: str = "Painting Bucket" WV_HAMMER: str = "Hammer" - WV_SCULPTIN_TOOLS: str = "Sculpting Tools" + WV_SCULPTING_TOOLS: str = "Sculpting Tools" WF_GLUE_BUCKET: str = "Glue Bucket" WF_CABLE_CAR_ACCESS_CARD: str = "Cable Car Access Card" WD_SCISSORS: str = "Scissors" WL_ROPE: str = "Rope" WL_HOOK: str = "Hook" - WL_DRILLL: str = "Drill" + WL_DRILL: str = "Drill" WL_SCOUT_CLOTHES: str = "Scout Clothes" class useful_items: @@ -288,7 +284,7 @@ MISSION_ITEMS_TABLE: dict[str, GrinchItemData] = { IC.progression, [GrinchRamData(0x0101F9, binary_bit_pos=5)], ), - grinch_items.level_items.WL_DRILLL: GrinchItemData( + grinch_items.level_items.WL_DRILL: GrinchItemData( [ grinch_categories.MISSION_SPECIFIC_ITEMS, grinch_categories.USEFUL_ITEMS, @@ -315,7 +311,7 @@ MISSION_ITEMS_TABLE: dict[str, GrinchItemData] = { IC.progression_deprioritized, [GrinchRamData(0x0101FA, binary_bit_pos=0)], ), - grinch_items.level_items.WV_SCULPTIN_TOOLS: GrinchItemData( + grinch_items.level_items.WV_SCULPTING_TOOLS: GrinchItemData( [ grinch_categories.MISSION_SPECIFIC_ITEMS, grinch_categories.USEFUL_ITEMS, diff --git a/worlds/grinch/Locations.py b/worlds/grinch/Locations.py index fa930655..c3184926 100644 --- a/worlds/grinch/Locations.py +++ b/worlds/grinch/Locations.py @@ -1,17 +1,41 @@ -from typing import NamedTuple, Optional +from typing import Optional from .RamHandler import GrinchRamData from BaseClasses import Location, Region -class GrinchLocationData(NamedTuple): +class GrinchLocationData: region: str location_group: Optional[list[str]] id: Optional[int] update_ram_addr: list[GrinchRamData] - reset_addr: Optional[list[GrinchRamData]] = ( - None # Addresses to update once we find the item - ) + reset_addr: Optional[list[GrinchRamData]] = None # Addresses to update once we find the item + + def __init__( + self, + region: str, + location_group: Optional[list[str]] = None, + id: Optional[int] = None, + update_ram_addr: list[GrinchRamData] = [], + reset_addr: Optional[list[GrinchRamData]] = None, + ): + self.region = region + + if location_group: + self.location_group = location_group + + if id: + self.id = id + else: + raise ValueError(f"id is required on GrinchLocationData") + + if update_ram_addr: + self.update_ram_addr = update_ram_addr + else: + raise ValueError(f"udpate_ram_addr is required on GrinchLocationData") + + if reset_addr: + self.reset_addr = reset_addr class GrinchLocation(Location): @@ -23,17 +47,18 @@ class GrinchLocation(Location): return base_id + id if id is not None else None def __init__( - self, player: int, name: str, parent: Region, data: GrinchLocationData + self, + player: int, + name: str, + parent: Region, + data: GrinchLocationData, ): address = None if data.id is None else GrinchLocation.get_apid(data.id) - super(GrinchLocation, self).__init__( - player, name, address=address, parent=parent - ) + super(GrinchLocation, self).__init__(player, name, address=address, parent=parent) self.code = data.id self.region = data.region self.type = data.location_group - self.address = self.address def get_location_names_per_category() -> dict[str, set[str]]: @@ -1151,7 +1176,10 @@ grinch_locations = { [GrinchRamData(0x0100BF, binary_bit_pos=6)], ), "MC - Sleigh Ride - Neutralizing Santa": GrinchLocationData( - "Sleigh Room", None, None, [GrinchRamData(0x0100BF, binary_bit_pos=7)] + "Sleigh Room", + ["Sleigh Ride"], + 1301, + [GrinchRamData(0x0100BF, binary_bit_pos=7)], ), # [GrinchRamData(0x010000, value=0x3E)]), # Heart of Stones "WV - Post Office - Heart of Stone": GrinchLocationData( @@ -1224,19 +1252,44 @@ grinch_locations = { ), # Mount Crumpit Locations "MC - 1st Crate Squashed": GrinchLocationData( - "Mount Crumpit", ["Mount Crumpit"], 1700, [GrinchRamData(0x095343, value=1)] + "Mount Crumpit", + ["Mount Crumpit"], + 1700, + [ + GrinchRamData(0x095343, value=1), + ], ), "MC - 2nd Crate Squashed": GrinchLocationData( - "Mount Crumpit", ["Mount Crumpit"], 1701, [GrinchRamData(0x095343, value=2)] + "Mount Crumpit", + ["Mount Crumpit"], + 1701, + [ + GrinchRamData(0x095343, value=2), + ], ), "MC - 3rd Crate Squashed": GrinchLocationData( - "Mount Crumpit", ["Mount Crumpit"], 1702, [GrinchRamData(0x095343, value=3)] + "Mount Crumpit", + ["Mount Crumpit"], + 1702, + [ + GrinchRamData(0x095343, value=3), + ], ), "MC - 4th Crate Squashed": GrinchLocationData( - "Mount Crumpit", ["Mount Crumpit"], 1703, [GrinchRamData(0x095343, value=4)] + "Mount Crumpit", + ["Mount Crumpit"], + 1703, + [ + GrinchRamData(0x095343, value=4), + ], ), "MC - 5th Crate Squashed": GrinchLocationData( - "Mount Crumpit", ["Mount Crumpit"], 1704, [GrinchRamData(0x095343, value=5)] + "Mount Crumpit", + ["Mount Crumpit"], + 1704, + [ + GrinchRamData(0x095343, value=5), + ], ), } @@ -1244,7 +1297,5 @@ grinch_locations = { def grinch_locations_to_id() -> dict[str, int]: location_mappings: dict[str, int] = {} for LocationName, LocationData in grinch_locations.items(): - location_mappings.update( - {LocationName: GrinchLocation.get_apid(LocationData.id)} - ) + location_mappings.update({LocationName: GrinchLocation.get_apid(LocationData.id)}) return location_mappings diff --git a/worlds/grinch/RamHandler.py b/worlds/grinch/RamHandler.py index 6b40e6bb..74ae0fbe 100644 --- a/worlds/grinch/RamHandler.py +++ b/worlds/grinch/RamHandler.py @@ -1,5 +1,5 @@ from enum import STRICT, IntEnum -from typing import NamedTuple, Optional +from typing import Optional class UpdateMethod(IntEnum, boundary=STRICT): @@ -9,7 +9,7 @@ class UpdateMethod(IntEnum, boundary=STRICT): FREEZE = 4 -class GrinchRamData(NamedTuple): +class GrinchRamData: """A Representation of an update to RAM data for The Grinch. ram_address (int): The RAM address that we are updating, usually passed in with hex, representation (0x11111111) @@ -23,22 +23,25 @@ class GrinchRamData(NamedTuple): ram_address: int value: Optional[int] = None # none is empty/null - # Either set or add either hex or unsigned values through Client.py - # Hex uses 0x00, unsigned are base whole numbers binary_bit_pos: Optional[int] = None byte_size: int = 1 + endian = "little" update_method: UpdateMethod = UpdateMethod.SET min_count: int = 0 max_count: int = 255 + ram_area = "MainRAM" def __init__( self, ram_address: int, - value: Optional[int], - byte_size: int, - update_method: UpdateMethod, - min_count: int, - max_count: int, + value: Optional[int] = None, + binary_bit_pos: int = -1, + byte_size: int = 1, + update_method: UpdateMethod = UpdateMethod.SET, + min_count: int = -1, + max_count: int = -1, + endian: str = "little", + ram_area: str = "MainRAM", ): self.ram_address = ram_address @@ -47,7 +50,10 @@ class GrinchRamData(NamedTuple): else: self.value = 1 - if byte_size: + if binary_bit_pos > -1: + self.binary_bit_pos = bin + + if byte_size > 0: self.byte_size = byte_size if update_method: @@ -59,8 +65,26 @@ class GrinchRamData(NamedTuple): if max_count and max_count > -1: self.max_count = max_count elif max_count and max_count > ((2 ** (self.byte_size * 8)) - 1): - raise ValueError( - "max_count cannot be larger than the RAM addresses max possible value" - ) + raise ValueError("max_count cannot be larger than the RAM addresses max possible value") else: self.max_count = (2 ** (self.byte_size * 8)) - 1 + + self.endian = endian + self.ram_area = ram_area + + # Error Handling + if self.value and self.value > self.max_count: + raise ValueError( + f"Value passed in is greater than max_count.\n\nRAM Address: {self.ram_address}\nValue: {self.value}\nMax Count: {self.max_count}" + ) + + if self.value and self.value < self.min_count: + raise ValueError( + f"Value passed in is lower than min_count.\n\nRAM Address: {self.ram_address}\nValue: {self.value}\nMin Count: {self.max_count}" + ) + + if self.binary_bit_pos and self.update_method not in [UpdateMethod.SET, UpdateMethod.FREEZE]: + raise ValueError(f"binary_bit_position can only be passed in if update_method is SET or FREEZE") + + if self.binary_bit_pos and self.value not in [0, 1]: + raise ValueError(f"value must be 0 or 1 if using binary_bit_position") diff --git a/worlds/grinch/Regions.py b/worlds/grinch/Regions.py index 2335a9cb..d18dec18 100644 --- a/worlds/grinch/Regions.py +++ b/worlds/grinch/Regions.py @@ -41,22 +41,16 @@ supadow_list = [ def create_regions(world: "GrinchWorld"): - for mainarea in mainareas_list: - # Each area in mainarea, create a region for the given player - world.multiworld.regions.append( - Region(mainarea, world.player, world.multiworld) - ) - for subarea in subareas_list: - # Each area in subarea, create a region for the given player - world.multiworld.regions.append(Region(subarea, world.player, world.multiworld)) - for supadow in supadow_list: - # Each area in supadow, create a region for the given player - world.multiworld.regions.append(Region(supadow, world.player, world.multiworld)) + for area in [*mainareas_list, *subareas_list, *supadow_list]: + # Each area in mainarea, subarea, and supadow create a region for the given player + world.multiworld.regions.append(Region(area, world.player, world.multiworld)) # TODO Optimize this function def grinchconnect( - world: "GrinchWorld", current_region_name: str, connected_region_name: str + world: "GrinchWorld", + current_region_name: str, + connected_region_name: str, ): current_region = world.get_region(current_region_name) connected_region = world.get_region(connected_region_name) @@ -66,6 +60,7 @@ def grinchconnect( current_region.connect(connected_region) # Goes from connected to current connected_region.connect(current_region) + for access_rule in rule_list: for region_entrance in current_region.entrances: if ( @@ -74,8 +69,10 @@ def grinchconnect( ): if rule_list.index(access_rule) == 0: add_rule(region_entrance, access_rule) + else: add_rule(region_entrance, access_rule, combine="or") + for region_entrance in connected_region.entrances: if ( region_entrance.connected_region.name == connected_region_name @@ -83,6 +80,7 @@ def grinchconnect( ): if rule_list.index(access_rule) == 0: add_rule(region_entrance, access_rule) + else: add_rule(region_entrance, access_rule, combine="or") diff --git a/worlds/grinch/Rules.py b/worlds/grinch/Rules.py index fac34e55..1ab47d8c 100644 --- a/worlds/grinch/Rules.py +++ b/worlds/grinch/Rules.py @@ -20,7 +20,10 @@ def set_location_rules(world: World): add_rule(location, access_rule, "or") -def interpret_rule(rule_set: list[list[str]], player: int): +def interpret_rule( + rule_set: list[list[str]], + player: int, +): # If a region/location does not have any items required, make the section(s) return no logic. if len(rule_set) < 1: return True @@ -29,9 +32,7 @@ def interpret_rule(rule_set: list[list[str]], player: int): access_list: list[Callable[[CollectionState], bool]] = [] for item_set in rule_set: - access_list.append( - lambda state, items=tuple(item_set): state.has_all(items, player) - ) + access_list.append(lambda state, items=tuple(item_set): state.has_all(items, player)) return access_list # Each item in the list is a separate list of rules. Each separate list is just an "OR" condition. @@ -130,12 +131,12 @@ access_rules_dict: dict[str, list[list[str]]] = { ], "North Shore": [ [ - grinch_items.level_items.WL_SCOUT_CLOTHESL, + grinch_items.level_items.WL_SCOUT_CLOTHES, ] ], "Mayor's Villa": [ [ - grinch_items.level_items.WL_SCOUT_CLOTHESL, + grinch_items.level_items.WL_SCOUT_CLOTHES, ] ], "Submarine World": [ @@ -408,9 +409,7 @@ rules_dict: dict[str, list[list[str]]] = { "WV - TEL BP left of City Hall": [[]], "WV - REL BP left of Clock Tower": [[]], "WV - Post Office - REL BP inside Silver Room": [[]], - "WV - Post Office - REL BP at Entrance Door after Migrinch_items.gadgets.SLIME_SHOOTERion Completion": [ - [] - ], + "WV - Post Office - REL BP at Entrance Door after Migrinch_items.gadgets.SLIME_SHOOTERion Completion": [[]], "WV - City Hall - GC BP in Safe Room": [[]], "WV - City Hall - GC BP in Statue Room": [[]], "WV - Clock Tower - GC BP in Bedroom": [ @@ -764,9 +763,7 @@ rules_dict: dict[str, list[list[str]]] = { "WL - North Shore - MM BP inside Boulder Box behind Skunk Hut": [[]], "WL - North Shore - MM BP inside Drill House": [[]], "WL - North Shore - MM BP on Crow Platform near Drill House": [[]], - "WL - Submarine World - GC BP Just Below Water Surface": [ - [grinch_items.gadgets.MARINE_MOBILE] - ], + "WL - Submarine World - GC BP Just Below Water Surface": [[grinch_items.gadgets.MARINE_MOBILE]], "WL - Submarine World - GC BP Underwater": [ [ grinch_items.gadgets.MARINE_MOBILE, diff --git a/worlds/grinch/__init__.py b/worlds/grinch/__init__.py index b13185db..c4b6d73f 100644 --- a/worlds/grinch/__init__.py +++ b/worlds/grinch/__init__.py @@ -18,53 +18,65 @@ class GrinchWorld(World): game: ClassVar[str] = "The Grinch" options_dataclass = Options.GrinchOptions options: Options.GrinchOptions - topology_present = True #not an open world game, very linear - item_name_to_id: ClassVar[dict[str,int]] = grinch_items_to_id() - location_name_to_id: ClassVar[dict[str,int]] = grinch_locations_to_id() + topology_present = True # not an open world game, very linear + item_name_to_id: ClassVar[dict[str, int]] = grinch_items_to_id() + location_name_to_id: ClassVar[dict[str, int]] = grinch_locations_to_id() required_client_version = (0, 6, 3) item_name_groups = get_item_names_per_category() location_name_groups = get_location_names_per_category() - def __init__(self, *args, **kwargs): #Pulls __init__ function and takes control from there in BaseClasses.py + def __init__(self, *args, **kwargs): # Pulls __init__ function and takes control from there in BaseClasses.py self.origin_region_name: str = "Mount Crumpit" super(GrinchWorld, self).__init__(*args, **kwargs) - def generate_early(self) -> None: #Special conditions changed before generation occurs + def generate_early(self) -> None: # Special conditions changed before generation occurs if self.options.ring_link == 1 and self.options.unlimited_eggs == 1: - raise OptionError("Cannot enable both unlimited rotten eggs and ring links. You can only enable one of these at a time." + - f"The following player's YAML needs to be fixed: {self.player_name}") + raise OptionError( + "Cannot enable both unlimited rotten eggs and ring links. You can only enable one of these at a time." + + f"The following player's YAML needs to be fixed: {self.player_name}" + ) - - def create_regions(self): #Generates all regions for the multiworld + def create_regions(self): # Generates all regions for the multiworld for region_name in access_rules_dict.keys(): self.multiworld.regions.append(Region(region_name, self.player, self.multiworld)) + self.multiworld.regions.append(Region("Mount Crumpit", self.player, self.multiworld)) + for location, data in grinch_locations.items(): region = self.get_region(data.region) entry = GrinchLocation(self.player, location, region, data) + if location == "MC - Sleigh Ride - Neutralizing Santa": entry.place_locked_item(Item("Goal", ItemClassification.progression, None, self.player)) + region.locations.append(entry) + connect_regions(self) - def create_item(self, item: str) -> GrinchItem: #Creates specific items on demand + def create_item(self, item: str) -> GrinchItem: # Creates specific items on demand if item in ALL_ITEMS_TABLE.keys(): return GrinchItem(item, self.player, ALL_ITEMS_TABLE[item]) + raise Exception(f"Invalid item name: {item}") - def create_items(self): #Generates all items for the multiworld + def create_items(self): # Generates all items for the multiworld self_itempool: list[GrinchItem] = [] + for item, data in ALL_ITEMS_TABLE.items(): self_itempool.append(self.create_item(item)) + if item == "Heart of Stone": for _ in range(3): self_itempool.append(self.create_item(item)) - #Get number of current unfilled locations - unfilled_locations: int = len(self.multiworld.get_unfilled_locations(self.player)) - len(ALL_ITEMS_TABLE.keys()) - 3 + # Get number of current unfilled locations + unfilled_locations: int = ( + len(self.multiworld.get_unfilled_locations(self.player)) - len(ALL_ITEMS_TABLE.keys()) - 3 + ) for _ in range(unfilled_locations): self_itempool.append(self.create_item((self.get_other_filler_item(list(MISC_ITEMS_TABLE.keys()))))) + self.multiworld.itempool += self_itempool def set_rules(self): @@ -82,4 +94,4 @@ class GrinchWorld(World): def generate_output(self, output_directory: str) -> None: # print("") - pass \ No newline at end of file + pass