diff --git a/.github/pyright-config.json b/.github/pyright-config.json index 6ad7fa5f19b5..7d981778905f 100644 --- a/.github/pyright-config.json +++ b/.github/pyright-config.json @@ -16,7 +16,7 @@ "reportMissingImports": true, "reportMissingTypeStubs": true, - "pythonVersion": "3.8", + "pythonVersion": "3.10", "pythonPlatform": "Windows", "executionEnvironments": [ diff --git a/.github/workflows/analyze-modified-files.yml b/.github/workflows/analyze-modified-files.yml index c9995fa2d043..b59336fafe9b 100644 --- a/.github/workflows/analyze-modified-files.yml +++ b/.github/workflows/analyze-modified-files.yml @@ -53,7 +53,7 @@ jobs: - uses: actions/setup-python@v5 if: env.diff != '' with: - python-version: 3.8 + python-version: '3.10' - name: "Install dependencies" if: env.diff != '' diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 23c463fb947a..c013172ea034 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,14 +24,14 @@ env: jobs: # build-release-macos: # LF volunteer - build-win-py38: # RCs will still be built and signed by hand + build-win-py310: # RCs will still be built and signed by hand runs-on: windows-latest steps: - uses: actions/checkout@v4 - name: Install python uses: actions/setup-python@v5 with: - python-version: '3.8' + python-version: '3.10' - name: Download run-time dependencies run: | Invoke-WebRequest -Uri https://github.com/Ijwu/Enemizer/releases/download/${Env:ENEMIZER_VERSION}/win-x64.zip -OutFile enemizer.zip diff --git a/.github/workflows/unittests.yml b/.github/workflows/unittests.yml index a38fef8fda08..88b5d12987ad 100644 --- a/.github/workflows/unittests.yml +++ b/.github/workflows/unittests.yml @@ -33,13 +33,11 @@ jobs: matrix: os: [ubuntu-latest] python: - - {version: '3.8'} - - {version: '3.9'} - {version: '3.10'} - {version: '3.11'} - {version: '3.12'} include: - - python: {version: '3.8'} # win7 compat + - python: {version: '3.10'} # old compat os: windows-latest - python: {version: '3.12'} # current os: windows-latest diff --git a/BaseClasses.py b/BaseClasses.py index 46edeb5ea059..2e4efd606df9 100644 --- a/BaseClasses.py +++ b/BaseClasses.py @@ -1,18 +1,16 @@ from __future__ import annotations import collections -import itertools import functools import logging import random import secrets -import typing # this can go away when Python 3.8 support is dropped from argparse import Namespace from collections import Counter, deque from collections.abc import Collection, MutableSequence from enum import IntEnum, IntFlag from typing import (AbstractSet, Any, Callable, ClassVar, Dict, Iterable, Iterator, List, Mapping, NamedTuple, - Optional, Protocol, Set, Tuple, Union, Type) + Optional, Protocol, Set, Tuple, Union, TYPE_CHECKING) from typing_extensions import NotRequired, TypedDict @@ -20,7 +18,7 @@ import Options import Utils -if typing.TYPE_CHECKING: +if TYPE_CHECKING: from worlds import AutoWorld @@ -231,7 +229,7 @@ def set_options(self, args: Namespace) -> None: for player in self.player_ids: world_type = AutoWorld.AutoWorldRegister.world_types[self.game[player]] self.worlds[player] = world_type(self, player) - options_dataclass: typing.Type[Options.PerGameCommonOptions] = world_type.options_dataclass + options_dataclass: type[Options.PerGameCommonOptions] = world_type.options_dataclass self.worlds[player].options = options_dataclass(**{option_key: getattr(args, option_key)[player] for option_key in options_dataclass.type_hints}) @@ -975,7 +973,7 @@ class Region: entrances: List[Entrance] exits: List[Entrance] locations: List[Location] - entrance_type: ClassVar[Type[Entrance]] = Entrance + entrance_type: ClassVar[type[Entrance]] = Entrance class Register(MutableSequence): region_manager: MultiWorld.RegionManager @@ -1075,7 +1073,7 @@ def get_connecting_entrance(self, is_main_entrance: Callable[[Entrance], bool]) return entrance.parent_region.get_connecting_entrance(is_main_entrance) def add_locations(self, locations: Dict[str, Optional[int]], - location_type: Optional[Type[Location]] = None) -> None: + location_type: Optional[type[Location]] = None) -> None: """ Adds locations to the Region object, where location_type is your Location class and locations is a dict of location names to address. diff --git a/CommonClient.py b/CommonClient.py index 77ed85b5c652..47100a7383ab 100644 --- a/CommonClient.py +++ b/CommonClient.py @@ -710,6 +710,11 @@ def run_gui(self): def run_cli(self): if sys.stdin: + if sys.stdin.fileno() != 0: + from multiprocessing import parent_process + if parent_process(): + return # ignore MultiProcessing pipe + # steam overlay breaks when starting console_loop if 'gameoverlayrenderer' in os.environ.get('LD_PRELOAD', ''): logger.info("Skipping terminal input, due to conflicting Steam Overlay detected. Please use GUI only.") diff --git a/Generate.py b/Generate.py index bc359a203da7..8aba72abafe9 100644 --- a/Generate.py +++ b/Generate.py @@ -453,6 +453,10 @@ def roll_settings(weights: dict, plando_options: PlandoOptions = PlandoOptions.b raise Exception(f"Option {option_key} has to be in a game's section, not on its own.") ret.game = get_choice("game", weights) + if not isinstance(ret.game, str): + if ret.game is None: + raise Exception('"game" not specified') + raise Exception(f"Invalid game: {ret.game}") if ret.game not in AutoWorldRegister.world_types: from worlds import failed_world_loads picks = Utils.get_fuzzy_results(ret.game, list(AutoWorldRegister.world_types) + failed_world_loads, limit=1)[0] diff --git a/Launcher.py b/Launcher.py index 2620f786a54b..f04d67a5aa0d 100644 --- a/Launcher.py +++ b/Launcher.py @@ -22,16 +22,15 @@ from shutil import which from typing import Callable, Optional, Sequence, Tuple, Union -import Utils -import settings -from worlds.LauncherComponents import Component, components, Type, SuffixIdentifier, icon_paths - if __name__ == "__main__": import ModuleUpdate ModuleUpdate.update() -from Utils import is_frozen, user_path, local_path, init_logging, open_filename, messagebox, \ - is_windows, is_macos, is_linux +import settings +import Utils +from Utils import (init_logging, is_frozen, is_linux, is_macos, is_windows, local_path, messagebox, open_filename, + user_path) +from worlds.LauncherComponents import Component, components, icon_paths, SuffixIdentifier, Type def open_host_yaml(): @@ -182,6 +181,11 @@ def update_label(self, dt): App.get_running_app().stop() Window.close() + def _stop(self, *largs): + # see run_gui Launcher _stop comment for details + self.root_window.close() + super()._stop(*largs) + Popup().run() diff --git a/ModuleUpdate.py b/ModuleUpdate.py index f49182bb7863..dada16cefcaf 100644 --- a/ModuleUpdate.py +++ b/ModuleUpdate.py @@ -5,8 +5,8 @@ import warnings -if sys.version_info < (3, 8, 6): - raise RuntimeError("Incompatible Python Version. 3.8.7+ is supported.") +if sys.version_info < (3, 10, 11): + raise RuntimeError(f"Incompatible Python Version found: {sys.version_info}. 3.10.11+ is supported.") # don't run update if environment is frozen/compiled or if not the parent process (skip in subprocess) _skip_update = bool(getattr(sys, "frozen", False) or multiprocessing.parent_process()) diff --git a/MultiServer.py b/MultiServer.py index 764b56362ecc..847a0b281c40 100644 --- a/MultiServer.py +++ b/MultiServer.py @@ -727,15 +727,15 @@ def notify_hints(self, team: int, hints: typing.List[NetUtils.Hint], only_new: b if not hint.local and data not in concerns[hint.finding_player]: concerns[hint.finding_player].append(data) # remember hints in all cases - if not hint.found: - # since hints are bidirectional, finding player and receiving player, - # we can check once if hint already exists - if hint not in self.hints[team, hint.finding_player]: - self.hints[team, hint.finding_player].add(hint) - new_hint_events.add(hint.finding_player) - for player in self.slot_set(hint.receiving_player): - self.hints[team, player].add(hint) - new_hint_events.add(player) + + # since hints are bidirectional, finding player and receiving player, + # we can check once if hint already exists + if hint not in self.hints[team, hint.finding_player]: + self.hints[team, hint.finding_player].add(hint) + new_hint_events.add(hint.finding_player) + for player in self.slot_set(hint.receiving_player): + self.hints[team, player].add(hint) + new_hint_events.add(player) self.logger.info("Notice (Team #%d): %s" % (team + 1, format_hint(self, team, hint))) for slot in new_hint_events: diff --git a/Options.py b/Options.py index aa6f175fa58d..992348cb546d 100644 --- a/Options.py +++ b/Options.py @@ -15,7 +15,7 @@ from schema import And, Optional, Or, Schema from typing_extensions import Self -from Utils import get_fuzzy_results, is_iterable_except_str, output_path +from Utils import get_file_safe_name, get_fuzzy_results, is_iterable_except_str, output_path if typing.TYPE_CHECKING: from BaseClasses import MultiWorld, PlandoOptions @@ -1531,7 +1531,7 @@ def yaml_dump_scalar(scalar) -> str: del file_data - with open(os.path.join(target_folder, game_name + ".yaml"), "w", encoding="utf-8-sig") as f: + with open(os.path.join(target_folder, get_file_safe_name(game_name) + ".yaml"), "w", encoding="utf-8-sig") as f: f.write(res) diff --git a/Utils.py b/Utils.py index 412011200f8a..535933d815b1 100644 --- a/Utils.py +++ b/Utils.py @@ -18,8 +18,8 @@ from argparse import Namespace from settings import Settings, get_settings -from typing import BinaryIO, Coroutine, Optional, Set, Dict, Any, Union -from typing_extensions import TypeGuard +from time import sleep +from typing import BinaryIO, Coroutine, Optional, Set, Dict, Any, Union, TypeGuard from yaml import load, load_all, dump try: @@ -47,7 +47,7 @@ def as_simple_string(self) -> str: return ".".join(str(item) for item in self) -__version__ = "0.5.1" +__version__ = "0.6.0" version_tuple = tuplize_version(__version__) is_linux = sys.platform.startswith("linux") @@ -568,6 +568,8 @@ def queuer(): else: if text: queue.put_nowait(text) + else: + sleep(0.01) # non-blocking stream from threading import Thread thread = Thread(target=queuer, name=f"Stream handler for {stream.name}", daemon=True) diff --git a/WebHost.py b/WebHost.py index e597de24763d..3790a5f6f4d2 100644 --- a/WebHost.py +++ b/WebHost.py @@ -12,11 +12,12 @@ # in case app gets imported by something like gunicorn import Utils import settings +from Utils import get_file_safe_name if typing.TYPE_CHECKING: from flask import Flask -Utils.local_path.cached_path = os.path.dirname(__file__) or "." # py3.8 is not abs. remove "." when dropping 3.8 +Utils.local_path.cached_path = os.path.dirname(__file__) settings.no_gui = True configpath = os.path.abspath("config.yaml") if not os.path.exists(configpath): # fall back to config.yaml in home @@ -71,7 +72,7 @@ def create_ordered_tutorials_file() -> typing.List[typing.Dict[str, typing.Any]] shutil.rmtree(base_target_path, ignore_errors=True) for game, world in worlds.items(): # copy files from world's docs folder to the generated folder - target_path = os.path.join(base_target_path, game) + target_path = os.path.join(base_target_path, get_file_safe_name(game)) os.makedirs(target_path, exist_ok=True) if world.zip_path: diff --git a/WebHostLib/__init__.py b/WebHostLib/__init__.py index fdf3037fe015..dbe2182b0747 100644 --- a/WebHostLib/__init__.py +++ b/WebHostLib/__init__.py @@ -9,7 +9,7 @@ from pony.flask import Pony from werkzeug.routing import BaseConverter -from Utils import title_sorted +from Utils import title_sorted, get_file_safe_name UPLOAD_FOLDER = os.path.relpath('uploads') LOGS_FOLDER = os.path.relpath('logs') @@ -20,6 +20,7 @@ app.jinja_env.filters['any'] = any app.jinja_env.filters['all'] = all +app.jinja_env.filters['get_file_safe_name'] = get_file_safe_name app.config["SELFHOST"] = True # application process is in charge of running the websites app.config["GENERATORS"] = 8 # maximum concurrent world gens diff --git a/WebHostLib/requirements.txt b/WebHostLib/requirements.txt index 5c79415312d4..b7b14dea1e6f 100644 --- a/WebHostLib/requirements.txt +++ b/WebHostLib/requirements.txt @@ -5,9 +5,7 @@ waitress>=3.0.0 Flask-Caching>=2.3.0 Flask-Compress>=1.15 Flask-Limiter>=3.8.0 -bokeh>=3.1.1; python_version <= '3.8' -bokeh>=3.4.3; python_version == '3.9' -bokeh>=3.5.2; python_version >= '3.10' +bokeh>=3.5.2 markupsafe>=2.1.5 Markdown>=3.7 mdx-breakless-lists>=1.0.1 diff --git a/WebHostLib/templates/gameInfo.html b/WebHostLib/templates/gameInfo.html index c5ebba82848d..3b908004b1be 100644 --- a/WebHostLib/templates/gameInfo.html +++ b/WebHostLib/templates/gameInfo.html @@ -11,7 +11,7 @@ {% block body %} {% include 'header/'+theme+'Header.html' %} -
+
{% endblock %} diff --git a/WebHostLib/templates/genericTracker.html b/WebHostLib/templates/genericTracker.html index 947cf2837278..b92097ceea08 100644 --- a/WebHostLib/templates/genericTracker.html +++ b/WebHostLib/templates/genericTracker.html @@ -98,6 +98,8 @@ {% if hint.finding_player == player %} {{ player_names_with_alias[(team, hint.finding_player)] }} + {% elif get_slot_info(team, hint.finding_player).type == 2 %} + {{ player_names_with_alias[(team, hint.finding_player)] }} {% else %} {{ player_names_with_alias[(team, hint.finding_player)] }} @@ -107,6 +109,8 @@ {% if hint.receiving_player == player %} {{ player_names_with_alias[(team, hint.receiving_player)] }} + {% elif get_slot_info(team, hint.receiving_player).type == 2 %} + {{ player_names_with_alias[(team, hint.receiving_player)] }} {% else %} {{ player_names_with_alias[(team, hint.receiving_player)] }} diff --git a/WebHostLib/templates/multitrackerHintTable.html b/WebHostLib/templates/multitrackerHintTable.html index a931e9b04845..fcc15fb37a9f 100644 --- a/WebHostLib/templates/multitrackerHintTable.html +++ b/WebHostLib/templates/multitrackerHintTable.html @@ -21,8 +21,20 @@ ) -%} - {{ player_names_with_alias[(team, hint.finding_player)] }} - {{ player_names_with_alias[(team, hint.receiving_player)] }} + + {% if get_slot_info(team, hint.finding_player).type == 2 %} + {{ player_names_with_alias[(team, hint.finding_player)] }} + {% else %} + {{ player_names_with_alias[(team, hint.finding_player)] }} + {% endif %} + + + {% if get_slot_info(team, hint.receiving_player).type == 2 %} + {{ player_names_with_alias[(team, hint.receiving_player)] }} + {% else %} + {{ player_names_with_alias[(team, hint.receiving_player)] }} + {% endif %} + {{ item_id_to_name[games[(team, hint.receiving_player)]][hint.item] }} {{ location_id_to_name[games[(team, hint.finding_player)]][hint.location] }} {{ games[(team, hint.finding_player)] }} diff --git a/WebHostLib/templates/playerOptions/playerOptions.html b/WebHostLib/templates/playerOptions/playerOptions.html index 73de5d56eb20..7e2f0ee11cb4 100644 --- a/WebHostLib/templates/playerOptions/playerOptions.html +++ b/WebHostLib/templates/playerOptions/playerOptions.html @@ -42,7 +42,7 @@

Player Options

A list of all games you have generated can be found on the
User Content Page.
You may also download the - template file for this game. + template file for this game.

diff --git a/WebHostLib/templates/tutorial.html b/WebHostLib/templates/tutorial.html index d3a7e0a05ecc..4b6622c31336 100644 --- a/WebHostLib/templates/tutorial.html +++ b/WebHostLib/templates/tutorial.html @@ -11,7 +11,7 @@ {% endblock %} {% block body %} -
+
{% endblock %} diff --git a/WebHostLib/templates/weightedOptions/macros.html b/WebHostLib/templates/weightedOptions/macros.html index 68d3968a178a..d18d0f0b8957 100644 --- a/WebHostLib/templates/weightedOptions/macros.html +++ b/WebHostLib/templates/weightedOptions/macros.html @@ -53,7 +53,7 @@ {{ RangeRow(option_name, option, option.range_start, option.range_start, True) }} - {% if option.range_start < option.default < option.range_end %} + {% if option.default is number and option.range_start < option.default < option.range_end %} {{ RangeRow(option_name, option, option.default, option.default, True) }} {% endif %} {{ RangeRow(option_name, option, option.range_end, option.range_end, True) }} diff --git a/WebHostLib/tracker.py b/WebHostLib/tracker.py index 5450ef510373..043764a53b08 100644 --- a/WebHostLib/tracker.py +++ b/WebHostLib/tracker.py @@ -423,6 +423,7 @@ def render_generic_tracker(tracker_data: TrackerData, team: int, player: int) -> template_name_or_list="genericTracker.html", game_specific_tracker=game in _player_trackers, room=tracker_data.room, + get_slot_info=tracker_data.get_slot_info, team=team, player=player, player_name=tracker_data.get_room_long_player_names()[team, player], @@ -446,6 +447,7 @@ def render_generic_multiworld_tracker(tracker_data: TrackerData, enabled_tracker enabled_trackers=enabled_trackers, current_tracker="Generic", room=tracker_data.room, + get_slot_info=tracker_data.get_slot_info, all_slots=tracker_data.get_all_slots(), room_players=tracker_data.get_all_players(), locations=tracker_data.get_room_locations(), @@ -497,7 +499,7 @@ def render_Factorio_multiworld_tracker(tracker_data: TrackerData, enabled_tracke (team, player): collections.Counter({ tracker_data.item_id_to_name["Factorio"][item_id]: count for item_id, count in tracker_data.get_player_inventory_counts(team, player).items() - }) for team, players in tracker_data.get_all_slots().items() for player in players + }) for team, players in tracker_data.get_all_players().items() for player in players if tracker_data.get_player_game(team, player) == "Factorio" } @@ -506,6 +508,7 @@ def render_Factorio_multiworld_tracker(tracker_data: TrackerData, enabled_tracke enabled_trackers=enabled_trackers, current_tracker="Factorio", room=tracker_data.room, + get_slot_info=tracker_data.get_slot_info, all_slots=tracker_data.get_all_slots(), room_players=tracker_data.get_all_players(), locations=tracker_data.get_room_locations(), @@ -638,6 +641,7 @@ def render_ALinkToThePast_multiworld_tracker(tracker_data: TrackerData, enabled_ enabled_trackers=enabled_trackers, current_tracker="A Link to the Past", room=tracker_data.room, + get_slot_info=tracker_data.get_slot_info, all_slots=tracker_data.get_all_slots(), room_players=tracker_data.get_all_players(), locations=tracker_data.get_room_locations(), diff --git a/data/options.yaml b/data/options.yaml index ee8866627d52..09bfcdcec1f6 100644 --- a/data/options.yaml +++ b/data/options.yaml @@ -28,9 +28,9 @@ name: Player{number} # Used to describe your yaml. Useful if you have multiple files. -description: Default {{ game }} Template +description: {{ yaml_dump("Default %s Template" % game) }} -game: {{ game }} +game: {{ yaml_dump(game) }} requires: version: {{ __version__ }} # Version of Archipelago required for this yaml to work as expected. @@ -44,7 +44,7 @@ requires: {%- endfor -%} {% endmacro %} -{{ game }}: +{{ yaml_dump(game) }}: {%- for group_name, group_options in option_groups.items() %} # {{ group_name }} diff --git a/docs/CODEOWNERS b/docs/CODEOWNERS index 233571a06372..6c7799e22f2c 100644 --- a/docs/CODEOWNERS +++ b/docs/CODEOWNERS @@ -146,7 +146,7 @@ /worlds/shivers/ @GodlFire # A Short Hike -/worlds/shorthike/ @chandler05 +/worlds/shorthike/ @chandler05 @BrandenEK # Sonic Adventure 2 Battle /worlds/sa2b/ @PoryGone @RaspberrySpace diff --git a/docs/contributing.md b/docs/contributing.md index 9fd21408eb7b..96fc316be82c 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -16,7 +16,7 @@ game contributions: * **Do not introduce unit test failures/regressions.** Archipelago supports multiple versions of Python. You may need to download older Python versions to fully test your changes. Currently, the oldest supported version - is [Python 3.8](https://www.python.org/downloads/release/python-380/). + is [Python 3.10](https://www.python.org/downloads/release/python-31015/). It is recommended that automated github actions are turned on in your fork to have github run unit tests after pushing. You can turn them on here: diff --git a/docs/running from source.md b/docs/running from source.md index ef1594da9588..66dd1925c897 100644 --- a/docs/running from source.md +++ b/docs/running from source.md @@ -7,7 +7,7 @@ use that version. These steps are for developers or platforms without compiled r ## General What you'll need: - * [Python 3.8.7 or newer](https://www.python.org/downloads/), not the Windows Store version + * [Python 3.10.15 or newer](https://www.python.org/downloads/), not the Windows Store version * Python 3.12.x is currently the newest supported version * pip: included in downloads from python.org, separate in many Linux distributions * Matching C compiler diff --git a/kvui.py b/kvui.py index 74d8ad06734a..2723654214c1 100644 --- a/kvui.py +++ b/kvui.py @@ -12,10 +12,7 @@ # kivy 2.2.0 introduced DPI awareness on Windows, but it makes the UI enter an infinitely recursive re-layout # by setting the application to not DPI Aware, Windows handles scaling the entire window on its own, ignoring kivy's - try: - ctypes.windll.shcore.SetProcessDpiAwareness(0) - except FileNotFoundError: # shcore may not be found on <= Windows 7 - pass # TODO: remove silent except when Python 3.8 is phased out. + ctypes.windll.shcore.SetProcessDpiAwareness(0) os.environ["KIVY_NO_CONSOLELOG"] = "1" os.environ["KIVY_NO_FILELOG"] = "1" diff --git a/setup.py b/setup.py index afbe17726df4..f075551d58b0 100644 --- a/setup.py +++ b/setup.py @@ -634,7 +634,7 @@ def find_lib(lib: str, arch: str, libc: str) -> Optional[str]: "excludes": ["numpy", "Cython", "PySide2", "PIL", "pandas", "zstandard"], "zip_include_packages": ["*"], - "zip_exclude_packages": ["worlds", "sc2", "orjson"], # TODO: remove orjson here once we drop py3.8 support + "zip_exclude_packages": ["worlds", "sc2"], "include_files": [], # broken in cx 6.14.0, we use more special sauce now "include_msvcr": False, "replace_paths": ["*."], diff --git a/test/general/test_options.py b/test/general/test_options.py index d6d5ce6da06b..7a3743e5a4e7 100644 --- a/test/general/test_options.py +++ b/test/general/test_options.py @@ -78,4 +78,4 @@ def test_pickle_dumps(self): if not world_type.hidden: for option_key, option in world_type.options_dataclass.type_hints.items(): with self.subTest(game=gamename, option=option_key): - pickle.dumps(option(option.default)) + pickle.dumps(option.from_any(option.default)) diff --git a/test/options/test_generate_templates.py b/test/options/test_generate_templates.py new file mode 100644 index 000000000000..cab97c54b129 --- /dev/null +++ b/test/options/test_generate_templates.py @@ -0,0 +1,55 @@ +import unittest + +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import TYPE_CHECKING, Dict, Type +from Utils import parse_yaml + +if TYPE_CHECKING: + from worlds.AutoWorld import World + + +class TestGenerateYamlTemplates(unittest.TestCase): + old_world_types: Dict[str, Type["World"]] + + def setUp(self) -> None: + import worlds.AutoWorld + + self.old_world_types = worlds.AutoWorld.AutoWorldRegister.world_types + + def tearDown(self) -> None: + import worlds.AutoWorld + + worlds.AutoWorld.AutoWorldRegister.world_types = self.old_world_types + + if "World: with colon" in worlds.AutoWorld.AutoWorldRegister.world_types: + del worlds.AutoWorld.AutoWorldRegister.world_types["World: with colon"] + + def test_name_with_colon(self) -> None: + from Options import generate_yaml_templates + from worlds.AutoWorld import AutoWorldRegister + from worlds.AutoWorld import World + + class WorldWithColon(World): + game = "World: with colon" + item_name_to_id = {} + location_name_to_id = {} + + AutoWorldRegister.world_types = {WorldWithColon.game: WorldWithColon} + with TemporaryDirectory(f"archipelago_{__name__}") as temp_dir: + generate_yaml_templates(temp_dir) + path: Path + for path in Path(temp_dir).iterdir(): + self.assertTrue(path.is_file()) + self.assertTrue(path.suffix == ".yaml") + with path.open(encoding="utf-8") as f: + try: + data = parse_yaml(f) + except: + f.seek(0) + print(f"Error in {path.name}:\n{f.read()}") + raise + self.assertIn("game", data) + self.assertIn(":", data["game"]) + self.assertIn(data["game"], data) + self.assertIsInstance(data[data["game"]], dict) diff --git a/test/webhost/test_docs.py b/test/webhost/test_docs.py index 68aba05f9dcc..1e6c1b88f42c 100644 --- a/test/webhost/test_docs.py +++ b/test/webhost/test_docs.py @@ -30,10 +30,16 @@ def test_has_tutorial(self): def test_has_game_info(self): for game_name, world_type in AutoWorldRegister.world_types.items(): if not world_type.hidden: - target_path = Utils.local_path("WebHostLib", "static", "generated", "docs", game_name) + safe_name = Utils.get_file_safe_name(game_name) + target_path = Utils.local_path("WebHostLib", "static", "generated", "docs", safe_name) for game_info_lang in world_type.web.game_info_languages: with self.subTest(game_name): self.assertTrue( - os.path.isfile(Utils.local_path(target_path, f'{game_info_lang}_{game_name}.md')), + safe_name == game_name or + not os.path.isfile(Utils.local_path(target_path, f'{game_info_lang}_{game_name}.md')), + f'Info docs have be named _{safe_name}.md for {game_name}.' + ) + self.assertTrue( + os.path.isfile(Utils.local_path(target_path, f'{game_info_lang}_{safe_name}.md')), f'{game_name} missing game info file for "{game_info_lang}" language.' ) diff --git a/test/webhost/test_option_presets.py b/test/webhost/test_option_presets.py index b0af8a871183..7105c7f80593 100644 --- a/test/webhost/test_option_presets.py +++ b/test/webhost/test_option_presets.py @@ -1,5 +1,6 @@ import unittest +from BaseClasses import PlandoOptions from worlds import AutoWorldRegister from Options import ItemDict, NamedRange, NumericOption, OptionList, OptionSet @@ -14,6 +15,10 @@ def test_option_presets_have_valid_options(self): with self.subTest(game=game_name, preset=preset_name, option=option_name): try: option = world_type.options_dataclass.type_hints[option_name].from_any(option_value) + # some options may need verification to ensure the provided option is actually valid + # pass in all plando options in case a preset wants to require certain plando options + # for some reason + option.verify(world_type, "Test Player", PlandoOptions(sum(PlandoOptions))) supported_types = [NumericOption, OptionSet, OptionList, ItemDict] if not any([issubclass(option.__class__, t) for t in supported_types]): self.fail(f"'{option_name}' in preset '{preset_name}' for game '{game_name}' " diff --git a/worlds/AutoSNIClient.py b/worlds/AutoSNIClient.py index b3f40be2958d..f9444eee73c6 100644 --- a/worlds/AutoSNIClient.py +++ b/worlds/AutoSNIClient.py @@ -2,9 +2,7 @@ from __future__ import annotations import abc import logging -from typing import TYPE_CHECKING, ClassVar, Dict, Iterable, Tuple, Any, Optional, Union - -from typing_extensions import TypeGuard +from typing import TYPE_CHECKING, ClassVar, Dict, Iterable, Tuple, Any, Optional, Union, TypeGuard from worlds.LauncherComponents import Component, SuffixIdentifier, Type, components diff --git a/worlds/LauncherComponents.py b/worlds/LauncherComponents.py index fe6e44bb308e..3c4c4477ef09 100644 --- a/worlds/LauncherComponents.py +++ b/worlds/LauncherComponents.py @@ -100,10 +100,16 @@ def _install_apworld(apworld_src: str = "") -> Optional[Tuple[pathlib.Path, path apworld_path = pathlib.Path(apworld_src) - module_name = pathlib.Path(apworld_path.name).stem try: import zipfile - zipfile.ZipFile(apworld_path).open(module_name + "/__init__.py") + zip = zipfile.ZipFile(apworld_path) + directories = [f.filename.strip('/') for f in zip.filelist if f.CRC == 0 and f.file_size == 0 and f.filename.count('/') == 1] + if len(directories) == 1 and directories[0] in apworld_path.stem: + module_name = directories[0] + apworld_name = module_name + ".apworld" + else: + raise Exception("APWorld appears to be invalid or damaged. (expected a single directory)") + zip.open(module_name + "/__init__.py") except ValueError as e: raise Exception("Archive appears invalid or damaged.") from e except KeyError as e: @@ -122,7 +128,7 @@ def _install_apworld(apworld_src: str = "") -> Optional[Tuple[pathlib.Path, path # TODO: run generic test suite over the apworld. # TODO: have some kind of version system to tell from metadata if the apworld should be compatible. - target = pathlib.Path(worlds.user_folder) / apworld_path.name + target = pathlib.Path(worlds.user_folder) / apworld_name import shutil shutil.copyfile(apworld_path, target) diff --git a/worlds/__init__.py b/worlds/__init__.py index c277ac9ca1de..7db651bdd9e3 100644 --- a/worlds/__init__.py +++ b/worlds/__init__.py @@ -66,19 +66,12 @@ def load(self) -> bool: start = time.perf_counter() if self.is_zip: importer = zipimport.zipimporter(self.resolved_path) - if hasattr(importer, "find_spec"): # new in Python 3.10 - spec = importer.find_spec(os.path.basename(self.path).rsplit(".", 1)[0]) - assert spec, f"{self.path} is not a loadable module" - mod = importlib.util.module_from_spec(spec) - else: # TODO: remove with 3.8 support - mod = importer.load_module(os.path.basename(self.path).rsplit(".", 1)[0]) - - if mod.__package__ is not None: - mod.__package__ = f"worlds.{mod.__package__}" - else: - # load_module does not populate package, we'll have to assume mod.__name__ is correct here - # probably safe to remove with 3.8 support - mod.__package__ = f"worlds.{mod.__name__}" + spec = importer.find_spec(os.path.basename(self.path).rsplit(".", 1)[0]) + assert spec, f"{self.path} is not a loadable module" + mod = importlib.util.module_from_spec(spec) + + mod.__package__ = f"worlds.{mod.__package__}" + mod.__name__ = f"worlds.{mod.__name__}" sys.modules[mod.__name__] = mod with warnings.catch_warnings(): diff --git a/worlds/ahit/Regions.py b/worlds/ahit/Regions.py index c70f08b475eb..31edf1d0b057 100644 --- a/worlds/ahit/Regions.py +++ b/worlds/ahit/Regions.py @@ -740,17 +740,20 @@ def is_valid_first_act(world: "HatInTimeWorld", act: Region) -> bool: def connect_time_rift(world: "HatInTimeWorld", time_rift: Region, exit_region: Region): - i = 1 - while i <= len(rift_access_regions[time_rift.name]): + for i, access_region in enumerate(rift_access_regions[time_rift.name], start=1): + # Matches the naming convention and iteration order in `create_rift_connections()`. name = f"{time_rift.name} Portal - Entrance {i}" entrance: Entrance try: - entrance = world.multiworld.get_entrance(name, world.player) + entrance = world.get_entrance(name) + # Reconnect the rift access region to the new exit region. reconnect_regions(entrance, entrance.parent_region, exit_region) except KeyError: - time_rift.connect(exit_region, name) - - i += 1 + # The original entrance to the time rift has been deleted by already reconnecting a telescope act to the + # time rift, so create a new entrance from the original rift access region to the new exit region. + # Normally, acts and time rifts are sorted such that time rifts are reconnected to acts/rifts first, but + # starting acts/rifts and act-plando can reconnect acts to time rifts before this happens. + world.get_region(access_region).connect(exit_region, name) def get_shuffleable_act_regions(world: "HatInTimeWorld") -> List[Region]: diff --git a/worlds/aquaria/Regions.py b/worlds/aquaria/Regions.py index 792d7b73dfdb..7a41e0d0c864 100755 --- a/worlds/aquaria/Regions.py +++ b/worlds/aquaria/Regions.py @@ -1152,79 +1152,79 @@ def __adjusting_manual_rules(self) -> None: def __no_progression_hard_or_hidden_location(self) -> None: self.multiworld.get_location("Energy Temple boss area, Fallen God Tooth", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Mithalas boss area, beating Mithalan God", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Kelp Forest boss area, beating Drunian God", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Sun Temple boss area, beating Sun God", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Sunken City, bulb on top of the boss area", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Home Water, Nautilus Egg", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Energy Temple blaster room, Blaster Egg", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Mithalas City Castle, beating the Priests", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Mermog cave, Piranha Egg", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Octopus Cave, Dumbo Egg", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("King Jellyfish Cave, bulb in the right path from King Jelly", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("King Jellyfish Cave, Jellyfish Costume", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Final Boss area, bulb in the boss third form room", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Sun Worm path, first cliff bulb", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Sun Worm path, second cliff bulb", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("The Veil top right area, bulb at the top of the waterfall", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Bubble Cave, bulb in the left cave wall", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Bubble Cave, bulb in the right cave wall (behind the ice crystal)", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Bubble Cave, Verse Egg", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Kelp Forest bottom left area, bulb close to the spirit crystals", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Kelp Forest bottom left area, Walker Baby", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Sun Temple, Sun Key", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("The Body bottom area, Mutant Costume", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Sun Temple, bulb in the hidden room of the right part", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement self.multiworld.get_location("Arnassi Ruins, Arnassi Armor", self.player).item_rule = \ - lambda item: item.classification != ItemClassification.progression + lambda item: not item.advancement def adjusting_rules(self, options: AquariaOptions) -> None: """ diff --git a/worlds/aquaria/__init__.py b/worlds/aquaria/__init__.py index f79978f25fc4..f620bf6d7306 100644 --- a/worlds/aquaria/__init__.py +++ b/worlds/aquaria/__init__.py @@ -117,16 +117,13 @@ def create_item(self, name: str) -> AquariaItem: Create an AquariaItem using 'name' as item name. """ result: AquariaItem - try: - data = item_table[name] - classification: ItemClassification = ItemClassification.useful - if data.type == ItemType.JUNK: - classification = ItemClassification.filler - elif data.type == ItemType.PROGRESSION: - classification = ItemClassification.progression - result = AquariaItem(name, classification, data.id, self.player) - except BaseException: - raise Exception('The item ' + name + ' is not valid.') + data = item_table[name] + classification: ItemClassification = ItemClassification.useful + if data.type == ItemType.JUNK: + classification = ItemClassification.filler + elif data.type == ItemType.PROGRESSION: + classification = ItemClassification.progression + result = AquariaItem(name, classification, data.id, self.player) return result diff --git a/worlds/aquaria/test/test_no_progression_hard_hidden_locations.py b/worlds/aquaria/test/test_no_progression_hard_hidden_locations.py index f015b26de10b..517af3028dd2 100644 --- a/worlds/aquaria/test/test_no_progression_hard_hidden_locations.py +++ b/worlds/aquaria/test/test_no_progression_hard_hidden_locations.py @@ -49,7 +49,7 @@ def test_unconfine_home_water_both_location_fillable(self) -> None: for location in self.unfillable_locations: for item_name in self.world.item_names: item = self.get_item_by_name(item_name) - if item.classification == ItemClassification.progression: + if item.advancement: self.assertFalse( self.world.get_location(location).can_fill(self.multiworld.state, item, False), "The location \"" + location + "\" can be filled with \"" + item_name + "\"") diff --git a/worlds/cv64/client.py b/worlds/cv64/client.py index 2430cc5ffc67..cec5f551b9e5 100644 --- a/worlds/cv64/client.py +++ b/worlds/cv64/client.py @@ -66,8 +66,9 @@ def on_package(self, ctx: "BizHawkClientContext", cmd: str, args: dict) -> None: self.received_deathlinks += 1 if "cause" in args["data"]: cause = args["data"]["cause"] - if len(cause) > 88: - cause = cause[0x00:0x89] + # Truncate the death cause message at 120 characters. + if len(cause) > 120: + cause = cause[0:120] else: cause = f"{args['data']['source']} killed you!" self.death_causes.append(cause) @@ -146,8 +147,18 @@ async def game_watcher(self, ctx: "BizHawkClientContext") -> None: text_color = bytearray([0xA2, 0x0B]) else: text_color = bytearray([0xA2, 0x02]) + + # Get the item's player's name. If it's longer than 40 characters, truncate it at 40. + # 35 should be the max number of characters in a server player name right now (16 for the original + # name + 16 for the alias + 3 for the added parenthesis and space), but if it ever goes higher it + # should be future-proofed now. No need to truncate CV64 items names because its longest item name + # gets nowhere near the limit. + player_name = ctx.player_names[next_item.player] + if len(player_name) > 40: + player_name = player_name[0:40] + received_text, num_lines = cv64_text_wrap(f"{ctx.item_names.lookup_in_game(next_item.item)}\n" - f"from {ctx.player_names[next_item.player]}", 96) + f"from {player_name}", 96) await bizhawk.guarded_write(ctx.bizhawk_ctx, [(0x389BE1, [next_item.item & 0xFF], "RDRAM"), (0x18C0A8, text_color + cv64_string_to_bytearray(received_text, False), diff --git a/worlds/cv64/data/patches.py b/worlds/cv64/data/patches.py index 938b615b3213..6ef4eafb67d3 100644 --- a/worlds/cv64/data/patches.py +++ b/worlds/cv64/data/patches.py @@ -197,6 +197,23 @@ 0xA168FFFD, # SB T0, 0xFFFD (T3) ] +deathlink_nitro_state_checker = [ + # Checks to see if the player is in an alright state before exploding them. If not, then the Nitro explosion spawn + # code will be aborted, and they should eventually explode after getting out of that state. + # + # Invalid states so far include: interacting/going through a door, being grabbed by a vampire. + 0x90880009, # LBU T0, 0x0009 (A0) + 0x24090005, # ADDIU T1, R0, 0x0005 + 0x11090005, # BEQ T0, T1, [forward 0x05] + 0x24090002, # ADDIU T1, R0, 0x0002 + 0x11090003, # BEQ T0, T1, [forward 0x03] + 0x00000000, # NOP + 0x08000660, # J 0x80001980 + 0x00000000, # NOP + 0x03E00008, # JR RA + 0xAC400048 # SW R0, 0x0048 (V0) +] + launch_fall_killer = [ # Custom code to force the instant fall death if at a high enough falling speed after getting killed by something # that launches you (whether it be the Nitro explosion or a Big Toss hit). The game doesn't normally run the check diff --git a/worlds/cv64/rom.py b/worlds/cv64/rom.py index ab4371b0ac12..db621c7101d6 100644 --- a/worlds/cv64/rom.py +++ b/worlds/cv64/rom.py @@ -357,8 +357,12 @@ def apply_patches(caller: APProcedurePatch, rom: bytes, options_file: str) -> by # Make received DeathLinks blow you to smithereens instead of kill you normally. if options["death_link"] == DeathLink.option_explosive: - rom_data.write_int32(0x27A70, 0x10000008) # B [forward 0x08] rom_data.write_int32s(0xBFC0D0, patches.deathlink_nitro_edition) + rom_data.write_int32(0x27A70, 0x10000008) # B [forward 0x08] + rom_data.write_int32(0x27AA0, 0x0C0FFA78) # JAL 0x803FE9E0 + rom_data.write_int32s(0xBFE9E0, patches.deathlink_nitro_state_checker) + # NOP the function call to subtract Nitro from the inventory after exploding, just in case. + rom_data.write_int32(0x32DBC, 0x00000000) # Set the DeathLink ROM flag if it's on at all. if options["death_link"] != DeathLink.option_off: @@ -944,13 +948,19 @@ def write_patch(world: "CV64World", patch: CV64ProcedurePatch, offset_data: Dict for loc in active_locations: if loc.address is None or get_location_info(loc.name, "type") == "shop" or loc.item.player == world.player: continue - if len(loc.item.name) > 67: - item_name = loc.item.name[0x00:0x68] + # If the Item's name is longer than 104 characters, truncate the name to inject at 104. + if len(loc.item.name) > 104: + item_name = loc.item.name[0:104] else: item_name = loc.item.name + # Get the item's player's name. If it's longer than 16 characters (which can happen if it's an ItemLinked item), + # truncate it at 16. + player_name = world.multiworld.get_player_name(loc.item.player) + if len(player_name) > 16: + player_name = player_name[0:16] + inject_address = 0xBB7164 + (256 * (loc.address & 0xFFF)) - wrapped_name, num_lines = cv64_text_wrap(item_name + "\nfor " + - world.multiworld.get_player_name(loc.item.player), 96) + wrapped_name, num_lines = cv64_text_wrap(item_name + "\nfor " + player_name, 96) patch.write_token(APTokenTypes.WRITE, inject_address, bytes(get_item_text_color(loc) + cv64_string_to_bytearray(wrapped_name))) patch.write_token(APTokenTypes.WRITE, inject_address + 255, bytes([num_lines])) diff --git a/worlds/dark_souls_3/__init__.py b/worlds/dark_souls_3/__init__.py index 1aec6945eb8b..765ffb1fc544 100644 --- a/worlds/dark_souls_3/__init__.py +++ b/worlds/dark_souls_3/__init__.py @@ -1568,6 +1568,16 @@ def fill_slot_data(self) -> Dict[str, object]: "apIdsToItemIds": ap_ids_to_ds3_ids, "itemCounts": item_counts, "locationIdsToKeys": location_ids_to_keys, + # The range of versions of the static randomizer that are compatible + # with this slot data. Incompatible versions should have at least a + # minor version bump. Pre-release versions should generally only be + # compatible with a single version, except very close to a stable + # release when no changes are expected. + # + # This is checked by the static randomizer, which will surface an + # error to the user if its version doesn't fall into the allowed + # range. + "versions": ">=3.0.0-beta.24 <3.1.0", } return slot_data diff --git a/worlds/factorio/data/mod_template/control.lua b/worlds/factorio/data/mod_template/control.lua index 4383357546d9..b08608a60ae9 100644 --- a/worlds/factorio/data/mod_template/control.lua +++ b/worlds/factorio/data/mod_template/control.lua @@ -105,8 +105,8 @@ function on_player_changed_position(event) end local target_direction = exit_table[outbound_direction] - local target_position = {(CHUNK_OFFSET[target_direction][1] + last_x_chunk) * 32 + 16, - (CHUNK_OFFSET[target_direction][2] + last_y_chunk) * 32 + 16} + local target_position = {(CHUNK_OFFSET[target_direction][1] + last_x_chunk) * 32 + 16, + (CHUNK_OFFSET[target_direction][2] + last_y_chunk) * 32 + 16} target_position = character.surface.find_non_colliding_position(character.prototype.name, target_position, 32, 0.5) if target_position ~= nil then @@ -134,40 +134,96 @@ end script.on_event(defines.events.on_player_changed_position, on_player_changed_position) {% endif %} - +function count_energy_bridges() + local count = 0 + for i, bridge in pairs(storage.energy_link_bridges) do + if validate_energy_link_bridge(i, bridge) then + count = count + 1 + (bridge.quality.level * 0.3) + end + end + return count +end +function get_energy_increment(bridge) + return ENERGY_INCREMENT + (ENERGY_INCREMENT * 0.3 * bridge.quality.level) +end function on_check_energy_link(event) --- assuming 1 MJ increment and 5MJ battery: --- first 2 MJ request fill, last 2 MJ push energy, middle 1 MJ does nothing if event.tick % 60 == 30 then - local surface = game.get_surface(1) local force = "player" - local bridges = surface.find_entities_filtered({name="ap-energy-bridge", force=force}) - local bridgecount = table_size(bridges) + local bridges = storage.energy_link_bridges + local bridgecount = count_energy_bridges() storage.forcedata[force].energy_bridges = bridgecount if storage.forcedata[force].energy == nil then storage.forcedata[force].energy = 0 end if storage.forcedata[force].energy < ENERGY_INCREMENT * bridgecount * 5 then - for i, bridge in ipairs(bridges) do - if bridge.energy > ENERGY_INCREMENT*3 then - storage.forcedata[force].energy = storage.forcedata[force].energy + (ENERGY_INCREMENT * ENERGY_LINK_EFFICIENCY) - bridge.energy = bridge.energy - ENERGY_INCREMENT + for i, bridge in pairs(bridges) do + if validate_energy_link_bridge(i, bridge) then + energy_increment = get_energy_increment(bridge) + if bridge.energy > energy_increment*3 then + storage.forcedata[force].energy = storage.forcedata[force].energy + (energy_increment * ENERGY_LINK_EFFICIENCY) + bridge.energy = bridge.energy - energy_increment + end end end end - for i, bridge in ipairs(bridges) do - if storage.forcedata[force].energy < ENERGY_INCREMENT then - break - end - if bridge.energy < ENERGY_INCREMENT*2 and storage.forcedata[force].energy > ENERGY_INCREMENT then - storage.forcedata[force].energy = storage.forcedata[force].energy - ENERGY_INCREMENT - bridge.energy = bridge.energy + ENERGY_INCREMENT + for i, bridge in pairs(bridges) do + if validate_energy_link_bridge(i, bridge) then + energy_increment = get_energy_increment(bridge) + if storage.forcedata[force].energy < energy_increment and bridge.quality.level == 0 then + break + end + if bridge.energy < energy_increment*2 and storage.forcedata[force].energy > energy_increment then + storage.forcedata[force].energy = storage.forcedata[force].energy - energy_increment + bridge.energy = bridge.energy + energy_increment + end end end end end +function string_starts_with(str, start) + return str:sub(1, #start) == start +end +function validate_energy_link_bridge(unit_number, entity) + if not entity then + if storage.energy_link_bridges[unit_number] == nil then return false end + storage.energy_link_bridges[unit_number] = nil + return false + end + if not entity.valid then + if storage.energy_link_bridges[unit_number] == nil then return false end + storage.energy_link_bridges[unit_number] = nil + return false + end + return true +end +function on_energy_bridge_constructed(entity) + if entity and entity.valid then + if string_starts_with(entity.prototype.name, "ap-energy-bridge") then + storage.energy_link_bridges[entity.unit_number] = entity + end + end +end +function on_energy_bridge_removed(entity) + if string_starts_with(entity.prototype.name, "ap-energy-bridge") then + if storage.energy_link_bridges[entity.unit_number] == nil then return end + storage.energy_link_bridges[entity.unit_number] = nil + end +end if (ENERGY_INCREMENT) then script.on_event(defines.events.on_tick, on_check_energy_link) + + script.on_event({defines.events.on_built_entity}, function(event) on_energy_bridge_constructed(event.entity) end) + script.on_event({defines.events.on_robot_built_entity}, function(event) on_energy_bridge_constructed(event.entity) end) + script.on_event({defines.events.on_entity_cloned}, function(event) on_energy_bridge_constructed(event.destination) end) + + script.on_event({defines.events.script_raised_revive}, function(event) on_energy_bridge_constructed(event.entity) end) + script.on_event({defines.events.script_raised_built}, function(event) on_energy_bridge_constructed(event.entity) end) + + script.on_event({defines.events.on_entity_died}, function(event) on_energy_bridge_removed(event.entity) end) + script.on_event({defines.events.on_player_mined_entity}, function(event) on_energy_bridge_removed(event.entity) end) + script.on_event({defines.events.on_robot_mined_entity}, function(event) on_energy_bridge_removed(event.entity) end) end {% if not imported_blueprints -%} @@ -410,6 +466,7 @@ script.on_init(function() {% if not imported_blueprints %}set_permissions(){% endif %} storage.forcedata = {} storage.playerdata = {} + storage.energy_link_bridges = {} -- Fire dummy events for all currently existing forces. local e = {} for name, _ in pairs(game.forces) do diff --git a/worlds/ffmq/Client.py b/worlds/ffmq/Client.py index 93688a6116f6..401c240a46ba 100644 --- a/worlds/ffmq/Client.py +++ b/worlds/ffmq/Client.py @@ -47,6 +47,17 @@ def get_flag(data, flag): bit = int(0x80 / (2 ** (flag % 8))) return (data[byte] & bit) > 0 +def validate_read_state(data1, data2): + validation_array = bytes([0x01, 0x46, 0x46, 0x4D, 0x51, 0x52]) + + if data1 is None or data2 is None: + return False + for i in range(6): + if data1[i] != validation_array[i] or data2[i] != validation_array[i]: + return False; + return True + + class FFMQClient(SNIClient): game = "Final Fantasy Mystic Quest" @@ -67,11 +78,11 @@ async def validate_rom(self, ctx): async def game_watcher(self, ctx): from SNIClient import snes_buffered_write, snes_flush_writes, snes_read - check_1 = await snes_read(ctx, 0xF53749, 1) + check_1 = await snes_read(ctx, 0xF53749, 6) received = await snes_read(ctx, RECEIVED_DATA[0], RECEIVED_DATA[1]) data = await snes_read(ctx, READ_DATA_START, READ_DATA_END - READ_DATA_START) - check_2 = await snes_read(ctx, 0xF53749, 1) - if check_1 != b'\x01' or check_2 != b'\x01': + check_2 = await snes_read(ctx, 0xF53749, 6) + if not validate_read_state(check_1, check_2): return def get_range(data_range): diff --git a/worlds/generic/Rules.py b/worlds/generic/Rules.py index e930c4b8d6e9..31d725bff722 100644 --- a/worlds/generic/Rules.py +++ b/worlds/generic/Rules.py @@ -69,7 +69,7 @@ def forbid(sender: int, receiver: int, items: typing.Set[str]): if (location.player, location.item_rule) in func_cache: location.item_rule = func_cache[location.player, location.item_rule] # empty rule that just returns True, overwrite - elif location.item_rule is location.__class__.item_rule: + elif location.item_rule is Location.item_rule: func_cache[location.player, location.item_rule] = location.item_rule = \ lambda i, sending_blockers = forbid_data[location.player], \ old_rule = location.item_rule: \ @@ -103,7 +103,7 @@ def set_rule(spot: typing.Union["BaseClasses.Location", "BaseClasses.Entrance"], def add_rule(spot: typing.Union["BaseClasses.Location", "BaseClasses.Entrance"], rule: CollectionRule, combine="and"): old_rule = spot.access_rule # empty rule, replace instead of add - if old_rule is spot.__class__.access_rule: + if old_rule is Location.access_rule or old_rule is Entrance.access_rule: spot.access_rule = rule if combine == "and" else old_rule else: if combine == "and": @@ -115,7 +115,7 @@ def add_rule(spot: typing.Union["BaseClasses.Location", "BaseClasses.Entrance"], def forbid_item(location: "BaseClasses.Location", item: str, player: int): old_rule = location.item_rule # empty rule - if old_rule is location.__class__.item_rule: + if old_rule is Location.item_rule: location.item_rule = lambda i: i.name != item or i.player != player else: location.item_rule = lambda i: (i.name != item or i.player != player) and old_rule(i) @@ -135,7 +135,7 @@ def forbid_items(location: "BaseClasses.Location", items: typing.Set[str]): def add_item_rule(location: "BaseClasses.Location", rule: ItemRule, combine: str = "and"): old_rule = location.item_rule # empty rule, replace instead of add - if old_rule is location.__class__.item_rule: + if old_rule is Location.item_rule: location.item_rule = rule if combine == "and" else old_rule else: if combine == "and": diff --git a/worlds/hk/Extractor.py b/worlds/hk/Extractor.py index 61fabc4da0d9..866608489ec2 100644 --- a/worlds/hk/Extractor.py +++ b/worlds/hk/Extractor.py @@ -9,11 +9,7 @@ import jinja2 -try: - from ast import unparse -except ImportError: - # Py 3.8 and earlier compatibility module - from astunparse import unparse +from ast import unparse from Utils import get_text_between diff --git a/worlds/hk/__init__.py b/worlds/hk/__init__.py index 486aa164cd5d..aede8e59cca5 100644 --- a/worlds/hk/__init__.py +++ b/worlds/hk/__init__.py @@ -231,7 +231,7 @@ def create_regions(self): all_event_names.update(set(godhome_event_names)) # Link regions - for event_name in all_event_names: + for event_name in sorted(all_event_names): #if event_name in wp_exclusions: # continue loc = HKLocation(self.player, event_name, None, menu_region) diff --git a/worlds/hk/requirements.txt b/worlds/hk/requirements.txt deleted file mode 100644 index 1b410ffb2aed..000000000000 --- a/worlds/hk/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -astunparse>=1.6.3; python_version <= '3.8' \ No newline at end of file diff --git a/worlds/kh1/Rules.py b/worlds/kh1/Rules.py index e1f72f5b3e54..130238e5048e 100644 --- a/worlds/kh1/Rules.py +++ b/worlds/kh1/Rules.py @@ -235,6 +235,11 @@ def set_rules(kh1world): lambda state: ( state.has("Progressive Glide", player) or + ( + state.has("High Jump", player, 2) + and state.has("Footprints", player) + ) + or ( options.advanced_logic and state.has_all({ @@ -246,6 +251,11 @@ def set_rules(kh1world): lambda state: ( state.has("Progressive Glide", player) or + ( + state.has("High Jump", player, 2) + and state.has("Footprints", player) + ) + or ( options.advanced_logic and state.has_all({ @@ -258,7 +268,6 @@ def set_rules(kh1world): state.has("Footprints", player) or (options.advanced_logic and state.has("Progressive Glide", player)) - or state.has("High Jump", player, 2) )) add_rule(kh1world.get_location("Wonderland Tea Party Garden Across From Bizarre Room Entrance Chest"), lambda state: ( @@ -376,7 +385,7 @@ def set_rules(kh1world): lambda state: state.has("White Trinity", player)) add_rule(kh1world.get_location("Monstro Chamber 6 Other Platform Chest"), lambda state: ( - state.has("High Jump", player) + state.has_all(("High Jump", "Progressive Glide"), player) or (options.advanced_logic and state.has("Combo Master", player)) )) add_rule(kh1world.get_location("Monstro Chamber 6 Platform Near Chamber 5 Entrance Chest"), @@ -386,7 +395,7 @@ def set_rules(kh1world): )) add_rule(kh1world.get_location("Monstro Chamber 6 Raised Area Near Chamber 1 Entrance Chest"), lambda state: ( - state.has("High Jump", player) + state.has_all(("High Jump", "Progressive Glide"), player) or (options.advanced_logic and state.has("Combo Master", player)) )) add_rule(kh1world.get_location("Halloween Town Moonlight Hill White Trinity Chest"), @@ -595,6 +604,7 @@ def set_rules(kh1world): lambda state: ( state.has("Green Trinity", player) and has_all_magic_lvx(state, player, 2) + and has_defensive_tools(state, player) )) add_rule(kh1world.get_location("Neverland Hold Flight 2nd Chest"), lambda state: ( @@ -710,8 +720,7 @@ def set_rules(kh1world): lambda state: state.has("White Trinity", player)) add_rule(kh1world.get_location("End of the World Giant Crevasse 5th Chest"), lambda state: ( - state.has("High Jump", player) - or state.has("Progressive Glide", player) + state.has("Progressive Glide", player) )) add_rule(kh1world.get_location("End of the World Giant Crevasse 1st Chest"), lambda state: ( @@ -1441,10 +1450,11 @@ def set_rules(kh1world): has_emblems(state, player, options.keyblades_unlock_chests) and has_x_worlds(state, player, 7, options.keyblades_unlock_chests) and has_defensive_tools(state, player) + and state.has("Progressive Blizzard", player, 3) )) add_rule(kh1world.get_location("Agrabah Defeat Kurt Zisa Zantetsuken Event"), lambda state: ( - has_emblems(state, player, options.keyblades_unlock_chests) and has_x_worlds(state, player, 7, options.keyblades_unlock_chests) and has_defensive_tools(state, player) + has_emblems(state, player, options.keyblades_unlock_chests) and has_x_worlds(state, player, 7, options.keyblades_unlock_chests) and has_defensive_tools(state, player) and state.has("Progressive Blizzard", player, 3) )) if options.super_bosses or options.goal.current_key == "sephiroth": add_rule(kh1world.get_location("Olympus Coliseum Defeat Sephiroth Ansem's Report 12"), diff --git a/worlds/landstalker/Locations.py b/worlds/landstalker/Locations.py index b0148269eab3..0fe63526c63b 100644 --- a/worlds/landstalker/Locations.py +++ b/worlds/landstalker/Locations.py @@ -34,7 +34,7 @@ def create_locations(player: int, regions_table: Dict[str, LandstalkerRegion], n for data in WORLD_PATHS_JSON: if "requiredNodes" in data: regions_with_entrance_checks.extend([region_id for region_id in data["requiredNodes"]]) - regions_with_entrance_checks = list(set(regions_with_entrance_checks)) + regions_with_entrance_checks = sorted(set(regions_with_entrance_checks)) for region_id in regions_with_entrance_checks: region = regions_table[region_id] location = LandstalkerLocation(player, 'event_visited_' + region_id, None, region, "event") diff --git a/worlds/lufia2ac/__init__.py b/worlds/lufia2ac/__init__.py index 6433452cefea..96de24a4b6a0 100644 --- a/worlds/lufia2ac/__init__.py +++ b/worlds/lufia2ac/__init__.py @@ -118,7 +118,7 @@ def create_regions(self) -> None: L2ACItem("Progressive chest access", ItemClassification.progression, None, self.player)) chest_access.show_in_spoiler = False ancient_dungeon.locations.append(chest_access) - for iris in self.item_name_groups["Iris treasures"]: + for iris in sorted(self.item_name_groups["Iris treasures"]): treasure_name: str = f"Iris treasure {self.item_name_to_id[iris] - self.item_name_to_id['Iris sword'] + 1}" iris_treasure: Location = \ L2ACLocation(self.player, treasure_name, self.location_name_to_id[treasure_name], ancient_dungeon) diff --git a/worlds/messenger/__init__.py b/worlds/messenger/__init__.py index 9a38953ffbdf..59e724d3fb7f 100644 --- a/worlds/messenger/__init__.py +++ b/worlds/messenger/__init__.py @@ -1,5 +1,5 @@ import logging -from typing import Any, ClassVar, Dict, List, Optional, Set, TextIO +from typing import Any, ClassVar, TextIO from BaseClasses import CollectionState, Entrance, Item, ItemClassification, MultiWorld, Tutorial from Options import Accessibility @@ -120,16 +120,16 @@ class MessengerWorld(World): required_seals: int = 0 created_seals: int = 0 total_shards: int = 0 - shop_prices: Dict[str, int] - figurine_prices: Dict[str, int] - _filler_items: List[str] - starting_portals: List[str] - plando_portals: List[str] - spoiler_portal_mapping: Dict[str, str] - portal_mapping: List[int] - transitions: List[Entrance] + shop_prices: dict[str, int] + figurine_prices: dict[str, int] + _filler_items: list[str] + starting_portals: list[str] + plando_portals: list[str] + spoiler_portal_mapping: dict[str, str] + portal_mapping: list[int] + transitions: list[Entrance] reachable_locs: int = 0 - filler: Dict[str, int] + filler: dict[str, int] def generate_early(self) -> None: if self.options.goal == Goal.option_power_seal_hunt: @@ -178,7 +178,7 @@ def create_regions(self) -> None: for reg_name in sub_region] for region in complex_regions: - region_name = region.name.replace(f"{region.parent} - ", "") + region_name = region.name.removeprefix(f"{region.parent} - ") connection_data = CONNECTIONS[region.parent][region_name] for exit_region in connection_data: region.connect(self.multiworld.get_region(exit_region, self.player)) @@ -191,7 +191,7 @@ def create_items(self) -> None: # create items that are always in the item pool main_movement_items = ["Rope Dart", "Wingsuit"] precollected_names = [item.name for item in self.multiworld.precollected_items[self.player]] - itempool: List[MessengerItem] = [ + itempool: list[MessengerItem] = [ self.create_item(item) for item in self.item_name_to_id if item not in { @@ -290,7 +290,7 @@ def write_spoiler_header(self, spoiler_handle: TextIO) -> None: for portal, output in portal_info: spoiler.set_entrance(f"{portal} Portal", output, "I can write anything I want here lmao", self.player) - def fill_slot_data(self) -> Dict[str, Any]: + def fill_slot_data(self) -> dict[str, Any]: slot_data = { "shop": {SHOP_ITEMS[item].internal_name: price for item, price in self.shop_prices.items()}, "figures": {FIGURINES[item].internal_name: price for item, price in self.figurine_prices.items()}, @@ -316,7 +316,7 @@ def get_filler_item_name(self) -> str: return self._filler_items.pop(0) def create_item(self, name: str) -> MessengerItem: - item_id: Optional[int] = self.item_name_to_id.get(name, None) + item_id: int | None = self.item_name_to_id.get(name, None) return MessengerItem( name, ItemClassification.progression if item_id is None else self.get_item_classification(name), @@ -351,7 +351,7 @@ def get_item_classification(self, name: str) -> ItemClassification: return ItemClassification.filler @classmethod - def create_group(cls, multiworld: "MultiWorld", new_player_id: int, players: Set[int]) -> World: + def create_group(cls, multiworld: "MultiWorld", new_player_id: int, players: set[int]) -> World: group = super().create_group(multiworld, new_player_id, players) assert isinstance(group, MessengerWorld) diff --git a/worlds/messenger/client_setup.py b/worlds/messenger/client_setup.py index 77a0f634326c..6b98a1b44013 100644 --- a/worlds/messenger/client_setup.py +++ b/worlds/messenger/client_setup.py @@ -5,7 +5,7 @@ import subprocess import urllib.request from shutil import which -from typing import Any, Optional +from typing import Any from zipfile import ZipFile from Utils import open_file @@ -17,7 +17,7 @@ MOD_URL = "https://api.github.com/repos/alwaysintreble/TheMessengerRandomizerModAP/releases/latest" -def ask_yes_no_cancel(title: str, text: str) -> Optional[bool]: +def ask_yes_no_cancel(title: str, text: str) -> bool | None: """ Wrapper for tkinter.messagebox.askyesnocancel, that creates a popup dialog box with yes, no, and cancel buttons. @@ -33,7 +33,6 @@ def ask_yes_no_cancel(title: str, text: str) -> Optional[bool]: return ret - def launch_game(*args) -> None: """Check the game installation, then launch it""" def courier_installed() -> bool: diff --git a/worlds/messenger/connections.py b/worlds/messenger/connections.py index 69dd7aa7f286..79912a5688c2 100644 --- a/worlds/messenger/connections.py +++ b/worlds/messenger/connections.py @@ -1,6 +1,4 @@ -from typing import Dict, List - -CONNECTIONS: Dict[str, Dict[str, List[str]]] = { +CONNECTIONS: dict[str, dict[str, list[str]]] = { "Ninja Village": { "Right": [ "Autumn Hills - Left", @@ -640,7 +638,7 @@ }, } -RANDOMIZED_CONNECTIONS: Dict[str, str] = { +RANDOMIZED_CONNECTIONS: dict[str, str] = { "Ninja Village - Right": "Autumn Hills - Left", "Autumn Hills - Left": "Ninja Village - Right", "Autumn Hills - Right": "Forlorn Temple - Left", @@ -680,7 +678,7 @@ "Sunken Shrine - Left": "Howling Grotto - Bottom", } -TRANSITIONS: List[str] = [ +TRANSITIONS: list[str] = [ "Ninja Village - Right", "Autumn Hills - Left", "Autumn Hills - Right", diff --git a/worlds/messenger/constants.py b/worlds/messenger/constants.py index ea15c71068db..47b5a1a85cff 100644 --- a/worlds/messenger/constants.py +++ b/worlds/messenger/constants.py @@ -2,7 +2,7 @@ # items # listing individual groups first for easy lookup -NOTES = [ +NOTES: list[str] = [ "Key of Hope", "Key of Chaos", "Key of Courage", @@ -11,7 +11,7 @@ "Key of Symbiosis", ] -PROG_ITEMS = [ +PROG_ITEMS: list[str] = [ "Wingsuit", "Rope Dart", "Lightfoot Tabi", @@ -28,18 +28,18 @@ "Seashell", ] -PHOBEKINS = [ +PHOBEKINS: list[str] = [ "Necro", "Pyro", "Claustro", "Acro", ] -USEFUL_ITEMS = [ +USEFUL_ITEMS: list[str] = [ "Windmill Shuriken", ] -FILLER = { +FILLER: dict[str, int] = { "Time Shard": 5, "Time Shard (10)": 10, "Time Shard (50)": 20, @@ -48,13 +48,13 @@ "Time Shard (500)": 5, } -TRAPS = { +TRAPS: dict[str, int] = { "Teleport Trap": 5, "Prophecy Trap": 10, } # item_name_to_id needs to be deterministic and match upstream -ALL_ITEMS = [ +ALL_ITEMS: list[str] = [ *NOTES, "Windmill Shuriken", "Wingsuit", @@ -83,7 +83,7 @@ # locations # the names of these don't actually matter, but using the upstream's names for now # order must be exactly the same as upstream -ALWAYS_LOCATIONS = [ +ALWAYS_LOCATIONS: list[str] = [ # notes "Sunken Shrine - Key of Love", "Corrupted Future - Key of Courage", @@ -160,7 +160,7 @@ "Elemental Skylands Seal - Fire", ] -BOSS_LOCATIONS = [ +BOSS_LOCATIONS: list[str] = [ "Autumn Hills - Leaf Golem", "Catacombs - Ruxxtin", "Howling Grotto - Emerald Golem", diff --git a/worlds/messenger/options.py b/worlds/messenger/options.py index 59e694cd3963..8b61a9435422 100644 --- a/worlds/messenger/options.py +++ b/worlds/messenger/options.py @@ -1,5 +1,4 @@ from dataclasses import dataclass -from typing import Dict from schema import And, Optional, Or, Schema @@ -167,7 +166,7 @@ class ShopPrices(Range): default = 100 -def planned_price(location: str) -> Dict[Optional, Or]: +def planned_price(location: str) -> dict[Optional, Or]: return { Optional(location): Or( And(int, lambda n: n >= 0), diff --git a/worlds/messenger/portals.py b/worlds/messenger/portals.py index 17152a1a1538..896fefa686f1 100644 --- a/worlds/messenger/portals.py +++ b/worlds/messenger/portals.py @@ -1,5 +1,5 @@ from copy import deepcopy -from typing import List, TYPE_CHECKING +from typing import TYPE_CHECKING from BaseClasses import CollectionState, PlandoOptions from Options import PlandoConnection @@ -8,7 +8,7 @@ from . import MessengerWorld -PORTALS = [ +PORTALS: list[str] = [ "Autumn Hills", "Riviere Turquoise", "Howling Grotto", @@ -18,7 +18,7 @@ ] -SHOP_POINTS = { +SHOP_POINTS: dict[str, list[str]] = { "Autumn Hills": [ "Climbing Claws", "Hope Path", @@ -113,7 +113,7 @@ } -CHECKPOINTS = { +CHECKPOINTS: dict[str, list[str]] = { "Autumn Hills": [ "Hope Latch", "Key of Hope", @@ -186,7 +186,7 @@ } -REGION_ORDER = [ +REGION_ORDER: list[str] = [ "Autumn Hills", "Forlorn Temple", "Catacombs", @@ -228,7 +228,7 @@ def create_mapping(in_portal: str, warp: str) -> str: return parent - def handle_planned_portals(plando_connections: List[PlandoConnection]) -> None: + def handle_planned_portals(plando_connections: list[PlandoConnection]) -> None: """checks the provided plando connections for portals and connects them""" nonlocal available_portals diff --git a/worlds/messenger/regions.py b/worlds/messenger/regions.py index 153f8510f1bd..d53b84fe3401 100644 --- a/worlds/messenger/regions.py +++ b/worlds/messenger/regions.py @@ -1,7 +1,4 @@ -from typing import Dict, List - - -LOCATIONS: Dict[str, List[str]] = { +LOCATIONS: dict[str, list[str]] = { "Ninja Village - Nest": [ "Ninja Village - Candle", "Ninja Village - Astral Seed", @@ -201,7 +198,7 @@ } -SUB_REGIONS: Dict[str, List[str]] = { +SUB_REGIONS: dict[str, list[str]] = { "Ninja Village": [ "Right", ], @@ -385,7 +382,7 @@ # order is slightly funky here for back compat -MEGA_SHARDS: Dict[str, List[str]] = { +MEGA_SHARDS: dict[str, list[str]] = { "Autumn Hills - Lakeside Checkpoint": ["Autumn Hills Mega Shard"], "Forlorn Temple - Outside Shop": ["Hidden Entrance Mega Shard"], "Catacombs - Top Left": ["Catacombs Mega Shard"], @@ -414,7 +411,7 @@ } -REGION_CONNECTIONS: Dict[str, Dict[str, str]] = { +REGION_CONNECTIONS: dict[str, dict[str, str]] = { "Menu": {"Tower HQ": "Start Game"}, "Tower HQ": { "Autumn Hills - Portal": "ToTHQ Autumn Hills Portal", @@ -436,7 +433,7 @@ # regions that don't have sub-regions -LEVELS: List[str] = [ +LEVELS: list[str] = [ "Menu", "Tower HQ", "The Shop", diff --git a/worlds/messenger/rules.py b/worlds/messenger/rules.py index c354ad70aba6..f09025c7edce 100644 --- a/worlds/messenger/rules.py +++ b/worlds/messenger/rules.py @@ -1,4 +1,4 @@ -from typing import Dict, TYPE_CHECKING +from typing import TYPE_CHECKING from BaseClasses import CollectionState from worlds.generic.Rules import CollectionRule, add_rule, allow_self_locking_items @@ -12,9 +12,9 @@ class MessengerRules: player: int world: "MessengerWorld" - connection_rules: Dict[str, CollectionRule] - region_rules: Dict[str, CollectionRule] - location_rules: Dict[str, CollectionRule] + connection_rules: dict[str, CollectionRule] + region_rules: dict[str, CollectionRule] + location_rules: dict[str, CollectionRule] maximum_price: int required_seals: int diff --git a/worlds/messenger/shop.py b/worlds/messenger/shop.py index 3c8c7bf6f21e..6ab72f9765f3 100644 --- a/worlds/messenger/shop.py +++ b/worlds/messenger/shop.py @@ -1,11 +1,11 @@ -from typing import Dict, List, NamedTuple, Optional, Set, TYPE_CHECKING, Tuple, Union +from typing import NamedTuple, TYPE_CHECKING if TYPE_CHECKING: from . import MessengerWorld else: MessengerWorld = object -PROG_SHOP_ITEMS: List[str] = [ +PROG_SHOP_ITEMS: list[str] = [ "Path of Resilience", "Meditation", "Strike of the Ninja", @@ -14,7 +14,7 @@ "Aerobatics Warrior", ] -USEFUL_SHOP_ITEMS: List[str] = [ +USEFUL_SHOP_ITEMS: list[str] = [ "Karuta Plates", "Serendipitous Bodies", "Kusari Jacket", @@ -29,10 +29,10 @@ class ShopData(NamedTuple): internal_name: str min_price: int max_price: int - prerequisite: Optional[Union[str, Set[str]]] = None + prerequisite: str | set[str] | None = None -SHOP_ITEMS: Dict[str, ShopData] = { +SHOP_ITEMS: dict[str, ShopData] = { "Karuta Plates": ShopData("HP_UPGRADE_1", 20, 200), "Serendipitous Bodies": ShopData("ENEMY_DROP_HP", 20, 300, "The Shop - Karuta Plates"), "Path of Resilience": ShopData("DAMAGE_REDUCTION", 100, 500, "The Shop - Serendipitous Bodies"), @@ -56,7 +56,7 @@ class ShopData(NamedTuple): "Focused Power Sense": ShopData("POWER_SEAL_WORLD_MAP", 300, 600, "The Shop - Power Sense"), } -FIGURINES: Dict[str, ShopData] = { +FIGURINES: dict[str, ShopData] = { "Green Kappa Figurine": ShopData("GREEN_KAPPA", 100, 500), "Blue Kappa Figurine": ShopData("BLUE_KAPPA", 100, 500), "Ountarde Figurine": ShopData("OUNTARDE", 100, 500), @@ -73,12 +73,12 @@ class ShopData(NamedTuple): } -def shuffle_shop_prices(world: MessengerWorld) -> Tuple[Dict[str, int], Dict[str, int]]: +def shuffle_shop_prices(world: MessengerWorld) -> tuple[dict[str, int], dict[str, int]]: shop_price_mod = world.options.shop_price.value shop_price_planned = world.options.shop_price_plan - shop_prices: Dict[str, int] = {} - figurine_prices: Dict[str, int] = {} + shop_prices: dict[str, int] = {} + figurine_prices: dict[str, int] = {} for item, price in shop_price_planned.value.items(): if not isinstance(price, int): price = world.random.choices(list(price.keys()), weights=list(price.values()))[0] diff --git a/worlds/messenger/subclasses.py b/worlds/messenger/subclasses.py index b60aeb179feb..29e3ea8953ec 100644 --- a/worlds/messenger/subclasses.py +++ b/worlds/messenger/subclasses.py @@ -1,5 +1,5 @@ from functools import cached_property -from typing import Optional, TYPE_CHECKING +from typing import TYPE_CHECKING from BaseClasses import CollectionState, Entrance, Item, ItemClassification, Location, Region from .regions import LOCATIONS, MEGA_SHARDS @@ -10,14 +10,14 @@ class MessengerEntrance(Entrance): - world: Optional["MessengerWorld"] = None + world: "MessengerWorld | None" = None class MessengerRegion(Region): parent: str entrance_type = MessengerEntrance - def __init__(self, name: str, world: "MessengerWorld", parent: Optional[str] = None) -> None: + def __init__(self, name: str, world: "MessengerWorld", parent: str | None = None) -> None: super().__init__(name, world.player, world.multiworld) self.parent = parent locations = [] @@ -48,7 +48,7 @@ def __init__(self, name: str, world: "MessengerWorld", parent: Optional[str] = N class MessengerLocation(Location): game = "The Messenger" - def __init__(self, player: int, name: str, loc_id: Optional[int], parent: MessengerRegion) -> None: + def __init__(self, player: int, name: str, loc_id: int | None, parent: MessengerRegion) -> None: super().__init__(player, name, loc_id, parent) if loc_id is None: if name == "Rescue Phantom": @@ -59,7 +59,7 @@ def __init__(self, player: int, name: str, loc_id: Optional[int], parent: Messen class MessengerShopLocation(MessengerLocation): @cached_property def cost(self) -> int: - name = self.name.replace("The Shop - ", "") # TODO use `remove_prefix` when 3.8 finally gets dropped + name = self.name.removeprefix("The Shop - ") world = self.parent_region.multiworld.worlds[self.player] shop_data = SHOP_ITEMS[name] if shop_data.prerequisite: diff --git a/worlds/messenger/test/test_shop.py b/worlds/messenger/test/test_shop.py index ce6fd19e33c8..21a0c352bff4 100644 --- a/worlds/messenger/test/test_shop.py +++ b/worlds/messenger/test/test_shop.py @@ -77,7 +77,7 @@ def test_costs(self) -> None: loc = f"The Shop - {loc}" self.assertLessEqual(price, self.multiworld.get_location(loc, self.player).cost) - self.assertTrue(loc.replace("The Shop - ", "") in SHOP_ITEMS) + self.assertTrue(loc.removeprefix("The Shop - ") in SHOP_ITEMS) self.assertEqual(len(prices), len(SHOP_ITEMS)) figures = self.world.figurine_prices diff --git a/worlds/mm2/__init__.py b/worlds/mm2/__init__.py index 07e1823f9387..4a43ee8df0f0 100644 --- a/worlds/mm2/__init__.py +++ b/worlds/mm2/__init__.py @@ -96,13 +96,13 @@ class MM2World(World): location_name_groups = location_groups web = MM2WebWorld() rom_name: bytearray - world_version: Tuple[int, int, int] = (0, 3, 1) + world_version: Tuple[int, int, int] = (0, 3, 2) wily_5_weapons: Dict[int, List[int]] - def __init__(self, world: MultiWorld, player: int): + def __init__(self, multiworld: MultiWorld, player: int): self.rom_name = bytearray() self.rom_name_available_event = threading.Event() - super().__init__(world, player) + super().__init__(multiworld, player) self.weapon_damage = deepcopy(weapon_damage) self.wily_5_weapons = {} diff --git a/worlds/mm2/rules.py b/worlds/mm2/rules.py index eddd09927445..7e2ce1f3c752 100644 --- a/worlds/mm2/rules.py +++ b/worlds/mm2/rules.py @@ -133,28 +133,6 @@ def set_rules(world: "MM2World") -> None: # Wily Machine needs all three weaknesses present, so allow elif 4 > world.weapon_damage[weapon][i] > 0: world.weapon_damage[weapon][i] = 0 - # handle special cases - for boss in range(14): - for weapon in (1, 3, 6, 8): - if (0 < world.weapon_damage[weapon][boss] < minimum_weakness_requirement[weapon] and - not any(world.weapon_damage[i][boss] > 0 for i in range(1, 8) if i != weapon)): - # Weapon does not have enough possible ammo to kill the boss, raise the damage - if boss == 9: - if weapon != 3: - # Atomic Fire and Crash Bomber cannot be Picopico-kun's only weakness - world.weapon_damage[weapon][boss] = 0 - weakness = world.random.choice((2, 3, 4, 5, 7, 8)) - world.weapon_damage[weakness][boss] = minimum_weakness_requirement[weakness] - elif boss == 11: - if weapon == 1: - # Atomic Fire cannot be Boobeam Trap's only weakness - world.weapon_damage[weapon][boss] = 0 - weakness = world.random.choice((2, 3, 4, 5, 6, 7, 8)) - world.weapon_damage[weakness][boss] = minimum_weakness_requirement[weakness] - else: - world.weapon_damage[weapon][boss] = minimum_weakness_requirement[weapon] - starting = world.options.starting_robot_master.value - world.weapon_damage[0][starting] = 1 for p_boss in world.options.plando_weakness: for p_weapon in world.options.plando_weakness[p_boss]: @@ -168,6 +146,28 @@ def set_rules(world: "MM2World") -> None: world.weapon_damage[weapons_to_id[p_weapon]][bosses[p_boss]] \ = world.options.plando_weakness[p_boss][p_weapon] + # handle special cases + for boss in range(14): + for weapon in (1, 2, 3, 6, 8): + if (0 < world.weapon_damage[weapon][boss] < minimum_weakness_requirement[weapon] and + not any(world.weapon_damage[i][boss] >= minimum_weakness_requirement[weapon] + for i in range(9) if i != weapon)): + # Weapon does not have enough possible ammo to kill the boss, raise the damage + if boss == 9: + if weapon in (1, 6): + # Atomic Fire and Crash Bomber cannot be Picopico-kun's only weakness + world.weapon_damage[weapon][boss] = 0 + weakness = world.random.choice((2, 3, 4, 5, 7, 8)) + world.weapon_damage[weakness][boss] = minimum_weakness_requirement[weakness] + elif boss == 11: + if weapon == 1: + # Atomic Fire cannot be Boobeam Trap's only weakness + world.weapon_damage[weapon][boss] = 0 + weakness = world.random.choice((2, 3, 4, 5, 6, 7, 8)) + world.weapon_damage[weakness][boss] = minimum_weakness_requirement[weakness] + else: + world.weapon_damage[weapon][boss] = minimum_weakness_requirement[weapon] + if world.weapon_damage[0][world.options.starting_robot_master.value] < 1: world.weapon_damage[0][world.options.starting_robot_master.value] = weapon_damage[0][world.options.starting_robot_master.value] @@ -209,11 +209,11 @@ def set_rules(world: "MM2World") -> None: continue highest, wp = max(zip(weapon_weight.values(), weapon_weight.keys())) uses = weapon_energy[wp] // weapon_costs[wp] - used_weapons[boss].add(wp) if int(uses * boss_damage[wp]) > boss_health[boss]: used = ceil(boss_health[boss] / boss_damage[wp]) weapon_energy[wp] -= weapon_costs[wp] * used boss_health[boss] = 0 + used_weapons[boss].add(wp) elif highest <= 0: # we are out of weapons that can actually damage the boss # so find the weapon that has the most uses, and apply that as an additional weakness @@ -221,18 +221,21 @@ def set_rules(world: "MM2World") -> None: # Quick Boomerang and no other, it would only be 28 off from defeating all 9, which Metal Blade should # be able to cover wp, max_uses = max((weapon, weapon_energy[weapon] // weapon_costs[weapon]) for weapon in weapon_weight - if weapon != 0) + if weapon != 0 and (weapon != 8 or boss != 12)) + # Wily Machine cannot under any circumstances take damage from Time Stopper, prevent this world.weapon_damage[wp][boss] = minimum_weakness_requirement[wp] used = min(int(weapon_energy[wp] // weapon_costs[wp]), - ceil(boss_health[boss] // minimum_weakness_requirement[wp])) + ceil(boss_health[boss] / minimum_weakness_requirement[wp])) weapon_energy[wp] -= weapon_costs[wp] * used boss_health[boss] -= int(used * minimum_weakness_requirement[wp]) weapon_weight.pop(wp) + used_weapons[boss].add(wp) else: # drain the weapon and continue boss_health[boss] -= int(uses * boss_damage[wp]) weapon_energy[wp] -= weapon_costs[wp] * uses weapon_weight.pop(wp) + used_weapons[boss].add(wp) world.wily_5_weapons = {boss: sorted(used_weapons[boss]) for boss in used_weapons} diff --git a/worlds/mm2/text.py b/worlds/mm2/text.py index 32d665bf6c7f..7dda12ac0346 100644 --- a/worlds/mm2/text.py +++ b/worlds/mm2/text.py @@ -1,7 +1,7 @@ from typing import DefaultDict from collections import defaultdict -MM2_WEAPON_ENCODING: DefaultDict[str, int] = defaultdict(lambda x: 0x6F, { +MM2_WEAPON_ENCODING: DefaultDict[str, int] = defaultdict(lambda: 0x6F, { ' ': 0x40, 'A': 0x41, 'B': 0x42, diff --git a/worlds/osrs/LogicCSV/locations_generated.py b/worlds/osrs/LogicCSV/locations_generated.py index 073e505ad8f4..2d617a7038fe 100644 --- a/worlds/osrs/LogicCSV/locations_generated.py +++ b/worlds/osrs/LogicCSV/locations_generated.py @@ -57,11 +57,11 @@ LocationRow('Catch a Swordfish', 'fishing', ['Lobster Spot', ], [SkillRequirement('Fishing', 50), ], [], 12), LocationRow('Bake a Redberry Pie', 'cooking', ['Redberry Bush', 'Wheat', 'Windmill', 'Pie Dish', ], [SkillRequirement('Cooking', 10), ], [], 0), LocationRow('Cook some Stew', 'cooking', ['Bowl', 'Meat', 'Potato', ], [SkillRequirement('Cooking', 25), ], [], 0), - LocationRow('Bake an Apple Pie', 'cooking', ['Cooking Apple', 'Wheat', 'Windmill', 'Pie Dish', ], [SkillRequirement('Cooking', 30), ], [], 2), + LocationRow('Bake an Apple Pie', 'cooking', ['Cooking Apple', 'Wheat', 'Windmill', 'Pie Dish', ], [SkillRequirement('Cooking', 32), ], [], 2), LocationRow('Bake a Cake', 'cooking', ['Wheat', 'Windmill', 'Egg', 'Milk', 'Cake Tin', ], [SkillRequirement('Cooking', 40), ], [], 6), LocationRow('Bake a Meat Pizza', 'cooking', ['Wheat', 'Windmill', 'Cheese', 'Tomato', 'Meat', ], [SkillRequirement('Cooking', 45), ], [], 8), - LocationRow('Burn some Oak Logs', 'firemaking', ['Oak Tree', ], [SkillRequirement('Firemaking', 15), ], [], 0), - LocationRow('Burn some Willow Logs', 'firemaking', ['Willow Tree', ], [SkillRequirement('Firemaking', 30), ], [], 0), + LocationRow('Burn some Oak Logs', 'firemaking', ['Oak Tree', ], [SkillRequirement('Firemaking', 15), SkillRequirement('Woodcutting', 15), ], [], 0), + LocationRow('Burn some Willow Logs', 'firemaking', ['Willow Tree', ], [SkillRequirement('Firemaking', 30), SkillRequirement('Woodcutting', 30), ], [], 0), LocationRow('Travel on a Canoe', 'woodcutting', ['Canoe Tree', ], [SkillRequirement('Woodcutting', 12), ], [], 0), LocationRow('Cut an Oak Log', 'woodcutting', ['Oak Tree', ], [SkillRequirement('Woodcutting', 15), ], [], 0), LocationRow('Cut a Willow Log', 'woodcutting', ['Willow Tree', ], [SkillRequirement('Woodcutting', 30), ], [], 0), diff --git a/worlds/osrs/Names.py b/worlds/osrs/Names.py index cc92439ef859..1a44aa389c6a 100644 --- a/worlds/osrs/Names.py +++ b/worlds/osrs/Names.py @@ -31,7 +31,7 @@ class RegionNames(str, Enum): Mudskipper_Point = "Mudskipper Point" Karamja = "Karamja" Corsair_Cove = "Corsair Cove" - Wilderness = "The Wilderness" + Wilderness = "Wilderness" Crandor = "Crandor" # Resource Regions Egg = "Egg" diff --git a/worlds/osrs/Rules.py b/worlds/osrs/Rules.py new file mode 100644 index 000000000000..22a19934c8e1 --- /dev/null +++ b/worlds/osrs/Rules.py @@ -0,0 +1,337 @@ +""" + Ensures a target level can be reached with available resources + """ +from worlds.generic.Rules import CollectionRule, add_rule +from .Names import RegionNames, ItemNames + + +def get_fishing_skill_rule(level, player, options) -> CollectionRule: + if options.max_fishing_level < level: + return lambda state: False + + if options.brutal_grinds or level < 5: + return lambda state: state.can_reach_region(RegionNames.Shrimp, player) + if level < 20: + return lambda state: state.can_reach_region(RegionNames.Shrimp, player) and \ + state.can_reach_region(RegionNames.Port_Sarim, player) + else: + return lambda state: state.can_reach_region(RegionNames.Shrimp, player) and \ + state.can_reach_region(RegionNames.Port_Sarim, player) and \ + state.can_reach_region(RegionNames.Fly_Fish, player) + + +def get_mining_skill_rule(level, player, options) -> CollectionRule: + if options.max_mining_level < level: + return lambda state: False + + if options.brutal_grinds or level < 15: + return lambda state: state.can_reach_region(RegionNames.Bronze_Ores, player) or \ + state.can_reach_region(RegionNames.Clay_Rock, player) + else: + # Iron is the best way to train all the way to 99, so having access to iron is all you need to check for + return lambda state: (state.can_reach_region(RegionNames.Bronze_Ores, player) or + state.can_reach_region(RegionNames.Clay_Rock, player)) and \ + state.can_reach_region(RegionNames.Iron_Rock, player) + + +def get_woodcutting_skill_rule(level, player, options) -> CollectionRule: + if options.max_woodcutting_level < level: + return lambda state: False + + if options.brutal_grinds or level < 15: + # I've checked. There is not a single chunk in the f2p that does not have at least one normal tree. + # Even the desert. + return lambda state: True + if level < 30: + return lambda state: state.can_reach_region(RegionNames.Oak_Tree, player) + else: + return lambda state: state.can_reach_region(RegionNames.Oak_Tree, player) and \ + state.can_reach_region(RegionNames.Willow_Tree, player) + + +def get_smithing_skill_rule(level, player, options) -> CollectionRule: + if options.max_smithing_level < level: + return lambda state: False + + if options.brutal_grinds: + return lambda state: state.can_reach_region(RegionNames.Bronze_Ores, player) and \ + state.can_reach_region(RegionNames.Furnace, player) + if level < 15: + # Lumbridge has a special bronze-only anvil. This is the only anvil of its type so it's not included + # in the "Anvil" resource region. We still need to check for it though. + return lambda state: state.can_reach_region(RegionNames.Bronze_Ores, player) and \ + state.can_reach_region(RegionNames.Furnace, player) and \ + (state.can_reach_region(RegionNames.Anvil, player) or + state.can_reach_region(RegionNames.Lumbridge, player)) + if level < 30: + # For levels between 15 and 30, the lumbridge anvil won't cut it. Only a real one will do + return lambda state: state.can_reach_region(RegionNames.Bronze_Ores, player) and \ + state.can_reach_region(RegionNames.Iron_Rock, player) and \ + state.can_reach_region(RegionNames.Furnace, player) and \ + state.can_reach_region(RegionNames.Anvil, player) + else: + return lambda state: state.can_reach_region(RegionNames.Bronze_Ores, player) and \ + state.can_reach_region(RegionNames.Iron_Rock, player) and \ + state.can_reach_region(RegionNames.Coal_Rock, player) and \ + state.can_reach_region(RegionNames.Furnace, player) and \ + state.can_reach_region(RegionNames.Anvil, player) + + +def get_crafting_skill_rule(level, player, options): + if options.max_crafting_level < level: + return lambda state: False + + # Crafting is really complex. Need a lot of sub-rules to make this even remotely readable + def can_spin(state): + return state.can_reach_region(RegionNames.Sheep, player) and \ + state.can_reach_region(RegionNames.Spinning_Wheel, player) + + def can_pot(state): + return state.can_reach_region(RegionNames.Clay_Rock, player) and \ + state.can_reach_region(RegionNames.Barbarian_Village, player) + + def can_tan(state): + return state.can_reach_region(RegionNames.Milk, player) and \ + state.can_reach_region(RegionNames.Al_Kharid, player) + + def mould_access(state): + return state.can_reach_region(RegionNames.Al_Kharid, player) or \ + state.can_reach_region(RegionNames.Rimmington, player) + + def can_silver(state): + return state.can_reach_region(RegionNames.Silver_Rock, player) and \ + state.can_reach_region(RegionNames.Furnace, player) and mould_access(state) + + def can_gold(state): + return state.can_reach_region(RegionNames.Gold_Rock, player) and \ + state.can_reach_region(RegionNames.Furnace, player) and mould_access(state) + + if options.brutal_grinds or level < 5: + return lambda state: can_spin(state) or can_pot(state) or can_tan(state) + + can_smelt_gold = get_smithing_skill_rule(40, player, options) + can_smelt_silver = get_smithing_skill_rule(20, player, options) + if level < 16: + return lambda state: can_pot(state) or can_tan(state) or (can_gold(state) and can_smelt_gold(state)) + else: + return lambda state: can_tan(state) or (can_silver(state) and can_smelt_silver(state)) or \ + (can_gold(state) and can_smelt_gold(state)) + + +def get_cooking_skill_rule(level, player, options) -> CollectionRule: + if options.max_cooking_level < level: + return lambda state: False + + if options.brutal_grinds or level < 15: + return lambda state: state.can_reach_region(RegionNames.Milk, player) or \ + state.can_reach_region(RegionNames.Egg, player) or \ + state.can_reach_region(RegionNames.Shrimp, player) or \ + (state.can_reach_region(RegionNames.Wheat, player) and + state.can_reach_region(RegionNames.Windmill, player)) + else: + can_catch_fly_fish = get_fishing_skill_rule(20, player, options) + + return lambda state: ( + (state.can_reach_region(RegionNames.Fly_Fish, player) and can_catch_fly_fish(state)) or + (state.can_reach_region(RegionNames.Port_Sarim, player)) + ) and ( + state.can_reach_region(RegionNames.Milk, player) or + state.can_reach_region(RegionNames.Egg, player) or + state.can_reach_region(RegionNames.Shrimp, player) or + (state.can_reach_region(RegionNames.Wheat, player) and + state.can_reach_region(RegionNames.Windmill, player)) + ) + + +def get_runecraft_skill_rule(level, player, options) -> CollectionRule: + if options.max_runecraft_level < level: + return lambda state: False + if not options.brutal_grinds: + # Ensure access to the relevant altars + if level >= 5: + return lambda state: state.has(ItemNames.QP_Rune_Mysteries, player) and \ + state.can_reach_region(RegionNames.Falador_Farm, player) and \ + state.can_reach_region(RegionNames.Lumbridge_Swamp, player) + if level >= 9: + return lambda state: state.has(ItemNames.QP_Rune_Mysteries, player) and \ + state.can_reach_region(RegionNames.Falador_Farm, player) and \ + state.can_reach_region(RegionNames.Lumbridge_Swamp, player) and \ + state.can_reach_region(RegionNames.East_Of_Varrock, player) + if level >= 14: + return lambda state: state.has(ItemNames.QP_Rune_Mysteries, player) and \ + state.can_reach_region(RegionNames.Falador_Farm, player) and \ + state.can_reach_region(RegionNames.Lumbridge_Swamp, player) and \ + state.can_reach_region(RegionNames.East_Of_Varrock, player) and \ + state.can_reach_region(RegionNames.Al_Kharid, player) + + return lambda state: state.has(ItemNames.QP_Rune_Mysteries, player) and \ + state.can_reach_region(RegionNames.Falador_Farm, player) + + +def get_magic_skill_rule(level, player, options) -> CollectionRule: + if options.max_magic_level < level: + return lambda state: False + + return lambda state: state.can_reach_region(RegionNames.Mind_Runes, player) + + +def get_firemaking_skill_rule(level, player, options) -> CollectionRule: + if options.max_firemaking_level < level: + return lambda state: False + if not options.brutal_grinds: + if level >= 30: + can_chop_willows = get_woodcutting_skill_rule(30, player, options) + return lambda state: state.can_reach_region(RegionNames.Willow_Tree, player) and can_chop_willows(state) + if level >= 15: + can_chop_oaks = get_woodcutting_skill_rule(15, player, options) + return lambda state: state.can_reach_region(RegionNames.Oak_Tree, player) and can_chop_oaks(state) + # If brutal grinds are on, or if the level is less than 15, you can train it. + return lambda state: True + + +def get_skill_rule(skill, level, player, options) -> CollectionRule: + if skill.lower() == "fishing": + return get_fishing_skill_rule(level, player, options) + if skill.lower() == "mining": + return get_mining_skill_rule(level, player, options) + if skill.lower() == "woodcutting": + return get_woodcutting_skill_rule(level, player, options) + if skill.lower() == "smithing": + return get_smithing_skill_rule(level, player, options) + if skill.lower() == "crafting": + return get_crafting_skill_rule(level, player, options) + if skill.lower() == "cooking": + return get_cooking_skill_rule(level, player, options) + if skill.lower() == "runecraft": + return get_runecraft_skill_rule(level, player, options) + if skill.lower() == "magic": + return get_magic_skill_rule(level, player, options) + if skill.lower() == "firemaking": + return get_firemaking_skill_rule(level, player, options) + + return lambda state: True + + +def generate_special_rules_for(entrance, region_row, outbound_region_name, player, options): + if outbound_region_name == RegionNames.Cooks_Guild: + add_rule(entrance, get_cooking_skill_rule(32, player, options)) + elif outbound_region_name == RegionNames.Crafting_Guild: + add_rule(entrance, get_crafting_skill_rule(40, player, options)) + elif outbound_region_name == RegionNames.Corsair_Cove: + # Need to be able to start Corsair Curse in addition to having the item + add_rule(entrance, lambda state: state.can_reach(RegionNames.Falador_Farm, "Region", player)) + elif outbound_region_name == "Camdozaal*": + add_rule(entrance, lambda state: state.has(ItemNames.QP_Below_Ice_Mountain, player)) + elif region_row.name == "Dwarven Mountain Pass" and outbound_region_name == "Anvil*": + add_rule(entrance, lambda state: state.has(ItemNames.QP_Dorics_Quest, player)) + + # Special logic for canoes + canoe_regions = [RegionNames.Lumbridge, RegionNames.South_Of_Varrock, RegionNames.Barbarian_Village, + RegionNames.Edgeville, RegionNames.Wilderness] + if region_row.name in canoe_regions: + # Skill rules for greater distances + woodcutting_rule_d1 = get_woodcutting_skill_rule(12, player, options) + woodcutting_rule_d2 = get_woodcutting_skill_rule(27, player, options) + woodcutting_rule_d3 = get_woodcutting_skill_rule(42, player, options) + woodcutting_rule_all = get_woodcutting_skill_rule(57, player, options) + + if region_row.name == RegionNames.Lumbridge: + # Canoe Tree access for the Location + if outbound_region_name == RegionNames.Canoe_Tree: + add_rule(entrance, + lambda state: (state.can_reach_region(RegionNames.South_Of_Varrock, player) + and woodcutting_rule_d1(state)) or + (state.can_reach_region(RegionNames.Barbarian_Village, player) + and woodcutting_rule_d2(state)) or + (state.can_reach_region(RegionNames.Edgeville, player) + and woodcutting_rule_d3(state)) or + (state.can_reach_region(RegionNames.Wilderness, player) + and woodcutting_rule_all(state))) + + # Access to other chunks based on woodcutting settings + elif outbound_region_name == RegionNames.South_Of_Varrock: + add_rule(entrance, woodcutting_rule_d1) + elif outbound_region_name == RegionNames.Barbarian_Village: + add_rule(entrance, woodcutting_rule_d2) + elif outbound_region_name == RegionNames.Edgeville: + add_rule(entrance, woodcutting_rule_d3) + elif outbound_region_name == RegionNames.Wilderness: + add_rule(entrance, woodcutting_rule_all) + + elif region_row.name == RegionNames.South_Of_Varrock: + if outbound_region_name == RegionNames.Canoe_Tree: + add_rule(entrance, + lambda state: (state.can_reach_region(RegionNames.Lumbridge, player) + and woodcutting_rule_d1(state)) or + (state.can_reach_region(RegionNames.Barbarian_Village, player) + and woodcutting_rule_d1(state)) or + (state.can_reach_region(RegionNames.Edgeville, player) + and woodcutting_rule_d2(state)) or + (state.can_reach_region(RegionNames.Wilderness, player) + and woodcutting_rule_d3(state))) + + # Access to other chunks based on woodcutting settings + elif outbound_region_name == RegionNames.Lumbridge: + add_rule(entrance, woodcutting_rule_d1) + elif outbound_region_name == RegionNames.Barbarian_Village: + add_rule(entrance, woodcutting_rule_d1) + elif outbound_region_name == RegionNames.Edgeville: + add_rule(entrance, woodcutting_rule_d3) + elif outbound_region_name == RegionNames.Wilderness: + add_rule(entrance, woodcutting_rule_all) + elif region_row.name == RegionNames.Barbarian_Village: + if outbound_region_name == RegionNames.Canoe_Tree: + add_rule(entrance, + lambda state: (state.can_reach_region(RegionNames.Lumbridge, player) + and woodcutting_rule_d2(state)) or (state.can_reach_region(RegionNames.South_Of_Varrock, player) + and woodcutting_rule_d1(state)) or (state.can_reach_region(RegionNames.Edgeville, player) + and woodcutting_rule_d1(state)) or (state.can_reach_region(RegionNames.Wilderness, player) + and woodcutting_rule_d2(state))) + + # Access to other chunks based on woodcutting settings + elif outbound_region_name == RegionNames.Lumbridge: + add_rule(entrance, woodcutting_rule_d2) + elif outbound_region_name == RegionNames.South_Of_Varrock: + add_rule(entrance, woodcutting_rule_d1) + # Edgeville does not need to be checked, because it's already adjacent + elif outbound_region_name == RegionNames.Wilderness: + add_rule(entrance, woodcutting_rule_d3) + elif region_row.name == RegionNames.Edgeville: + if outbound_region_name == RegionNames.Canoe_Tree: + add_rule(entrance, + lambda state: (state.can_reach_region(RegionNames.Lumbridge, player) + and woodcutting_rule_d3(state)) or + (state.can_reach_region(RegionNames.South_Of_Varrock, player) + and woodcutting_rule_d2(state)) or + (state.can_reach_region(RegionNames.Barbarian_Village, player) + and woodcutting_rule_d1(state)) or + (state.can_reach_region(RegionNames.Wilderness, player) + and woodcutting_rule_d1(state))) + + # Access to other chunks based on woodcutting settings + elif outbound_region_name == RegionNames.Lumbridge: + add_rule(entrance, woodcutting_rule_d3) + elif outbound_region_name == RegionNames.South_Of_Varrock: + add_rule(entrance, woodcutting_rule_d2) + # Barbarian Village does not need to be checked, because it's already adjacent + # Wilderness does not need to be checked, because it's already adjacent + elif region_row.name == RegionNames.Wilderness: + if outbound_region_name == RegionNames.Canoe_Tree: + add_rule(entrance, + lambda state: (state.can_reach_region(RegionNames.Lumbridge, player) + and woodcutting_rule_all(state)) or + (state.can_reach_region(RegionNames.South_Of_Varrock, player) + and woodcutting_rule_d3(state)) or + (state.can_reach_region(RegionNames.Barbarian_Village, player) + and woodcutting_rule_d2(state)) or + (state.can_reach_region(RegionNames.Edgeville, player) + and woodcutting_rule_d1(state))) + + # Access to other chunks based on woodcutting settings + elif outbound_region_name == RegionNames.Lumbridge: + add_rule(entrance, woodcutting_rule_all) + elif outbound_region_name == RegionNames.South_Of_Varrock: + add_rule(entrance, woodcutting_rule_d3) + elif outbound_region_name == RegionNames.Barbarian_Village: + add_rule(entrance, woodcutting_rule_d2) + # Edgeville does not need to be checked, because it's already adjacent diff --git a/worlds/osrs/__init__.py b/worlds/osrs/__init__.py index 58f23a2bc1d9..d6ddd63875f4 100644 --- a/worlds/osrs/__init__.py +++ b/worlds/osrs/__init__.py @@ -1,12 +1,12 @@ import typing -from BaseClasses import Item, Tutorial, ItemClassification, Region, MultiWorld +from BaseClasses import Item, Tutorial, ItemClassification, Region, MultiWorld, CollectionState +from Fill import fill_restrictive, FillError from worlds.AutoWorld import WebWorld, World -from worlds.generic.Rules import add_rule, CollectionRule from .Items import OSRSItem, starting_area_dict, chunksanity_starting_chunks, QP_Items, ItemRow, \ chunksanity_special_region_names from .Locations import OSRSLocation, LocationRow - +from .Rules import * from .Options import OSRSOptions, StartingArea from .Names import LocationNames, ItemNames, RegionNames @@ -46,6 +46,7 @@ class OSRSWorld(World): web = OSRSWeb() base_id = 0x070000 data_version = 1 + explicit_indirect_conditions = False item_name_to_id = {item_rows[i].name: 0x070000 + i for i in range(len(item_rows))} location_name_to_id = {location_rows[i].name: 0x070000 + i for i in range(len(location_rows))} @@ -61,6 +62,7 @@ class OSRSWorld(World): starting_area_item: str locations_by_category: typing.Dict[str, typing.List[LocationRow]] + available_QP_locations: typing.List[str] def __init__(self, multiworld: MultiWorld, player: int): super().__init__(multiworld, player) @@ -75,6 +77,7 @@ def __init__(self, multiworld: MultiWorld, player: int): self.starting_area_item = "" self.locations_by_category = {} + self.available_QP_locations = [] def generate_early(self) -> None: location_categories = [location_row.category for location_row in location_rows] @@ -90,9 +93,9 @@ def generate_early(self) -> None: rnd = self.random starting_area = self.options.starting_area - + #UT specific override, if we are in normal gen, resolve starting area, we will get it from slot_data in UT - if not hasattr(self.multiworld, "generation_is_fake"): + if not hasattr(self.multiworld, "generation_is_fake"): if starting_area.value == StartingArea.option_any_bank: self.starting_area_item = rnd.choice(starting_area_dict) elif starting_area.value < StartingArea.option_chunksanity: @@ -127,7 +130,6 @@ def interpret_slot_data(self, slot_data: typing.Dict[str, typing.Any]) -> None: starting_entrance.access_rule = lambda state: state.has(self.starting_area_item, self.player) starting_entrance.connect(self.region_name_to_data[starting_area_region]) - def create_regions(self) -> None: """ called to place player's regions into the MultiWorld's regions list. If it's hard to separate, this can be done @@ -145,7 +147,8 @@ def create_regions(self) -> None: # Removes the word "Area: " from the item name to get the region it applies to. # I figured tacking "Area: " at the beginning would make it _easier_ to tell apart. Turns out it made it worse - if self.starting_area_item != "": #if area hasn't been set, then we shouldn't connect it + # if area hasn't been set, then we shouldn't connect it + if self.starting_area_item != "": if self.starting_area_item in chunksanity_special_region_names: starting_area_region = chunksanity_special_region_names[self.starting_area_item] else: @@ -164,11 +167,8 @@ def create_regions(self) -> None: entrance.connect(self.region_name_to_data[parsed_outbound]) item_name = self.region_rows_by_name[parsed_outbound].itemReq - if "*" not in outbound_region_name and "*" not in item_name: - entrance.access_rule = lambda state, item_name=item_name: state.has(item_name, self.player) - continue - - self.generate_special_rules_for(entrance, region_row, outbound_region_name) + entrance.access_rule = lambda state, item_name=item_name.replace("*",""): state.has(item_name, self.player) + generate_special_rules_for(entrance, region_row, outbound_region_name, self.player, self.options) for resource_region in region_row.resources: if not resource_region: @@ -178,321 +178,34 @@ def create_regions(self) -> None: if "*" not in resource_region: entrance.connect(self.region_name_to_data[resource_region]) else: - self.generate_special_rules_for(entrance, region_row, resource_region) entrance.connect(self.region_name_to_data[resource_region.replace('*', '')]) + generate_special_rules_for(entrance, region_row, resource_region, self.player, self.options) self.roll_locations() - def generate_special_rules_for(self, entrance, region_row, outbound_region_name): - # print(f"Special rules required to access region {outbound_region_name} from {region_row.name}") - if outbound_region_name == RegionNames.Cooks_Guild: - item_name = self.region_rows_by_name[outbound_region_name].itemReq.replace('*', '') - cooking_level_rule = self.get_skill_rule("cooking", 32) - entrance.access_rule = lambda state: state.has(item_name, self.player) and \ - cooking_level_rule(state) - if self.options.brutal_grinds: - cooking_level_32_regions = { - RegionNames.Milk, - RegionNames.Egg, - RegionNames.Shrimp, - RegionNames.Wheat, - RegionNames.Windmill, - } - else: - # Level 15 cooking and higher requires level 20 fishing. - fishing_level_20_regions = { - RegionNames.Shrimp, - RegionNames.Port_Sarim, - } - cooking_level_32_regions = { - RegionNames.Milk, - RegionNames.Egg, - RegionNames.Shrimp, - RegionNames.Wheat, - RegionNames.Windmill, - RegionNames.Fly_Fish, - *fishing_level_20_regions, - } - for region_name in cooking_level_32_regions: - self.multiworld.register_indirect_condition(self.get_region(region_name), entrance) - return - if outbound_region_name == RegionNames.Crafting_Guild: - item_name = self.region_rows_by_name[outbound_region_name].itemReq.replace('*', '') - crafting_level_rule = self.get_skill_rule("crafting", 40) - entrance.access_rule = lambda state: state.has(item_name, self.player) and \ - crafting_level_rule(state) - if self.options.brutal_grinds: - crafting_level_40_regions = { - # can_spin - RegionNames.Sheep, - RegionNames.Spinning_Wheel, - # can_pot - RegionNames.Clay_Rock, - RegionNames.Barbarian_Village, - # can_tan - RegionNames.Milk, - RegionNames.Al_Kharid, - } - else: - mould_access_regions = { - RegionNames.Al_Kharid, - RegionNames.Rimmington, - } - smithing_level_20_regions = { - RegionNames.Bronze_Ores, - RegionNames.Iron_Rock, - RegionNames.Furnace, - RegionNames.Anvil, - } - smithing_level_40_regions = { - *smithing_level_20_regions, - RegionNames.Coal_Rock, - } - crafting_level_40_regions = { - # can_tan - RegionNames.Milk, - RegionNames.Al_Kharid, - # can_silver - RegionNames.Silver_Rock, - RegionNames.Furnace, - *mould_access_regions, - # can_smelt_silver - *smithing_level_20_regions, - # can_gold - RegionNames.Gold_Rock, - RegionNames.Furnace, - *mould_access_regions, - # can_smelt_gold - *smithing_level_40_regions, - } - for region_name in crafting_level_40_regions: - self.multiworld.register_indirect_condition(self.get_region(region_name), entrance) - return - if outbound_region_name == RegionNames.Corsair_Cove: - item_name = self.region_rows_by_name[outbound_region_name].itemReq.replace('*', '') - # Need to be able to start Corsair Curse in addition to having the item - entrance.access_rule = lambda state: state.has(item_name, self.player) and \ - state.can_reach(RegionNames.Falador_Farm, "Region", self.player) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Falador_Farm, self.player), entrance) - - return - if outbound_region_name == "Camdozaal*": - item_name = self.region_rows_by_name[outbound_region_name.replace('*', '')].itemReq - entrance.access_rule = lambda state: state.has(item_name, self.player) and \ - state.has(ItemNames.QP_Below_Ice_Mountain, self.player) - return - if region_row.name == "Dwarven Mountain Pass" and outbound_region_name == "Anvil*": - entrance.access_rule = lambda state: state.has(ItemNames.QP_Dorics_Quest, self.player) - return - # Special logic for canoes - canoe_regions = [RegionNames.Lumbridge, RegionNames.South_Of_Varrock, RegionNames.Barbarian_Village, - RegionNames.Edgeville, RegionNames.Wilderness] - if region_row.name in canoe_regions: - # Skill rules for greater distances - woodcutting_rule_d1 = self.get_skill_rule("woodcutting", 12) - woodcutting_rule_d2 = self.get_skill_rule("woodcutting", 27) - woodcutting_rule_d3 = self.get_skill_rule("woodcutting", 42) - woodcutting_rule_all = self.get_skill_rule("woodcutting", 57) - - def add_indirect_conditions_for_woodcutting_levels(entrance, *levels: int): - if self.options.brutal_grinds: - # No access to specific regions required. - return - # Currently, each level requirement requires everything from the previous level requirements, so the - # maximum level requirement can be taken. - max_level = max(levels, default=0) - max_level = min(max_level, self.options.max_woodcutting_level.value) - if 15 <= max_level < 30: - self.multiworld.register_indirect_condition(self.get_region(RegionNames.Oak_Tree), entrance) - elif 30 <= max_level: - self.multiworld.register_indirect_condition(self.get_region(RegionNames.Oak_Tree), entrance) - self.multiworld.register_indirect_condition(self.get_region(RegionNames.Willow_Tree), entrance) - - if region_row.name == RegionNames.Lumbridge: - # Canoe Tree access for the Location - if outbound_region_name == RegionNames.Canoe_Tree: - entrance.access_rule = \ - lambda state: (state.can_reach_region(RegionNames.South_Of_Varrock, self.player) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) or \ - (state.can_reach_region(RegionNames.Barbarian_Village) - and woodcutting_rule_d2(state) and self.options.max_woodcutting_level >= 27) or \ - (state.can_reach_region(RegionNames.Edgeville) - and woodcutting_rule_d3(state) and self.options.max_woodcutting_level >= 42) or \ - (state.can_reach_region(RegionNames.Wilderness) - and woodcutting_rule_all(state) and self.options.max_woodcutting_level >= 57) - add_indirect_conditions_for_woodcutting_levels(entrance, 12, 27, 42, 57) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.South_Of_Varrock, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Barbarian_Village, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Edgeville, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Wilderness, self.player), entrance) - # Access to other chunks based on woodcutting settings - # South of Varrock does not need to be checked, because it's already adjacent - if outbound_region_name == RegionNames.Barbarian_Village: - entrance.access_rule = lambda state: woodcutting_rule_d2(state) \ - and self.options.max_woodcutting_level >= 27 - add_indirect_conditions_for_woodcutting_levels(entrance, 27) - if outbound_region_name == RegionNames.Edgeville: - entrance.access_rule = lambda state: woodcutting_rule_d3(state) \ - and self.options.max_woodcutting_level >= 42 - add_indirect_conditions_for_woodcutting_levels(entrance, 42) - if outbound_region_name == RegionNames.Wilderness: - entrance.access_rule = lambda state: woodcutting_rule_all(state) \ - and self.options.max_woodcutting_level >= 57 - add_indirect_conditions_for_woodcutting_levels(entrance, 57) - - if region_row.name == RegionNames.South_Of_Varrock: - if outbound_region_name == RegionNames.Canoe_Tree: - entrance.access_rule = \ - lambda state: (state.can_reach_region(RegionNames.Lumbridge, self.player) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) or \ - (state.can_reach_region(RegionNames.Barbarian_Village) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) or \ - (state.can_reach_region(RegionNames.Edgeville) - and woodcutting_rule_d2(state) and self.options.max_woodcutting_level >= 27) or \ - (state.can_reach_region(RegionNames.Wilderness) - and woodcutting_rule_d3(state) and self.options.max_woodcutting_level >= 42) - add_indirect_conditions_for_woodcutting_levels(entrance, 12, 27, 42) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Lumbridge, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Barbarian_Village, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Edgeville, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Wilderness, self.player), entrance) - # Access to other chunks based on woodcutting settings - # Lumbridge does not need to be checked, because it's already adjacent - if outbound_region_name == RegionNames.Barbarian_Village: - entrance.access_rule = lambda state: woodcutting_rule_d1(state) \ - and self.options.max_woodcutting_level >= 12 - add_indirect_conditions_for_woodcutting_levels(entrance, 12) - if outbound_region_name == RegionNames.Edgeville: - entrance.access_rule = lambda state: woodcutting_rule_d3(state) \ - and self.options.max_woodcutting_level >= 27 - add_indirect_conditions_for_woodcutting_levels(entrance, 27) - if outbound_region_name == RegionNames.Wilderness: - entrance.access_rule = lambda state: woodcutting_rule_all(state) \ - and self.options.max_woodcutting_level >= 42 - add_indirect_conditions_for_woodcutting_levels(entrance, 42) - if region_row.name == RegionNames.Barbarian_Village: - if outbound_region_name == RegionNames.Canoe_Tree: - entrance.access_rule = \ - lambda state: (state.can_reach_region(RegionNames.Lumbridge, self.player) - and woodcutting_rule_d2(state) and self.options.max_woodcutting_level >= 27) or \ - (state.can_reach_region(RegionNames.South_Of_Varrock) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) or \ - (state.can_reach_region(RegionNames.Edgeville) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) or \ - (state.can_reach_region(RegionNames.Wilderness) - and woodcutting_rule_d2(state) and self.options.max_woodcutting_level >= 27) - add_indirect_conditions_for_woodcutting_levels(entrance, 12, 27) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Lumbridge, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.South_Of_Varrock, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Edgeville, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Wilderness, self.player), entrance) - # Access to other chunks based on woodcutting settings - if outbound_region_name == RegionNames.Lumbridge: - entrance.access_rule = lambda state: woodcutting_rule_d2(state) \ - and self.options.max_woodcutting_level >= 27 - add_indirect_conditions_for_woodcutting_levels(entrance, 27) - if outbound_region_name == RegionNames.South_Of_Varrock: - entrance.access_rule = lambda state: woodcutting_rule_d1(state) \ - and self.options.max_woodcutting_level >= 12 - add_indirect_conditions_for_woodcutting_levels(entrance, 12) - # Edgeville does not need to be checked, because it's already adjacent - if outbound_region_name == RegionNames.Wilderness: - entrance.access_rule = lambda state: woodcutting_rule_d3(state) \ - and self.options.max_woodcutting_level >= 42 - add_indirect_conditions_for_woodcutting_levels(entrance, 42) - if region_row.name == RegionNames.Edgeville: - if outbound_region_name == RegionNames.Canoe_Tree: - entrance.access_rule = \ - lambda state: (state.can_reach_region(RegionNames.Lumbridge, self.player) - and woodcutting_rule_d3(state) and self.options.max_woodcutting_level >= 42) or \ - (state.can_reach_region(RegionNames.South_Of_Varrock) - and woodcutting_rule_d2(state) and self.options.max_woodcutting_level >= 27) or \ - (state.can_reach_region(RegionNames.Barbarian_Village) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) or \ - (state.can_reach_region(RegionNames.Wilderness) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) - add_indirect_conditions_for_woodcutting_levels(entrance, 12, 27, 42) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Lumbridge, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.South_Of_Varrock, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Barbarian_Village, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Wilderness, self.player), entrance) - # Access to other chunks based on woodcutting settings - if outbound_region_name == RegionNames.Lumbridge: - entrance.access_rule = lambda state: woodcutting_rule_d3(state) \ - and self.options.max_woodcutting_level >= 42 - add_indirect_conditions_for_woodcutting_levels(entrance, 42) - if outbound_region_name == RegionNames.South_Of_Varrock: - entrance.access_rule = lambda state: woodcutting_rule_d2(state) \ - and self.options.max_woodcutting_level >= 27 - add_indirect_conditions_for_woodcutting_levels(entrance, 27) - # Barbarian Village does not need to be checked, because it's already adjacent - # Wilderness does not need to be checked, because it's already adjacent - if region_row.name == RegionNames.Wilderness: - if outbound_region_name == RegionNames.Canoe_Tree: - entrance.access_rule = \ - lambda state: (state.can_reach_region(RegionNames.Lumbridge, self.player) - and woodcutting_rule_all(state) and self.options.max_woodcutting_level >= 57) or \ - (state.can_reach_region(RegionNames.South_Of_Varrock) - and woodcutting_rule_d3(state) and self.options.max_woodcutting_level >= 42) or \ - (state.can_reach_region(RegionNames.Barbarian_Village) - and woodcutting_rule_d2(state) and self.options.max_woodcutting_level >= 27) or \ - (state.can_reach_region(RegionNames.Edgeville) - and woodcutting_rule_d1(state) and self.options.max_woodcutting_level >= 12) - add_indirect_conditions_for_woodcutting_levels(entrance, 12, 27, 42, 57) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Lumbridge, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.South_Of_Varrock, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Barbarian_Village, self.player), entrance) - self.multiworld.register_indirect_condition( - self.multiworld.get_region(RegionNames.Edgeville, self.player), entrance) - # Access to other chunks based on woodcutting settings - if outbound_region_name == RegionNames.Lumbridge: - entrance.access_rule = lambda state: woodcutting_rule_all(state) \ - and self.options.max_woodcutting_level >= 57 - add_indirect_conditions_for_woodcutting_levels(entrance, 57) - if outbound_region_name == RegionNames.South_Of_Varrock: - entrance.access_rule = lambda state: woodcutting_rule_d3(state) \ - and self.options.max_woodcutting_level >= 42 - add_indirect_conditions_for_woodcutting_levels(entrance, 42) - if outbound_region_name == RegionNames.Barbarian_Village: - entrance.access_rule = lambda state: woodcutting_rule_d2(state) \ - and self.options.max_woodcutting_level >= 27 - add_indirect_conditions_for_woodcutting_levels(entrance, 27) - # Edgeville does not need to be checked, because it's already adjacent + def task_within_skill_levels(self, skills_required): + # Loop through each required skill. If any of its requirements are out of the defined limit, return false + for skill in skills_required: + max_level_for_skill = getattr(self.options, f"max_{skill.skill.lower()}_level") + if skill.level > max_level_for_skill: + return False + return True def roll_locations(self): - locations_required = 0 generation_is_fake = hasattr(self.multiworld, "generation_is_fake") # UT specific override + locations_required = 0 for item_row in item_rows: locations_required += item_row.amount locations_added = 1 # At this point we've already added the starting area, so we start at 1 instead of 0 - # Quests are always added + # Quests are always added first, before anything else is rolled for i, location_row in enumerate(location_rows): if location_row.category in {"quest", "points", "goal"}: - self.create_and_add_location(i) - if location_row.category == "quest": - locations_added += 1 + if self.task_within_skill_levels(location_row.skills): + self.create_and_add_location(i) + if location_row.category == "quest": + locations_added += 1 # Build up the weighted Task Pool rnd = self.random @@ -516,10 +229,9 @@ def roll_locations(self): task_types = ["prayer", "magic", "runecraft", "mining", "crafting", "smithing", "fishing", "cooking", "firemaking", "woodcutting", "combat"] for task_type in task_types: - max_level_for_task_type = getattr(self.options, f"max_{task_type}_level") max_amount_for_task_type = getattr(self.options, f"max_{task_type}_tasks") tasks_for_this_type = [task for task in self.locations_by_category[task_type] - if task.skills[0].level <= max_level_for_task_type] + if self.task_within_skill_levels(task.skills)] if not self.options.progressive_tasks: rnd.shuffle(tasks_for_this_type) else: @@ -568,6 +280,7 @@ def roll_locations(self): self.add_location(task) locations_added += 1 + def add_location(self, location): index = [i for i in range(len(location_rows)) if location_rows[i].name == location.name][0] self.create_and_add_location(index) @@ -586,11 +299,15 @@ def get_filler_item_name(self) -> str: def create_and_add_location(self, row_index) -> None: location_row = location_rows[row_index] - # print(f"Adding task {location_row.name}") + + # Quest Points are handled differently now, but in case this gets fed an older version of the data sheet, + # the points might still be listed in a different row + if location_row.category == "points": + return # Create Location location_id = self.base_id + row_index - if location_row.category == "points" or location_row.category == "goal": + if location_row.category == "goal": location_id = None location = OSRSLocation(self.player, location_row.name, location_id) self.location_name_to_data[location_row.name] = location @@ -602,6 +319,14 @@ def create_and_add_location(self, row_index) -> None: location.parent_region = region region.locations.append(location) + # If it's a quest, generate a "Points" location we'll add an event to + if location_row.category == "quest": + points_name = location_row.name.replace("Quest:", "Points:") + points_location = OSRSLocation(self.player, points_name) + self.location_name_to_data[points_name] = points_location + points_location.parent_region = region + region.locations.append(points_location) + def set_rules(self) -> None: """ called to set access and item rules on locations and entrances. @@ -612,18 +337,26 @@ def set_rules(self) -> None: "Witchs_Potion", "Knights_Sword", "Goblin_Diplomacy", "Pirates_Treasure", "Rune_Mysteries", "Misthalin_Mystery", "Corsair_Curse", "X_Marks_the_Spot", "Below_Ice_Mountain"] - for qp_attr_name in quest_attr_names: - loc_name = getattr(LocationNames, f"QP_{qp_attr_name}") - item_name = getattr(ItemNames, f"QP_{qp_attr_name}") - self.multiworld.get_location(loc_name, self.player) \ - .place_locked_item(self.create_event(item_name)) for quest_attr_name in quest_attr_names: qp_loc_name = getattr(LocationNames, f"QP_{quest_attr_name}") + qp_loc = self.location_name_to_data.get(qp_loc_name) + q_loc_name = getattr(LocationNames, f"Q_{quest_attr_name}") - add_rule(self.multiworld.get_location(qp_loc_name, self.player), lambda state, q_loc_name=q_loc_name: ( - self.multiworld.get_location(q_loc_name, self.player).can_reach(state) - )) + q_loc = self.location_name_to_data.get(q_loc_name) + + # Checks to make sure the task is actually in the list before trying to create its rules + if qp_loc and q_loc: + # Create the QP Event Item + item_name = getattr(ItemNames, f"QP_{quest_attr_name}") + qp_loc.place_locked_item(self.create_event(item_name)) + + # If a quest is excluded, don't actually consider it for quest point progression + if q_loc_name not in self.options.exclude_locations: + self.available_QP_locations.append(item_name) + + # Set the access rule for the QP Location + add_rule(qp_loc, lambda state, loc=q_loc: (loc.can_reach(state))) # place "Victory" at "Dragon Slayer" and set collection as win condition self.multiworld.get_location(LocationNames.Q_Dragon_Slayer, self.player) \ @@ -639,7 +372,7 @@ def set_rules(self) -> None: lambda state, region_required=region_required: state.can_reach(region_required, "Region", self.player)) for skill_req in location_row.skills: - add_rule(location, self.get_skill_rule(skill_req.skill, skill_req.level)) + add_rule(location, get_skill_rule(skill_req.skill, skill_req.level, self.player, self.options)) for item_req in location_row.items: add_rule(location, lambda state, item_req=item_req: state.has(item_req, self.player)) if location_row.qp: @@ -664,124 +397,8 @@ def create_event(self, event: str): def quest_points(self, state): qp = 0 - for qp_event in QP_Items: + for qp_event in self.available_QP_locations: if state.has(qp_event, self.player): qp += int(qp_event[0]) return qp - """ - Ensures a target level can be reached with available resources - """ - - def get_skill_rule(self, skill, level) -> CollectionRule: - if skill.lower() == "fishing": - if self.options.brutal_grinds or level < 5: - return lambda state: state.can_reach(RegionNames.Shrimp, "Region", self.player) - if level < 20: - return lambda state: state.can_reach(RegionNames.Shrimp, "Region", self.player) and \ - state.can_reach(RegionNames.Port_Sarim, "Region", self.player) - else: - return lambda state: state.can_reach(RegionNames.Shrimp, "Region", self.player) and \ - state.can_reach(RegionNames.Port_Sarim, "Region", self.player) and \ - state.can_reach(RegionNames.Fly_Fish, "Region", self.player) - if skill.lower() == "mining": - if self.options.brutal_grinds or level < 15: - return lambda state: state.can_reach(RegionNames.Bronze_Ores, "Region", self.player) or \ - state.can_reach(RegionNames.Clay_Rock, "Region", self.player) - else: - # Iron is the best way to train all the way to 99, so having access to iron is all you need to check for - return lambda state: (state.can_reach(RegionNames.Bronze_Ores, "Region", self.player) or - state.can_reach(RegionNames.Clay_Rock, "Region", self.player)) and \ - state.can_reach(RegionNames.Iron_Rock, "Region", self.player) - if skill.lower() == "woodcutting": - if self.options.brutal_grinds or level < 15: - # I've checked. There is not a single chunk in the f2p that does not have at least one normal tree. - # Even the desert. - return lambda state: True - if level < 30: - return lambda state: state.can_reach(RegionNames.Oak_Tree, "Region", self.player) - else: - return lambda state: state.can_reach(RegionNames.Oak_Tree, "Region", self.player) and \ - state.can_reach(RegionNames.Willow_Tree, "Region", self.player) - if skill.lower() == "smithing": - if self.options.brutal_grinds: - return lambda state: state.can_reach(RegionNames.Bronze_Ores, "Region", self.player) and \ - state.can_reach(RegionNames.Furnace, "Region", self.player) - if level < 15: - # Lumbridge has a special bronze-only anvil. This is the only anvil of its type so it's not included - # in the "Anvil" resource region. We still need to check for it though. - return lambda state: state.can_reach(RegionNames.Bronze_Ores, "Region", self.player) and \ - state.can_reach(RegionNames.Furnace, "Region", self.player) and \ - (state.can_reach(RegionNames.Anvil, "Region", self.player) or - state.can_reach(RegionNames.Lumbridge, "Region", self.player)) - if level < 30: - # For levels between 15 and 30, the lumbridge anvil won't cut it. Only a real one will do - return lambda state: state.can_reach(RegionNames.Bronze_Ores, "Region", self.player) and \ - state.can_reach(RegionNames.Iron_Rock, "Region", self.player) and \ - state.can_reach(RegionNames.Furnace, "Region", self.player) and \ - state.can_reach(RegionNames.Anvil, "Region", self.player) - else: - return lambda state: state.can_reach(RegionNames.Bronze_Ores, "Region", self.player) and \ - state.can_reach(RegionNames.Iron_Rock, "Region", self.player) and \ - state.can_reach(RegionNames.Coal_Rock, "Region", self.player) and \ - state.can_reach(RegionNames.Furnace, "Region", self.player) and \ - state.can_reach(RegionNames.Anvil, "Region", self.player) - if skill.lower() == "crafting": - # Crafting is really complex. Need a lot of sub-rules to make this even remotely readable - def can_spin(state): - return state.can_reach(RegionNames.Sheep, "Region", self.player) and \ - state.can_reach(RegionNames.Spinning_Wheel, "Region", self.player) - - def can_pot(state): - return state.can_reach(RegionNames.Clay_Rock, "Region", self.player) and \ - state.can_reach(RegionNames.Barbarian_Village, "Region", self.player) - - def can_tan(state): - return state.can_reach(RegionNames.Milk, "Region", self.player) and \ - state.can_reach(RegionNames.Al_Kharid, "Region", self.player) - - def mould_access(state): - return state.can_reach(RegionNames.Al_Kharid, "Region", self.player) or \ - state.can_reach(RegionNames.Rimmington, "Region", self.player) - - def can_silver(state): - - return state.can_reach(RegionNames.Silver_Rock, "Region", self.player) and \ - state.can_reach(RegionNames.Furnace, "Region", self.player) and mould_access(state) - - def can_gold(state): - return state.can_reach(RegionNames.Gold_Rock, "Region", self.player) and \ - state.can_reach(RegionNames.Furnace, "Region", self.player) and mould_access(state) - - if self.options.brutal_grinds or level < 5: - return lambda state: can_spin(state) or can_pot(state) or can_tan(state) - - can_smelt_gold = self.get_skill_rule("smithing", 40) - can_smelt_silver = self.get_skill_rule("smithing", 20) - if level < 16: - return lambda state: can_pot(state) or can_tan(state) or (can_gold(state) and can_smelt_gold(state)) - else: - return lambda state: can_tan(state) or (can_silver(state) and can_smelt_silver(state)) or \ - (can_gold(state) and can_smelt_gold(state)) - if skill.lower() == "cooking": - if self.options.brutal_grinds or level < 15: - return lambda state: state.can_reach(RegionNames.Milk, "Region", self.player) or \ - state.can_reach(RegionNames.Egg, "Region", self.player) or \ - state.can_reach(RegionNames.Shrimp, "Region", self.player) or \ - (state.can_reach(RegionNames.Wheat, "Region", self.player) and - state.can_reach(RegionNames.Windmill, "Region", self.player)) - else: - can_catch_fly_fish = self.get_skill_rule("fishing", 20) - return lambda state: state.can_reach(RegionNames.Fly_Fish, "Region", self.player) and \ - can_catch_fly_fish(state) and \ - (state.can_reach(RegionNames.Milk, "Region", self.player) or - state.can_reach(RegionNames.Egg, "Region", self.player) or - state.can_reach(RegionNames.Shrimp, "Region", self.player) or - (state.can_reach(RegionNames.Wheat, "Region", self.player) and - state.can_reach(RegionNames.Windmill, "Region", self.player))) - if skill.lower() == "runecraft": - return lambda state: state.has(ItemNames.QP_Rune_Mysteries, self.player) - if skill.lower() == "magic": - return lambda state: state.can_reach(RegionNames.Mind_Runes, "Region", self.player) - - return lambda state: True diff --git a/worlds/pokemon_rb/__init__.py b/worlds/pokemon_rb/__init__.py index 98b1a0c614b8..809179cbef74 100644 --- a/worlds/pokemon_rb/__init__.py +++ b/worlds/pokemon_rb/__init__.py @@ -528,8 +528,8 @@ def stage_post_fill(cls, multiworld): for sphere in multiworld.get_spheres(): mon_locations_in_sphere = {} for location in sphere: - if (location.game == "Pokemon Red and Blue" and (location.item.name in poke_data.pokemon_data.keys() - or "Static " in location.item.name) + if (location.game == location.item.game == "Pokemon Red and Blue" + and (location.item.name in poke_data.pokemon_data.keys() or "Static " in location.item.name) and location.item.advancement): key = (location.player, location.item.name) if key in found_mons: diff --git a/worlds/pokemon_rb/rules.py b/worlds/pokemon_rb/rules.py index ba4bfd471c52..3c1cdc57e99b 100644 --- a/worlds/pokemon_rb/rules.py +++ b/worlds/pokemon_rb/rules.py @@ -94,6 +94,9 @@ def prize_rule(i): "Route 22 - Trainer Parties": lambda state: state.has("Oak's Parcel", player), + "Victory Road 1F - Top Item": lambda state: logic.can_strength(state, world, player), + "Victory Road 1F - Left Item": lambda state: logic.can_strength(state, world, player), + # # Rock Tunnel "Rock Tunnel 1F - PokeManiac": lambda state: logic.rock_tunnel(state, world, player), "Rock Tunnel 1F - Hiker 1": lambda state: logic.rock_tunnel(state, world, player), diff --git a/worlds/sc2/Locations.py b/worlds/sc2/Locations.py index 53f41f4e4c3d..b9c30bb70106 100644 --- a/worlds/sc2/Locations.py +++ b/worlds/sc2/Locations.py @@ -1387,7 +1387,7 @@ def get_locations(world: Optional[World]) -> Tuple[LocationData, ...]: lambda state: logic.templars_return_requirement(state)), LocationData("The Host", "The Host: Victory", SC2LOTV_LOC_ID_OFFSET + 2100, LocationType.VICTORY, lambda state: logic.the_host_requirement(state)), - LocationData("The Host", "The Host: Southeast Void Shard", SC2LOTV_LOC_ID_OFFSET + 2101, LocationType.VICTORY, + LocationData("The Host", "The Host: Southeast Void Shard", SC2LOTV_LOC_ID_OFFSET + 2101, LocationType.EXTRA, lambda state: logic.the_host_requirement(state)), LocationData("The Host", "The Host: South Void Shard", SC2LOTV_LOC_ID_OFFSET + 2102, LocationType.EXTRA, lambda state: logic.the_host_requirement(state)), diff --git a/worlds/sc2/MissionTables.py b/worlds/sc2/MissionTables.py index 4dece46411bf..08e1f133deda 100644 --- a/worlds/sc2/MissionTables.py +++ b/worlds/sc2/MissionTables.py @@ -43,6 +43,9 @@ def __init__(self, campaign_id: int, name: str, goal_priority: SC2CampaignGoalPr self.goal_priority = goal_priority self.race = race + def __lt__(self, other: "SC2Campaign"): + return self.id < other.id + GLOBAL = 0, "Global", SC2CampaignGoalPriority.NONE, SC2Race.ANY WOL = 1, "Wings of Liberty", SC2CampaignGoalPriority.VERY_HARD, SC2Race.TERRAN PROPHECY = 2, "Prophecy", SC2CampaignGoalPriority.MINI_CAMPAIGN, SC2Race.PROTOSS diff --git a/worlds/sc2/Regions.py b/worlds/sc2/Regions.py index 84830a9a32bd..273bc4a5e87c 100644 --- a/worlds/sc2/Regions.py +++ b/worlds/sc2/Regions.py @@ -50,7 +50,7 @@ def create_vanilla_regions( names: Dict[str, int] = {} # Generating all regions and locations for each enabled campaign - for campaign in enabled_campaigns: + for campaign in sorted(enabled_campaigns): for region_name in vanilla_mission_req_table[campaign].keys(): regions.append(create_region(world, locations_per_region, location_cache, region_name)) world.multiworld.regions += regions diff --git a/worlds/stardew_valley/__init__.py b/worlds/stardew_valley/__init__.py index f9df8c292e37..44306011361c 100644 --- a/worlds/stardew_valley/__init__.py +++ b/worlds/stardew_valley/__init__.py @@ -319,7 +319,7 @@ def create_item(self, item: Union[str, ItemData], override_classification: ItemC if override_classification is None: override_classification = item.classification - if override_classification == ItemClassification.progression: + if override_classification & ItemClassification.progression: self.total_progression_items += 1 return StardewItem(item.name, override_classification, item.code, self.player) diff --git a/worlds/stardew_valley/content/unpacking.py b/worlds/stardew_valley/content/unpacking.py index f069866d56cd..3c57f91afe3a 100644 --- a/worlds/stardew_valley/content/unpacking.py +++ b/worlds/stardew_valley/content/unpacking.py @@ -1,16 +1,12 @@ from __future__ import annotations +from graphlib import TopologicalSorter from typing import Iterable, Mapping, Callable from .game_content import StardewContent, ContentPack, StardewFeatures from .vanilla.base import base_game as base_game_content_pack from ..data.game_item import GameItem, ItemSource -try: - from graphlib import TopologicalSorter -except ImportError: - from graphlib_backport import TopologicalSorter # noqa - def unpack_content(features: StardewFeatures, packs: Iterable[ContentPack]) -> StardewContent: # Base game is always registered first. diff --git a/worlds/stardew_valley/data/artisan.py b/worlds/stardew_valley/data/artisan.py index 593ab6a3ddf0..90be5b1684f0 100644 --- a/worlds/stardew_valley/data/artisan.py +++ b/worlds/stardew_valley/data/artisan.py @@ -1,9 +1,9 @@ from dataclasses import dataclass -from .game_item import kw_only, ItemSource +from .game_item import ItemSource -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class MachineSource(ItemSource): item: str # this should be optional (worm bin) machine: str diff --git a/worlds/stardew_valley/data/game_item.py b/worlds/stardew_valley/data/game_item.py index 6c8d30ed8e6f..c6e4717cd1e0 100644 --- a/worlds/stardew_valley/data/game_item.py +++ b/worlds/stardew_valley/data/game_item.py @@ -1,5 +1,4 @@ import enum -import sys from abc import ABC from dataclasses import dataclass, field from types import MappingProxyType @@ -7,11 +6,6 @@ from ..stardew_rule.protocol import StardewRule -if sys.version_info >= (3, 10): - kw_only = {"kw_only": True} -else: - kw_only = {} - DEFAULT_REQUIREMENT_TAGS = MappingProxyType({}) @@ -36,21 +30,17 @@ class ItemTag(enum.Enum): class ItemSource(ABC): add_tags: ClassVar[Tuple[ItemTag]] = () + other_requirements: Tuple[Requirement, ...] = field(kw_only=True, default_factory=tuple) + @property def requirement_tags(self) -> Mapping[str, Tuple[ItemTag, ...]]: return DEFAULT_REQUIREMENT_TAGS - # FIXME this should just be an optional field, but kw_only requires python 3.10... - @property - def other_requirements(self) -> Iterable[Requirement]: - return () - -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class GenericSource(ItemSource): regions: Tuple[str, ...] = () """No region means it's available everywhere.""" - other_requirements: Tuple[Requirement, ...] = () @dataclass(frozen=True) @@ -59,7 +49,7 @@ class CustomRuleSource(ItemSource): create_rule: Callable[[Any], StardewRule] -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class CompoundSource(ItemSource): sources: Tuple[ItemSource, ...] = () diff --git a/worlds/stardew_valley/data/harvest.py b/worlds/stardew_valley/data/harvest.py index 087d7c3fa86b..0fdae9549587 100644 --- a/worlds/stardew_valley/data/harvest.py +++ b/worlds/stardew_valley/data/harvest.py @@ -1,18 +1,17 @@ from dataclasses import dataclass from typing import Tuple, Sequence, Mapping -from .game_item import ItemSource, kw_only, ItemTag, Requirement +from .game_item import ItemSource, ItemTag from ..strings.season_names import Season -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class ForagingSource(ItemSource): regions: Tuple[str, ...] seasons: Tuple[str, ...] = Season.all - other_requirements: Tuple[Requirement, ...] = () -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class SeasonalForagingSource(ItemSource): season: str days: Sequence[int] @@ -22,17 +21,17 @@ def as_foraging_source(self) -> ForagingSource: return ForagingSource(seasons=(self.season,), regions=self.regions) -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class FruitBatsSource(ItemSource): ... -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class MushroomCaveSource(ItemSource): ... -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class HarvestFruitTreeSource(ItemSource): add_tags = (ItemTag.CROPSANITY,) @@ -46,7 +45,7 @@ def requirement_tags(self) -> Mapping[str, Tuple[ItemTag, ...]]: } -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class HarvestCropSource(ItemSource): add_tags = (ItemTag.CROPSANITY,) @@ -61,6 +60,6 @@ def requirement_tags(self) -> Mapping[str, Tuple[ItemTag, ...]]: } -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class ArtifactSpotSource(ItemSource): amount: int diff --git a/worlds/stardew_valley/data/items.csv b/worlds/stardew_valley/data/items.csv index ffcae223e251..05af275ba472 100644 --- a/worlds/stardew_valley/data/items.csv +++ b/worlds/stardew_valley/data/items.csv @@ -7,7 +7,7 @@ id,name,classification,groups,mod_name 19,Glittering Boulder Removed,progression,COMMUNITY_REWARD, 20,Minecarts Repair,useful,COMMUNITY_REWARD, 21,Bus Repair,progression,COMMUNITY_REWARD, -22,Progressive Movie Theater,progression,COMMUNITY_REWARD, +22,Progressive Movie Theater,"progression,trap",COMMUNITY_REWARD, 23,Stardrop,progression,, 24,Progressive Backpack,progression,, 25,Rusty Sword,filler,"WEAPON,DEPRECATED", diff --git a/worlds/stardew_valley/data/shop.py b/worlds/stardew_valley/data/shop.py index f14dbac82131..cc9506023f19 100644 --- a/worlds/stardew_valley/data/shop.py +++ b/worlds/stardew_valley/data/shop.py @@ -1,40 +1,39 @@ from dataclasses import dataclass from typing import Tuple, Optional -from .game_item import ItemSource, kw_only, Requirement +from .game_item import ItemSource from ..strings.season_names import Season ItemPrice = Tuple[int, str] -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class ShopSource(ItemSource): shop_region: str money_price: Optional[int] = None items_price: Optional[Tuple[ItemPrice, ...]] = None seasons: Tuple[str, ...] = Season.all - other_requirements: Tuple[Requirement, ...] = () def __post_init__(self): assert self.money_price is not None or self.items_price is not None, "At least money price or items price need to be defined." assert self.items_price is None or all(isinstance(p, tuple) for p in self.items_price), "Items price should be a tuple." -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class MysteryBoxSource(ItemSource): amount: int -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class ArtifactTroveSource(ItemSource): amount: int -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class PrizeMachineSource(ItemSource): amount: int -@dataclass(frozen=True, **kw_only) +@dataclass(frozen=True, kw_only=True) class FishingTreasureChestSource(ItemSource): amount: int diff --git a/worlds/stardew_valley/data/skill.py b/worlds/stardew_valley/data/skill.py index d0674f34c0e1..4c754ddd8716 100644 --- a/worlds/stardew_valley/data/skill.py +++ b/worlds/stardew_valley/data/skill.py @@ -1,9 +1,7 @@ from dataclasses import dataclass, field -from ..data.game_item import kw_only - @dataclass(frozen=True) class Skill: name: str - has_mastery: bool = field(**kw_only) + has_mastery: bool = field(kw_only=True) diff --git a/worlds/stardew_valley/docs/en_Stardew Valley.md b/worlds/stardew_valley/docs/en_Stardew Valley.md index 0ed693031b82..62755dad798d 100644 --- a/worlds/stardew_valley/docs/en_Stardew Valley.md +++ b/worlds/stardew_valley/docs/en_Stardew Valley.md @@ -138,7 +138,7 @@ This means that, for these specific mods, if you decide to include them in your with the assumption that you will install and play with these mods. The multiworld will contain related items and locations for these mods, the specifics will vary from mod to mod -[Supported Mods Documentation](https://github.com/agilbert1412/StardewArchipelago/blob/5.x.x/Documentation/Supported%20Mods.md) +[Supported Mods Documentation](https://github.com/agilbert1412/StardewArchipelago/blob/6.x.x/Documentation/Supported%20Mods.md) List of supported mods: diff --git a/worlds/stardew_valley/docs/setup_en.md b/worlds/stardew_valley/docs/setup_en.md index c672152543cf..801bf345e916 100644 --- a/worlds/stardew_valley/docs/setup_en.md +++ b/worlds/stardew_valley/docs/setup_en.md @@ -12,7 +12,7 @@ - Archipelago from the [Archipelago Releases Page](https://github.com/ArchipelagoMW/Archipelago/releases) * (Only for the TextClient) - Other Stardew Valley Mods [Nexus Mods](https://www.nexusmods.com/stardewvalley) - * There are [supported mods](https://github.com/agilbert1412/StardewArchipelago/blob/5.x.x/Documentation/Supported%20Mods.md) + * There are [supported mods](https://github.com/agilbert1412/StardewArchipelago/blob/6.x.x/Documentation/Supported%20Mods.md) that you can add to your yaml to include them with the Archipelago randomization * It is **not** recommended to further mod Stardew Valley with unsupported mods, although it is possible to do so. diff --git a/worlds/stardew_valley/items.py b/worlds/stardew_valley/items.py index 31c7da5e3ade..993863bf5bf5 100644 --- a/worlds/stardew_valley/items.py +++ b/worlds/stardew_valley/items.py @@ -2,6 +2,7 @@ import enum import logging from dataclasses import dataclass, field +from functools import reduce from pathlib import Path from random import Random from typing import Dict, List, Protocol, Union, Set, Optional @@ -124,17 +125,14 @@ def __call__(self, item: Item): def load_item_csv(): - try: - from importlib.resources import files - except ImportError: - from importlib_resources import files # noqa + from importlib.resources import files items = [] with files(data).joinpath("items.csv").open() as file: item_reader = csv.DictReader(file) for item in item_reader: id = int(item["id"]) if item["id"] else None - classification = ItemClassification[item["classification"]] + classification = reduce((lambda a, b: a | b), {ItemClassification[str_classification] for str_classification in item["classification"].split(",")}) groups = {Group[group] for group in item["groups"].split(",") if group} mod_name = str(item["mod_name"]) if item["mod_name"] else None items.append(ItemData(id, item["name"], classification, mod_name, groups)) diff --git a/worlds/stardew_valley/locations.py b/worlds/stardew_valley/locations.py index 43246a94a356..1d67d535ccee 100644 --- a/worlds/stardew_valley/locations.py +++ b/worlds/stardew_valley/locations.py @@ -130,10 +130,7 @@ def __call__(self, name: str, code: Optional[int], region: str) -> None: def load_location_csv() -> List[LocationData]: - try: - from importlib.resources import files - except ImportError: - from importlib_resources import files + from importlib.resources import files with files(data).joinpath("locations.csv").open() as file: reader = csv.DictReader(file) diff --git a/worlds/stardew_valley/presets.py b/worlds/stardew_valley/presets.py index 1861a914235c..62672f29e424 100644 --- a/worlds/stardew_valley/presets.py +++ b/worlds/stardew_valley/presets.py @@ -41,9 +41,7 @@ Friendsanity.internal_name: "random", FriendsanityHeartSize.internal_name: "random", Booksanity.internal_name: "random", - Walnutsanity.internal_name: "random", NumberOfMovementBuffs.internal_name: "random", - EnabledFillerBuffs.internal_name: "random", ExcludeGingerIsland.internal_name: "random", TrapItems.internal_name: "random", MultipleDaySleepEnabled.internal_name: "random", diff --git a/worlds/stardew_valley/requirements.txt b/worlds/stardew_valley/requirements.txt deleted file mode 100644 index 65e922a64483..000000000000 --- a/worlds/stardew_valley/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -importlib_resources; python_version <= '3.8' -graphlib_backport; python_version <= '3.8' diff --git a/worlds/stardew_valley/test/TestGeneration.py b/worlds/stardew_valley/test/TestGeneration.py index 8431e6857eaf..56f338fe8e11 100644 --- a/worlds/stardew_valley/test/TestGeneration.py +++ b/worlds/stardew_valley/test/TestGeneration.py @@ -35,7 +35,7 @@ def test_all_progression_items_are_added_to_the_pool(self): items_to_ignore.extend(baby.name for baby in items.items_by_group[Group.BABY]) items_to_ignore.extend(resource_pack.name for resource_pack in items.items_by_group[Group.RESOURCE_PACK]) items_to_ignore.append("The Gateway Gazette") - progression_items = [item for item in items.all_items if item.classification is ItemClassification.progression and item.name not in items_to_ignore] + progression_items = [item for item in items.all_items if item.classification & ItemClassification.progression and item.name not in items_to_ignore] for progression_item in progression_items: with self.subTest(f"{progression_item.name}"): self.assertIn(progression_item.name, all_created_items) @@ -86,7 +86,7 @@ def test_all_progression_items_except_island_are_added_to_the_pool(self): items_to_ignore.extend(season.name for season in items.items_by_group[Group.WEAPON]) items_to_ignore.extend(baby.name for baby in items.items_by_group[Group.BABY]) items_to_ignore.append("The Gateway Gazette") - progression_items = [item for item in items.all_items if item.classification is ItemClassification.progression and item.name not in items_to_ignore] + progression_items = [item for item in items.all_items if item.classification & ItemClassification.progression and item.name not in items_to_ignore] for progression_item in progression_items: with self.subTest(f"{progression_item.name}"): if Group.GINGER_ISLAND in progression_item.groups: diff --git a/worlds/stardew_valley/test/__init__.py b/worlds/stardew_valley/test/__init__.py index 3fe05d205ce0..8f4e5af28f84 100644 --- a/worlds/stardew_valley/test/__init__.py +++ b/worlds/stardew_valley/test/__init__.py @@ -306,7 +306,7 @@ def collect(self, item: Union[str, Item, Iterable[Item]], count: int = 1) -> Uni def create_item(self, item: str) -> StardewItem: created_item = self.world.create_item(item) - if created_item.classification == ItemClassification.progression: + if created_item.classification & ItemClassification.progression: self.multiworld.worlds[self.player].total_progression_items -= 1 return created_item diff --git a/worlds/stardew_valley/test/mods/TestMods.py b/worlds/stardew_valley/test/mods/TestMods.py index 97184b1338b8..07a75f21b1de 100644 --- a/worlds/stardew_valley/test/mods/TestMods.py +++ b/worlds/stardew_valley/test/mods/TestMods.py @@ -75,7 +75,7 @@ def test_all_progression_items_are_added_to_the_pool(self): items_to_ignore.extend(baby.name for baby in items.items_by_group[Group.BABY]) items_to_ignore.extend(resource_pack.name for resource_pack in items.items_by_group[Group.RESOURCE_PACK]) items_to_ignore.append("The Gateway Gazette") - progression_items = [item for item in items.all_items if item.classification is ItemClassification.progression + progression_items = [item for item in items.all_items if item.classification & ItemClassification.progression and item.name not in items_to_ignore] for progression_item in progression_items: with self.subTest(f"{progression_item.name}"): @@ -105,7 +105,7 @@ def test_all_progression_items_except_island_are_added_to_the_pool(self): items_to_ignore.extend(baby.name for baby in items.items_by_group[Group.BABY]) items_to_ignore.extend(resource_pack.name for resource_pack in items.items_by_group[Group.RESOURCE_PACK]) items_to_ignore.append("The Gateway Gazette") - progression_items = [item for item in items.all_items if item.classification is ItemClassification.progression + progression_items = [item for item in items.all_items if item.classification & ItemClassification.progression and item.name not in items_to_ignore] for progression_item in progression_items: with self.subTest(f"{progression_item.name}"): diff --git a/worlds/stardew_valley/test/rules/TestStateRules.py b/worlds/stardew_valley/test/rules/TestStateRules.py index 4f53b9a7f536..7d10f4ceb1d3 100644 --- a/worlds/stardew_valley/test/rules/TestStateRules.py +++ b/worlds/stardew_valley/test/rules/TestStateRules.py @@ -8,5 +8,5 @@ class TestHasProgressionPercent(unittest.TestCase): def test_max_item_amount_is_full_collection(self): # Not caching because it fails too often for some reason with solo_multiworld(world_caching=False) as (multiworld, world): - progression_item_count = sum(1 for i in multiworld.get_items() if ItemClassification.progression in i.classification) + progression_item_count = sum(1 for i in multiworld.get_items() if i.classification & ItemClassification.progression) self.assertEqual(world.total_progression_items, progression_item_count - 1) # -1 to skip Victory diff --git a/worlds/stardew_valley/test/stability/TestStability.py b/worlds/stardew_valley/test/stability/TestStability.py index 8bb904a56ea2..137a7172aff4 100644 --- a/worlds/stardew_valley/test/stability/TestStability.py +++ b/worlds/stardew_valley/test/stability/TestStability.py @@ -12,8 +12,6 @@ # at 0x102ca98a0> lambda_regex = re.compile(r"^ at (.*)>$") -# Python 3.10.2\r\n -python_version_regex = re.compile(r"^Python (\d+)\.(\d+)\.(\d+)\s*$") class TestGenerationIsStable(SVTestCase): diff --git a/worlds/subnautica/options.py b/worlds/subnautica/options.py index 4bdd9aafa53f..6cdcb33d8954 100644 --- a/worlds/subnautica/options.py +++ b/worlds/subnautica/options.py @@ -112,8 +112,7 @@ def get_pool(self) -> typing.List[str]: class SubnauticaDeathLink(DeathLink): - """When you die, everyone dies. Of course the reverse is true too. - Note: can be toggled via in-game console command "deathlink".""" + __doc__ = DeathLink.__doc__ + "\n\n Note: can be toggled via in-game console command \"deathlink\"." class FillerItemsDistribution(ItemDict): diff --git a/worlds/timespinner/Options.py b/worlds/timespinner/Options.py index f6a3dba3e311..c06dd36797fd 100644 --- a/worlds/timespinner/Options.py +++ b/worlds/timespinner/Options.py @@ -379,6 +379,7 @@ class TimespinnerOptions(PerGameCommonOptions, DeathLinkMixin): cantoran: Cantoran lore_checks: LoreChecks boss_rando: BossRando + enemy_rando: EnemyRando damage_rando: DamageRando damage_rando_overrides: DamageRandoOverrides hp_cap: HpCap @@ -445,6 +446,7 @@ class BackwardsCompatiableTimespinnerOptions(TimespinnerOptions): Cantoran: hidden(Cantoran) # type: ignore LoreChecks: hidden(LoreChecks) # type: ignore BossRando: hidden(BossRando) # type: ignore + EnemyRando: hidden(EnemyRando) # type: ignore DamageRando: hidden(DamageRando) # type: ignore DamageRandoOverrides: HiddenDamageRandoOverrides HpCap: hidden(HpCap) # type: ignore @@ -516,6 +518,10 @@ def handle_backward_compatibility(self) -> None: self.boss_rando == BossRando.default: self.boss_rando.value = self.BossRando.value self.has_replaced_options.value = Toggle.option_true + if self.EnemyRando != EnemyRando.default and \ + self.enemy_rando == EnemyRando.default: + self.enemy_rando.value = self.EnemyRando.value + self.has_replaced_options.value = Toggle.option_true if self.DamageRando != DamageRando.default and \ self.damage_rando == DamageRando.default: self.damage_rando.value = self.DamageRando.value diff --git a/worlds/timespinner/__init__.py b/worlds/timespinner/__init__.py index f241d4468162..72903bd5ffea 100644 --- a/worlds/timespinner/__init__.py +++ b/worlds/timespinner/__init__.py @@ -98,6 +98,7 @@ def fill_slot_data(self) -> Dict[str, object]: "Cantoran": self.options.cantoran.value, "LoreChecks": self.options.lore_checks.value, "BossRando": self.options.boss_rando.value, + "EnemyRando": self.options.enemy_rando.value, "DamageRando": self.options.damage_rando.value, "DamageRandoOverrides": self.options.damage_rando_overrides.value, "HpCap": self.options.hp_cap.value, diff --git a/worlds/tloz/Locations.py b/worlds/tloz/Locations.py index 9715cc684291..f95e5d80443e 100644 --- a/worlds/tloz/Locations.py +++ b/worlds/tloz/Locations.py @@ -108,11 +108,15 @@ ] food_locations = [ - "Level 7 Map", "Level 7 Boss", "Level 7 Triforce", "Level 7 Key Drop (Goriyas)", + "Level 7 Item (Red Candle)", "Level 7 Map", "Level 7 Boss", "Level 7 Triforce", "Level 7 Key Drop (Goriyas)", "Level 7 Bomb Drop (Moldorms North)", "Level 7 Bomb Drop (Goriyas North)", "Level 7 Bomb Drop (Dodongos)", "Level 7 Rupee Drop (Goriyas North)" ] +gohma_locations = [ + "Level 6 Boss", "Level 6 Triforce", "Level 8 Item (Magical Key)", "Level 8 Bomb Drop (Darknuts North)" +] + gleeok_locations = [ "Level 4 Boss", "Level 4 Triforce", "Level 8 Boss", "Level 8 Triforce" ] diff --git a/worlds/tloz/Rules.py b/worlds/tloz/Rules.py index 39c3b954f0d4..de627a533bd3 100644 --- a/worlds/tloz/Rules.py +++ b/worlds/tloz/Rules.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING from worlds.generic.Rules import add_rule -from .Locations import food_locations, shop_locations, gleeok_locations +from .Locations import food_locations, shop_locations, gleeok_locations, gohma_locations from .ItemPool import dangerous_weapon_locations from .Options import StartingPosition @@ -10,13 +10,12 @@ def set_rules(tloz_world: "TLoZWorld"): player = tloz_world.player - world = tloz_world.multiworld options = tloz_world.options # Boss events for a nicer spoiler log play through for level in range(1, 9): - boss = world.get_location(f"Level {level} Boss", player) - boss_event = world.get_location(f"Level {level} Boss Status", player) + boss = tloz_world.get_location(f"Level {level} Boss") + boss_event = tloz_world.get_location(f"Level {level} Boss Status") status = tloz_world.create_event(f"Boss {level} Defeated") boss_event.place_locked_item(status) add_rule(boss_event, lambda state, b=boss: state.can_reach(b, "Location", player)) @@ -26,136 +25,131 @@ def set_rules(tloz_world: "TLoZWorld"): for location in level.locations: if options.StartingPosition < StartingPosition.option_dangerous \ or location.name not in dangerous_weapon_locations: - add_rule(world.get_location(location.name, player), + add_rule(tloz_world.get_location(location.name), lambda state: state.has_group("weapons", player)) # This part of the loop sets up an expected amount of defense needed for each dungeon if i > 0: # Don't need an extra heart for Level 1 - add_rule(world.get_location(location.name, player), + add_rule(tloz_world.get_location(location.name), lambda state, hearts=i: state.has("Heart Container", player, hearts) or (state.has("Blue Ring", player) and state.has("Heart Container", player, int(hearts / 2))) or (state.has("Red Ring", player) and state.has("Heart Container", player, int(hearts / 4)))) if "Pols Voice" in location.name: # This enemy needs specific weapons - add_rule(world.get_location(location.name, player), - lambda state: state.has_group("swords", player) or state.has("Bow", player)) + add_rule(tloz_world.get_location(location.name), + lambda state: state.has_group("swords", player) or + (state.has("Bow", player) and state.has_group("arrows", player))) # No requiring anything in a shop until we can farm for money for location in shop_locations: - add_rule(world.get_location(location, player), + add_rule(tloz_world.get_location(location), lambda state: state.has_group("weapons", player)) # Everything from 4 on up has dark rooms for level in tloz_world.levels[4:]: for location in level.locations: - add_rule(world.get_location(location.name, player), + add_rule(tloz_world.get_location(location.name), lambda state: state.has_group("candles", player) or (state.has("Magical Rod", player) and state.has("Book of Magic", player))) # Everything from 5 on up has gaps for level in tloz_world.levels[5:]: for location in level.locations: - add_rule(world.get_location(location.name, player), + add_rule(tloz_world.get_location(location.name), lambda state: state.has("Stepladder", player)) - add_rule(world.get_location("Level 5 Boss", player), - lambda state: state.has("Recorder", player)) - - add_rule(world.get_location("Level 6 Boss", player), - lambda state: state.has("Bow", player) and state.has_group("arrows", player)) + # Level 4 Access + for location in tloz_world.levels[4].locations: + add_rule(tloz_world.get_location(location.name), + lambda state: state.has_any(("Raft", "Recorder"), player)) - add_rule(world.get_location("Level 7 Item (Red Candle)", player), + # Digdogger boss. Rework this once ER happens + add_rule(tloz_world.get_location("Level 5 Boss"), lambda state: state.has("Recorder", player)) - add_rule(world.get_location("Level 7 Boss", player), + add_rule(tloz_world.get_location("Level 5 Triforce"), lambda state: state.has("Recorder", player)) - if options.ExpandedPool: - add_rule(world.get_location("Level 7 Key Drop (Stalfos)", player), - lambda state: state.has("Recorder", player)) - add_rule(world.get_location("Level 7 Bomb Drop (Digdogger)", player), - lambda state: state.has("Recorder", player)) - add_rule(world.get_location("Level 7 Rupee Drop (Dodongos)", player), + + for location in gohma_locations: + if options.ExpandedPool or "Drop" not in location: + add_rule(tloz_world.get_location(location), + lambda state: state.has("Bow", player) and state.has_group("arrows", player)) + + # Recorder Access for Level 7 + for location in tloz_world.levels[7].locations: + add_rule(tloz_world.get_location(location.name), lambda state: state.has("Recorder", player)) for location in food_locations: if options.ExpandedPool or "Drop" not in location: - add_rule(world.get_location(location, player), + add_rule(tloz_world.get_location(location), lambda state: state.has("Food", player)) for location in gleeok_locations: - add_rule(world.get_location(location, player), + add_rule(tloz_world.get_location(location), lambda state: state.has_group("swords", player) or state.has("Magical Rod", player)) # Candle access for Level 8 for location in tloz_world.levels[8].locations: - add_rule(world.get_location(location.name, player), + add_rule(tloz_world.get_location(location.name), lambda state: state.has_group("candles", player)) - add_rule(world.get_location("Level 8 Item (Magical Key)", player), + add_rule(tloz_world.get_location("Level 8 Item (Magical Key)"), lambda state: state.has("Bow", player) and state.has_group("arrows", player)) if options.ExpandedPool: - add_rule(world.get_location("Level 8 Bomb Drop (Darknuts North)", player), + add_rule(tloz_world.get_location("Level 8 Bomb Drop (Darknuts North)"), lambda state: state.has("Bow", player) and state.has_group("arrows", player)) for location in tloz_world.levels[9].locations: - add_rule(world.get_location(location.name, player), + add_rule(tloz_world.get_location(location.name), lambda state: state.has("Triforce Fragment", player, 8) and state.has_group("swords", player)) # Yes we are looping this range again for Triforce locations. No I can't add it to the boss event loop for level in range(1, 9): - add_rule(world.get_location(f"Level {level} Triforce", player), + add_rule(tloz_world.get_location(f"Level {level} Triforce"), lambda state, l=level: state.has(f"Boss {l} Defeated", player)) # Sword, raft, and ladder spots - add_rule(world.get_location("White Sword Pond", player), + add_rule(tloz_world.get_location("White Sword Pond"), lambda state: state.has("Heart Container", player, 2)) - add_rule(world.get_location("Magical Sword Grave", player), + add_rule(tloz_world.get_location("Magical Sword Grave"), lambda state: state.has("Heart Container", player, 9)) stepladder_locations = ["Ocean Heart Container", "Level 4 Triforce", "Level 4 Boss", "Level 4 Map"] stepladder_locations_expanded = ["Level 4 Key Drop (Keese North)"] for location in stepladder_locations: - add_rule(world.get_location(location, player), + add_rule(tloz_world.get_location(location), lambda state: state.has("Stepladder", player)) if options.ExpandedPool: for location in stepladder_locations_expanded: - add_rule(world.get_location(location, player), + add_rule(tloz_world.get_location(location), lambda state: state.has("Stepladder", player)) # Don't allow Take Any Items until we can actually get in one if options.ExpandedPool: - add_rule(world.get_location("Take Any Item Left", player), + add_rule(tloz_world.get_location("Take Any Item Left"), lambda state: state.has_group("candles", player) or state.has("Raft", player)) - add_rule(world.get_location("Take Any Item Middle", player), + add_rule(tloz_world.get_location("Take Any Item Middle"), lambda state: state.has_group("candles", player) or state.has("Raft", player)) - add_rule(world.get_location("Take Any Item Right", player), + add_rule(tloz_world.get_location("Take Any Item Right"), lambda state: state.has_group("candles", player) or state.has("Raft", player)) - for location in tloz_world.levels[4].locations: - add_rule(world.get_location(location.name, player), - lambda state: state.has("Raft", player) or state.has("Recorder", player)) - for location in tloz_world.levels[7].locations: - add_rule(world.get_location(location.name, player), - lambda state: state.has("Recorder", player)) - for location in tloz_world.levels[8].locations: - add_rule(world.get_location(location.name, player), - lambda state: state.has("Bow", player)) - add_rule(world.get_location("Potion Shop Item Left", player), + add_rule(tloz_world.get_location("Potion Shop Item Left"), lambda state: state.has("Letter", player)) - add_rule(world.get_location("Potion Shop Item Middle", player), + add_rule(tloz_world.get_location("Potion Shop Item Middle"), lambda state: state.has("Letter", player)) - add_rule(world.get_location("Potion Shop Item Right", player), + add_rule(tloz_world.get_location("Potion Shop Item Right"), lambda state: state.has("Letter", player)) - add_rule(world.get_location("Shield Shop Item Left", player), + add_rule(tloz_world.get_location("Shield Shop Item Left"), lambda state: state.has_group("candles", player) or state.has("Bomb", player)) - add_rule(world.get_location("Shield Shop Item Middle", player), + add_rule(tloz_world.get_location("Shield Shop Item Middle"), lambda state: state.has_group("candles", player) or state.has("Bomb", player)) - add_rule(world.get_location("Shield Shop Item Right", player), + add_rule(tloz_world.get_location("Shield Shop Item Right"), lambda state: state.has_group("candles", player) or - state.has("Bomb", player)) \ No newline at end of file + state.has("Bomb", player)) diff --git a/worlds/tunic/__init__.py b/worlds/tunic/__init__.py index 6360ba493853..d1430aac1895 100644 --- a/worlds/tunic/__init__.py +++ b/worlds/tunic/__init__.py @@ -83,6 +83,11 @@ class TunicWorld(World): shop_num: int = 1 # need to make it so that you can walk out of shops, but also that they aren't all connected er_regions: Dict[str, RegionInfo] # absolutely needed so outlet regions work + # so we only loop the multiworld locations once + # if these are locations instead of their info, it gives a memory leak error + item_link_locations: Dict[int, Dict[str, List[Tuple[int, str]]]] = {} + player_item_link_locations: Dict[str, List[Location]] + def generate_early(self) -> None: if self.options.logic_rules >= LogicRules.option_no_major_glitches: self.options.laurels_zips.value = LaurelsZips.option_true @@ -387,6 +392,18 @@ def extend_hint_information(self, hint_data: Dict[int, Dict[int, str]]) -> None: if hint_text: hint_data[self.player][location.address] = hint_text + def get_real_location(self, location: Location) -> Tuple[str, int]: + # if it's not in a group, it's not in an item link + if location.player not in self.multiworld.groups or not location.item: + return location.name, location.player + try: + loc = self.player_item_link_locations[location.item.name].pop() + return loc.name, loc.player + except IndexError: + warning(f"TUNIC: Failed to parse item location for in-game hints for {self.player_name}. " + f"Using a potentially incorrect location name instead.") + return location.name, location.player + def fill_slot_data(self) -> Dict[str, Any]: slot_data: Dict[str, Any] = { "seed": self.random.randint(0, 2147483647), @@ -412,12 +429,35 @@ def fill_slot_data(self) -> Dict[str, Any]: "disable_local_spoiler": int(self.settings.disable_local_spoiler or self.multiworld.is_race), } + # this would be in a stage if there was an appropriate stage for it + self.player_item_link_locations = {} + groups = self.multiworld.get_player_groups(self.player) + # checking if groups so that this doesn't run if the player isn't in a group + if groups: + if not self.item_link_locations: + tunic_worlds: Tuple[TunicWorld] = self.multiworld.get_game_worlds("TUNIC") + # figure out our groups and the items in them + for tunic in tunic_worlds: + for group in self.multiworld.get_player_groups(tunic.player): + self.item_link_locations.setdefault(group, {}) + for location in self.multiworld.get_locations(): + if location.item and location.item.player in self.item_link_locations.keys(): + (self.item_link_locations[location.item.player].setdefault(location.item.name, []) + .append((location.player, location.name))) + + # if item links are on, set up the player's personal item link locations, so we can pop them as needed + for group, item_links in self.item_link_locations.items(): + if group in groups: + for item_name, locs in item_links.items(): + self.player_item_link_locations[item_name] = \ + [self.multiworld.get_location(location_name, player) for player, location_name in locs] + for tunic_item in filter(lambda item: item.location is not None and item.code is not None, self.slot_data_items): if tunic_item.name not in slot_data: slot_data[tunic_item.name] = [] if tunic_item.name == gold_hexagon and len(slot_data[gold_hexagon]) >= 6: continue - slot_data[tunic_item.name].extend([tunic_item.location.name, tunic_item.location.player]) + slot_data[tunic_item.name].extend(self.get_real_location(tunic_item.location)) for start_item in self.options.start_inventory_from_pool: if start_item in slot_data_item_names: @@ -436,7 +476,7 @@ def fill_slot_data(self) -> Dict[str, Any]: if item in slot_data_item_names: slot_data[item] = [] for item_location in self.multiworld.find_item_locations(item, self.player): - slot_data[item].extend([item_location.name, item_location.player]) + slot_data[item].extend(self.get_real_location(item_location)) return slot_data diff --git a/worlds/tunic/er_data.py b/worlds/tunic/er_data.py index 343bf3055378..1269f3b85e45 100644 --- a/worlds/tunic/er_data.py +++ b/worlds/tunic/er_data.py @@ -807,7 +807,7 @@ class DeadEnd(IntEnum): [], # drop a rudeling, icebolt or ice bomb "Overworld to West Garden from Furnace": - [["IG3"]], + [["IG3"], ["LS1"]], }, "East Overworld": { "Above Ruined Passage": diff --git a/worlds/tunic/er_rules.py b/worlds/tunic/er_rules.py index 6f5eec020be6..3b111ad83488 100644 --- a/worlds/tunic/er_rules.py +++ b/worlds/tunic/er_rules.py @@ -501,9 +501,11 @@ def set_er_region_rules(world: "TunicWorld", regions: Dict[str, Region], portal_ regions["Dark Tomb Upper"].connect( connecting_region=regions["Dark Tomb Entry Point"]) + # ice grapple through the wall, get the little secret sound to trigger regions["Dark Tomb Upper"].connect( connecting_region=regions["Dark Tomb Main"], - rule=lambda state: has_ladder("Ladder in Dark Tomb", state, world)) + rule=lambda state: has_ladder("Ladder in Dark Tomb", state, world) + or has_ice_grapple_logic(False, IceGrappling.option_hard, state, world)) regions["Dark Tomb Main"].connect( connecting_region=regions["Dark Tomb Upper"], rule=lambda state: has_ladder("Ladder in Dark Tomb", state, world)) @@ -779,12 +781,10 @@ def set_er_region_rules(world: "TunicWorld", regions: Dict[str, Region], portal_ regions["Fortress East Shortcut Upper"].connect( connecting_region=regions["Fortress East Shortcut Lower"]) - # nmg: can ice grapple upwards regions["Fortress East Shortcut Lower"].connect( connecting_region=regions["Fortress East Shortcut Upper"], rule=lambda state: has_ice_grapple_logic(True, IceGrappling.option_easy, state, world)) - # nmg: ice grapple through the big gold door, can do it both ways regions["Eastern Vault Fortress"].connect( connecting_region=regions["Eastern Vault Fortress Gold Door"], rule=lambda state: state.has_all({"Activate Eastern Vault West Fuses", @@ -807,7 +807,6 @@ def set_er_region_rules(world: "TunicWorld", regions: Dict[str, Region], portal_ regions["Fortress Hero's Grave Region"].connect( connecting_region=regions["Fortress Grave Path"]) - # nmg: ice grapple from upper grave path to lower regions["Fortress Grave Path Upper"].connect( connecting_region=regions["Fortress Grave Path"], rule=lambda state: has_ice_grapple_logic(True, IceGrappling.option_easy, state, world)) @@ -1139,6 +1138,9 @@ def ls_connect(origin_name: str, portal_sdt: str) -> None: for portal_dest in region_info.portals: ls_connect(ladder_region, "Overworld Redux, " + portal_dest) + # convenient staircase means this one is easy difficulty, even though there's an elevation change + ls_connect("LS Elev 0", "Overworld Redux, Furnace_gyro_west") + # connect ls elevation regions to regions where you can get an enemy to knock you down, also well rail if options.ladder_storage >= LadderStorage.option_medium: for ladder_region, region_info in ow_ladder_groups.items(): @@ -1154,6 +1156,7 @@ def ls_connect(origin_name: str, portal_sdt: str) -> None: if options.ladder_storage >= LadderStorage.option_hard: ls_connect("LS Elev 1", "Overworld Redux, EastFiligreeCache_") ls_connect("LS Elev 2", "Overworld Redux, Town_FiligreeRoom_") + ls_connect("LS Elev 2", "Overworld Redux, Ruins Passage_west") ls_connect("LS Elev 3", "Overworld Redux, Overworld Interiors_house") ls_connect("LS Elev 5", "Overworld Redux, Temple_main") diff --git a/worlds/tunic/ladder_storage_data.py b/worlds/tunic/ladder_storage_data.py index a29d50b4f455..c6dda42bca79 100644 --- a/worlds/tunic/ladder_storage_data.py +++ b/worlds/tunic/ladder_storage_data.py @@ -17,7 +17,7 @@ class OWLadderInfo(NamedTuple): ["Overworld Beach"]), # also the east filigree room "LS Elev 1": OWLadderInfo({"Ladders near Weathervane", "Ladders in Overworld Town", "Ladder to Swamp"}, - ["Furnace_gyro_lower", "Swamp Redux 2_wall"], + ["Furnace_gyro_lower", "Furnace_gyro_west", "Swamp Redux 2_wall"], ["Overworld Tunnel Turret"]), # also the fountain filigree room and ruined passage door "LS Elev 2": OWLadderInfo({"Ladders near Weathervane", "Ladders to West Bell"}, diff --git a/worlds/witness/__init__.py b/worlds/witness/__init__.py index a21a5bb3ca7e..ac9197bd92bb 100644 --- a/worlds/witness/__init__.py +++ b/worlds/witness/__init__.py @@ -80,7 +80,7 @@ class WitnessWorld(World): def _get_slot_data(self) -> Dict[str, Any]: return { - "seed": self.random.randrange(0, 1000000), + "seed": self.options.puzzle_randomization_seed.value, "victory_location": int(self.player_logic.VICTORY_LOCATION, 16), "panelhex_to_id": self.player_locations.CHECK_PANELHEX_TO_ID, "item_id_to_door_hexes": static_witness_items.get_item_to_door_mappings(), diff --git a/worlds/witness/options.py b/worlds/witness/options.py index 4de966abe96d..d1713e73c541 100644 --- a/worlds/witness/options.py +++ b/worlds/witness/options.py @@ -401,6 +401,17 @@ class DeathLinkAmnesty(Range): default = 1 +class PuzzleRandomizationSeed(Range): + """ + Sigma Rando, which is the basis for all puzzle randomization in this randomizer, uses a seed from 1 to 9999999 for the puzzle randomization. + This option lets you set this seed yourself. + """ + display_name = "Puzzle Randomization Seed" + range_start = 1 + range_end = 9999999 + default = "random" + + @dataclass class TheWitnessOptions(PerGameCommonOptions): puzzle_randomization: PuzzleRandomization @@ -435,6 +446,7 @@ class TheWitnessOptions(PerGameCommonOptions): laser_hints: LaserHints death_link: DeathLink death_link_amnesty: DeathLinkAmnesty + puzzle_randomization_seed: PuzzleRandomizationSeed shuffle_dog: ShuffleDog @@ -445,7 +457,7 @@ class TheWitnessOptions(PerGameCommonOptions): MountainLasers, ChallengeLasers, ]), - OptionGroup("Panel Hunt Settings", [ + OptionGroup("Panel Hunt Options", [ PanelHuntRequiredPercentage, PanelHuntTotal, PanelHuntPostgame, @@ -483,6 +495,7 @@ class TheWitnessOptions(PerGameCommonOptions): ElevatorsComeToYou, DeathLink, DeathLinkAmnesty, + PuzzleRandomizationSeed, ]), OptionGroup("Silly Options", [ ShuffleDog, diff --git a/worlds/witness/player_items.py b/worlds/witness/player_items.py index 4c98cb78495e..3be298ebccae 100644 --- a/worlds/witness/player_items.py +++ b/worlds/witness/player_items.py @@ -2,7 +2,7 @@ Defines progression, junk and event items for The Witness """ import copy -from typing import TYPE_CHECKING, Dict, List, Set, cast +from typing import TYPE_CHECKING, Dict, List, Set from BaseClasses import Item, ItemClassification, MultiWorld diff --git a/worlds/zillion/options.py b/worlds/zillion/options.py index 5de0b65c82f0..ec0fdb0b22e1 100644 --- a/worlds/zillion/options.py +++ b/worlds/zillion/options.py @@ -1,7 +1,6 @@ from collections import Counter from dataclasses import dataclass -from typing import ClassVar, Dict, Literal, Tuple -from typing_extensions import TypeGuard # remove when Python >= 3.10 +from typing import ClassVar, Dict, Literal, Tuple, TypeGuard from Options import Choice, DefaultOnToggle, NamedRange, OptionGroup, PerGameCommonOptions, Range, Removed, Toggle @@ -233,6 +232,7 @@ class ZillionSkill(Range): range_start = 0 range_end = 5 default = 2 + display_name = "skill" class ZillionStartingCards(NamedRange):