From 1307754f0291aa117ace540e54574923487e0a46 Mon Sep 17 00:00:00 2001 From: zig-for Date: Fri, 19 Jan 2024 12:14:26 -0800 Subject: [PATCH 01/15] LADX: music shuffle (#2101) --- worlds/ladx/Options.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/worlds/ladx/Options.py b/worlds/ladx/Options.py index 691891c0b350..117242208be2 100644 --- a/worlds/ladx/Options.py +++ b/worlds/ladx/Options.py @@ -399,6 +399,26 @@ class Palette(Choice): option_pink = 4 option_inverted = 5 +class Music(Choice, LADXROption): + """ + [Vanilla] Regular Music + [Shuffled] Shuffled Music + [Off] No music + """ + ladxr_name = "music" + option_vanilla = 0 + option_shuffled = 1 + option_off = 2 + + + def to_ladxr_option(self, all_options): + s = "" + if self.value == self.option_shuffled: + s = "random" + elif self.value == self.option_off: + s = "off" + return self.ladxr_name, s + class WarpImprovements(DefaultOffToggle): """ [On] Adds remake style warp screen to the game. Choose your warp destination on the map after jumping in a portal and press B to select. @@ -444,6 +464,7 @@ class AdditionalWarpPoints(DefaultOffToggle): 'shuffle_maps': ShuffleMaps, 'shuffle_compasses': ShuffleCompasses, 'shuffle_stone_beaks': ShuffleStoneBeaks, + 'music': Music, 'music_change_condition': MusicChangeCondition, 'nag_messages': NagMessages, 'ap_title_screen': APTitleScreen, From 5f9ce2b7b60fe05a54ccd3498c67da7cac361a63 Mon Sep 17 00:00:00 2001 From: Scipio Wright Date: Fri, 19 Jan 2024 15:31:45 -0500 Subject: [PATCH 02/15] Noita: Update to use new Options API (#2370) Reworking the options to make it work with the new options API. Also reworked stuff in several spots to use world: NoitaWorld instead of multiworld: MultiWorld --- worlds/noita/Events.py | 42 ----- worlds/noita/Rules.py | 166 ------------------- worlds/noita/__init__.py | 31 ++-- worlds/noita/events.py | 43 +++++ worlds/noita/{Items.py => items.py} | 44 ++--- worlds/noita/{Locations.py => locations.py} | 23 +-- worlds/noita/{Options.py => options.py} | 30 ++-- worlds/noita/{Regions.py => regions.py} | 64 ++++---- worlds/noita/rules.py | 172 ++++++++++++++++++++ 9 files changed, 314 insertions(+), 301 deletions(-) delete mode 100644 worlds/noita/Events.py delete mode 100644 worlds/noita/Rules.py create mode 100644 worlds/noita/events.py rename worlds/noita/{Items.py => items.py} (82%) rename worlds/noita/{Locations.py => locations.py} (94%) rename worlds/noita/{Options.py => options.py} (87%) rename worlds/noita/{Regions.py => regions.py} (61%) create mode 100644 worlds/noita/rules.py diff --git a/worlds/noita/Events.py b/worlds/noita/Events.py deleted file mode 100644 index e759d38c6c7a..000000000000 --- a/worlds/noita/Events.py +++ /dev/null @@ -1,42 +0,0 @@ -from typing import Dict - -from BaseClasses import Item, ItemClassification, Location, MultiWorld, Region -from . import Items, Locations - - -def create_event(player: int, name: str) -> Item: - return Items.NoitaItem(name, ItemClassification.progression, None, player) - - -def create_location(player: int, name: str, region: Region) -> Location: - return Locations.NoitaLocation(player, name, None, region) - - -def create_locked_location_event(multiworld: MultiWorld, player: int, region_name: str, item: str) -> Location: - region = multiworld.get_region(region_name, player) - - new_location = create_location(player, item, region) - new_location.place_locked_item(create_event(player, item)) - - region.locations.append(new_location) - return new_location - - -def create_all_events(multiworld: MultiWorld, player: int) -> None: - for region, event in event_locks.items(): - create_locked_location_event(multiworld, player, region, event) - - multiworld.completion_condition[player] = lambda state: state.has("Victory", player) - - -# Maps region names to event names -event_locks: Dict[str, str] = { - "The Work": "Victory", - "Mines": "Portal to Holy Mountain 1", - "Coal Pits": "Portal to Holy Mountain 2", - "Snowy Depths": "Portal to Holy Mountain 3", - "Hiisi Base": "Portal to Holy Mountain 4", - "Underground Jungle": "Portal to Holy Mountain 5", - "The Vault": "Portal to Holy Mountain 6", - "Temple of the Art": "Portal to Holy Mountain 7", -} diff --git a/worlds/noita/Rules.py b/worlds/noita/Rules.py deleted file mode 100644 index 8190b80dc710..000000000000 --- a/worlds/noita/Rules.py +++ /dev/null @@ -1,166 +0,0 @@ -from typing import List, NamedTuple, Set - -from BaseClasses import CollectionState, MultiWorld -from . import Items, Locations -from .Options import BossesAsChecks, VictoryCondition -from worlds.generic import Rules as GenericRules - - -class EntranceLock(NamedTuple): - source: str - destination: str - event: str - items_needed: int - - -entrance_locks: List[EntranceLock] = [ - EntranceLock("Mines", "Coal Pits Holy Mountain", "Portal to Holy Mountain 1", 1), - EntranceLock("Coal Pits", "Snowy Depths Holy Mountain", "Portal to Holy Mountain 2", 2), - EntranceLock("Snowy Depths", "Hiisi Base Holy Mountain", "Portal to Holy Mountain 3", 3), - EntranceLock("Hiisi Base", "Underground Jungle Holy Mountain", "Portal to Holy Mountain 4", 4), - EntranceLock("Underground Jungle", "Vault Holy Mountain", "Portal to Holy Mountain 5", 5), - EntranceLock("The Vault", "Temple of the Art Holy Mountain", "Portal to Holy Mountain 6", 6), - EntranceLock("Temple of the Art", "Laboratory Holy Mountain", "Portal to Holy Mountain 7", 7), -] - - -holy_mountain_regions: List[str] = [ - "Coal Pits Holy Mountain", - "Snowy Depths Holy Mountain", - "Hiisi Base Holy Mountain", - "Underground Jungle Holy Mountain", - "Vault Holy Mountain", - "Temple of the Art Holy Mountain", - "Laboratory Holy Mountain", -] - - -wand_tiers: List[str] = [ - "Wand (Tier 1)", # Coal Pits - "Wand (Tier 2)", # Snowy Depths - "Wand (Tier 3)", # Hiisi Base - "Wand (Tier 4)", # Underground Jungle - "Wand (Tier 5)", # The Vault - "Wand (Tier 6)", # Temple of the Art -] - -items_hidden_from_shops: List[str] = ["Gold (200)", "Gold (1000)", "Potion", "Random Potion", "Secret Potion", - "Chaos Die", "Greed Die", "Kammi", "Refreshing Gourd", "Sädekivi", "Broken Wand", - "Powder Pouch"] - -perk_list: List[str] = list(filter(Items.item_is_perk, Items.item_table.keys())) - - -# ---------------- -# Helper Functions -# ---------------- - - -def has_perk_count(state: CollectionState, player: int, amount: int) -> bool: - return sum(state.count(perk, player) for perk in perk_list) >= amount - - -def has_orb_count(state: CollectionState, player: int, amount: int) -> bool: - return state.count("Orb", player) >= amount - - -def forbid_items_at_location(multiworld: MultiWorld, location_name: str, items: Set[str], player: int): - location = multiworld.get_location(location_name, player) - GenericRules.forbid_items_for_player(location, items, player) - - -# ---------------- -# Rule Functions -# ---------------- - - -# Prevent gold and potions from appearing as purchasable items in shops (because physics will destroy them) -def ban_items_from_shops(multiworld: MultiWorld, player: int) -> None: - for location_name in Locations.location_name_to_id.keys(): - if "Shop Item" in location_name: - forbid_items_at_location(multiworld, location_name, items_hidden_from_shops, player) - - -# Prevent high tier wands from appearing in early Holy Mountain shops -def ban_early_high_tier_wands(multiworld: MultiWorld, player: int) -> None: - for i, region_name in enumerate(holy_mountain_regions): - wands_to_forbid = wand_tiers[i+1:] - - locations_in_region = Locations.location_region_mapping[region_name].keys() - for location_name in locations_in_region: - forbid_items_at_location(multiworld, location_name, wands_to_forbid, player) - - # Prevent high tier wands from appearing in the Secret shop - wands_to_forbid = wand_tiers[3:] - locations_in_region = Locations.location_region_mapping["Secret Shop"].keys() - for location_name in locations_in_region: - forbid_items_at_location(multiworld, location_name, wands_to_forbid, player) - - -def lock_holy_mountains_into_spheres(multiworld: MultiWorld, player: int) -> None: - for lock in entrance_locks: - location = multiworld.get_entrance(f"From {lock.source} To {lock.destination}", player) - GenericRules.set_rule(location, lambda state, evt=lock.event: state.has(evt, player)) - - -def holy_mountain_unlock_conditions(multiworld: MultiWorld, player: int) -> None: - victory_condition = multiworld.victory_condition[player].value - for lock in entrance_locks: - location = multiworld.get_location(lock.event, player) - - if victory_condition == VictoryCondition.option_greed_ending: - location.access_rule = lambda state, items_needed=lock.items_needed: ( - has_perk_count(state, player, items_needed//2) - ) - elif victory_condition == VictoryCondition.option_pure_ending: - location.access_rule = lambda state, items_needed=lock.items_needed: ( - has_perk_count(state, player, items_needed//2) and - has_orb_count(state, player, items_needed) - ) - elif victory_condition == VictoryCondition.option_peaceful_ending: - location.access_rule = lambda state, items_needed=lock.items_needed: ( - has_perk_count(state, player, items_needed//2) and - has_orb_count(state, player, items_needed * 3) - ) - - -def biome_unlock_conditions(multiworld: MultiWorld, player: int): - lukki_entrances = multiworld.get_region("Lukki Lair", player).entrances - magical_entrances = multiworld.get_region("Magical Temple", player).entrances - wizard_entrances = multiworld.get_region("Wizards' Den", player).entrances - for entrance in lukki_entrances: - entrance.access_rule = lambda state: state.has("Melee Immunity Perk", player) and\ - state.has("All-Seeing Eye Perk", player) - for entrance in magical_entrances: - entrance.access_rule = lambda state: state.has("All-Seeing Eye Perk", player) - for entrance in wizard_entrances: - entrance.access_rule = lambda state: state.has("All-Seeing Eye Perk", player) - - -def victory_unlock_conditions(multiworld: MultiWorld, player: int) -> None: - victory_condition = multiworld.victory_condition[player].value - victory_location = multiworld.get_location("Victory", player) - - if victory_condition == VictoryCondition.option_pure_ending: - victory_location.access_rule = lambda state: has_orb_count(state, player, 11) - elif victory_condition == VictoryCondition.option_peaceful_ending: - victory_location.access_rule = lambda state: has_orb_count(state, player, 33) - - -# ---------------- -# Main Function -# ---------------- - - -def create_all_rules(multiworld: MultiWorld, player: int) -> None: - if multiworld.players > 1: - ban_items_from_shops(multiworld, player) - ban_early_high_tier_wands(multiworld, player) - lock_holy_mountains_into_spheres(multiworld, player) - holy_mountain_unlock_conditions(multiworld, player) - biome_unlock_conditions(multiworld, player) - victory_unlock_conditions(multiworld, player) - - # Prevent the Map perk (used to find Toveri) from being on Toveri (boss) - if multiworld.bosses_as_checks[player].value >= BossesAsChecks.option_all_bosses: - forbid_items_at_location(multiworld, "Toveri", {"Spatial Awareness Perk"}, player) diff --git a/worlds/noita/__init__.py b/worlds/noita/__init__.py index 792b90e3f551..b8f8e4ae8346 100644 --- a/worlds/noita/__init__.py +++ b/worlds/noita/__init__.py @@ -1,6 +1,8 @@ from BaseClasses import Item, Tutorial from worlds.AutoWorld import WebWorld, World -from . import Events, Items, Locations, Options, Regions, Rules +from typing import Dict, Any +from . import events, items, locations, regions, rules +from .options import NoitaOptions class NoitaWeb(WebWorld): @@ -24,13 +26,14 @@ class NoitaWorld(World): """ game = "Noita" - option_definitions = Options.noita_options + options: NoitaOptions + options_dataclass = NoitaOptions - item_name_to_id = Items.item_name_to_id - location_name_to_id = Locations.location_name_to_id + item_name_to_id = items.item_name_to_id + location_name_to_id = locations.location_name_to_id - item_name_groups = Items.item_name_groups - location_name_groups = Locations.location_name_groups + item_name_groups = items.item_name_groups + location_name_groups = locations.location_name_groups data_version = 2 web = NoitaWeb() @@ -40,21 +43,21 @@ def generate_early(self): raise Exception("Noita yaml's slot name has invalid character(s).") # Returned items will be sent over to the client - def fill_slot_data(self): - return {name: getattr(self.multiworld, name)[self.player].value for name in self.option_definitions} + def fill_slot_data(self) -> Dict[str, Any]: + return self.options.as_dict("death_link", "victory_condition", "path_option", "hidden_chests", + "pedestal_checks", "orbs_as_checks", "bosses_as_checks", "extra_orbs", "shop_price") def create_regions(self) -> None: - Regions.create_all_regions_and_connections(self.multiworld, self.player) - Events.create_all_events(self.multiworld, self.player) + regions.create_all_regions_and_connections(self) def create_item(self, name: str) -> Item: - return Items.create_item(self.player, name) + return items.create_item(self.player, name) def create_items(self) -> None: - Items.create_all_items(self.multiworld, self.player) + items.create_all_items(self) def set_rules(self) -> None: - Rules.create_all_rules(self.multiworld, self.player) + rules.create_all_rules(self) def get_filler_item_name(self) -> str: - return self.multiworld.random.choice(Items.filler_items) + return self.random.choice(items.filler_items) diff --git a/worlds/noita/events.py b/worlds/noita/events.py new file mode 100644 index 000000000000..4ec04e98b457 --- /dev/null +++ b/worlds/noita/events.py @@ -0,0 +1,43 @@ +from typing import Dict, TYPE_CHECKING +from BaseClasses import Item, ItemClassification, Location, Region +from . import items, locations + +if TYPE_CHECKING: + from . import NoitaWorld + + +def create_event(player: int, name: str) -> Item: + return items.NoitaItem(name, ItemClassification.progression, None, player) + + +def create_location(player: int, name: str, region: Region) -> Location: + return locations.NoitaLocation(player, name, None, region) + + +def create_locked_location_event(player: int, region: Region, item: str) -> Location: + new_location = create_location(player, item, region) + new_location.place_locked_item(create_event(player, item)) + + region.locations.append(new_location) + return new_location + + +def create_all_events(world: "NoitaWorld", created_regions: Dict[str, Region]) -> None: + for region_name, event in event_locks.items(): + region = created_regions[region_name] + create_locked_location_event(world.player, region, event) + + world.multiworld.completion_condition[world.player] = lambda state: state.has("Victory", world.player) + + +# Maps region names to event names +event_locks: Dict[str, str] = { + "The Work": "Victory", + "Mines": "Portal to Holy Mountain 1", + "Coal Pits": "Portal to Holy Mountain 2", + "Snowy Depths": "Portal to Holy Mountain 3", + "Hiisi Base": "Portal to Holy Mountain 4", + "Underground Jungle": "Portal to Holy Mountain 5", + "The Vault": "Portal to Holy Mountain 6", + "Temple of the Art": "Portal to Holy Mountain 7", +} diff --git a/worlds/noita/Items.py b/worlds/noita/items.py similarity index 82% rename from worlds/noita/Items.py rename to worlds/noita/items.py index c859a8039494..6b662fbee692 100644 --- a/worlds/noita/Items.py +++ b/worlds/noita/items.py @@ -1,9 +1,14 @@ import itertools from collections import Counter -from typing import Dict, List, NamedTuple, Set +from typing import Dict, List, NamedTuple, Set, TYPE_CHECKING -from BaseClasses import Item, ItemClassification, MultiWorld -from .Options import BossesAsChecks, VictoryCondition, ExtraOrbs +from BaseClasses import Item, ItemClassification +from .options import BossesAsChecks, VictoryCondition, ExtraOrbs + +if TYPE_CHECKING: + from . import NoitaWorld +else: + NoitaWorld = object class ItemData(NamedTuple): @@ -44,39 +49,40 @@ def create_kantele(victory_condition: VictoryCondition) -> List[str]: return ["Kantele"] if victory_condition.value >= VictoryCondition.option_pure_ending else [] -def create_random_items(multiworld: MultiWorld, player: int, weights: Dict[str, int], count: int) -> List[str]: +def create_random_items(world: NoitaWorld, weights: Dict[str, int], count: int) -> List[str]: filler_pool = weights.copy() - if multiworld.bad_effects[player].value == 0: + if not world.options.bad_effects: del filler_pool["Trap"] - return multiworld.random.choices(population=list(filler_pool.keys()), - weights=list(filler_pool.values()), - k=count) + return world.random.choices(population=list(filler_pool.keys()), + weights=list(filler_pool.values()), + k=count) -def create_all_items(multiworld: MultiWorld, player: int) -> None: - locations_to_fill = len(multiworld.get_unfilled_locations(player)) +def create_all_items(world: NoitaWorld) -> None: + player = world.player + locations_to_fill = len(world.multiworld.get_unfilled_locations(player)) itempool = ( create_fixed_item_pool() - + create_orb_items(multiworld.victory_condition[player], multiworld.extra_orbs[player]) - + create_spatial_awareness_item(multiworld.bosses_as_checks[player]) - + create_kantele(multiworld.victory_condition[player]) + + create_orb_items(world.options.victory_condition, world.options.extra_orbs) + + create_spatial_awareness_item(world.options.bosses_as_checks) + + create_kantele(world.options.victory_condition) ) # if there's not enough shop-allowed items in the pool, we can encounter gen issues # 39 is the number of shop-valid items we need to guarantee if len(itempool) < 39: - itempool += create_random_items(multiworld, player, shop_only_filler_weights, 39 - len(itempool)) + itempool += create_random_items(world, shop_only_filler_weights, 39 - len(itempool)) # this is so that it passes tests and gens if you have minimal locations and only one player - if multiworld.players == 1: - for location in multiworld.get_unfilled_locations(player): + if world.multiworld.players == 1: + for location in world.multiworld.get_unfilled_locations(player): if "Shop Item" in location.name: location.item = create_item(player, itempool.pop()) - locations_to_fill = len(multiworld.get_unfilled_locations(player)) + locations_to_fill = len(world.multiworld.get_unfilled_locations(player)) - itempool += create_random_items(multiworld, player, filler_weights, locations_to_fill - len(itempool)) - multiworld.itempool += [create_item(player, name) for name in itempool] + itempool += create_random_items(world, filler_weights, locations_to_fill - len(itempool)) + world.multiworld.itempool += [create_item(player, name) for name in itempool] # 110000 - 110032 diff --git a/worlds/noita/Locations.py b/worlds/noita/locations.py similarity index 94% rename from worlds/noita/Locations.py rename to worlds/noita/locations.py index 7c27d699ccba..afe16c54e4b2 100644 --- a/worlds/noita/Locations.py +++ b/worlds/noita/locations.py @@ -201,11 +201,10 @@ class LocationFlag(IntEnum): } -# Iterating the hidden chest and pedestal locations here to avoid clutter above -def generate_location_entries(locname: str, locinfo: LocationData) -> Dict[str, int]: - if locinfo.ltype in ["chest", "pedestal"]: - return {f"{locname} {i + 1}": locinfo.id + i for i in range(20)} - return {locname: locinfo.id} +def make_location_range(location_name: str, base_id: int, amt: int) -> Dict[str, int]: + if amt == 1: + return {location_name: base_id} + return {f"{location_name} {i+1}": base_id + i for i in range(amt)} location_name_groups: Dict[str, Set[str]] = {"shop": set(), "orb": set(), "boss": set(), "chest": set(), @@ -215,9 +214,11 @@ def generate_location_entries(locname: str, locinfo: LocationData) -> Dict[str, for location_group in location_region_mapping.values(): for locname, locinfo in location_group.items(): - location_name_to_id.update(generate_location_entries(locname, locinfo)) - if locinfo.ltype in ["chest", "pedestal"]: - for i in range(20): - location_name_groups[locinfo.ltype].add(f"{locname} {i + 1}") - else: - location_name_groups[locinfo.ltype].add(locname) + # Iterating the hidden chest and pedestal locations here to avoid clutter above + amount = 20 if locinfo.ltype in ["chest", "pedestal"] else 1 + entries = make_location_range(locname, locinfo.id, amount) + + location_name_to_id.update(entries) + location_name_groups[locinfo.ltype].update(entries.keys()) + +shop_locations = {name for name in location_name_to_id.keys() if "Shop Item" in name} diff --git a/worlds/noita/Options.py b/worlds/noita/options.py similarity index 87% rename from worlds/noita/Options.py rename to worlds/noita/options.py index 0b54597f364d..7d987571a589 100644 --- a/worlds/noita/Options.py +++ b/worlds/noita/options.py @@ -1,5 +1,5 @@ -from typing import Dict -from Options import AssembleOptions, Choice, DeathLink, DefaultOnToggle, Range, StartInventoryPool +from Options import Choice, DeathLink, DefaultOnToggle, Range, StartInventoryPool, PerGameCommonOptions +from dataclasses import dataclass class PathOption(Choice): @@ -99,16 +99,16 @@ class ShopPrice(Choice): default = 100 -noita_options: Dict[str, AssembleOptions] = { - "start_inventory_from_pool": StartInventoryPool, - "death_link": DeathLink, - "bad_effects": Traps, - "victory_condition": VictoryCondition, - "path_option": PathOption, - "hidden_chests": HiddenChests, - "pedestal_checks": PedestalChecks, - "orbs_as_checks": OrbsAsChecks, - "bosses_as_checks": BossesAsChecks, - "extra_orbs": ExtraOrbs, - "shop_price": ShopPrice, -} +@dataclass +class NoitaOptions(PerGameCommonOptions): + start_inventory_from_pool: StartInventoryPool + death_link: DeathLink + bad_effects: Traps + victory_condition: VictoryCondition + path_option: PathOption + hidden_chests: HiddenChests + pedestal_checks: PedestalChecks + orbs_as_checks: OrbsAsChecks + bosses_as_checks: BossesAsChecks + extra_orbs: ExtraOrbs + shop_price: ShopPrice diff --git a/worlds/noita/Regions.py b/worlds/noita/regions.py similarity index 61% rename from worlds/noita/Regions.py rename to worlds/noita/regions.py index 561d483b4865..6a9c86772381 100644 --- a/worlds/noita/Regions.py +++ b/worlds/noita/regions.py @@ -1,48 +1,43 @@ # Regions are areas in your game that you travel to. -from typing import Dict, Set, List +from typing import Dict, List, TYPE_CHECKING -from BaseClasses import Entrance, MultiWorld, Region -from . import Locations +from BaseClasses import Entrance, Region +from . import locations +from .events import create_all_events +if TYPE_CHECKING: + from . import NoitaWorld -def add_location(player: int, loc_name: str, id: int, region: Region) -> None: - location = Locations.NoitaLocation(player, loc_name, id, region) - region.locations.append(location) - -def add_locations(multiworld: MultiWorld, player: int, region: Region) -> None: - locations = Locations.location_region_mapping.get(region.name, {}) - for location_name, location_data in locations.items(): +def create_locations(world: "NoitaWorld", region: Region) -> None: + locs = locations.location_region_mapping.get(region.name, {}) + for location_name, location_data in locs.items(): location_type = location_data.ltype flag = location_data.flag - opt_orbs = multiworld.orbs_as_checks[player].value - opt_bosses = multiworld.bosses_as_checks[player].value - opt_paths = multiworld.path_option[player].value - opt_num_chests = multiworld.hidden_chests[player].value - opt_num_pedestals = multiworld.pedestal_checks[player].value + is_orb_allowed = location_type == "orb" and flag <= world.options.orbs_as_checks + is_boss_allowed = location_type == "boss" and flag <= world.options.bosses_as_checks + amount = 0 + if flag == locations.LocationFlag.none or is_orb_allowed or is_boss_allowed: + amount = 1 + elif location_type == "chest" and flag <= world.options.path_option: + amount = world.options.hidden_chests.value + elif location_type == "pedestal" and flag <= world.options.path_option: + amount = world.options.pedestal_checks.value - is_orb_allowed = location_type == "orb" and flag <= opt_orbs - is_boss_allowed = location_type == "boss" and flag <= opt_bosses - if flag == Locations.LocationFlag.none or is_orb_allowed or is_boss_allowed: - add_location(player, location_name, location_data.id, region) - elif location_type == "chest" and flag <= opt_paths: - for i in range(opt_num_chests): - add_location(player, f"{location_name} {i+1}", location_data.id + i, region) - elif location_type == "pedestal" and flag <= opt_paths: - for i in range(opt_num_pedestals): - add_location(player, f"{location_name} {i+1}", location_data.id + i, region) + region.add_locations(locations.make_location_range(location_name, location_data.id, amount), + locations.NoitaLocation) # Creates a new Region with the locations found in `location_region_mapping` and adds them to the world. -def create_region(multiworld: MultiWorld, player: int, region_name: str) -> Region: - new_region = Region(region_name, player, multiworld) - add_locations(multiworld, player, new_region) +def create_region(world: "NoitaWorld", region_name: str) -> Region: + new_region = Region(region_name, world.player, world.multiworld) + create_locations(world, new_region) return new_region -def create_regions(multiworld: MultiWorld, player: int) -> Dict[str, Region]: - return {name: create_region(multiworld, player, name) for name in noita_regions} +def create_regions(world: "NoitaWorld") -> Dict[str, Region]: + return {name: create_region(world, name) for name in noita_regions} # An "Entrance" is really just a connection between two regions @@ -60,11 +55,12 @@ def create_connections(player: int, regions: Dict[str, Region]) -> None: # Creates all regions and connections. Called from NoitaWorld. -def create_all_regions_and_connections(multiworld: MultiWorld, player: int) -> None: - created_regions = create_regions(multiworld, player) - create_connections(player, created_regions) +def create_all_regions_and_connections(world: "NoitaWorld") -> None: + created_regions = create_regions(world) + create_connections(world.player, created_regions) + create_all_events(world, created_regions) - multiworld.regions += created_regions.values() + world.multiworld.regions += created_regions.values() # Oh, what a tangled web we weave diff --git a/worlds/noita/rules.py b/worlds/noita/rules.py new file mode 100644 index 000000000000..95039bee4635 --- /dev/null +++ b/worlds/noita/rules.py @@ -0,0 +1,172 @@ +from typing import List, NamedTuple, Set, TYPE_CHECKING + +from BaseClasses import CollectionState +from . import items, locations +from .options import BossesAsChecks, VictoryCondition +from worlds.generic import Rules as GenericRules + +if TYPE_CHECKING: + from . import NoitaWorld + + +class EntranceLock(NamedTuple): + source: str + destination: str + event: str + items_needed: int + + +entrance_locks: List[EntranceLock] = [ + EntranceLock("Mines", "Coal Pits Holy Mountain", "Portal to Holy Mountain 1", 1), + EntranceLock("Coal Pits", "Snowy Depths Holy Mountain", "Portal to Holy Mountain 2", 2), + EntranceLock("Snowy Depths", "Hiisi Base Holy Mountain", "Portal to Holy Mountain 3", 3), + EntranceLock("Hiisi Base", "Underground Jungle Holy Mountain", "Portal to Holy Mountain 4", 4), + EntranceLock("Underground Jungle", "Vault Holy Mountain", "Portal to Holy Mountain 5", 5), + EntranceLock("The Vault", "Temple of the Art Holy Mountain", "Portal to Holy Mountain 6", 6), + EntranceLock("Temple of the Art", "Laboratory Holy Mountain", "Portal to Holy Mountain 7", 7), +] + + +holy_mountain_regions: List[str] = [ + "Coal Pits Holy Mountain", + "Snowy Depths Holy Mountain", + "Hiisi Base Holy Mountain", + "Underground Jungle Holy Mountain", + "Vault Holy Mountain", + "Temple of the Art Holy Mountain", + "Laboratory Holy Mountain", +] + + +wand_tiers: List[str] = [ + "Wand (Tier 1)", # Coal Pits + "Wand (Tier 2)", # Snowy Depths + "Wand (Tier 3)", # Hiisi Base + "Wand (Tier 4)", # Underground Jungle + "Wand (Tier 5)", # The Vault + "Wand (Tier 6)", # Temple of the Art +] + + +items_hidden_from_shops: Set[str] = {"Gold (200)", "Gold (1000)", "Potion", "Random Potion", "Secret Potion", + "Chaos Die", "Greed Die", "Kammi", "Refreshing Gourd", "Sädekivi", "Broken Wand", + "Powder Pouch"} + +perk_list: List[str] = list(filter(items.item_is_perk, items.item_table.keys())) + + +# ---------------- +# Helper Functions +# ---------------- + + +def has_perk_count(state: CollectionState, player: int, amount: int) -> bool: + return sum(state.count(perk, player) for perk in perk_list) >= amount + + +def has_orb_count(state: CollectionState, player: int, amount: int) -> bool: + return state.count("Orb", player) >= amount + + +def forbid_items_at_locations(world: "NoitaWorld", shop_locations: Set[str], forbidden_items: Set[str]): + for shop_location in shop_locations: + location = world.multiworld.get_location(shop_location, world.player) + GenericRules.forbid_items_for_player(location, forbidden_items, world.player) + + +# ---------------- +# Rule Functions +# ---------------- + + +# Prevent gold and potions from appearing as purchasable items in shops (because physics will destroy them) +# def ban_items_from_shops(world: "NoitaWorld") -> None: +# for location_name in Locations.location_name_to_id.keys(): +# if "Shop Item" in location_name: +# forbid_items_at_location(world, location_name, items_hidden_from_shops) +def ban_items_from_shops(world: "NoitaWorld") -> None: + forbid_items_at_locations(world, locations.shop_locations, items_hidden_from_shops) + + +# Prevent high tier wands from appearing in early Holy Mountain shops +def ban_early_high_tier_wands(world: "NoitaWorld") -> None: + for i, region_name in enumerate(holy_mountain_regions): + wands_to_forbid = set(wand_tiers[i+1:]) + + locations_in_region = set(locations.location_region_mapping[region_name].keys()) + forbid_items_at_locations(world, locations_in_region, wands_to_forbid) + + # Prevent high tier wands from appearing in the Secret shop + wands_to_forbid = set(wand_tiers[3:]) + locations_in_region = set(locations.location_region_mapping["Secret Shop"].keys()) + forbid_items_at_locations(world, locations_in_region, wands_to_forbid) + + +def lock_holy_mountains_into_spheres(world: "NoitaWorld") -> None: + for lock in entrance_locks: + location = world.multiworld.get_entrance(f"From {lock.source} To {lock.destination}", world.player) + GenericRules.set_rule(location, lambda state, evt=lock.event: state.has(evt, world.player)) + + +def holy_mountain_unlock_conditions(world: "NoitaWorld") -> None: + victory_condition = world.options.victory_condition.value + for lock in entrance_locks: + location = world.multiworld.get_location(lock.event, world.player) + + if victory_condition == VictoryCondition.option_greed_ending: + location.access_rule = lambda state, items_needed=lock.items_needed: ( + has_perk_count(state, world.player, items_needed//2) + ) + elif victory_condition == VictoryCondition.option_pure_ending: + location.access_rule = lambda state, items_needed=lock.items_needed: ( + has_perk_count(state, world.player, items_needed//2) and + has_orb_count(state, world.player, items_needed) + ) + elif victory_condition == VictoryCondition.option_peaceful_ending: + location.access_rule = lambda state, items_needed=lock.items_needed: ( + has_perk_count(state, world.player, items_needed//2) and + has_orb_count(state, world.player, items_needed * 3) + ) + + +def biome_unlock_conditions(world: "NoitaWorld"): + lukki_entrances = world.multiworld.get_region("Lukki Lair", world.player).entrances + magical_entrances = world.multiworld.get_region("Magical Temple", world.player).entrances + wizard_entrances = world.multiworld.get_region("Wizards' Den", world.player).entrances + for entrance in lukki_entrances: + entrance.access_rule = lambda state: state.has("Melee Immunity Perk", world.player) and\ + state.has("All-Seeing Eye Perk", world.player) + for entrance in magical_entrances: + entrance.access_rule = lambda state: state.has("All-Seeing Eye Perk", world.player) + for entrance in wizard_entrances: + entrance.access_rule = lambda state: state.has("All-Seeing Eye Perk", world.player) + + +def victory_unlock_conditions(world: "NoitaWorld") -> None: + victory_condition = world.options.victory_condition.value + victory_location = world.multiworld.get_location("Victory", world.player) + + if victory_condition == VictoryCondition.option_pure_ending: + victory_location.access_rule = lambda state: has_orb_count(state, world.player, 11) + elif victory_condition == VictoryCondition.option_peaceful_ending: + victory_location.access_rule = lambda state: has_orb_count(state, world.player, 33) + + +# ---------------- +# Main Function +# ---------------- + + +def create_all_rules(world: "NoitaWorld") -> None: + if world.multiworld.players > 1: + ban_items_from_shops(world) + ban_early_high_tier_wands(world) + lock_holy_mountains_into_spheres(world) + holy_mountain_unlock_conditions(world) + biome_unlock_conditions(world) + victory_unlock_conditions(world) + + # Prevent the Map perk (used to find Toveri) from being on Toveri (boss) + if world.options.bosses_as_checks.value >= BossesAsChecks.option_all_bosses: + toveri = world.multiworld.get_location("Toveri", world.player) + GenericRules.forbid_items_for_player(toveri, {"Spatial Awareness Perk"}, world.player) From aa72f671bc7a0690200476b0630afd9e06279207 Mon Sep 17 00:00:00 2001 From: black-sliver <59490463+black-sliver@users.noreply.github.com> Date: Sun, 21 Jan 2024 19:34:24 +0100 Subject: [PATCH 03/15] SoE: fix naming of atlas medallion (#2747) In pyevermizer, it's called Atlas Medallion, not Amulet, leading to an empty group and to code not considering them as an alchemy ingredient when swapping out for a trap or an energy core fragment. Also adds a test. --- worlds/soe/__init__.py | 2 +- worlds/soe/test/test_item_mapping.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 worlds/soe/test/test_item_mapping.py diff --git a/worlds/soe/__init__.py b/worlds/soe/__init__.py index 74387fb1be80..bbe018da5329 100644 --- a/worlds/soe/__init__.py +++ b/worlds/soe/__init__.py @@ -81,7 +81,7 @@ # item helpers _ingredients = ( 'Wax', 'Water', 'Vinegar', 'Root', 'Oil', 'Mushroom', 'Mud Pepper', 'Meteorite', 'Limestone', 'Iron', - 'Gunpowder', 'Grease', 'Feather', 'Ethanol', 'Dry Ice', 'Crystal', 'Clay', 'Brimstone', 'Bone', 'Atlas Amulet', + 'Gunpowder', 'Grease', 'Feather', 'Ethanol', 'Dry Ice', 'Crystal', 'Clay', 'Brimstone', 'Bone', 'Atlas Medallion', 'Ash', 'Acorn' ) _other_items = ( diff --git a/worlds/soe/test/test_item_mapping.py b/worlds/soe/test/test_item_mapping.py new file mode 100644 index 000000000000..7df05837c78b --- /dev/null +++ b/worlds/soe/test/test_item_mapping.py @@ -0,0 +1,21 @@ +from unittest import TestCase +from .. import SoEWorld + + +class TestMapping(TestCase): + def test_atlas_medallion_name_group(self) -> None: + """ + Test that we used the pyevermizer name for Atlas Medallion (not Amulet) in item groups. + """ + self.assertIn("Any Atlas Medallion", SoEWorld.item_name_groups) + + def test_atlas_medallion_name_items(self) -> None: + """ + Test that we used the pyevermizer name for Atlas Medallion (not Amulet) in items. + """ + found_medallion = False + for name in SoEWorld.item_name_to_id: + self.assertNotIn("Atlas Amulet", name, "Expected Atlas Medallion, not Amulet") + if "Atlas Medallion" in name: + found_medallion = True + self.assertTrue(found_medallion, "Did not find Atlas Medallion in items") From b4212d1c3eaef5980fae7329796636274d80df1a Mon Sep 17 00:00:00 2001 From: Scipio Wright Date: Sun, 28 Jan 2024 15:13:03 -0500 Subject: [PATCH 04/15] TUNIC: Fix for nmg logic bug (#2772) --- worlds/tunic/er_data.py | 51 ++++++++++++++++++++++---------------- worlds/tunic/er_rules.py | 19 +++++++++++--- worlds/tunic/er_scripts.py | 6 ++--- 3 files changed, 48 insertions(+), 28 deletions(-) diff --git a/worlds/tunic/er_data.py b/worlds/tunic/er_data.py index 2d3bcc025f4b..95d33d4aff67 100644 --- a/worlds/tunic/er_data.py +++ b/worlds/tunic/er_data.py @@ -37,7 +37,7 @@ def scene_destination(self) -> str: # full, nonchanging name to interpret by th destination="Furnace_gyro_lower"), Portal(name="Caustic Light Cave Entrance", region="Overworld", destination="Overworld Cave_"), - Portal(name="Swamp Upper Entrance", region="Overworld Laurels", + Portal(name="Swamp Upper Entrance", region="Overworld Swamp Upper Entry", destination="Swamp Redux 2_wall"), Portal(name="Swamp Lower Entrance", region="Overworld", destination="Swamp Redux 2_conduit"), @@ -49,7 +49,7 @@ def scene_destination(self) -> str: # full, nonchanging name to interpret by th destination="Atoll Redux_upper"), Portal(name="Atoll Lower Entrance", region="Overworld", destination="Atoll Redux_lower"), - Portal(name="Special Shop Entrance", region="Overworld Laurels", + Portal(name="Special Shop Entrance", region="Overworld Special Shop Entry", destination="ShopSpecial_"), Portal(name="Maze Cave Entrance", region="Overworld", destination="Maze Room_"), @@ -57,7 +57,7 @@ def scene_destination(self) -> str: # full, nonchanging name to interpret by th destination="Archipelagos Redux_upper"), Portal(name="West Garden Entrance from Furnace", region="Overworld to West Garden from Furnace", destination="Archipelagos Redux_lower"), - Portal(name="West Garden Laurels Entrance", region="Overworld Laurels", + Portal(name="West Garden Laurels Entrance", region="Overworld West Garden Laurels Entry", destination="Archipelagos Redux_lowest"), Portal(name="Temple Door Entrance", region="Overworld Temple Door", destination="Temple_main"), @@ -533,7 +533,9 @@ class Hint(IntEnum): "Overworld": RegionInfo("Overworld Redux"), "Overworld Holy Cross": RegionInfo("Fake", dead_end=DeadEnd.all_cats), "Overworld Belltower": RegionInfo("Overworld Redux"), # the area with the belltower and chest - "Overworld Laurels": RegionInfo("Overworld Redux"), # all spots in Overworld that you need laurels to reach + "Overworld Swamp Upper Entry": RegionInfo("Overworld Redux"), # upper swamp entry spot + "Overworld Special Shop Entry": RegionInfo("Overworld Redux"), # special shop entry spot + "Overworld West Garden Laurels Entry": RegionInfo("Overworld Redux"), # west garden laurels entry "Overworld to West Garden from Furnace": RegionInfo("Overworld Redux", hint=Hint.region), "Overworld Well to Furnace Rail": RegionInfo("Overworld Redux"), # the tiny rail passageway "Overworld Ruined Passage Door": RegionInfo("Overworld Redux"), # the small space betweeen the door and the portal @@ -710,7 +712,7 @@ class Hint(IntEnum): hallway_helper[p2] = p1 # so we can just loop over this instead of doing some complicated thing to deal with hallways in the hints -hallways_nmg: Dict[str, str] = { +hallways_ur: Dict[str, str] = { "Ruins Passage, Overworld Redux_east": "Ruins Passage, Overworld Redux_west", "East Forest Redux Interior, East Forest Redux_upper": "East Forest Redux Interior, East Forest Redux_lower", "Forest Boss Room, East Forest Redux Laddercave_": "Forest Boss Room, Forest Belltower_", @@ -720,20 +722,22 @@ class Hint(IntEnum): "ziggurat2020_0, Quarry Redux_": "ziggurat2020_0, ziggurat2020_1_", "Purgatory, Purgatory_bottom": "Purgatory, Purgatory_top", } -hallway_helper_nmg: Dict[str, str] = {} -for p1, p2 in hallways.items(): - hallway_helper[p1] = p2 - hallway_helper[p2] = p1 +hallway_helper_ur: Dict[str, str] = {} +for p1, p2 in hallways_ur.items(): + hallway_helper_ur[p1] = p2 + hallway_helper_ur[p2] = p1 # the key is the region you have, the value is the regions you get for having that region # this is mostly so we don't have to do something overly complex to get this information dependent_regions: Dict[Tuple[str, ...], List[str]] = { - ("Overworld", "Overworld Belltower", "Overworld Laurels", "Overworld Southeast Cross Door", "Overworld Temple Door", + ("Overworld", "Overworld Belltower", "Overworld Swamp Upper Entry", "Overworld Special Shop Entry", + "Overworld West Garden Laurels Entry", "Overworld Southeast Cross Door", "Overworld Temple Door", "Overworld Fountain Cross Door", "Overworld Town Portal", "Overworld Spawn Portal"): - ["Overworld", "Overworld Belltower", "Overworld Laurels", "Overworld Ruined Passage Door", - "Overworld Southeast Cross Door", "Overworld Old House Door", "Overworld Temple Door", - "Overworld Fountain Cross Door", "Overworld Town Portal", "Overworld Spawn Portal"], + ["Overworld", "Overworld Belltower", "Overworld Swamp Upper Entry", "Overworld Special Shop Entry", + "Overworld West Garden Laurels Entry", "Overworld Ruined Passage Door", "Overworld Southeast Cross Door", + "Overworld Old House Door", "Overworld Temple Door", "Overworld Fountain Cross Door", "Overworld Town Portal", + "Overworld Spawn Portal"], ("Old House Front",): ["Old House Front", "Old House Back"], ("Furnace Fuse", "Furnace Ladder Area", "Furnace Walking Path"): @@ -818,12 +822,14 @@ class Hint(IntEnum): dependent_regions_nmg: Dict[Tuple[str, ...], List[str]] = { - ("Overworld", "Overworld Belltower", "Overworld Laurels", "Overworld Southeast Cross Door", "Overworld Temple Door", + ("Overworld", "Overworld Belltower", "Overworld Swamp Upper Entry", "Overworld Special Shop Entry", + "Overworld West Garden Laurels Entry", "Overworld Southeast Cross Door", "Overworld Temple Door", "Overworld Fountain Cross Door", "Overworld Town Portal", "Overworld Spawn Portal", "Overworld Ruined Passage Door"): - ["Overworld", "Overworld Belltower", "Overworld Laurels", "Overworld Ruined Passage Door", - "Overworld Southeast Cross Door", "Overworld Old House Door", "Overworld Temple Door", - "Overworld Fountain Cross Door", "Overworld Town Portal", "Overworld Spawn Portal"], + ["Overworld", "Overworld Belltower", "Overworld Swamp Upper Entry", "Overworld Special Shop Entry", + "Overworld West Garden Laurels Entry", "Overworld Ruined Passage Door", "Overworld Southeast Cross Door", + "Overworld Old House Door", "Overworld Temple Door", "Overworld Fountain Cross Door", "Overworld Town Portal", + "Overworld Spawn Portal"], # can laurels through the gate ("Old House Front", "Old House Back"): ["Old House Front", "Old House Back"], @@ -908,13 +914,14 @@ class Hint(IntEnum): dependent_regions_ur: Dict[Tuple[str, ...], List[str]] = { # can use ladder storage to get to the well rail - ("Overworld", "Overworld Belltower", "Overworld Laurels", "Overworld Southeast Cross Door", "Overworld Temple Door", + ("Overworld", "Overworld Belltower", "Overworld Swamp Upper Entry", "Overworld Special Shop Entry", + "Overworld West Garden Laurels Entry", "Overworld Southeast Cross Door", "Overworld Temple Door", "Overworld Fountain Cross Door", "Overworld Town Portal", "Overworld Spawn Portal", "Overworld Ruined Passage Door"): - ["Overworld", "Overworld Belltower", "Overworld Laurels", "Overworld Ruined Passage Door", - "Overworld Southeast Cross Door", "Overworld Old House Door", "Overworld Temple Door", - "Overworld Fountain Cross Door", "Overworld Town Portal", "Overworld Spawn Portal", - "Overworld Well to Furnace Rail"], + ["Overworld", "Overworld Belltower", "Overworld Swamp Upper Entry", "Overworld Special Shop Entry", + "Overworld West Garden Laurels Entry", "Overworld Ruined Passage Door", "Overworld Southeast Cross Door", + "Overworld Old House Door", "Overworld Temple Door", "Overworld Fountain Cross Door", "Overworld Town Portal", + "Overworld Spawn Portal", "Overworld Well to Furnace Rail"], # can laurels through the gate ("Old House Front", "Old House Back"): ["Old House Front", "Old House Back"], diff --git a/worlds/tunic/er_rules.py b/worlds/tunic/er_rules.py index 5d88022dc159..ab0cf02bd97c 100644 --- a/worlds/tunic/er_rules.py +++ b/worlds/tunic/er_rules.py @@ -53,9 +53,23 @@ def set_er_region_rules(world: "TunicWorld", ability_unlocks: Dict[str, int], re or (state.has(laurels, player) and options.logic_rules)) regions["Overworld"].connect( - connecting_region=regions["Overworld Laurels"], + connecting_region=regions["Overworld Swamp Upper Entry"], rule=lambda state: state.has(laurels, player)) - regions["Overworld Laurels"].connect( + regions["Overworld Swamp Upper Entry"].connect( + connecting_region=regions["Overworld"], + rule=lambda state: state.has(laurels, player)) + + regions["Overworld"].connect( + connecting_region=regions["Overworld Special Shop Entry"], + rule=lambda state: state.has(laurels, player)) + regions["Overworld Special Shop Entry"].connect( + connecting_region=regions["Overworld"], + rule=lambda state: state.has(laurels, player)) + + regions["Overworld"].connect( + connecting_region=regions["Overworld West Garden Laurels Entry"], + rule=lambda state: state.has(laurels, player)) + regions["Overworld West Garden Laurels Entry"].connect( connecting_region=regions["Overworld"], rule=lambda state: state.has(laurels, player)) @@ -230,7 +244,6 @@ def set_er_region_rules(world: "TunicWorld", ability_unlocks: Dict[str, int], re connecting_region=regions["West Garden Laurels Exit"], rule=lambda state: state.has(laurels, player)) - # todo: can you wake the boss, then grapple to it, then kill it? regions["West Garden after Boss"].connect( connecting_region=regions["West Garden"], rule=lambda state: state.has(laurels, player)) diff --git a/worlds/tunic/er_scripts.py b/worlds/tunic/er_scripts.py index 4d640b2fda78..4e28344b20ad 100644 --- a/worlds/tunic/er_scripts.py +++ b/worlds/tunic/er_scripts.py @@ -1,7 +1,7 @@ from typing import Dict, List, Set, Tuple, TYPE_CHECKING from BaseClasses import Region, ItemClassification, Item, Location from .locations import location_table -from .er_data import Portal, tunic_er_regions, portal_mapping, hallway_helper, hallway_helper_nmg, \ +from .er_data import Portal, tunic_er_regions, portal_mapping, hallway_helper, hallway_helper_ur, \ dependent_regions, dependent_regions_nmg, dependent_regions_ur from .er_rules import set_er_region_rules @@ -28,8 +28,8 @@ def hint_helper(portal: Portal, hint_string: str = "") -> str: if hint_string == "": hint_string = portal.name - if logic_rules: - hallways = hallway_helper_nmg + if logic_rules == "unrestricted": + hallways = hallway_helper_ur else: hallways = hallway_helper From 0bc9966d6f4d216948c7db345b54a04ce94f2d73 Mon Sep 17 00:00:00 2001 From: JusticePS <5125765+JusticePS@users.noreply.github.com> Date: Mon, 29 Jan 2024 09:37:55 -0800 Subject: [PATCH 05/15] Adventure: Fix iterable copy error when freeincarnate_max is tuned low (#2774) --- worlds/adventure/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worlds/adventure/__init__.py b/worlds/adventure/__init__.py index 105725bd053c..9b9b0d77d800 100644 --- a/worlds/adventure/__init__.py +++ b/worlds/adventure/__init__.py @@ -271,7 +271,7 @@ def pre_fill(self): overworld_locations_copy = overworld.locations.copy() all_locations = self.multiworld.get_locations(self.player) - locations_copy = all_locations.copy() + locations_copy = list(all_locations) for loc in all_locations: if loc.item is not None or loc.progress_type != LocationProgressType.DEFAULT: locations_copy.remove(loc) From 69c80501c494be4edf8210949fa5fed7e9f73f7c Mon Sep 17 00:00:00 2001 From: JaredWeakStrike <96694163+JaredWeakStrike@users.noreply.github.com> Date: Mon, 29 Jan 2024 12:39:45 -0500 Subject: [PATCH 06/15] KH2: Fix empty location groups (#2757) Co-authored-by: Aaron Wagener --- worlds/kh2/Locations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worlds/kh2/Locations.py b/worlds/kh2/Locations.py index 61fafe909412..100e971e7dff 100644 --- a/worlds/kh2/Locations.py +++ b/worlds/kh2/Locations.py @@ -1356,5 +1356,5 @@ location_groups: typing.Dict[str, list] location_groups = { Region_Name: [loc for loc in Region_Locs if "Event" not in loc] - for Region_Name, Region_Locs in KH2REGIONS.items() if Region_Locs + for Region_Name, Region_Locs in KH2REGIONS.items() if Region_Locs and "Event" not in Region_Locs[0] } From 1b188bab3c3de90bcba374aec2e95f3fbe56999d Mon Sep 17 00:00:00 2001 From: black-sliver <59490463+black-sliver@users.noreply.github.com> Date: Tue, 30 Jan 2024 08:21:23 +0100 Subject: [PATCH 07/15] Doc: add GM libs to network protocol.md (#2744) --- docs/network protocol.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/network protocol.md b/docs/network protocol.md index d10e6519a93b..338db55299b6 100644 --- a/docs/network protocol.md +++ b/docs/network protocol.md @@ -27,6 +27,8 @@ There are also a number of community-supported libraries available that implemen | Haxe | [hxArchipelago](https://lib.haxe.org/p/hxArchipelago) | | | Rust | [ArchipelagoRS](https://github.com/ryanisaacg/archipelago_rs) | | | Lua | [lua-apclientpp](https://github.com/black-sliver/lua-apclientpp) | | +| Game Maker + Studio 1.x | [gm-apclientpp](https://github.com/black-sliver/gm-apclientpp) | For GM7, GM8 and GMS1.x, maybe older | +| GameMaker: Studio 2.x+ | [see Discord](https://discord.com/channels/731205301247803413/1166418532519653396) | | ## Synchronizing Items When the client receives a [ReceivedItems](#ReceivedItems) packet, if the `index` argument does not match the next index that the client expects then it is expected that the client will re-sync items with the server. This can be accomplished by sending the server a [Sync](#Sync) packet and then a [LocationChecks](#LocationChecks) packet. From 5663c21f3990eea1e3f5f37f975d0a76ac032b00 Mon Sep 17 00:00:00 2001 From: black-sliver <59490463+black-sliver@users.noreply.github.com> Date: Tue, 30 Jan 2024 08:34:54 +0100 Subject: [PATCH 08/15] Tests: test that item/location name groups are not empty (#2748) * Tests: test that item/location name groups are not empty * Tests: better name for test_groups TestCase --------- Co-authored-by: Fabian Dill --- test/general/test_groups.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 test/general/test_groups.py diff --git a/test/general/test_groups.py b/test/general/test_groups.py new file mode 100644 index 000000000000..486d3311fa6b --- /dev/null +++ b/test/general/test_groups.py @@ -0,0 +1,27 @@ +from unittest import TestCase + +from worlds.AutoWorld import AutoWorldRegister + + +class TestNameGroups(TestCase): + def test_item_name_groups_not_empty(self) -> None: + """ + Test that there are no empty item name groups, which is likely a bug. + """ + for game_name, world_type in AutoWorldRegister.world_types.items(): + if not world_type.item_id_to_name: + continue # ignore worlds without items + with self.subTest(game=game_name): + for name, group in world_type.item_name_groups.items(): + self.assertTrue(group, f"Item name group \"{name}\" of \"{game_name}\" is empty") + + def test_location_name_groups_not_empty(self) -> None: + """ + Test that there are no empty location name groups, which is likely a bug. + """ + for game_name, world_type in AutoWorldRegister.world_types.items(): + if not world_type.location_id_to_name: + continue # ignore worlds without locations + with self.subTest(game=game_name): + for name, group in world_type.location_name_groups.items(): + self.assertTrue(group, f"Location name group \"{name}\" of \"{game_name}\" is empty") From dc49d50c2ceb12258c06aaad6bd6f4a0f9267194 Mon Sep 17 00:00:00 2001 From: Benny D <78334662+benny-dreamly@users.noreply.github.com> Date: Tue, 30 Jan 2024 00:58:31 -0700 Subject: [PATCH 09/15] Docs: fixed typo in Stardew Valley setup guide (#2770) * fix typo * fix another typo * Update worlds/stardew_valley/docs/en_Stardew Valley.md Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com> --------- Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com> --- worlds/stardew_valley/docs/en_Stardew Valley.md | 2 +- worlds/stardew_valley/docs/setup_en.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/worlds/stardew_valley/docs/en_Stardew Valley.md b/worlds/stardew_valley/docs/en_Stardew Valley.md index a880a40b971a..04ba9c15c3c1 100644 --- a/worlds/stardew_valley/docs/en_Stardew Valley.md +++ b/worlds/stardew_valley/docs/en_Stardew Valley.md @@ -124,6 +124,6 @@ List of supported mods: ## Multiplayer -You cannot play an Archipelago Slot in multiplayer at the moment. There is no short-terms plans to support that feature. +You cannot play an Archipelago Slot in multiplayer at the moment. There are no short-term plans to support that feature. You can, however, send Stardew Valley objects as gifts from one Stardew Player to another Stardew player, using in-game Joja Prime delivery, for a fee. This exclusive feature can be turned off if you don't want to send and receive gifts. diff --git a/worlds/stardew_valley/docs/setup_en.md b/worlds/stardew_valley/docs/setup_en.md index 68c7fb9af6a0..d8f0e16b1017 100644 --- a/worlds/stardew_valley/docs/setup_en.md +++ b/worlds/stardew_valley/docs/setup_en.md @@ -84,4 +84,4 @@ See the [Supported mods documentation](https://github.com/agilbert1412/StardewAr ### Multiplayer -You cannot play an Archipelago Slot in multiplayer at the moment. There are no short-terms plans to support that feature. \ No newline at end of file +You cannot play an Archipelago Slot in multiplayer at the moment. There are no short-term plans to support that feature. From 144769a14183492a5b73ede4c6e0c0109038416e Mon Sep 17 00:00:00 2001 From: Ixrec Date: Tue, 30 Jan 2024 08:00:47 +0000 Subject: [PATCH 10/15] Tests: use strict equality in some tests # (#2778) * Tests: replace .assertLess/GreaterEqual() with .assertEqual() in two tests where strict equality seems more correct --- test/general/test_items.py | 8 ++++---- test/general/test_locations.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/general/test_items.py b/test/general/test_items.py index bd6c3fd85305..1612937225f2 100644 --- a/test/general/test_items.py +++ b/test/general/test_items.py @@ -43,15 +43,15 @@ def test_item_name_group_conflict(self): with self.subTest(group_name, group_name=group_name): self.assertNotIn(group_name, world_type.item_name_to_id) - def test_item_count_greater_equal_locations(self): - """Test that by the pre_fill step under default settings, each game submits items >= locations""" + def test_item_count_equal_locations(self): + """Test that by the pre_fill step under default settings, each game submits items == locations""" for game_name, world_type in AutoWorldRegister.world_types.items(): with self.subTest("Game", game=game_name): multiworld = setup_solo_multiworld(world_type) - self.assertGreaterEqual( + self.assertEqual( len(multiworld.itempool), len(multiworld.get_unfilled_locations()), - f"{game_name} Item count MUST meet or exceed the number of locations", + f"{game_name} Item count MUST match the number of locations", ) def test_items_in_datapackage(self): diff --git a/test/general/test_locations.py b/test/general/test_locations.py index 725b48e62f72..2ac059312c17 100644 --- a/test/general/test_locations.py +++ b/test/general/test_locations.py @@ -11,14 +11,14 @@ def test_create_duplicate_locations(self): multiworld = setup_solo_multiworld(world_type) locations = Counter(location.name for location in multiworld.get_locations()) if locations: - self.assertLessEqual(locations.most_common(1)[0][1], 1, - f"{world_type.game} has duplicate of location name {locations.most_common(1)}") + self.assertEqual(locations.most_common(1)[0][1], 1, + f"{world_type.game} has duplicate of location name {locations.most_common(1)}") locations = Counter(location.address for location in multiworld.get_locations() if type(location.address) is int) if locations: - self.assertLessEqual(locations.most_common(1)[0][1], 1, - f"{world_type.game} has duplicate of location ID {locations.most_common(1)}") + self.assertEqual(locations.most_common(1)[0][1], 1, + f"{world_type.game} has duplicate of location ID {locations.most_common(1)}") def test_locations_in_datapackage(self): """Tests that created locations not filled before fill starts exist in the datapackage.""" From 697deb98b4df3bee4b8bd0c4bdf024c7276e770d Mon Sep 17 00:00:00 2001 From: Alchav <59858495+Alchav@users.noreply.github.com> Date: Tue, 30 Jan 2024 03:06:10 -0500 Subject: [PATCH 11/15] =?UTF-8?q?=20Pok=C3=A9mon=20R/B:=20Fix=20Thunder=20?= =?UTF-8?q?Stone=20item=20groups=20#2740?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- worlds/pokemon_rb/items.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worlds/pokemon_rb/items.py b/worlds/pokemon_rb/items.py index b584869f41b9..24cad13252b1 100644 --- a/worlds/pokemon_rb/items.py +++ b/worlds/pokemon_rb/items.py @@ -42,7 +42,7 @@ def __init__(self, item_id, classification, groups): "Repel": ItemData(30, ItemClassification.filler, ["Consumables"]), "Old Amber": ItemData(31, ItemClassification.progression_skip_balancing, ["Unique", "Fossils", "Key Items"]), "Fire Stone": ItemData(32, ItemClassification.progression_skip_balancing, ["Unique", "Evolution Stones", "Key Items"]), - "Thunder Stone": ItemData(33, ItemClassification.progression_skip_balancing, ["Unique", "Evolution Stones" "Key Items"]), + "Thunder Stone": ItemData(33, ItemClassification.progression_skip_balancing, ["Unique", "Evolution Stones", "Key Items"]), "Water Stone": ItemData(34, ItemClassification.progression_skip_balancing, ["Unique", "Evolution Stones", "Key Items"]), "HP Up": ItemData(35, ItemClassification.filler, ["Consumables", "Vitamins"]), "Protein": ItemData(36, ItemClassification.filler, ["Consumables", "Vitamins"]), From 016c1e9bb4e539e80df260d114285a48f7fd6e76 Mon Sep 17 00:00:00 2001 From: Aaron Wagener Date: Tue, 30 Jan 2024 14:42:33 -0600 Subject: [PATCH 12/15] Docs: world api general cleanup/overhaul (#2598) * Docs: world api general cleanup/overhaul * add pep-0287 to style doc * some cleanup, reorganization, and grammar improvements * reorder item and region creation * address review comments * fix indent * linter grammar Co-authored-by: Exempt-Medic <60412657+Exempt-Medic@users.noreply.github.com> --------- Co-authored-by: Exempt-Medic <60412657+Exempt-Medic@users.noreply.github.com> --- docs/options api.md | 31 +- docs/style.md | 7 +- docs/world api.md | 745 ++++++++++++++++++++------------------------ 3 files changed, 358 insertions(+), 425 deletions(-) diff --git a/docs/options api.md b/docs/options api.md index 48a3f763fa92..bfab0096bbaf 100644 --- a/docs/options api.md +++ b/docs/options api.md @@ -27,14 +27,15 @@ Choice, and defining `alias_true = option_full`. - All options support `random` as a generic option. `random` chooses from any of the available values for that option, and is reserved by AP. You can set this as your default value, but you cannot define your own `option_random`. -As an example, suppose we want an option that lets the user start their game with a sword in their inventory. Let's -create our option class (with a docstring), give it a `display_name`, and add it to our game's options dataclass: +As an example, suppose we want an option that lets the user start their game with a sword in their inventory, an option +to let the player choose the difficulty, and an option to choose how much health the final boss has. Let's create our +option classes (with a docstring), give them a `display_name`, and add them to our game's options dataclass: ```python # options.py from dataclasses import dataclass -from Options import Toggle, PerGameCommonOptions +from Options import Toggle, Range, Choice, PerGameCommonOptions class StartingSword(Toggle): @@ -42,13 +43,33 @@ class StartingSword(Toggle): display_name = "Start With Sword" +class Difficulty(Choice): + """Sets overall game difficulty.""" + display_name = "Difficulty" + option_easy = 0 + option_normal = 1 + option_hard = 2 + alias_beginner = 0 # same as easy but allows the player to use beginner as an alternative for easy in the result in their options + alias_expert = 2 # same as hard + default = 1 # default to normal + + +class FinalBossHP(Range): + """Sets the HP of the final boss""" + display_name = "Final Boss HP" + range_start = 100 + range_end = 10000 + default = 2000 + + @dataclass class ExampleGameOptions(PerGameCommonOptions): starting_sword: StartingSword + difficulty: Difficulty + final_boss_health: FinalBossHP ``` -This will create a `Toggle` option, internally called `starting_sword`. To then submit this to the multiworld, we add it -to our world's `__init__.py`: +To then submit this to the multiworld, we add it to our world's `__init__.py`: ```python from worlds.AutoWorld import World diff --git a/docs/style.md b/docs/style.md index 4cc8111425e3..fbf681f28e97 100644 --- a/docs/style.md +++ b/docs/style.md @@ -6,7 +6,6 @@ * 120 character per line for all source files. * Avoid white space errors like trailing spaces. - ## Python Code * We mostly follow [PEP8](https://peps.python.org/pep-0008/). Read below to see the differences. @@ -18,9 +17,10 @@ * Use type annotations where possible for function signatures and class members. * Use type annotations where appropriate for local variables (e.g. `var: List[int] = []`, or when the type is hard or impossible to deduce.) Clear annotations help developers look up and validate API calls. +* New classes, attributes, and methods in core code should have docstrings that follow + [reST style](https://peps.python.org/pep-0287/). * Worlds that do not follow PEP8 should still have a consistent style across its files to make reading easier. - ## Markdown * We almost follow [Google's styleguide](https://google.github.io/styleguide/docguide/style.html). @@ -30,20 +30,17 @@ * One space between bullet/number and text. * No lazy numbering. - ## HTML * Indent with 2 spaces for new code. * kebab-case for ids and classes. - ## CSS * Indent with 2 spaces for new code. * `{` on the same line as the selector. * No space between selector and `{`. - ## JS * Indent with 2 spaces. diff --git a/docs/world api.md b/docs/world api.md index 0ab06da65603..72a67bca9de3 100644 --- a/docs/world api.md +++ b/docs/world api.md @@ -1,95 +1,95 @@ # Archipelago API -This document tries to explain some internals required to implement a game for -Archipelago's generation and server. Once a seed is generated, a client or mod is -required to send and receive items between the game and server. +This document tries to explain some aspects of the Archipelago World API used when implementing the generation logic of +a game. -Client implementation is out of scope of this document. Please refer to an -existing game that provides a similar API to yours. -Refer to the following documents as well: -- [network protocol.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/network%20protocol.md) -- [adding games.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/adding%20games.md) +Client implementation is out of scope of this document. Please refer to an existing game that provides a similar API to +yours, and the following documents: -Archipelago will be abbreviated as "AP" from now on. +* [network protocol.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/network%20protocol.md) +* [adding games.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/adding%20games.md) +Archipelago will be abbreviated as "AP" from now on. ## Language AP worlds are written in python3. -Clients that connect to the server to sync items can be in any language that -allows using WebSockets. - +Clients that connect to the server to sync items can be in any language that allows using WebSockets. ## Coding style -AP follows [style.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/style.md). -When in doubt use an IDE with coding style linter, for example PyCharm Community Edition. - +AP follows a [style guide](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/style.md). +When in doubt, use an IDE with a code-style linter, for example PyCharm Community Edition. ## Docstrings -Docstrings are strings attached to an object in Python that describe what the -object is supposed to be. Certain docstrings will be picked up and used by AP. -They are assigned by writing a string without any assignment right below a -definition. The string must be a triple-quoted string. +Docstrings are strings attached to an object in Python that describe what the object is supposed to be. Certain +docstrings will be picked up and used by AP. They are assigned by writing a string without any assignment right below a +definition. The string must be a triple-quoted string, and should +follow [reST style](https://peps.python.org/pep-0287/). + Example: + ```python from worlds.AutoWorld import World + + class MyGameWorld(World): - """This is the description of My Game that will be displayed on the AP - website.""" + """This is the description of My Game that will be displayed on the AP website.""" ``` - ## Definitions -This section will cover various classes and objects you can use for your world. -While some of the attributes and methods are mentioned here, not all of them are, -but you can find them in `BaseClasses.py`. +This section covers various classes and objects you can use for your world. While some of the attributes and methods +are mentioned here, not all of them are, but you can find them in +[`BaseClasses.py`](https://github.com/ArchipelagoMW/Archipelago/blob/main/BaseClasses.py). ### World Class -A `World` class is the class with all the specifics of a certain game to be -included. It will be instantiated for each player that rolls a seed for that -game. +A `World` is the class with all the specifics of a certain game that is to be included. A new instance will be created +for each player of the game for any given generated multiworld. ### WebWorld Class -A `WebWorld` class contains specific attributes and methods that can be modified -for your world specifically on the webhost: +A `WebWorld` class contains specific attributes and methods that can be modified for your world specifically on the +webhost: -`settings_page`, which can be changed to a link instead of an AP generated settings page. +* `options_page` can be changed to a link instead of an AP-generated options page. -`theme` to be used for your game specific AP pages. Available themes: +* `theme` to be used for your game-specific AP pages. Available themes: -| dirt | grass (default) | grassFlowers | ice | jungle | ocean | partyTime | stone | -|---|---|---|---|---|---|---|---| -| | | | | | | | | + | dirt | grass (default) | grassFlowers | ice | jungle | ocean | partyTime | stone | + |--------------------------------------------|---------------------------------------------|----------------------------------------------------|-------------------------------------------|----------------------------------------------|---------------------------------------------|-------------------------------------------------|---------------------------------------------| + | | | | | | | | | -`bug_report_page` (optional) can be a link to a bug reporting page, most likely a GitHub issue page, that will be placed by the site to help direct users to report bugs. +* `bug_report_page` (optional) can be a link to a bug reporting page, most likely a GitHub issue page, that will be + placed by the site to help users report bugs. -`tutorials` list of `Tutorial` classes where each class represents a guide to be generated on the webhost. +* `tutorials` list of `Tutorial` classes where each class represents a guide to be generated on the webhost. -`game_info_languages` (optional) List of strings for defining the existing gameinfo pages your game supports. The documents must be -prefixed with the same string as defined here. Default already has 'en'. +* `game_info_languages` (optional) list of strings for defining the existing game info pages your game supports. The + documents must be prefixed with the same string as defined here. Default already has 'en'. -`options_presets` (optional) A `Dict[str, Dict[str, Any]]` where the keys are the names of the presets and the values -are the options to be set for that preset. The options are defined as a `Dict[str, Any]` where the keys are the names of -the options and the values are the values to be set for that option. These presets will be available for users to select from on the game's options page. +* `options_presets` (optional) `Dict[str, Dict[str, Any]]` where the keys are the names of the presets and the values + are the options to be set for that preset. The options are defined as a `Dict[str, Any]` where the keys are the names + of the options and the values are the values to be set for that option. These presets will be available for users to + select from on the game's options page. Note: The values must be a non-aliased value for the option type and can only include the following option types: - - If you have a `Range`/`NamedRange` option, the value should be an `int` between the `range_start` and `range_end` - values. - - If you have a `NamedRange` option, the value can alternatively be a `str` that is one of the +* If you have a `Range`/`NamedRange` option, the value should be an `int` between the `range_start` and `range_end` + values. + * If you have a `NamedRange` option, the value can alternatively be a `str` that is one of the `special_range_names` keys. - - If you have a `Choice` option, the value should be a `str` that is one of the `option_` values. - - If you have a `Toggle`/`DefaultOnToggle` option, the value should be a `bool`. - - `random` is also a valid value for any of these option types. +* If you have a `Choice` option, the value should be a `str` that is one of the `option_` values. +* If you have a `Toggle`/`DefaultOnToggle` option, the value should be a `bool`. +* `random` is also a valid value for any of these option types. -`OptionDict`, `OptionList`, `OptionSet`, `FreeText`, or custom `Option`-derived classes are not supported for presets on the webhost at this time. +`OptionDict`, `OptionList`, `OptionSet`, `FreeText`, or custom `Option`-derived classes are not supported for presets on +the webhost at this time. Here is an example of a defined preset: + ```python # presets.py options_presets = { @@ -114,6 +114,7 @@ options_presets = { } } + # __init__.py class RLWeb(WebWorld): options_presets = options_presets @@ -122,47 +123,55 @@ class RLWeb(WebWorld): ### MultiWorld Object -The `MultiWorld` object references the whole multiworld (all items and locations -for all players) and is accessible through `self.multiworld` inside a `World` object. +The `MultiWorld` object references the whole multiworld (all items and locations for all players) and is accessible +through `self.multiworld` from your `World` object. ### Player -The player is just an integer in AP and is accessible through `self.player` -inside a `World` object. +The player is just an `int` in AP and is accessible through `self.player` from your `World` object. ### Player Options -Players provide customized settings for their World in the form of yamls. -A `dataclass` of valid options definitions has to be provided in `self.options_dataclass`. -(It must be a subclass of `PerGameCommonOptions`.) -Option results are automatically added to the `World` object for easy access. -Those are accessible through `self.options.`, and you can get a dictionary of the option values via -`self.options.as_dict()`, passing the desired options as strings. +Options are provided by the user as part of the generation process, intended to affect how their randomizer experience +should play out. These can control aspects such as what locations should be shuffled, what items are in the itempool, +etc. Players provide the customized options for their World in the form of yamls. + +By convention, options are defined in `options.py` and will be used when parsing the players' yaml files. Each option +has its own class, which inherits from a base option type, a docstring to describe it, and a `display_name` property +shown on the website and in spoiler logs. + +The available options are defined by creating a `dataclass`, which must be a subclass of `PerGameCommonOptions`. It has +defined fields for the option names used in the player yamls and used for options access, with their types matching the +appropriate Option class. By convention, the strings that define your option names should be in `snake_case`. The +`dataclass` is then assigned to your `World` by defining its `options_dataclass`. Option results are then automatically +added to the `World` object for easy access, between `World` creation and `generate_early`. These are accessible through +`self.options.`, and you can get a dictionary with option values +via `self.options.as_dict()`, +passing the desired option names as strings. + +Common option types are `Toggle`, `DefaultOnToggle`, `Choice`, and `Range`. +For more information, see the [options api doc](options%20api.md). ### World Settings -Any AP installation can provide settings for a world, for example a ROM file, accessible through -`self.settings.` or `cls.settings.` (new API) -or `Utils.get_options()["_options"][""]` (deprecated). +Settings are set by the user outside the generation process. They can be used for those settings that may affect +generation or client behavior, but should remain static between generations, such as the path to a ROM file. +These settings are accessible through `self.settings.` or `cls.settings.`. -Users can set those in their `host.yaml` file. Some settings may automatically open a file browser if a file is missing. +Users can set these in their `host.yaml` file. Some settings may automatically open a file browser if a file is missing. -Refer to [settings api.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/settings%20api.md) -for details. +Refer to [settings api.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/settings%20api.md) for details. ### Locations -Locations are places where items can be located in your game. This may be chests -or boss drops for RPG-like games but could also be progress in a research tree. +Locations are places where items can be located in your game. This may be chests or boss drops for RPG-like games, but +could also be progress in a research tree, or even something more abstract like a level up. -Each location has a `name` and an `id` (a.k.a. "code" or "address"), is placed -in a Region, has access rules and a classification. -The name needs to be unique in each game and must not be numeric (has to -contain least 1 letter or symbol). The ID needs to be unique across all games -and is best in the same range as the item IDs. -World-specific IDs are 1 to 253-1, IDs ≤ 0 are global and reserved. +Each location has a `name` and an `address` (hereafter referred to as an `id`), is placed in a Region, has access rules, +and has a classification. The name needs to be unique within each game and must not be numeric (must contain least 1 +letter or symbol). The ID needs to be unique across all games, and is best kept in the same range as the item IDs. -Special locations with ID `None` can hold events. +World-specific IDs must be in the range 1 to 253-1; IDs ≤ 0 are global and reserved. Classification is one of `LocationProgressType.DEFAULT`, `PRIORITY` or `EXCLUDED`. The Fill algorithm will force progression items to be placed at priority locations, giving a higher chance of them being @@ -170,22 +179,21 @@ required, and will prevent progression and useful items from being placed at exc #### Documenting Locations -Worlds can optionally provide a `location_descriptions` map which contains -human-friendly descriptions of locations or location groups. These descriptions -will show up in location-selection options in the Weighted Options page. Extra +Worlds can optionally provide a `location_descriptions` map which contains human-friendly descriptions of locations and +location groups. These descriptions will show up in location-selection options on the Weighted Options page. Extra indentation and single newlines will be collapsed into spaces. ```python -# Locations.py +# locations.py location_descriptions = { "Red Potion #6": "In a secret destructible block under the second stairway", - "L2 Spaceship": """ - The group of all items in the spaceship in Level 2. + "L2 Spaceship": + """ + The group of all items in the spaceship in Level 2. - This doesn't include the item on the spaceship door, since it can be - accessed without the Spaeship Key. - """ + This doesn't include the item on the spaceship door, since it can be accessed without the Spaceship Key. + """ } ``` @@ -193,7 +201,7 @@ location_descriptions = { # __init__.py from worlds.AutoWorld import World -from .Locations import location_descriptions +from .locations import location_descriptions class MyGameWorld(World): @@ -202,47 +210,45 @@ class MyGameWorld(World): ### Items -Items are all things that can "drop" for your game. This may be RPG items like -weapons, could as well be technologies you normally research in a research tree. +Items are all things that can "drop" for your game. This may be RPG items like weapons, or technologies you normally +research in a research tree. -Each item has a `name`, an `id` (can be known as "code"), and a classification. -The most important classification is `progression` (formerly advancement). -Progression items are items which a player may require to progress in -their world. Progression items will be assigned to locations with higher -priority and moved around to meet defined rules and accomplish progression -balancing. +Each item has a `name`, a `code` (hereafter referred to as `id`), and a classification. +The most important classification is `progression`. Progression items are items which a player *may* require to progress +in their world. If an item can possibly be considered for logic (it's referenced in a location's rules) it *must* be +progression. Progression items will be assigned to locations with higher priority, and moved around to meet defined rules +and satisfy progression balancing. -The name needs to be unique in each game, meaning a duplicate item has the -same ID. Name must not be numeric (has to contain at least 1 letter or symbol). +The name needs to be unique within each game, meaning if you need to create multiple items with the same name, they +will all have the same ID. Name must not be numeric (must contain at least 1 letter or symbol). -Special items with ID `None` can mark events (read below). +Other classifications include: -Other classifications include * `filler`: a regular item or trash item -* `useful`: generally quite useful, but not required for anything logical +* `useful`: generally quite useful, but not required for anything logical. Cannot be placed on excluded locations * `trap`: negative impact on the player * `skip_balancing`: denotes that an item should not be moved to an earlier sphere for the purpose of balancing (to be combined with `progression`; see below) * `progression_skip_balancing`: the combination of `progression` and `skip_balancing`, i.e., a progression item that - will not be moved around by progression balancing; used, e.g., for currency or tokens + will not be moved around by progression balancing; used, e.g., for currency or tokens, to not flood early spheres #### Documenting Items -Worlds can optionally provide an `item_descriptions` map which contains -human-friendly descriptions of items or item groups. These descriptions will -show up in item-selection options in the Weighted Options page. Extra -indentation and single newlines will be collapsed into spaces. +Worlds can optionally provide an `item_descriptions` map which contains human-friendly descriptions of items and item +groups. These descriptions will show up in item-selection options on the Weighted Options page. Extra indentation and +single newlines will be collapsed into spaces. ```python -# Items.py +# items.py item_descriptions = { "Red Potion": "A standard health potion", - "Spaceship Key": """ - The key to the spaceship in Level 2. + "Spaceship Key": + """ + The key to the spaceship in Level 2. - This is necessary to get to the Star Realm. - """ + This is necessary to get to the Star Realm. + """ } ``` @@ -250,7 +256,7 @@ item_descriptions = { # __init__.py from worlds.AutoWorld import World -from .Items import item_descriptions +from .items import item_descriptions class MyGameWorld(World): @@ -259,215 +265,128 @@ class MyGameWorld(World): ### Events -Events will mark some progress. You define an event location, an -event item, strap some rules to the location (i.e. hold certain -items) and manually place the event item at the event location. +An Event is a special combination of a Location and an Item, with both having an `id` of `None`. These can be used to +track certain logic interactions, with the Event Item being required for access in other locations or regions, but not +being "real". Since the item and location have no ID, they get dropped at the end of generation and so the server is +never made aware of them and these locations can never be checked, nor can the items be received during play. +They may also be used for making the spoiler log look nicer, i.e. by having a `"Victory"` Event Item, that +is required to finish the game. This makes it very clear when the player finishes, rather than only seeing their last +relevant Item. Events function just like any other Location, and can still have their own access rules, etc. +By convention, the Event "pair" of Location and Item typically have the same name, though this is not a requirement. +They must not exist in the `name_to_id` lookups, as they have no ID. + +The most common way to create an Event pair is to create and place the Item on the Location as soon as it's created: -Events can be used to either simplify the logic or to get better spoiler logs. -Events will show up in the spoiler playthrough but they do not represent actual -items or locations within the game. +```python +from worlds.AutoWorld import World +from BaseClasses import ItemClassification +from .subclasses import MyGameLocation, MyGameItem -There is one special case for events: Victory. To get the win condition to show -up in the spoiler log, you create an event item and place it at an event -location with the `access_rules` for game completion. Once that's done, the -world's win condition can be as simple as checking for that item. -By convention the victory event is called `"Victory"`. It can be placed at one -or more event locations based on player options. +class MyGameWorld(World): + victory_loc = MyGameLocation(self.player, "Victory", None) + victory_loc.place_locked_item(MyGameItem("Victory", ItemClassification.progression, None, self.player)) +``` ### Regions -Regions are logical groups of locations that share some common access rules. If -location logic is written from scratch, using regions greatly simplifies the -definition and allows to somewhat easily implement things like entrance -randomizer in logic. +Regions are logical containers that typically hold locations that share some common access rules. If location logic is +written from scratch, using regions greatly simplifies the requirements and can help with implementing things +like entrance randomization in logic. -Regions have a list called `exits`, which are `Entrance` objects representing -transitions to other regions. +Regions have a list called `exits`, containing `Entrance` objects representing transitions to other regions. -There has to be one special region "Menu" from which the logic unfolds. AP -assumes that a player will always be able to return to the "Menu" region by -resetting the game ("Save and quit"). +There must be one special region, "Menu", from which the logic unfolds. AP assumes that a player will always be able to +return to the "Menu" region by resetting the game ("Save and quit"). ### Entrances -An `Entrance` connects to a region, is assigned to region's exits and has rules -to define if it and thus the connected region is accessible. -They can be static (regular logic) or be defined/connected during generation -(entrance randomizer). +An `Entrance` has a `parent_region` and `connected_region`, where it is in the `exits` of its parent, and the +`entrances` of its connected region. The `Entrance` then has rules assigned to it to determine if it can be passed +through, making the connected region accessible. They can be static (regular logic) or be defined/connected during +generation (entrance randomization). ### Access Rules -An access rule is a function that returns `True` or `False` for a `Location` or -`Entrance` based on the current `state` (items that can be collected). +An access rule is a function that returns `True` or `False` for a `Location` or `Entrance` based on the current `state` +(items that have been collected). ### Item Rules -An item rule is a function that returns `True` or `False` for a `Location` based -on a single item. It can be used to reject placement of an item there. - +An item rule is a function that returns `True` or `False` for a `Location` based on a single item. It can be used to +reject the placement of an item there. ## Implementation ### Your World -All code for your world implementation should be placed in a python package in -the `/worlds` directory. The starting point for the package is `__init__.py`. -Conventionally, your world class is placed in that file. +All code for your world implementation should be placed in a python package in the `/worlds` directory. The starting +point for the package is `__init__.py`. Conventionally, your `World` class is placed in that file. -World classes must inherit from the `World` class in `/worlds/AutoWorld.py`, -which can be imported as `from worlds.AutoWorld import World` from your package. +World classes must inherit from the `World` class in `/worlds/AutoWorld.py`, which can be imported as +`from worlds.AutoWorld import World` from your package. AP will pick up your world automatically due to the `AutoWorld` implementation. ### Requirements -If your world needs specific python packages, they can be listed in -`worlds//requirements.txt`. ModuleUpdate.py will automatically -pick up and install them. +If your world needs specific python packages, they can be listed in `worlds//requirements.txt`. +ModuleUpdate.py will automatically pick up and install them. See [pip documentation](https://pip.pypa.io/en/stable/cli/pip_install/#requirements-file-format). ### Relative Imports -AP will only import the `__init__.py`. Depending on code size it makes sense to -use multiple files and use relative imports to access them. +AP will only import the `__init__.py`. Depending on code size, it may make sense to use multiple files and use relative +imports to access them. -e.g. `from .options import MyGameOptions` from your `__init__.py` will load -`world/[world_name]/options.py` and make its `MyGameOptions` accessible. +e.g. `from .options import MyGameOptions` from your `__init__.py` will load `world/[world_name]/options.py` and make +its `MyGameOptions` accessible. -When imported names pile up it may be easier to use `from . import options` -and access the variable as `options.MyGameOptions`. +When imported names pile up, it may be easier to use `from . import options` and access the variable as +`options.MyGameOptions`. -Imports from directories outside your world should use absolute imports. -Correct use of relative / absolute imports is required for zipped worlds to -function, see [apworld specification.md](apworld%20specification.md). +Imports from directories outside your world should use absolute imports. Correct use of relative / absolute imports is +required for zipped worlds to function, see [apworld specification.md](apworld%20specification.md). ### Your Item Type -Each world uses its own subclass of `BaseClasses.Item`. The constructor can be -overridden to attach additional data to it, e.g. "price in shop". -Since the constructor is only ever called from your code, you can add whatever -arguments you like to the constructor. +Each world uses its own subclass of `BaseClasses.Item`. The constructor can be overridden to attach additional data to +it, e.g. "price in shop". Since the constructor is only ever called from your code, you can add whatever arguments you +like to the constructor. + +In its simplest form, we only set the game name and use the default constructor: -In its simplest form we only set the game name and use the default constructor ```python from BaseClasses import Item + class MyGameItem(Item): game: str = "My Game" ``` -By convention this class definition will either be placed in your `__init__.py` -or your `items.py`. For a more elaborate example see `worlds/oot/Items.py`. -### Your location type +By convention, this class definition will either be placed in your `__init__.py` or your `items.py`. For a more +elaborate example see +[`worlds/oot/Items.py`](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/oot/Items.py). + +### Your Location Type + +The same thing we did for items above, we will now do for locations: -The same we have done for items above, we will do for locations ```python from BaseClasses import Location + class MyGameLocation(Location): game: str = "My Game" # override constructor to automatically mark event locations as such - def __init__(self, player: int, name = "", code = None, parent = None) -> None: + def __init__(self, player: int, name="", code=None, parent=None) -> None: super(MyGameLocation, self).__init__(player, name, code, parent) self.event = code is None ``` -in your `__init__.py` or your `locations.py`. - -### Options - -By convention options are defined in `options.py` and will be used when parsing -the players' yaml files. - -Each option has its own class, inherits from a base option type, has a docstring -to describe it and a `display_name` property for display on the website and in -spoiler logs. - -The actual name as used in the yaml is defined via the field names of a `dataclass` that is -assigned to the world under `self.options_dataclass`. By convention, the strings -that define your option names should be in `snake_case`. - -Common option types are `Toggle`, `DefaultOnToggle`, `Choice`, `Range`. -For more see `Options.py` in AP's base directory. - -#### Toggle, DefaultOnToggle - -These don't need any additional properties defined. After parsing the option, -its `value` will either be True or False. - -#### Range - -Define properties `range_start`, `range_end` and `default`. Ranges will be -displayed as sliders on the website and can be set to random in the yaml. - -#### Choice - -Choices are like toggles, but have more options than just True and False. -Define a property `option_ = ` per selectable value and -`default = ` to set the default selection. Aliases can be set by -defining a property `alias_ = `. - -```python -option_off = 0 -option_on = 1 -option_some = 2 -alias_disabled = 0 -alias_enabled = 1 -default = 0 -``` - -#### Sample -```python -# options.py - -from dataclasses import dataclass -from Options import Toggle, Range, Choice, PerGameCommonOptions - -class Difficulty(Choice): - """Sets overall game difficulty.""" - display_name = "Difficulty" - option_easy = 0 - option_normal = 1 - option_hard = 2 - alias_beginner = 0 # same as easy - alias_expert = 2 # same as hard - default = 1 # default to normal - -class FinalBossHP(Range): - """Sets the HP of the final boss""" - display_name = "Final Boss HP" - range_start = 100 - range_end = 10000 - default = 2000 - -class FixXYZGlitch(Toggle): - """Fixes ABC when you do XYZ""" - display_name = "Fix XYZ Glitch" - -# By convention, we call the options dataclass `Options`. -# It has to be derived from 'PerGameCommonOptions'. -@dataclass -class MyGameOptions(PerGameCommonOptions): - difficulty: Difficulty - final_boss_hp: FinalBossHP - fix_xyz_glitch: FixXYZGlitch -``` - -```python -# __init__.py - -from worlds.AutoWorld import World -from .options import MyGameOptions # import the options dataclass - -class MyGameWorld(World): - # ... - options_dataclass = MyGameOptions # assign the options dataclass to the world - options: MyGameOptions # typing for option results - # ... -``` +in your `__init__.py` or your `locations.py`. ### A World Class Skeleton @@ -483,7 +402,6 @@ from worlds.AutoWorld import World from BaseClasses import Region, Location, Entrance, Item, RegionType, ItemClassification - class MyGameItem(Item): # or from Items import MyGameItem game = "My Game" # name of the game/world this item is from @@ -492,7 +410,6 @@ class MyGameLocation(Location): # or from Locations import MyGameLocation game = "My Game" # name of the game/world this location is in - class MyGameSettings(settings.Group): class RomFile(settings.SNESRomPath): """Insert help text for host.yaml here.""" @@ -511,7 +428,7 @@ class MyGameWorld(World): # ID of first item and location, could be hard-coded but code may be easier # to read with this as a property. base_id = 1234 - # Instead of dynamic numbering, IDs could be part of data. + # instead of dynamic numbering, IDs could be part of data # The following two dicts are required for the generation to know which # items exist. They could be generated from json or something else. They can @@ -530,74 +447,106 @@ class MyGameWorld(World): ### Generation -The world has to provide the following things for generation +The world has to provide the following things for generation: -* the properties mentioned above +* the properties mentioned above * additions to the item pool * additions to the regions list: at least one called "Menu" * locations placed inside those regions * a `def create_item(self, item: str) -> MyGameItem` to create any item on demand -* applying `self.multiworld.push_precollected` for world defined start inventory -* `required_client_version: Tuple[int, int, int]` - Optional client version as tuple of 3 ints to make sure the client is compatible to - this world (e.g. implements all required features) when connecting. +* applying `self.multiworld.push_precollected` for world-defined start inventory -In addition, the following methods can be implemented and are called in this order during generation +In addition, the following methods can be implemented and are called in this order during generation: -* `stage_assert_generate(cls, multiworld)` is a class method called at the start of - generation to check the existence of prerequisite files, usually a ROM for +* `stage_assert_generate(cls, multiworld: MultiWorld)` + a class method called at the start of generation to check for the existence of prerequisite files, usually a ROM for games which require one. * `generate_early(self)` - called per player before any items or locations are created. You can set properties on your world here. Already has - access to player options and RNG. This is the earliest step where the world should start setting up for the current - multiworld as any steps before this, the multiworld itself is still getting set up + called per player before any items or locations are created. You can set properties on your + world here. Already has access to player options and RNG. This is the earliest step where the world should start + setting up for the current multiworld, as the multiworld itself is still setting up before this point. * `create_regions(self)` - called to place player's regions and their locations into the MultiWorld's regions list. If it's - hard to separate, this can be done during `generate_early` or `create_items` as well. + called to place player's regions and their locations into the MultiWorld's regions list. + If it's hard to separate, this can be done during `generate_early` or `create_items` as well. * `create_items(self)` - called to place player's items into the MultiWorld's itempool. After this step all regions and items have to be in - the MultiWorld's regions and itempool, and these lists should not be modified afterwards. + called to place player's items into the MultiWorld's itempool. After this step all regions + and items have to be in the MultiWorld's regions and itempool, and these lists should not be modified afterward. * `set_rules(self)` - called to set access and item rules on locations and entrances. - Locations have to be defined before this, or rule application can miss them. + called to set access and item rules on locations and entrances. * `generate_basic(self)` - called after the previous steps. Some placement and player specific - randomizations can be done here. -* `pre_fill(self)`, `fill_hook(self)` and `post_fill(self)` are called to modify item placement - before, during and after the regular fill process, before `generate_output`. - If items need to be placed during pre_fill, these items can be determined - and created using `get_prefill_items` -* `generate_output(self, output_directory: str)` that creates the output - files if there is output to be generated. When this is - called, `self.multiworld.get_locations(self.player)` has all locations for the player, with - attribute `item` pointing to the item. - `location.item.player` can be used to see if it's a local item. + player-specific randomization that does not affect logic can be done here. +* `pre_fill(self)`, `fill_hook(self)` and `post_fill(self)` + called to modify item placement before, during, and after the regular fill process; all finishing before + `generate_output`. Any items that need to be placed during `pre_fill` should not exist in the itempool, and if there + are any items that need to be filled this way, but need to be in state while you fill other items, they can be + returned from `get_prefill_items`. +* `generate_output(self, output_directory: str)` + creates the output files if there is output to be generated. When this is called, + `self.multiworld.get_locations(self.player)` has all locations for the player, with attribute `item` pointing to the + item. `location.item.player` can be used to see if it's a local item. * `fill_slot_data(self)` and `modify_multidata(self, multidata: Dict[str, Any])` can be used to modify the data that will be used by the server to host the MultiWorld. +All instance methods can, optionally, have a class method defined which will be called after all instance methods are +finished running, by defining a method with `stage_` in front of the method name. These class methods will have the +args `(cls, multiworld: MultiWorld)`, followed by any other args that the relevant instance method has. #### generate_early ```python def generate_early(self) -> None: - # read player settings to world instance + # read player options to world instance self.final_boss_hp = self.options.final_boss_hp.value ``` +#### create_regions + +```python +def create_regions(self) -> None: + # Add regions to the multiworld. "Menu" is the required starting point. + # Arguments to Region() are name, player, multiworld, and optionally hint_text + menu_region = Region("Menu", self.player, self.multiworld) + self.multiworld.regions.append(menu_region) # or use += [menu_region...] + + main_region = Region("Main Area", self.player, self.multiworld) + # add main area's locations to main area (all but final boss) + main_region.add_locations(main_region_locations, MyGameLocation) + # or + # main_region.locations = \ + # [MyGameLocation(self.player, location_name, self.location_name_to_id[location_name], main_region] + self.multiworld.regions.append(main_region) + + boss_region = Region("Boss Room", self.player, self.multiworld) + # add event to Boss Room + boss_region.locations.append(MyGameLocation(self.player, "Final Boss", None, boss_region)) + + # if entrances are not randomized, they should be connected here, otherwise they can also be connected at a later stage + # create Entrances and connect the Regions + menu_region.connect(main_region) # connects the "Menu" and "Main Area", can also pass a rule + # or + main_region.add_exits({"Boss Room": "Boss Door"}, {"Boss Room": lambda state: state.has("Sword", self.player)}) + # connects the "Main Area" and "Boss Room" regions, and places a rule requiring the "Sword" item to traverse + + # if setting location access rules from data is easier here, set_rules can possibly be omitted +``` + #### create_item ```python -# we need a way to know if an item provides progress in the game ("key item") -# this can be part of the items definition, or depend on recipe randomization +# we need a way to know if an item provides progress in the game ("key item") this can be part of the items definition, +# or depend on recipe randomization from .items import is_progression # this is just a dummy + def create_item(self, item: str) -> MyGameItem: - # This is called when AP wants to create an item by name (for plando) or - # when you call it from your own code. - classification = ItemClassification.progression if is_progression(item) else \ - ItemClassification.filler - return MyGameItem(item, classification, self.item_name_to_id[item], - self.player) + # this is called when AP wants to create an item by name (for plando) or when you call it from your own code + classification = ItemClassification.progression if is_progression(item) else + ItemClassification.filler + + +return MyGameItem(item, classification, self.item_name_to_id[item], + self.player) + def create_event(self, event: str) -> MyGameItem: # while we are at it, we can also add a helper to create events @@ -610,8 +559,7 @@ def create_event(self, event: str) -> MyGameItem: def create_items(self) -> None: # Add items to the Multiworld. # If there are two of the same item, the item has to be twice in the pool. - # Which items are added to the pool may depend on player settings, - # e.g. custom win condition like triforce hunt. + # Which items are added to the pool may depend on player options, e.g. custom win condition like triforce hunt. # Having an item in the start inventory won't remove it from the pool. # If an item can't have duplicates it has to be excluded manually. @@ -627,67 +575,10 @@ def create_items(self) -> None: # itempool and number of locations should match up. # If this is not the case we want to fill the itempool with junk. - junk = 0 # calculate this based on player settings + junk = 0 # calculate this based on player options self.multiworld.itempool += [self.create_item("nothing") for _ in range(junk)] ``` -#### create_regions - -```python -def create_regions(self) -> None: - # Add regions to the multiworld. "Menu" is the required starting point. - # Arguments to Region() are name, player, world, and optionally hint_text - menu_region = Region("Menu", self.player, self.multiworld) - self.multiworld.regions.append(menu_region) # or use += [menu_region...] - - main_region = Region("Main Area", self.player, self.multiworld) - # Add main area's locations to main area (all but final boss) - main_region.add_locations(main_region_locations, MyGameLocation) - # or - # main_region.locations = \ - # [MyGameLocation(self.player, location_name, self.location_name_to_id[location_name], main_region] - self.multiworld.regions.append(main_region) - - boss_region = Region("Boss Room", self.player, self.multiworld) - # Add event to Boss Room - boss_region.locations.append(MyGameLocation(self.player, "Final Boss", None, boss_region)) - - # If entrances are not randomized, they should be connected here, - # otherwise they can also be connected at a later stage. - # Create Entrances and connect the Regions - menu_region.connect(main_region) # connects the "Menu" and "Main Area", can also pass a rule - # or - main_region.add_exits({"Boss Room": "Boss Door"}, {"Boss Room": lambda state: state.has("Sword", self.player)}) - # Connects the "Main Area" and "Boss Room" regions, and places a rule requiring the "Sword" item to traverse - - # If setting location access rules from data is easier here, set_rules can - # possibly omitted. -``` - -#### generate_basic - -```python -def generate_basic(self) -> None: - # place "Victory" at "Final Boss" and set collection as win condition - self.multiworld.get_location("Final Boss", self.player) - .place_locked_item(self.create_event("Victory")) - self.multiworld.completion_condition[self.player] = - lambda state: state.has("Victory", self.player) - - # place item Herb into location Chest1 for some reason - item = self.create_item("Herb") - self.multiworld.get_location("Chest1", self.player).place_locked_item(item) - # in most cases it's better to do this at the same time the itempool is - # filled to avoid accidental duplicates: - # manually placed and still in the itempool - - # for debugging purposes, you may want to visualize the layout of your world. Uncomment the following code to - # write a PlantUML diagram to the file "my_world.puml" that can help you see whether your regions and locations - # are connected and placed as desired - # from Utils import visualize_regions - # visualize_regions(self.multiworld.get_region("Menu", self.player), "my_world.puml") -``` - ### Setting Rules ```python @@ -703,6 +594,7 @@ def set_rules(self) -> None: # set a simple rule for an region set_rule(self.multiworld.get_entrance("Boss Door", self.player), lambda state: state.has("Boss Key", self.player)) + # location.access_rule = ... is likely to be a bit faster # combine rules to require two items add_rule(self.multiworld.get_location("Chest2", self.player), lambda state: state.has("Sword", self.player)) @@ -730,59 +622,80 @@ def set_rules(self) -> None: # get_item_type needs to take player/world into account # if MyGameItem has a type property, a more direct implementation would be add_item_rule(self.multiworld.get_location("Chest5", self.player), - lambda item: item.player != self.player or\ + lambda item: item.player != self.player or item.my_type == "weapon") # location.item_rule = ... is likely to be a bit faster -``` -### Logic Mixin + # place "Victory" at "Final Boss" and set collection as win condition + self.multiworld.get_location("Final Boss", self.player).place_locked_item(self.create_event("Victory")) -While lambdas and events could do pretty much anything, by convention we -implement more complex logic in logic mixins, even if there is no need to add -properties to the `BaseClasses.CollectionState` state object. - -When importing a file that defines a class that inherits from -`worlds.AutoWorld.LogicMixin` the state object's class is automatically extended by -the mixin's members. These members should be prefixed with underscore following -the name of the implementing world. This is due to sharing a namespace with all -other logic mixins. - -Typical uses are defining methods that are used instead of `state.has` -in lambdas, e.g.`state.mygame_has(custom, player)` or recurring checks -like `state.mygame_can_do_something(player)` to simplify lambdas. -Private members, only accessible from mixins, should start with `_mygame_`, -public members with `mygame_`. - -More advanced uses could be to add additional variables to the state object, -override `World.collect(self, state, item)` and `remove(self, state, item)` -to update the state object, and check those added variables in added methods. -Please do this with caution and only when necessary. + self.multiworld.completion_condition[self.player] = lambda state: state.has("Victory", self.player) + +# for debugging purposes, you may want to visualize the layout of your world. Uncomment the following code to +# write a PlantUML diagram to the file "my_world.puml" that can help you see whether your regions and locations +# are connected and placed as desired +# from Utils import visualize_regions +# visualize_regions(self.multiworld.get_region("Menu", self.player), "my_world.puml") +``` -#### Sample +### Custom Logic Rules + +Custom methods can be defined for your logic rules. The access rule that ultimately gets assigned to the Location or +Entrance should be +a [`CollectionRule`](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/generic/Rules.py#L9). +Typically, this is done by defining a lambda expression on demand at the relevant bit, typically calling other +functions, but this can also be achieved by defining a method with the appropriate format and assigning it directly. +For an example, see [The Messenger](/worlds/messenger/rules.py). ```python # logic.py -from worlds.AutoWorld import LogicMixin +from BaseClasses import CollectionState + -class MyGameLogic(LogicMixin): - def mygame_has_key(self, player: int) -> bool: - # Arguments above are free to choose - # MultiWorld can be accessed through self.multiworld, explicitly passing in - # MyGameWorld instance for easy options access is also a valid approach - return self.has("key", player) # or whatever +def mygame_has_key(self, state: CollectionState, player: int) -> bool: + # More arguments above are free to choose, since you can expect this is only called in your world + # MultiWorld can be accessed through state.multiworld. + # Explicitly passing in MyGameWorld instance for easy options access is also a valid approach, but it's generally + # better to check options before rule assignment since the individual functions can be called thousands of times + return state.has("key", player) # or whatever ``` + ```python # __init__.py from worlds.generic.Rules import set_rule -import .logic # apply the mixin by importing its file +from . import logic + class MyGameWorld(World): # ... def set_rules(self) -> None: set_rule(self.multiworld.get_location("A Door", self.player), - lambda state: state.mygame_has_key(self.player)) + lambda state: logic.mygame_has_key(state, self.player)) +``` + +### Logic Mixin + +While lambdas and events can do pretty much anything, more complex logic can be handled in logic mixins. + +When importing a file that defines a class that inherits from `worlds.AutoWorld.LogicMixin`, the `CollectionState` class +is automatically extended by the mixin's members. These members should be prefixed with the name of the implementing +world since the namespace is shared with all other logic mixins. + +Some uses could be to add additional variables to the state object, or to have a custom state machine that gets modified +with the state. +Please do this with caution and only when necessary. + +#### pre_fill + +```python +def pre_fill(self) -> None: + # place item Herb into location Chest1 for some reason + item = self.create_item("Herb") + self.multiworld.get_location("Chest1", self.player).place_locked_item(item) + # in most cases it's better to do this at the same time the itempool is + # filled to avoid accidental duplicates, such as manually placed and still in the itempool ``` ### Generate Output @@ -792,9 +705,9 @@ from .mod import generate_mod def generate_output(self, output_directory: str) -> None: - # How to generate the mod or ROM highly depends on the game - # if the mod is written in Lua, Jinja can be used to fill a template - # if the mod reads a json file, `json.dump()` can be used to generate that + # How to generate the mod or ROM highly depends on the game. + # If the mod is written in Lua, Jinja can be used to fill a template. + # If the mod reads a json file, `json.dump()` can be used to generate that. # code below is a dummy data = { "seed": self.multiworld.seed_name, # to verify the server's multiworld @@ -804,8 +717,7 @@ def generate_output(self, output_directory: str) -> None: for location in self.multiworld.get_filled_locations(self.player)}, # store start_inventory from player's .yaml # make sure to mark as not remote_start_inventory when connecting if stored in rom/mod - "starter_items": [item.name for item - in self.multiworld.precollected_items[self.player]], + "starter_items": [item.name for item in self.multiworld.precollected_items[self.player]], } # add needed option results to the dictionary @@ -824,20 +736,20 @@ def generate_output(self, output_directory: str) -> None: ### Slot Data If the game client needs to know information about the generated seed, a preferred method of transferring the data -is through the slot data. This can be filled from the `fill_slot_data` method of your world by returning a `Dict[str, Any]`, -but should be limited to data that is absolutely necessary to not waste resources. Slot data is sent to your client once -it has successfully [connected](network%20protocol.md#connected). -If you need to know information about locations in your world, instead -of propagating the slot data, it is preferable to use [LocationScouts](network%20protocol.md#locationscouts) since that -data already exists on the server. The most common usage of slot data is to send option results that the client needs -to be aware of. +is through the slot data. This is filled with the `fill_slot_data` method of your world by returning +a `Dict[str, Any]`, but, to not waste resources, should be limited to data that is absolutely necessary. Slot data is +sent to your client once it has successfully [connected](network%20protocol.md#connected). +If you need to know information about locations in your world, instead of propagating the slot data, it is preferable +to use [LocationScouts](network%20protocol.md#locationscouts), since that data already exists on the server. The most +common usage of slot data is sending option results that the client needs to be aware of. ```python def fill_slot_data(self) -> Dict[str, Any]: - # in order for our game client to handle the generated seed correctly we need to know what the user selected - # for their difficulty and final boss HP - # a dictionary returned from this method gets set as the slot_data and will be sent to the client after connecting - # the options dataclass has a method to return a `Dict[str, Any]` of each option name provided and the option's value + # In order for our game client to handle the generated seed correctly we need to know what the user selected + # for their difficulty and final boss HP. + # A dictionary returned from this method gets set as the slot_data and will be sent to the client after connecting. + # The options dataclass has a method to return a `Dict[str, Any]` of each option name provided and the relevant + # option's value. return self.options.as_dict("difficulty", "final_boss_hp") ``` @@ -847,15 +759,17 @@ Each world implementation should have a tutorial and a game info page. These are the `.md` files in your world's `/docs` directory. #### Game Info + The game info page is for a short breakdown of what your game is and how it works in Archipelago. Any additional information that may be useful to the player when learning your randomizer should also go here. The file name format is `_.md`. While you can write these docs for multiple languages, currently only the english version is displayed on the website. #### Tutorials + Your game can have as many tutorials in as many languages as you like, with each one having a relevant `Tutorial` -defined in the `WebWorld`. The file name you use aren't particularly important, but it should be descriptive of what -the tutorial is covering, and the name of the file must match the relative URL provided in the `Tutorial`. Currently, +defined in the `WebWorld`. The file name you use isn't particularly important, but it should be descriptive of what +the tutorial covers, and the name of the file must match the relative URL provided in the `Tutorial`. Currently, the JS that determines this ignores the provided file name and will search for `game/document_lang.md`, where `game/document/lang` is the provided URL. @@ -874,12 +788,13 @@ from test.bases import WorldTestBase class MyGameTestBase(WorldTestBase): - game = "My Game" + game = "My Game" ``` -Next using the rules defined in the above `set_rules` we can test that the chests have the correct access rules. +Next, using the rules defined in the above `set_rules` we can test that the chests have the correct access rules. Example `test_chest_access.py` + ```python from . import MyGameTestBase @@ -889,15 +804,15 @@ class TestChestAccess(MyGameTestBase): """Test locations that require a sword""" locations = ["Chest1", "Chest2"] items = [["Sword"]] - # this will test that each location can't be accessed without the "Sword", but can be accessed once obtained. + # this will test that each location can't be accessed without the "Sword", but can be accessed once obtained self.assertAccessDependency(locations, items) def test_any_weapon_chests(self) -> None: """Test locations that require any weapon""" locations = [f"Chest{i}" for i in range(3, 6)] items = [["Sword"], ["Axe"], ["Spear"]] - # this will test that chests 3-5 can't be accessed without any weapon, but can be with just one of them. + # this will test that chests 3-5 can't be accessed without any weapon, but can be with just one of them self.assertAccessDependency(locations, items) ``` -For more information on tests check the [tests doc](tests.md). +For more information on tests, check the [tests doc](tests.md). From 3a51c035ac0fa6c562f46bc3e4276be9455c022a Mon Sep 17 00:00:00 2001 From: Star Rauchenberger Date: Wed, 31 Jan 2024 01:56:35 -0500 Subject: [PATCH 13/15] Lingo: Enable start_inventory_from_pool (#2781) --- worlds/lingo/__init__.py | 7 +++++-- worlds/lingo/options.py | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/worlds/lingo/__init__.py b/worlds/lingo/__init__.py index 088967445007..2f9354193250 100644 --- a/worlds/lingo/__init__.py +++ b/worlds/lingo/__init__.py @@ -82,9 +82,8 @@ def create_items(self): skips = int(non_traps * skip_percentage / 100.0) non_skips = non_traps - skips - filler_list = [":)", "The Feeling of Being Lost", "Wanderlust", "Empty White Hallways"] for i in range(0, non_skips): - pool.append(self.create_item(filler_list[i % len(filler_list)])) + pool.append(self.create_item(self.get_filler_item_name())) for i in range(0, skips): pool.append(self.create_item("Puzzle Skip")) @@ -130,3 +129,7 @@ def fill_slot_data(self): slot_data["painting_entrance_to_exit"] = self.player_logic.painting_mapping return slot_data + + def get_filler_item_name(self) -> str: + filler_list = [":)", "The Feeling of Being Lost", "Wanderlust", "Empty White Hallways"] + return self.random.choice(filler_list) diff --git a/worlds/lingo/options.py b/worlds/lingo/options.py index ec6158fab5ae..ed1426450eb7 100644 --- a/worlds/lingo/options.py +++ b/worlds/lingo/options.py @@ -1,6 +1,6 @@ from dataclasses import dataclass -from Options import Toggle, Choice, DefaultOnToggle, Range, PerGameCommonOptions +from Options import Toggle, Choice, DefaultOnToggle, Range, PerGameCommonOptions, StartInventoryPool class ShuffleDoors(Choice): @@ -136,3 +136,4 @@ class LingoOptions(PerGameCommonOptions): trap_percentage: TrapPercentage puzzle_skip_percentage: PuzzleSkipPercentage death_link: DeathLink + start_inventory_from_pool: StartInventoryPool From 140f8025647ab38ecf9d8acefe5f48f36ab69ad1 Mon Sep 17 00:00:00 2001 From: t3hf1gm3nt <59876300+t3hf1gm3nt@users.noreply.github.com> Date: Wed, 31 Jan 2024 02:01:55 -0500 Subject: [PATCH 14/15] LTTP: Update playerSettings.yaml to require AP version 0.4.4 (#2737) Updating yaml to make sure people have the proper required version if they ever use this template to play with KDS --- playerSettings.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/playerSettings.yaml b/playerSettings.yaml index f9585da246b8..b6b474a9fffa 100644 --- a/playerSettings.yaml +++ b/playerSettings.yaml @@ -26,7 +26,7 @@ name: YourName{number} # Your name in-game. Spaces will be replaced with undersc game: # Pick a game to play A Link to the Past: 1 requires: - version: 0.4.3 # Version of Archipelago required for this yaml to work as expected. + version: 0.4.4 # Version of Archipelago required for this yaml to work as expected. A Link to the Past: progression_balancing: # A system that can move progression earlier, to try and prevent the player from getting stuck and bored early. From 57cb971177c22f723dd173f3fe29446514b61541 Mon Sep 17 00:00:00 2001 From: NewSoupVi <57900059+NewSoupVi@users.noreply.github.com> Date: Wed, 31 Jan 2024 21:07:07 +0100 Subject: [PATCH 15/15] The Witness: Junk hints for Shivers, Mystic Quest and Heretic (#2592) --- worlds/witness/hints.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/worlds/witness/hints.py b/worlds/witness/hints.py index c00827feee20..e2d1069bd1d6 100644 --- a/worlds/witness/hints.py +++ b/worlds/witness/hints.py @@ -75,6 +75,9 @@ "Have you tried Bumper Stickers?\nMaybe after spending so much time on this island, you are longing for a simpler puzzle game.", "Have you tried Pokemon Emerald?\nI'm going to say it: 10/10, just the right amount of water.", "Have you tried Terraria?\nA prime example of a survival sandbox game that beats the \"Wide as an ocean, deep as a puddle\" allegations.", + "Have you tried Final Fantasy Mystic Quest?\nApparently, it was made in an attempt to simplify Final Fantasy for the western market.\nThey were right, I suck at RPGs.", + "Have you tried Shivers?\nWitness 2 should totally feature a haunted Museum.", + "Have you tried Heretic?\nWait, there is a Doom Engine game where you can look UP AND DOWN???", "One day I was fascinated by the subject of generation of waves by wind.", "I don't like sandwiches. Why would you think I like sandwiches? Have you ever seen me with a sandwich?", @@ -148,7 +151,7 @@ "You don't have Boat? Invisible boat time!\nYou do have boat? Boat clipping time!", "Cet indice est en français. Nous nous excusons de tout inconvénients engendrés par cela.", "How many of you have personally witnessed a total solar eclipse?", - "In the Treehouse area, you will find \n[Error: Data not found] progression items.", + "In the Treehouse area, you will find 69 progression items.\nNice.\n(Source: Just trust me)", "Lingo\nLingoing\nLingone", "The name of the captain was Albert Einstein.", "Panel impossible Sigma plz fix",