diff --git a/.github/workflows/unittests.yml b/.github/workflows/unittests.yml index b2530bd06c7d..3ad29b007772 100644 --- a/.github/workflows/unittests.yml +++ b/.github/workflows/unittests.yml @@ -24,7 +24,7 @@ on: - '.github/workflows/unittests.yml' jobs: - build: + unit: runs-on: ${{ matrix.os }} name: Test Python ${{ matrix.python.version }} ${{ matrix.os }} @@ -60,3 +60,32 @@ jobs: - name: Unittests run: | pytest -n auto + + hosting: + runs-on: ${{ matrix.os }} + name: Test hosting with ${{ matrix.python.version }} on ${{ matrix.os }} + + strategy: + matrix: + os: + - ubuntu-latest + python: + - {version: '3.11'} # current + + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python.version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python.version }} + - name: Install dependencies + run: | + python -m venv venv + source venv/bin/activate + python -m pip install --upgrade pip + python ModuleUpdate.py --yes --force --append "WebHostLib/requirements.txt" + - name: Test hosting + run: | + source venv/bin/activate + export PYTHONPATH=$(pwd) + python test/hosting/__main__.py diff --git a/.gitignore b/.gitignore index 022abe38fe40..0bba6f17264b 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,7 @@ Output Logs/ /installdelete.iss /data/user.kv /datapackage +/custom_worlds # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/AHITClient.py b/AHITClient.py new file mode 100644 index 000000000000..6ed7d7b49d48 --- /dev/null +++ b/AHITClient.py @@ -0,0 +1,8 @@ +from worlds.ahit.Client import launch +import Utils +import ModuleUpdate +ModuleUpdate.update() + +if __name__ == "__main__": + Utils.init_logging("AHITClient", exception_logger="Client") + launch() diff --git a/AdventureClient.py b/AdventureClient.py index 06e4d60dad43..7bfbd5ef6bd3 100644 --- a/AdventureClient.py +++ b/AdventureClient.py @@ -112,7 +112,7 @@ def on_package(self, cmd: str, args: dict): if ': !' not in msg: self._set_message(msg, SYSTEM_MESSAGE_ID) elif cmd == "ReceivedItems": - msg = f"Received {', '.join([self.item_names[item.item] for item in args['items']])}" + msg = f"Received {', '.join([self.item_names.lookup_in_slot(item.item) for item in args['items']])}" self._set_message(msg, SYSTEM_MESSAGE_ID) elif cmd == "Retrieved": if f"adventure_{self.auth}_freeincarnates_used" in args["keys"]: diff --git a/BaseClasses.py b/BaseClasses.py index 53a6b3b19215..88857f803212 100644 --- a/BaseClasses.py +++ b/BaseClasses.py @@ -11,8 +11,8 @@ from collections import Counter, deque from collections.abc import Collection, MutableSequence from enum import IntEnum, IntFlag -from typing import Any, Callable, Dict, Iterable, Iterator, List, NamedTuple, Optional, Set, Tuple, TypedDict, Union, \ - Type, ClassVar +from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, NamedTuple, Optional, Set, Tuple, \ + TypedDict, Union, Type, ClassVar import NetUtils import Options @@ -707,15 +707,49 @@ def has_any(self, items: Iterable[str], player: int) -> bool: """Returns True if at least one item name of items is in state at least once.""" return any(self.prog_items[player][item] for item in items) + def has_all_counts(self, item_counts: Mapping[str, int], player: int) -> bool: + """Returns True if each item name is in the state at least as many times as specified.""" + return all(self.prog_items[player][item] >= count for item, count in item_counts.items()) + + def has_any_count(self, item_counts: Mapping[str, int], player: int) -> bool: + """Returns True if at least one item name is in the state at least as many times as specified.""" + return any(self.prog_items[player][item] >= count for item, count in item_counts.items()) + def count(self, item: str, player: int) -> int: return self.prog_items[player][item] - def item_count(self, item: str, player: int) -> int: - Utils.deprecate("Use count instead.") - return self.count(item, player) + def has_from_list(self, items: Iterable[str], player: int, count: int) -> bool: + """Returns True if the state contains at least `count` items matching any of the item names from a list.""" + found: int = 0 + player_prog_items = self.prog_items[player] + for item_name in items: + found += player_prog_items[item_name] + if found >= count: + return True + return False + + def has_from_list_unique(self, items: Iterable[str], player: int, count: int) -> bool: + """Returns True if the state contains at least `count` items matching any of the item names from a list. + Ignores duplicates of the same item.""" + found: int = 0 + player_prog_items = self.prog_items[player] + for item_name in items: + found += player_prog_items[item_name] > 0 + if found >= count: + return True + return False + + def count_from_list(self, items: Iterable[str], player: int) -> int: + """Returns the cumulative count of items from a list present in state.""" + return sum(self.prog_items[player][item_name] for item_name in items) + + def count_from_list_unique(self, items: Iterable[str], player: int) -> int: + """Returns the cumulative count of items from a list present in state. Ignores duplicates of the same item.""" + return sum(self.prog_items[player][item_name] > 0 for item_name in items) # item name group related def has_group(self, item_name_group: str, player: int, count: int = 1) -> bool: + """Returns True if the state contains at least `count` items present in a specified item group.""" found: int = 0 player_prog_items = self.prog_items[player] for item_name in self.multiworld.worlds[player].item_name_groups[item_name_group]: @@ -724,12 +758,34 @@ def has_group(self, item_name_group: str, player: int, count: int = 1) -> bool: return True return False - def count_group(self, item_name_group: str, player: int) -> int: + def has_group_unique(self, item_name_group: str, player: int, count: int = 1) -> bool: + """Returns True if the state contains at least `count` items present in a specified item group. + Ignores duplicates of the same item. + """ found: int = 0 player_prog_items = self.prog_items[player] for item_name in self.multiworld.worlds[player].item_name_groups[item_name_group]: - found += player_prog_items[item_name] - return found + found += player_prog_items[item_name] > 0 + if found >= count: + return True + return False + + def count_group(self, item_name_group: str, player: int) -> int: + """Returns the cumulative count of items from an item group present in state.""" + player_prog_items = self.prog_items[player] + return sum( + player_prog_items[item_name] + for item_name in self.multiworld.worlds[player].item_name_groups[item_name_group] + ) + + def count_group_unique(self, item_name_group: str, player: int) -> int: + """Returns the cumulative count of items from an item group present in state. + Ignores duplicates of the same item.""" + player_prog_items = self.prog_items[player] + return sum( + player_prog_items[item_name] > 0 + for item_name in self.multiworld.worlds[player].item_name_groups[item_name_group] + ) # Item related def collect(self, item: Item, event: bool = False, location: Optional[Location] = None) -> bool: @@ -990,7 +1046,7 @@ def __init__(self, player: int, name: str = '', address: Optional[int] = None, p self.parent_region = parent def can_fill(self, state: CollectionState, item: Item, check_access=True) -> bool: - return ((self.always_allow(state, item) and item.name not in state.multiworld.non_local_items[item.player]) + return ((self.always_allow(state, item) and item.name not in state.multiworld.worlds[item.player].options.non_local_items) or ((self.progress_type != LocationProgressType.EXCLUDED or not (item.advancement or item.useful)) and self.item_rule(item) and (not check_access or self.can_reach(state)))) @@ -1186,7 +1242,7 @@ def create_playthrough(self, create_paths: bool = True) -> None: logging.debug('The following items could not be reached: %s', ['%s (Player %d) at %s (Player %d)' % ( location.item.name, location.item.player, location.name, location.player) for location in sphere_candidates]) - if any([multiworld.accessibility[location.item.player] != 'minimal' for location in sphere_candidates]): + if any([multiworld.worlds[location.item.player].options.accessibility != 'minimal' for location in sphere_candidates]): raise RuntimeError(f'Not all progression items reachable ({sphere_candidates}). ' f'Something went terribly wrong here.') else: diff --git a/CommonClient.py b/CommonClient.py index 63cac098e22a..8f1e64c0591b 100644 --- a/CommonClient.py +++ b/CommonClient.py @@ -1,5 +1,6 @@ from __future__ import annotations +import collections import copy import logging import asyncio @@ -8,6 +9,7 @@ import typing import time import functools +import warnings import ModuleUpdate ModuleUpdate.update() @@ -173,10 +175,74 @@ class CommonContext: items_handling: typing.Optional[int] = None want_slot_data: bool = True # should slot_data be retrieved via Connect - # data package - # Contents in flux until connection to server is made, to download correct data for this multiworld. - item_names: typing.Dict[int, str] = Utils.KeyedDefaultDict(lambda code: f'Unknown item (ID:{code})') - location_names: typing.Dict[int, str] = Utils.KeyedDefaultDict(lambda code: f'Unknown location (ID:{code})') + class NameLookupDict: + """A specialized dict, with helper methods, for id -> name item/location data package lookups by game.""" + def __init__(self, ctx: CommonContext, lookup_type: typing.Literal["item", "location"]): + self.ctx: CommonContext = ctx + self.lookup_type: typing.Literal["item", "location"] = lookup_type + self._unknown_item: typing.Callable[[int], str] = lambda key: f"Unknown {lookup_type} (ID: {key})" + self._archipelago_lookup: typing.Dict[int, str] = {} + self._flat_store: typing.Dict[int, str] = Utils.KeyedDefaultDict(self._unknown_item) + self._game_store: typing.Dict[str, typing.ChainMap[int, str]] = collections.defaultdict( + lambda: collections.ChainMap(self._archipelago_lookup, Utils.KeyedDefaultDict(self._unknown_item))) + self.warned: bool = False + + # noinspection PyTypeChecker + def __getitem__(self, key: str) -> typing.Mapping[int, str]: + # TODO: In a future version (0.6.0?) this should be simplified by removing implicit id lookups support. + if isinstance(key, int): + if not self.warned: + # Use warnings instead of logger to avoid deprecation message from appearing on user side. + self.warned = True + warnings.warn(f"Implicit name lookup by id only is deprecated and only supported to maintain " + f"backwards compatibility for now. If multiple games share the same id for a " + f"{self.lookup_type}, name could be incorrect. Please use " + f"`{self.lookup_type}_names.lookup_in_game()` or " + f"`{self.lookup_type}_names.lookup_in_slot()` instead.") + return self._flat_store[key] # type: ignore + + return self._game_store[key] + + def __len__(self) -> int: + return len(self._game_store) + + def __iter__(self) -> typing.Iterator[str]: + return iter(self._game_store) + + def __repr__(self) -> str: + return self._game_store.__repr__() + + def lookup_in_game(self, code: int, game_name: typing.Optional[str] = None) -> str: + """Returns the name for an item/location id in the context of a specific game or own game if `game` is + omitted. + """ + if game_name is None: + game_name = self.ctx.game + assert game_name is not None, f"Attempted to lookup {self.lookup_type} with no game name available." + + return self._game_store[game_name][code] + + def lookup_in_slot(self, code: int, slot: typing.Optional[int] = None) -> str: + """Returns the name for an item/location id in the context of a specific slot or own slot if `slot` is + omitted. + """ + if slot is None: + slot = self.ctx.slot + assert slot is not None, f"Attempted to lookup {self.lookup_type} with no slot info available." + + return self.lookup_in_game(code, self.ctx.slot_info[slot].game) + + def update_game(self, game: str, name_to_id_lookup_table: typing.Dict[str, int]) -> None: + """Overrides existing lookup tables for a particular game.""" + id_to_name_lookup_table = Utils.KeyedDefaultDict(self._unknown_item) + id_to_name_lookup_table.update({code: name for name, code in name_to_id_lookup_table.items()}) + self._game_store[game] = collections.ChainMap(self._archipelago_lookup, id_to_name_lookup_table) + self._flat_store.update(id_to_name_lookup_table) # Only needed for legacy lookup method. + if game == "Archipelago": + # Keep track of the Archipelago data package separately so if it gets updated in a custom datapackage, + # it updates in all chain maps automatically. + self._archipelago_lookup.clear() + self._archipelago_lookup.update(id_to_name_lookup_table) # defaults starting_reconnect_delay: int = 5 @@ -231,7 +297,7 @@ class CommonContext: # message box reporting a loss of connection _messagebox_connection_loss: typing.Optional["kvui.MessageBox"] = None - def __init__(self, server_address: typing.Optional[str], password: typing.Optional[str]) -> None: + def __init__(self, server_address: typing.Optional[str] = None, password: typing.Optional[str] = None) -> None: # server state self.server_address = server_address self.username = None @@ -271,6 +337,9 @@ def __init__(self, server_address: typing.Optional[str], password: typing.Option self.exit_event = asyncio.Event() self.watcher_event = asyncio.Event() + self.item_names = self.NameLookupDict(self, "item") + self.location_names = self.NameLookupDict(self, "location") + self.jsontotextparser = JSONtoTextParser(self) self.rawjsontotextparser = RawJSONtoTextParser(self) self.update_data_package(network_data_package) @@ -424,6 +493,11 @@ def on_user_say(self, text: str) -> typing.Optional[str]: """Gets called before sending a Say to the server from the user. Returned text is sent, or sending is aborted if None is returned.""" return text + + def on_ui_command(self, text: str) -> None: + """Gets called by kivy when the user executes a command starting with `/` or `!`. + The command processor is still called; this is just intended for command echoing.""" + self.ui.print_json([{"text": text, "type": "color", "color": "orange"}]) def update_permissions(self, permissions: typing.Dict[str, int]): for permission_name, permission_flag in permissions.items(): @@ -486,19 +560,17 @@ async def prepare_data_package(self, relevant_games: typing.Set[str], or remote_checksum != cache_checksum: needed_updates.add(game) else: - self.update_game(cached_game) + self.update_game(cached_game, game) if needed_updates: await self.send_msgs([{"cmd": "GetDataPackage", "games": [game_name]} for game_name in needed_updates]) - def update_game(self, game_package: dict): - for item_name, item_id in game_package["item_name_to_id"].items(): - self.item_names[item_id] = item_name - for location_name, location_id in game_package["location_name_to_id"].items(): - self.location_names[location_id] = location_name + def update_game(self, game_package: dict, game: str): + self.item_names.update_game(game, game_package["item_name_to_id"]) + self.location_names.update_game(game, game_package["location_name_to_id"]) def update_data_package(self, data_package: dict): for game, game_data in data_package["games"].items(): - self.update_game(game_data) + self.update_game(game_data, game) def consume_network_data_package(self, data_package: dict): self.update_data_package(data_package) diff --git a/Fill.py b/Fill.py index e65f027408c1..d8147b2eac80 100644 --- a/Fill.py +++ b/Fill.py @@ -19,11 +19,12 @@ def _log_fill_progress(name: str, placed: int, total_items: int) -> None: logging.info(f"Current fill step ({name}) at {placed}/{total_items} items placed.") -def sweep_from_pool(base_state: CollectionState, itempool: typing.Sequence[Item] = tuple()) -> CollectionState: +def sweep_from_pool(base_state: CollectionState, itempool: typing.Sequence[Item] = tuple(), + locations: typing.Optional[typing.List[Location]] = None) -> CollectionState: new_state = base_state.copy() for item in itempool: new_state.collect(item, True) - new_state.sweep_for_events() + new_state.sweep_for_events(locations=locations) return new_state @@ -34,8 +35,8 @@ def fill_restrictive(multiworld: MultiWorld, base_state: CollectionState, locati """ :param multiworld: Multiworld to be filled. :param base_state: State assumed before fill. - :param locations: Locations to be filled with item_pool - :param item_pool: Items to fill into the locations + :param locations: Locations to be filled with item_pool, gets mutated by removing locations that get filled. + :param item_pool: Items to fill into the locations, gets mutated by removing items that get placed. :param single_player_placement: if true, can speed up placement if everything belongs to a single player :param lock: locations are set to locked as they are filled :param swap: if true, swaps of already place items are done in the event of a dead end @@ -66,7 +67,8 @@ def fill_restrictive(multiworld: MultiWorld, base_state: CollectionState, locati item_pool.pop(p) break maximum_exploration_state = sweep_from_pool( - base_state, item_pool + unplaced_items) + base_state, item_pool + unplaced_items, multiworld.get_filled_locations(item.player) + if single_player_placement else None) has_beaten_game = multiworld.has_beaten_game(maximum_exploration_state) @@ -112,7 +114,9 @@ def fill_restrictive(multiworld: MultiWorld, base_state: CollectionState, locati location.item = None placed_item.location = None - swap_state = sweep_from_pool(base_state, [placed_item, *item_pool] if unsafe else item_pool) + swap_state = sweep_from_pool(base_state, [placed_item, *item_pool] if unsafe else item_pool, + multiworld.get_filled_locations(item.player) + if single_player_placement else None) # unsafe means swap_state assumes we can somehow collect placed_item before item_to_place # by continuing to swap, which is not guaranteed. This is unsafe because there is no mechanic # to clean that up later, so there is a chance generation fails. @@ -170,7 +174,9 @@ def fill_restrictive(multiworld: MultiWorld, base_state: CollectionState, locati if cleanup_required: # validate all placements and remove invalid ones - state = sweep_from_pool(base_state, []) + state = sweep_from_pool( + base_state, [], multiworld.get_filled_locations(item.player) + if single_player_placement else None) for placement in placements: if multiworld.worlds[placement.item.player].options.accessibility != "minimal" and not placement.can_reach(state): placement.item.location = None @@ -214,7 +220,8 @@ def fill_restrictive(multiworld: MultiWorld, base_state: CollectionState, locati def remaining_fill(multiworld: MultiWorld, locations: typing.List[Location], itempool: typing.List[Item], - name: str = "Remaining") -> None: + name: str = "Remaining", + move_unplaceable_to_start_inventory: bool = False) -> None: unplaced_items: typing.List[Item] = [] placements: typing.List[Location] = [] swapped_items: typing.Counter[typing.Tuple[int, str]] = Counter() @@ -278,13 +285,21 @@ def remaining_fill(multiworld: MultiWorld, if unplaced_items and locations: # There are leftover unplaceable items and locations that won't accept them - raise FillError(f"No more spots to place {len(unplaced_items)} items. Remaining locations are invalid.\n" - f"Unplaced items:\n" - f"{', '.join(str(item) for item in unplaced_items)}\n" - f"Unfilled locations:\n" - f"{', '.join(str(location) for location in locations)}\n" - f"Already placed {len(placements)}:\n" - f"{', '.join(str(place) for place in placements)}") + if move_unplaceable_to_start_inventory: + last_batch = [] + for item in unplaced_items: + logging.debug(f"Moved {item} to start_inventory to prevent fill failure.") + multiworld.push_precollected(item) + last_batch.append(multiworld.worlds[item.player].create_filler()) + remaining_fill(multiworld, locations, unplaced_items, name + " Start Inventory Retry") + else: + raise FillError(f"No more spots to place {len(unplaced_items)} items. Remaining locations are invalid.\n" + f"Unplaced items:\n" + f"{', '.join(str(item) for item in unplaced_items)}\n" + f"Unfilled locations:\n" + f"{', '.join(str(location) for location in locations)}\n" + f"Already placed {len(placements)}:\n" + f"{', '.join(str(place) for place in placements)}") itempool.extend(unplaced_items) @@ -414,7 +429,8 @@ def distribute_early_items(multiworld: MultiWorld, return fill_locations, itempool -def distribute_items_restrictive(multiworld: MultiWorld) -> None: +def distribute_items_restrictive(multiworld: MultiWorld, + panic_method: typing.Literal["swap", "raise", "start_inventory"] = "swap") -> None: fill_locations = sorted(multiworld.get_unfilled_locations()) multiworld.random.shuffle(fill_locations) # get items to distribute @@ -456,14 +472,37 @@ def mark_for_locking(location: Location): if prioritylocations: # "priority fill" - fill_restrictive(multiworld, multiworld.state, prioritylocations, progitempool, swap=False, on_place=mark_for_locking, + fill_restrictive(multiworld, multiworld.state, prioritylocations, progitempool, + single_player_placement=multiworld.players == 1, swap=False, on_place=mark_for_locking, name="Priority") accessibility_corrections(multiworld, multiworld.state, prioritylocations, progitempool) defaultlocations = prioritylocations + defaultlocations if progitempool: # "advancement/progression fill" - fill_restrictive(multiworld, multiworld.state, defaultlocations, progitempool, name="Progression") + if panic_method == "swap": + fill_restrictive(multiworld, multiworld.state, defaultlocations, progitempool, + swap=True, + on_place=mark_for_locking, name="Progression", single_player_placement=multiworld.players == 1) + elif panic_method == "raise": + fill_restrictive(multiworld, multiworld.state, defaultlocations, progitempool, + swap=False, + on_place=mark_for_locking, name="Progression", single_player_placement=multiworld.players == 1) + elif panic_method == "start_inventory": + fill_restrictive(multiworld, multiworld.state, defaultlocations, progitempool, + swap=False, allow_partial=True, + on_place=mark_for_locking, name="Progression", single_player_placement=multiworld.players == 1) + if progitempool: + for item in progitempool: + logging.debug(f"Moved {item} to start_inventory to prevent fill failure.") + multiworld.push_precollected(item) + filleritempool.append(multiworld.worlds[item.player].create_filler()) + logging.warning(f"{len(progitempool)} items moved to start inventory," + f" due to failure in Progression fill step.") + progitempool[:] = [] + + else: + raise ValueError(f"Generator Panic Method {panic_method} not recognized.") if progitempool: raise FillError( f"Not enough locations for progression items. " @@ -478,7 +517,9 @@ def mark_for_locking(location: Location): inaccessible_location_rules(multiworld, multiworld.state, defaultlocations) - remaining_fill(multiworld, excludedlocations, filleritempool, "Remaining Excluded") + remaining_fill(multiworld, excludedlocations, filleritempool, "Remaining Excluded", + move_unplaceable_to_start_inventory=panic_method=="start_inventory") + if excludedlocations: raise FillError( f"Not enough filler items for excluded locations. " @@ -487,7 +528,8 @@ def mark_for_locking(location: Location): restitempool = filleritempool + usefulitempool - remaining_fill(multiworld, defaultlocations, restitempool) + remaining_fill(multiworld, defaultlocations, restitempool, + move_unplaceable_to_start_inventory=panic_method=="start_inventory") unplaced = restitempool unfilled = defaultlocations diff --git a/Generate.py b/Generate.py index 1b36c633d8ec..0cef081120e6 100644 --- a/Generate.py +++ b/Generate.py @@ -1,36 +1,32 @@ from __future__ import annotations import argparse +import copy import logging import os import random import string +import sys import urllib.parse import urllib.request from collections import Counter from typing import Any, Dict, Tuple, Union +from itertools import chain import ModuleUpdate ModuleUpdate.update() -import copy import Utils import Options from BaseClasses import seeddigits, get_seed, PlandoOptions -from Main import main as ERmain -from settings import get_settings from Utils import parse_yamls, version_tuple, __version__, tuplize_version -from worlds.alttp.EntranceRandomizer import parse_arguments -from worlds.alttp.Text import TextTable -from worlds.AutoWorld import AutoWorldRegister -from worlds.generic import PlandoConnection -from worlds import failed_world_loads def mystery_argparse(): - options = get_settings() - defaults = options.generator + from settings import get_settings + settings = get_settings() + defaults = settings.generator parser = argparse.ArgumentParser(description="CMD Generation Interface, defaults come from host.yaml.") parser.add_argument('--weights_file_path', default=defaults.weights_file_path, @@ -42,7 +38,7 @@ def mystery_argparse(): parser.add_argument('--seed', help='Define seed number to generate.', type=int) parser.add_argument('--multi', default=defaults.players, type=lambda value: max(int(value), 1)) parser.add_argument('--spoiler', type=int, default=defaults.spoiler) - parser.add_argument('--outputpath', default=options.general_options.output_path, + parser.add_argument('--outputpath', default=settings.general_options.output_path, help="Path to output folder. Absolute or relative to cwd.") # absolute or relative to cwd parser.add_argument('--race', action='store_true', default=defaults.race) parser.add_argument('--meta_file_path', default=defaults.meta_file_path) @@ -62,20 +58,21 @@ def mystery_argparse(): if not os.path.isabs(args.meta_file_path): args.meta_file_path = os.path.join(args.player_files_path, args.meta_file_path) args.plando: PlandoOptions = PlandoOptions.from_option_string(args.plando) - return args, options + return args def get_seed_name(random_source) -> str: return f"{random_source.randint(0, pow(10, seeddigits) - 1)}".zfill(seeddigits) -def main(args=None, callback=ERmain): +def main(args=None): if not args: - args, options = mystery_argparse() - else: - options = get_settings() + args = mystery_argparse() seed = get_seed(args.seed) + # __name__ == "__main__" check so unittests that already imported worlds don't trip this. + if __name__ == "__main__" and "worlds" in sys.modules: + raise Exception("Worlds system should not be loaded before logging init.") Utils.init_logging(f"Generate_{seed}", loglevel=args.log_level) random.seed(seed) seed_name = get_seed_name(random) @@ -144,6 +141,9 @@ def main(args=None, callback=ERmain): raise Exception(f"No weights found. " f"Provide a general weights file ({args.weights_file_path}) or individual player files. " f"A mix is also permitted.") + + from worlds.AutoWorld import AutoWorldRegister + from worlds.alttp.EntranceRandomizer import parse_arguments erargs = parse_arguments(['--multi', str(args.multi)]) erargs.seed = seed erargs.plando_options = args.plando @@ -235,7 +235,8 @@ def main(args=None, callback=ERmain): with open(os.path.join(args.outputpath if args.outputpath else ".", f"generate_{seed_name}.yaml"), "wt") as f: yaml.dump(important, f) - return callback(erargs, seed) + from Main import main as ERmain + return ERmain(erargs, seed) def read_weights_yamls(path) -> Tuple[Any, ...]: @@ -319,18 +320,34 @@ def update_weights(weights: dict, new_weights: dict, update_type: str, name: str logging.debug(f'Applying {new_weights}') cleaned_weights = {} for option in new_weights: - option_name = option.lstrip("+") + option_name = option.lstrip("+-") if option.startswith("+") and option_name in weights: cleaned_value = weights[option_name] new_value = new_weights[option] - if isinstance(new_value, (set, dict)): + if isinstance(new_value, set): cleaned_value.update(new_value) elif isinstance(new_value, list): cleaned_value.extend(new_value) + elif isinstance(new_value, dict): + cleaned_value = dict(Counter(cleaned_value) + Counter(new_value)) else: raise Exception(f"Cannot apply merge to non-dict, set, or list type {option_name}," f" received {type(new_value).__name__}.") cleaned_weights[option_name] = cleaned_value + elif option.startswith("-") and option_name in weights: + cleaned_value = weights[option_name] + new_value = new_weights[option] + if isinstance(new_value, set): + cleaned_value.difference_update(new_value) + elif isinstance(new_value, list): + for element in new_value: + cleaned_value.remove(element) + elif isinstance(new_value, dict): + cleaned_value = dict(Counter(cleaned_value) - Counter(new_value)) + else: + raise Exception(f"Cannot apply remove to non-dict, set, or list type {option_name}," + f" received {type(new_value).__name__}.") + cleaned_weights[option_name] = cleaned_value else: cleaned_weights[option_name] = new_weights[option] new_options = set(cleaned_weights) - set(weights) @@ -344,6 +361,8 @@ def update_weights(weights: dict, new_weights: dict, update_type: str, name: str def roll_meta_option(option_key, game: str, category_dict: Dict) -> Any: + from worlds import AutoWorldRegister + if not game: return get_choice(option_key, category_dict) if game in AutoWorldRegister.world_types: @@ -378,7 +397,7 @@ def roll_linked_options(weights: dict) -> dict: return weights -def roll_triggers(weights: dict, triggers: list) -> dict: +def roll_triggers(weights: dict, triggers: list, valid_keys: set) -> dict: weights = copy.deepcopy(weights) # make sure we don't write back to other weights sets in same_settings weights["_Generator_Version"] = Utils.__version__ for i, option_set in enumerate(triggers): @@ -401,7 +420,7 @@ def roll_triggers(weights: dict, triggers: list) -> dict: if category_name: currently_targeted_weights = currently_targeted_weights[category_name] update_weights(currently_targeted_weights, category_options, "Triggered", option_set["option_name"]) - + valid_keys.add(key) except Exception as e: raise ValueError(f"Your trigger number {i + 1} is invalid. " f"Please fix your triggers.") from e @@ -421,15 +440,19 @@ def handle_option(ret: argparse.Namespace, game_weights: dict, option_key: str, except Exception as e: raise Options.OptionError(f"Error generating option {option_key} in {ret.game}") from e else: + from worlds import AutoWorldRegister player_option.verify(AutoWorldRegister.world_types[ret.game], ret.name, plando_options) def roll_settings(weights: dict, plando_options: PlandoOptions = PlandoOptions.bosses): + from worlds import AutoWorldRegister + if "linked_options" in weights: weights = roll_linked_options(weights) + valid_keys = set() if "triggers" in weights: - weights = roll_triggers(weights, weights["triggers"]) + weights = roll_triggers(weights, weights["triggers"], valid_keys) requirements = weights.get("requires", {}) if requirements: @@ -450,6 +473,7 @@ def roll_settings(weights: dict, plando_options: PlandoOptions = PlandoOptions.b ret.game = get_choice("game", weights) 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] if picks[0] in failed_world_loads: raise Exception(f"No functional world found to handle game {ret.game}. " @@ -464,12 +488,14 @@ def roll_settings(weights: dict, plando_options: PlandoOptions = PlandoOptions.b world_type = AutoWorldRegister.world_types[ret.game] game_weights = weights[ret.game] - if any(weight.startswith("+") for weight in game_weights) or \ - any(weight.startswith("+") for weight in weights): - raise Exception(f"Merge tag cannot be used outside of trigger contexts.") + for weight in chain(game_weights, weights): + if weight.startswith("+"): + raise Exception(f"Merge tag cannot be used outside of trigger contexts. Found {weight}") + if weight.startswith("-"): + raise Exception(f"Remove tag cannot be used outside of trigger contexts. Found {weight}") if "triggers" in game_weights: - weights = roll_triggers(weights, game_weights["triggers"]) + weights = roll_triggers(weights, game_weights["triggers"], valid_keys) game_weights = weights[ret.game] ret.name = get_choice('name', weights) @@ -478,38 +504,20 @@ def roll_settings(weights: dict, plando_options: PlandoOptions = PlandoOptions.b for option_key, option in world_type.options_dataclass.type_hints.items(): handle_option(ret, game_weights, option_key, option, plando_options) + valid_keys.add(option_key) + for option_key in game_weights: + if option_key in {"triggers", *valid_keys}: + continue + logging.warning(f"{option_key} is not a valid option name for {ret.game} and is not present in triggers.") if PlandoOptions.items in plando_options: ret.plando_items = game_weights.get("plando_items", []) if ret.game == "A Link to the Past": - roll_alttp_settings(ret, game_weights, plando_options) - if PlandoOptions.connections in plando_options: - ret.plando_connections = [] - options = game_weights.get("plando_connections", []) - for placement in options: - if roll_percentage(get_choice("percentage", placement, 100)): - ret.plando_connections.append(PlandoConnection( - get_choice("entrance", placement), - get_choice("exit", placement), - get_choice("direction", placement, "both") - )) + roll_alttp_settings(ret, game_weights) return ret -def roll_alttp_settings(ret: argparse.Namespace, weights, plando_options): - - ret.plando_texts = {} - if PlandoOptions.texts in plando_options: - tt = TextTable() - tt.removeUnwantedText() - options = weights.get("plando_texts", []) - for placement in options: - if roll_percentage(get_choice_legacy("percentage", placement, 100)): - at = str(get_choice_legacy("at", placement)) - if at not in tt: - raise Exception(f"No text target \"{at}\" found.") - ret.plando_texts[at] = str(get_choice_legacy("text", placement)) - +def roll_alttp_settings(ret: argparse.Namespace, weights): ret.sprite_pool = weights.get('sprite_pool', []) ret.sprite = get_choice_legacy('sprite', weights, "Link") if 'random_sprite_on_event' in weights: diff --git a/Launcher.py b/Launcher.py index 6426380dd726..e4b65be93a68 100644 --- a/Launcher.py +++ b/Launcher.py @@ -19,7 +19,7 @@ import webbrowser from os.path import isfile from shutil import which -from typing import Sequence, Union, Optional +from typing import Callable, Sequence, Union, Optional import Utils import settings @@ -160,8 +160,12 @@ def launch(exe, in_terminal=False): subprocess.Popen(exe) +refresh_components: Optional[Callable[[], None]] = None + + def run_gui(): from kvui import App, ContainerLayout, GridLayout, Button, Label, ScrollBox, Widget + from kivy.core.window import Window from kivy.uix.image import AsyncImage from kivy.uix.relativelayout import RelativeLayout @@ -169,11 +173,8 @@ class Launcher(App): base_title: str = "Archipelago Launcher" container: ContainerLayout grid: GridLayout - - _tools = {c.display_name: c for c in components if c.type == Type.TOOL} - _clients = {c.display_name: c for c in components if c.type == Type.CLIENT} - _adjusters = {c.display_name: c for c in components if c.type == Type.ADJUSTER} - _miscs = {c.display_name: c for c in components if c.type == Type.MISC} + _tool_layout: Optional[ScrollBox] = None + _client_layout: Optional[ScrollBox] = None def __init__(self, ctx=None): self.title = self.base_title @@ -181,18 +182,7 @@ def __init__(self, ctx=None): self.icon = r"data/icon.png" super().__init__() - def build(self): - self.container = ContainerLayout() - self.grid = GridLayout(cols=2) - self.container.add_widget(self.grid) - self.grid.add_widget(Label(text="General", size_hint_y=None, height=40)) - self.grid.add_widget(Label(text="Clients", size_hint_y=None, height=40)) - tool_layout = ScrollBox() - tool_layout.layout.orientation = "vertical" - self.grid.add_widget(tool_layout) - client_layout = ScrollBox() - client_layout.layout.orientation = "vertical" - self.grid.add_widget(client_layout) + def _refresh_components(self) -> None: def build_button(component: Component) -> Widget: """ @@ -217,14 +207,49 @@ def build_button(component: Component) -> Widget: return box_layout return button + # clear before repopulating + assert self._tool_layout and self._client_layout, "must call `build` first" + tool_children = reversed(self._tool_layout.layout.children) + for child in tool_children: + self._tool_layout.layout.remove_widget(child) + client_children = reversed(self._client_layout.layout.children) + for child in client_children: + self._client_layout.layout.remove_widget(child) + + _tools = {c.display_name: c for c in components if c.type == Type.TOOL} + _clients = {c.display_name: c for c in components if c.type == Type.CLIENT} + _adjusters = {c.display_name: c for c in components if c.type == Type.ADJUSTER} + _miscs = {c.display_name: c for c in components if c.type == Type.MISC} + for (tool, client) in itertools.zip_longest(itertools.chain( - self._tools.items(), self._miscs.items(), self._adjusters.items()), self._clients.items()): + _tools.items(), _miscs.items(), _adjusters.items() + ), _clients.items()): # column 1 if tool: - tool_layout.layout.add_widget(build_button(tool[1])) + self._tool_layout.layout.add_widget(build_button(tool[1])) # column 2 if client: - client_layout.layout.add_widget(build_button(client[1])) + self._client_layout.layout.add_widget(build_button(client[1])) + + def build(self): + self.container = ContainerLayout() + self.grid = GridLayout(cols=2) + self.container.add_widget(self.grid) + self.grid.add_widget(Label(text="General", size_hint_y=None, height=40)) + self.grid.add_widget(Label(text="Clients", size_hint_y=None, height=40)) + self._tool_layout = ScrollBox() + self._tool_layout.layout.orientation = "vertical" + self.grid.add_widget(self._tool_layout) + self._client_layout = ScrollBox() + self._client_layout.layout.orientation = "vertical" + self.grid.add_widget(self._client_layout) + + self._refresh_components() + + global refresh_components + refresh_components = self._refresh_components + + Window.bind(on_drop_file=self._on_drop_file) return self.container @@ -235,6 +260,14 @@ def component_action(button): else: launch(get_exe(button.component), button.component.cli) + def _on_drop_file(self, window: Window, filename: bytes, x: int, y: int) -> None: + """ When a patch file is dropped into the window, run the associated component. """ + file, component = identify(filename.decode()) + if file and component: + run_component(component, file) + else: + logging.warning(f"unable to identify component for {filename}") + def _stop(self, *largs): # ran into what appears to be https://groups.google.com/g/kivy-users/c/saWDLoYCSZ4 with PyCharm. # Closing the window explicitly cleans it up. @@ -243,10 +276,17 @@ def _stop(self, *largs): Launcher().run() + # avoiding Launcher reference leak + # and don't try to do something with widgets after window closed + global refresh_components + refresh_components = None + def run_component(component: Component, *args): if component.func: component.func(*args) + if refresh_components: + refresh_components() elif component.script_name: subprocess.run([*get_exe(component.script_name), *args]) else: @@ -259,7 +299,7 @@ def main(args: Optional[Union[argparse.Namespace, dict]] = None): elif not args: args = {} - if "Patch|Game|Component" in args: + if args.get("Patch|Game|Component", None) is not None: file, component = identify(args["Patch|Game|Component"]) if file: args['file'] = file diff --git a/Main.py b/Main.py index 1be91a8bb2f1..de6b467f93d9 100644 --- a/Main.py +++ b/Main.py @@ -13,7 +13,7 @@ from BaseClasses import CollectionState, Item, Location, LocationProgressType, MultiWorld, Region from Fill import balance_multiworld_progression, distribute_items_restrictive, distribute_planned, flood_items from Options import StartInventoryPool -from Utils import __version__, output_path, version_tuple +from Utils import __version__, output_path, version_tuple, get_settings from settings import get_settings from worlds import AutoWorld from worlds.generic.Rules import exclusion_rules, locality_rules @@ -272,7 +272,7 @@ def find_common_pool(players: Set[int], shared_pool: Set[str]) -> Tuple[ if multiworld.algorithm == 'flood': flood_items(multiworld) # different algo, biased towards early game progress items elif multiworld.algorithm == 'balanced': - distribute_items_restrictive(multiworld) + distribute_items_restrictive(multiworld, get_settings().generator.panic_method) AutoWorld.call_all(multiworld, 'post_fill') @@ -372,6 +372,17 @@ def precollect_hint(location): checks_in_area: Dict[int, Dict[str, Union[int, List[int]]]] = {} + # get spheres -> filter address==None -> skip empty + spheres: List[Dict[int, Set[int]]] = [] + for sphere in multiworld.get_spheres(): + current_sphere: Dict[int, Set[int]] = collections.defaultdict(set) + for sphere_location in sphere: + if type(sphere_location.address) is int: + current_sphere[sphere_location.player].add(sphere_location.address) + + if current_sphere: + spheres.append(dict(current_sphere)) + multidata = { "slot_data": slot_data, "slot_info": slot_info, @@ -386,6 +397,7 @@ def precollect_hint(location): "tags": ["AP"], "minimum_versions": minimum_versions, "seed_name": multiworld.seed_name, + "spheres": spheres, "datapackage": data_package, } AutoWorld.call_all(multiworld, "modify_multidata", multidata) diff --git a/MultiServer.py b/MultiServer.py index 9ee6a8032c1f..dc5e3d21ac89 100644 --- a/MultiServer.py +++ b/MultiServer.py @@ -3,6 +3,7 @@ import argparse import asyncio import collections +import contextlib import copy import datetime import functools @@ -37,7 +38,7 @@ import NetUtils import Utils -from Utils import version_tuple, restricted_loads, Version, async_start +from Utils import version_tuple, restricted_loads, Version, async_start, get_intended_text from NetUtils import Endpoint, ClientStatus, NetworkItem, decode, encode, NetworkPlayer, Permission, NetworkSlot, \ SlotType, LocationStore @@ -168,18 +169,25 @@ class Context: slot_info: typing.Dict[int, NetworkSlot] generator_version = Version(0, 0, 0) checksums: typing.Dict[str, str] - item_names: typing.Dict[int, str] = Utils.KeyedDefaultDict(lambda code: f'Unknown item (ID:{code})') + item_names: typing.Dict[str, typing.Dict[int, str]] = ( + collections.defaultdict(lambda: Utils.KeyedDefaultDict(lambda code: f'Unknown item (ID:{code})'))) item_name_groups: typing.Dict[str, typing.Dict[str, typing.Set[str]]] - location_names: typing.Dict[int, str] = Utils.KeyedDefaultDict(lambda code: f'Unknown location (ID:{code})') + location_names: typing.Dict[str, typing.Dict[int, str]] = ( + collections.defaultdict(lambda: Utils.KeyedDefaultDict(lambda code: f'Unknown location (ID:{code})'))) location_name_groups: typing.Dict[str, typing.Dict[str, typing.Set[str]]] all_item_and_group_names: typing.Dict[str, typing.Set[str]] all_location_and_group_names: typing.Dict[str, typing.Set[str]] - non_hintable_names: typing.Dict[str, typing.Set[str]] + non_hintable_names: typing.Dict[str, typing.AbstractSet[str]] + spheres: typing.List[typing.Dict[int, typing.Set[int]]] + """ each sphere is { player: { location_id, ... } } """ + logger: logging.Logger + def __init__(self, host: str, port: int, server_password: str, password: str, location_check_points: int, hint_cost: int, item_cheat: bool, release_mode: str = "disabled", collect_mode="disabled", remaining_mode: str = "disabled", auto_shutdown: typing.SupportsFloat = 0, compatibility: int = 2, - log_network: bool = False): + log_network: bool = False, logger: logging.Logger = logging.getLogger()): + self.logger = logger super(Context, self).__init__() self.slot_info = {} self.log_network = log_network @@ -224,7 +232,7 @@ def __init__(self, host: str, port: int, server_password: str, password: str, lo self.embedded_blacklist = {"host", "port"} self.client_ids: typing.Dict[typing.Tuple[int, int], datetime.datetime] = {} self.auto_save_interval = 60 # in seconds - self.auto_saver_thread = None + self.auto_saver_thread: typing.Optional[threading.Thread] = None self.save_dirty = False self.tags = ['AP'] self.games: typing.Dict[int, str] = {} @@ -236,6 +244,7 @@ def __init__(self, host: str, port: int, server_password: str, password: str, lo self.stored_data = {} self.stored_data_notification_clients = collections.defaultdict(weakref.WeakSet) self.read_data = {} + self.spheres = [] # init empty to satisfy linter, I suppose self.gamespackage = {} @@ -260,19 +269,31 @@ def _load_game_data(self): for world_name, world in worlds.AutoWorldRegister.world_types.items(): self.non_hintable_names[world_name] = world.hint_blacklist + for game_package in self.gamespackage.values(): + # remove groups from data sent to clients + del game_package["item_name_groups"] + del game_package["location_name_groups"] + def _init_game_data(self): for game_name, game_package in self.gamespackage.items(): if "checksum" in game_package: self.checksums[game_name] = game_package["checksum"] for item_name, item_id in game_package["item_name_to_id"].items(): - self.item_names[item_id] = item_name + self.item_names[game_name][item_id] = item_name for location_name, location_id in game_package["location_name_to_id"].items(): - self.location_names[location_id] = location_name + self.location_names[game_name][location_id] = location_name self.all_item_and_group_names[game_name] = \ set(game_package["item_name_to_id"]) | set(self.item_name_groups[game_name]) self.all_location_and_group_names[game_name] = \ set(game_package["location_name_to_id"]) | set(self.location_name_groups.get(game_name, [])) + archipelago_item_names = self.item_names["Archipelago"] + archipelago_location_names = self.location_names["Archipelago"] + for game in [game_name for game_name in self.gamespackage if game_name != "Archipelago"]: + # Add Archipelago items and locations to each data package. + self.item_names[game].update(archipelago_item_names) + self.location_names[game].update(archipelago_location_names) + def item_names_for_game(self, game: str) -> typing.Optional[typing.Dict[str, int]]: return self.gamespackage[game]["item_name_to_id"] if game in self.gamespackage else None @@ -287,12 +308,12 @@ async def send_msgs(self, endpoint: Endpoint, msgs: typing.Iterable[dict]) -> bo try: await endpoint.socket.send(msg) except websockets.ConnectionClosed: - logging.exception(f"Exception during send_msgs, could not send {msg}") + self.logger.exception(f"Exception during send_msgs, could not send {msg}") await self.disconnect(endpoint) return False else: if self.log_network: - logging.info(f"Outgoing message: {msg}") + self.logger.info(f"Outgoing message: {msg}") return True async def send_encoded_msgs(self, endpoint: Endpoint, msg: str) -> bool: @@ -301,12 +322,12 @@ async def send_encoded_msgs(self, endpoint: Endpoint, msg: str) -> bool: try: await endpoint.socket.send(msg) except websockets.ConnectionClosed: - logging.exception("Exception during send_encoded_msgs") + self.logger.exception("Exception during send_encoded_msgs") await self.disconnect(endpoint) return False else: if self.log_network: - logging.info(f"Outgoing message: {msg}") + self.logger.info(f"Outgoing message: {msg}") return True async def broadcast_send_encoded_msgs(self, endpoints: typing.Iterable[Endpoint], msg: str) -> bool: @@ -317,11 +338,11 @@ async def broadcast_send_encoded_msgs(self, endpoints: typing.Iterable[Endpoint] try: websockets.broadcast(sockets, msg) except RuntimeError: - logging.exception("Exception during broadcast_send_encoded_msgs") + self.logger.exception("Exception during broadcast_send_encoded_msgs") return False else: if self.log_network: - logging.info(f"Outgoing broadcast: {msg}") + self.logger.info(f"Outgoing broadcast: {msg}") return True def broadcast_all(self, msgs: typing.List[dict]): @@ -330,7 +351,7 @@ def broadcast_all(self, msgs: typing.List[dict]): async_start(self.broadcast_send_encoded_msgs(endpoints, msgs)) def broadcast_text_all(self, text: str, additional_arguments: dict = {}): - logging.info("Notice (all): %s" % text) + self.logger.info("Notice (all): %s" % text) self.broadcast_all([{**{"cmd": "PrintJSON", "data": [{ "text": text }]}, **additional_arguments}]) def broadcast_team(self, team: int, msgs: typing.List[dict]): @@ -352,7 +373,7 @@ async def disconnect(self, endpoint: Client): def notify_client(self, client: Client, text: str, additional_arguments: dict = {}): if not client.auth: return - logging.info("Notice (Player %s in team %d): %s" % (client.name, client.team + 1, text)) + self.logger.info("Notice (Player %s in team %d): %s" % (client.name, client.team + 1, text)) async_start(self.send_msgs(client, [{"cmd": "PrintJSON", "data": [{ "text": text }], **additional_arguments}])) def notify_client_multiple(self, client: Client, texts: typing.List[str], additional_arguments: dict = {}): @@ -451,7 +472,7 @@ def _load(self, decoded_obj: dict, game_data_packages: typing.Dict[str, typing.A for game_name, data in decoded_obj.get("datapackage", {}).items(): if game_name in game_data_packages: data = game_data_packages[game_name] - logging.info(f"Loading embedded data package for game {game_name}") + self.logger.info(f"Loading embedded data package for game {game_name}") self.gamespackage[game_name] = data self.item_name_groups[game_name] = data["item_name_groups"] if "location_name_groups" in data: @@ -464,6 +485,9 @@ def _load(self, decoded_obj: dict, game_data_packages: typing.Dict[str, typing.A for game_name, data in self.location_name_groups.items(): self.read_data[f"location_name_groups_{game_name}"] = lambda lgame=game_name: self.location_name_groups[lgame] + # sorted access spheres + self.spheres = decoded_obj.get("spheres", []) + # saving def save(self, now=False) -> bool: @@ -483,7 +507,7 @@ def _save(self, exit_save: bool = False) -> bool: with open(self.save_filename, "wb") as f: f.write(zlib.compress(encoded_save)) except Exception as e: - logging.exception(e) + self.logger.exception(e) return False else: return True @@ -501,12 +525,12 @@ def init_save(self, enabled: bool = True): save_data = restricted_loads(zlib.decompress(f.read())) self.set_save(save_data) except FileNotFoundError: - logging.error('No save data found, starting a new game') + self.logger.error('No save data found, starting a new game') except Exception as e: - logging.exception(e) + self.logger.exception(e) self._start_async_saving() - def _start_async_saving(self): + def _start_async_saving(self, atexit_save: bool = True): if not self.auto_saver_thread: def save_regularly(): # time.time() is platform dependent, so using the expensive datetime method instead @@ -520,18 +544,19 @@ def get_datetime_second(): next_wakeup = (second - get_datetime_second()) % self.auto_save_interval time.sleep(max(1.0, next_wakeup)) if self.save_dirty: - logging.debug("Saving via thread.") + self.logger.debug("Saving via thread.") self._save() except OperationalError as e: - logging.exception(e) - logging.info(f"Saving failed. Retry in {self.auto_save_interval} seconds.") + self.logger.exception(e) + self.logger.info(f"Saving failed. Retry in {self.auto_save_interval} seconds.") else: self.save_dirty = False self.auto_saver_thread = threading.Thread(target=save_regularly, daemon=True) self.auto_saver_thread.start() - import atexit - atexit.register(self._save, True) # make sure we save on exit too + if atexit_save: + import atexit + atexit.register(self._save, True) # make sure we save on exit too def get_save(self) -> dict: self.recheck_hints() @@ -598,7 +623,7 @@ def set_save(self, savedata: dict): if "stored_data" in savedata: self.stored_data = savedata["stored_data"] # count items and slots from lists for items_handling = remote - logging.info( + self.logger.info( f'Loaded save file with {sum([len(v) for k, v in self.received_items.items() if k[2]])} received items ' f'for {sum(k[2] for k in self.received_items)} players') @@ -621,6 +646,16 @@ def get_rechecked_hints(self, team: int, slot: int): self.recheck_hints(team, slot) return self.hints[team, slot] + def get_sphere(self, player: int, location_id: int) -> int: + """Get sphere of a location, -1 if spheres are not available.""" + if self.spheres: + for i, sphere in enumerate(self.spheres): + if location_id in sphere.get(player, set()): + return i + raise KeyError(f"No Sphere found for location ID {location_id} belonging to player {player}. " + f"Location or player may not exist.") + return -1 + def get_players_package(self): return [NetworkPlayer(t, p, self.get_aliased_name(t, p), n) for (t, p), n in self.player_names.items()] @@ -640,13 +675,13 @@ def _set_options(self, server_options: dict): try: raise Exception(f"Could not set server option {key}, skipping.") from e except Exception as e: - logging.exception(e) - logging.debug(f"Setting server option {key} to {value} from supplied multidata") + self.logger.exception(e) + self.logger.debug(f"Setting server option {key} to {value} from supplied multidata") setattr(self, key, value) elif key == "disable_item_cheat": self.item_cheat = not bool(value) else: - logging.debug(f"Unrecognized server option {key}") + self.logger.debug(f"Unrecognized server option {key}") def get_aliased_name(self, team: int, slot: int): if (team, slot) in self.name_aliases: @@ -680,7 +715,7 @@ def notify_hints(self, team: int, hints: typing.List[NetUtils.Hint], only_new: b self.hints[team, player].add(hint) new_hint_events.add(player) - logging.info("Notice (Team #%d): %s" % (team + 1, format_hint(self, team, hint))) + self.logger.info("Notice (Team #%d): %s" % (team + 1, format_hint(self, team, hint))) for slot in new_hint_events: self.on_new_hint(team, slot) for slot, hint_data in concerns.items(): @@ -688,7 +723,7 @@ def notify_hints(self, team: int, hints: typing.List[NetUtils.Hint], only_new: b clients = self.clients[team].get(slot) if not clients: continue - client_hints = [datum[1] for datum in sorted(hint_data, key=lambda x: x[0].finding_player == slot)] + client_hints = [datum[1] for datum in sorted(hint_data, key=lambda x: x[0].finding_player != slot)] for client in clients: async_start(self.send_msgs(client, client_hints)) @@ -739,21 +774,21 @@ async def server(websocket, path: str = "/", ctx: Context = None): try: if ctx.log_network: - logging.info("Incoming connection") + ctx.logger.info("Incoming connection") await on_client_connected(ctx, client) if ctx.log_network: - logging.info("Sent Room Info") + ctx.logger.info("Sent Room Info") async for data in websocket: if ctx.log_network: - logging.info(f"Incoming message: {data}") + ctx.logger.info(f"Incoming message: {data}") for msg in decode(data): await process_client_cmd(ctx, client, msg) except Exception as e: if not isinstance(e, websockets.WebSocketException): - logging.exception(e) + ctx.logger.exception(e) finally: if ctx.log_network: - logging.info("Disconnected") + ctx.logger.info("Disconnected") await ctx.disconnect(client) @@ -763,10 +798,7 @@ async def on_client_connected(ctx: Context, client: Client): for slot, connected_clients in clients.items(): if connected_clients: name = ctx.player_names[team, slot] - players.append( - NetworkPlayer(team, slot, - ctx.name_aliases.get((team, slot), name), name) - ) + players.append(NetworkPlayer(team, slot, ctx.name_aliases.get((team, slot), name), name)) games = {ctx.games[x] for x in range(1, len(ctx.games) + 1)} games.add("Archipelago") await ctx.send_msgs(client, [{ @@ -781,8 +813,6 @@ async def on_client_connected(ctx: Context, client: Client): 'permissions': get_permissions(ctx), 'hint_cost': ctx.hint_cost, 'location_check_points': ctx.location_check_points, - 'datapackage_versions': {game: game_data["version"] for game, game_data - in ctx.gamespackage.items() if game in games}, 'datapackage_checksums': {game: game_data["checksum"] for game, game_data in ctx.gamespackage.items() if game in games and "checksum" in game_data}, 'seed_name': ctx.seed_name, @@ -985,9 +1015,9 @@ def register_location_checks(ctx: Context, team: int, slot: int, locations: typi new_item = NetworkItem(item_id, location, slot, flags) send_items_to(ctx, team, target_player, new_item) - logging.info('(Team #%d) %s sent %s to %s (%s)' % ( - team + 1, ctx.player_names[(team, slot)], ctx.item_names[item_id], - ctx.player_names[(team, target_player)], ctx.location_names[location])) + ctx.logger.info('(Team #%d) %s sent %s to %s (%s)' % ( + team + 1, ctx.player_names[(team, slot)], ctx.item_names[ctx.slot_info[target_player].game][item_id], + ctx.player_names[(team, target_player)], ctx.location_names[ctx.slot_info[slot].game][location])) info_text = json_format_send_event(new_item, target_player) ctx.broadcast_team(team, [info_text]) @@ -1041,8 +1071,8 @@ def collect_hint_location_id(ctx: Context, team: int, slot: int, seeked_location def format_hint(ctx: Context, team: int, hint: NetUtils.Hint) -> str: text = f"[Hint]: {ctx.player_names[team, hint.receiving_player]}'s " \ - f"{ctx.item_names[hint.item]} is " \ - f"at {ctx.location_names[hint.location]} " \ + f"{ctx.item_names[ctx.slot_info[hint.receiving_player].game][hint.item]} is " \ + f"at {ctx.location_names[ctx.slot_info[hint.finding_player].game][hint.location]} " \ f"in {ctx.player_names[team, hint.finding_player]}'s World" if hint.entrance: @@ -1071,28 +1101,6 @@ def json_format_send_event(net_item: NetworkItem, receiving_player: int): "item": net_item} -def get_intended_text(input_text: str, possible_answers) -> typing.Tuple[str, bool, str]: - picks = Utils.get_fuzzy_results(input_text, possible_answers, limit=2) - if len(picks) > 1: - dif = picks[0][1] - picks[1][1] - if picks[0][1] == 100: - return picks[0][0], True, "Perfect Match" - elif picks[0][1] < 75: - return picks[0][0], False, f"Didn't find something that closely matches '{input_text}', " \ - f"did you mean '{picks[0][0]}'? ({picks[0][1]}% sure)" - elif dif > 5: - return picks[0][0], True, "Close Match" - else: - return picks[0][0], False, f"Too many close matches for '{input_text}', " \ - f"did you mean '{picks[0][0]}'? ({picks[0][1]}% sure)" - else: - if picks[0][1] > 90: - return picks[0][0], True, "Only Option Match" - else: - return picks[0][0], False, f"Didn't find something that closely matches '{input_text}', " \ - f"did you mean '{picks[0][0]}'? ({picks[0][1]}% sure)" - - class CommandMeta(type): def __new__(cls, name, bases, attrs): commands = attrs["commands"] = {} @@ -1344,7 +1352,7 @@ def _cmd_remaining(self) -> bool: if self.ctx.remaining_mode == "enabled": remaining_item_ids = get_remaining(self.ctx, self.client.team, self.client.slot) if remaining_item_ids: - self.output("Remaining items: " + ", ".join(self.ctx.item_names[item_id] + self.output("Remaining items: " + ", ".join(self.ctx.item_names[self.client.slot.game][item_id] for item_id in remaining_item_ids)) else: self.output("No remaining items found.") @@ -1357,7 +1365,7 @@ def _cmd_remaining(self) -> bool: if self.ctx.client_game_state[self.client.team, self.client.slot] == ClientStatus.CLIENT_GOAL: remaining_item_ids = get_remaining(self.ctx, self.client.team, self.client.slot) if remaining_item_ids: - self.output("Remaining items: " + ", ".join(self.ctx.item_names[item_id] + self.output("Remaining items: " + ", ".join(self.ctx.item_names[self.client.slot.game][item_id] for item_id in remaining_item_ids)) else: self.output("No remaining items found.") @@ -1375,7 +1383,8 @@ def _cmd_missing(self, filter_text="") -> bool: locations = get_missing_checks(self.ctx, self.client.team, self.client.slot) if locations: - names = [self.ctx.location_names[location] for location in locations] + game = self.ctx.slot_info[self.client.slot].game + names = [self.ctx.location_names[game][location] for location in locations] if filter_text: location_groups = self.ctx.location_name_groups[self.ctx.games[self.client.slot]] if filter_text in location_groups: # location group name @@ -1400,7 +1409,8 @@ def _cmd_checked(self, filter_text="") -> bool: locations = get_checked_checks(self.ctx, self.client.team, self.client.slot) if locations: - names = [self.ctx.location_names[location] for location in locations] + game = self.ctx.slot_info[self.client.slot].game + names = [self.ctx.location_names[game][location] for location in locations] if filter_text: location_groups = self.ctx.location_name_groups[self.ctx.games[self.client.slot]] if filter_text in location_groups: # location group name @@ -1481,10 +1491,10 @@ def get_hints(self, input_text: str, for_location: bool = False) -> bool: elif input_text.isnumeric(): game = self.ctx.games[self.client.slot] hint_id = int(input_text) - hint_name = self.ctx.item_names[hint_id] \ - if not for_location and hint_id in self.ctx.item_names \ - else self.ctx.location_names[hint_id] \ - if for_location and hint_id in self.ctx.location_names \ + hint_name = self.ctx.item_names[game][hint_id] \ + if not for_location and hint_id in self.ctx.item_names[game] \ + else self.ctx.location_names[game][hint_id] \ + if for_location and hint_id in self.ctx.location_names[game] \ else None if hint_name in self.ctx.non_hintable_names[game]: self.output(f"Sorry, \"{hint_name}\" is marked as non-hintable.") @@ -1529,15 +1539,13 @@ def get_hints(self, input_text: str, for_location: bool = False) -> bool: if hints: new_hints = set(hints) - self.ctx.hints[self.client.team, self.client.slot] - old_hints = set(hints) - new_hints - if old_hints: - self.ctx.notify_hints(self.client.team, list(old_hints)) - if not new_hints: - self.output("Hint was previously used, no points deducted.") + old_hints = list(set(hints) - new_hints) + if old_hints and not new_hints: + self.ctx.notify_hints(self.client.team, old_hints) + self.output("Hint was previously used, no points deducted.") if new_hints: found_hints = [hint for hint in new_hints if hint.found] not_found_hints = [hint for hint in new_hints if not hint.found] - if not not_found_hints: # everything's been found, no need to pay can_pay = 1000 elif cost: @@ -1548,8 +1556,11 @@ def get_hints(self, input_text: str, for_location: bool = False) -> bool: self.ctx.random.shuffle(not_found_hints) # By popular vote, make hints prefer non-local placements not_found_hints.sort(key=lambda hint: int(hint.receiving_player != hint.finding_player)) + # By another popular vote, prefer early sphere + not_found_hints.sort(key=lambda hint: self.ctx.get_sphere(hint.finding_player, hint.location), + reverse=True) - hints = found_hints + hints = found_hints + old_hints while can_pay > 0: if not not_found_hints: break @@ -1557,9 +1568,10 @@ def get_hints(self, input_text: str, for_location: bool = False) -> bool: hints.append(hint) can_pay -= 1 self.ctx.hints_used[self.client.team, self.client.slot] += 1 - points_available = get_client_points(self.ctx, self.client) + self.ctx.notify_hints(self.client.team, hints) if not_found_hints: + points_available = get_client_points(self.ctx, self.client) if hints and cost and int((points_available // cost) == 0): self.output( f"There may be more hintables, however, you cannot afford to pay for any more. " @@ -1572,7 +1584,6 @@ def get_hints(self, input_text: str, for_location: bool = False) -> bool: self.output(f"You can't afford the hint. " f"You have {points_available} points and need at least " f"{self.ctx.get_hint_cost(self.client.slot)}.") - self.ctx.notify_hints(self.client.team, hints) self.ctx.save() return True @@ -1627,7 +1638,7 @@ async def process_client_cmd(ctx: Context, client: Client, args: dict): try: cmd: str = args["cmd"] except: - logging.exception(f"Could not get command from {args}") + ctx.logger.exception(f"Could not get command from {args}") await ctx.send_msgs(client, [{'cmd': 'InvalidPacket', "type": "cmd", "original_cmd": None, "text": f"Could not get command from {args} at `cmd`"}]) raise @@ -1670,7 +1681,7 @@ async def process_client_cmd(ctx: Context, client: Client, args: dict): if ctx.compatibility == 0 and args['version'] != version_tuple: errors.add('IncompatibleVersion') if errors: - logging.info(f"A client connection was refused due to: {errors}, the sent connect information was {args}.") + ctx.logger.info(f"A client connection was refused due to: {errors}, the sent connect information was {args}.") await ctx.send_msgs(client, [{"cmd": "ConnectionRefused", "errors": list(errors)}]) else: team, slot = ctx.connect_names[args['name']] @@ -1921,8 +1932,6 @@ def _cmd_status(self, tag: str = "") -> bool: def _cmd_exit(self) -> bool: """Shutdown the server""" self.ctx.server.ws_server.close() - if self.ctx.shutdown_task: - self.ctx.shutdown_task.cancel() self.ctx.exit_event.set() return True @@ -2280,7 +2289,8 @@ def parse_args() -> argparse.Namespace: async def auto_shutdown(ctx, to_cancel=None): - await asyncio.sleep(ctx.auto_shutdown) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(ctx.exit_event.wait(), ctx.auto_shutdown) def inactivity_shutdown(): ctx.server.ws_server.close() @@ -2288,7 +2298,7 @@ def inactivity_shutdown(): if to_cancel: for task in to_cancel: task.cancel() - logging.info("Shutting down due to inactivity.") + ctx.logger.info("Shutting down due to inactivity.") while not ctx.exit_event.is_set(): if not ctx.client_activity_timers.values(): @@ -2300,7 +2310,8 @@ def inactivity_shutdown(): if seconds < 0: inactivity_shutdown() else: - await asyncio.sleep(seconds) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(ctx.exit_event.wait(), seconds) def load_server_cert(path: str, cert_key: typing.Optional[str]) -> "ssl.SSLContext": diff --git a/NetUtils.py b/NetUtils.py index 8fc3929e60b4..f8d698c74fcc 100644 --- a/NetUtils.py +++ b/NetUtils.py @@ -198,7 +198,8 @@ class JSONtoTextParser(metaclass=HandlerMeta): "slateblue": "6D8BE8", "plum": "AF99EF", "salmon": "FA8072", - "white": "FFFFFF" + "white": "FFFFFF", + "orange": "FF7700", } def __init__(self, ctx): @@ -247,7 +248,7 @@ def _handle_item_name(self, node: JSONMessagePart): def _handle_item_id(self, node: JSONMessagePart): item_id = int(node["text"]) - node["text"] = self.ctx.item_names[item_id] + node["text"] = self.ctx.item_names.lookup_in_slot(item_id, node["player"]) return self._handle_item_name(node) def _handle_location_name(self, node: JSONMessagePart): @@ -255,8 +256,8 @@ def _handle_location_name(self, node: JSONMessagePart): return self._handle_color(node) def _handle_location_id(self, node: JSONMessagePart): - item_id = int(node["text"]) - node["text"] = self.ctx.location_names[item_id] + location_id = int(node["text"]) + node["text"] = self.ctx.location_names.lookup_in_slot(location_id, node["player"]) return self._handle_location_name(node) def _handle_entrance_name(self, node: JSONMessagePart): diff --git a/Options.py b/Options.py index 1eb0afeeeecb..40a6996d325a 100644 --- a/Options.py +++ b/Options.py @@ -12,6 +12,7 @@ from dataclasses import dataclass from schema import And, Optional, Or, Schema +from typing_extensions import Self from Utils import get_fuzzy_results, is_iterable_except_str @@ -24,7 +25,7 @@ class OptionError(ValueError): pass - + class Visibility(enum.IntFlag): none = 0b0000 template = 0b0001 @@ -140,12 +141,6 @@ def __hash__(self) -> int: def current_key(self) -> str: return self.name_lookup[self.value] - def get_current_option_name(self) -> str: - """Deprecated. use current_option_name instead. TODO remove around 0.4""" - logging.warning(DeprecationWarning(f"get_current_option_name for {self.__class__.__name__} is deprecated." - f" use current_option_name instead. Worlds should use {self}.current_key")) - return self.current_option_name - @property def current_option_name(self) -> str: """For display purposes. Worlds should be using current_key.""" @@ -750,39 +745,9 @@ def from_text(cls, text: str) -> Range: return super().from_text(text) -class SpecialRange(NamedRange): - special_range_cutoff = 0 - - # TODO: remove class SpecialRange, earliest 3 releases after 0.4.3 - def __new__(cls, value: int) -> SpecialRange: - from Utils import deprecate - deprecate(f"Option type {cls.__name__} is a subclass of SpecialRange, which is deprecated and pending removal. " - "Consider switching to NamedRange, which supports all use-cases of SpecialRange, and more. In " - "NamedRange, range_start specifies the lower end of the regular range, while special values can be " - "placed anywhere (below, inside, or above the regular range).") - return super().__new__(cls) - - @classmethod - def weighted_range(cls, text) -> Range: - if text == "random-low": - return cls(cls.triangular(cls.special_range_cutoff, cls.range_end, cls.special_range_cutoff)) - elif text == "random-high": - return cls(cls.triangular(cls.special_range_cutoff, cls.range_end, cls.range_end)) - elif text == "random-middle": - return cls(cls.triangular(cls.special_range_cutoff, cls.range_end)) - elif text.startswith("random-range-"): - return cls.custom_range(text) - elif text == "random": - return cls(random.randint(cls.special_range_cutoff, cls.range_end)) - else: - raise Exception(f"random text \"{text}\" did not resolve to a recognized pattern. " - f"Acceptable values are: random, random-high, random-middle, random-low, " - f"random-range-low--, random-range-middle--, " - f"random-range-high--, or random-range--.") - - class FreezeValidKeys(AssembleOptions): def __new__(mcs, name, bases, attrs): + assert not "_valid_keys" in attrs, "'_valid_keys' gets set by FreezeValidKeys, define 'valid_keys' instead." if "valid_keys" in attrs: attrs["_valid_keys"] = frozenset(attrs["valid_keys"]) return super(FreezeValidKeys, mcs).__new__(mcs, name, bases, attrs) @@ -932,6 +897,228 @@ class ItemSet(OptionSet): convert_name_groups = True +class PlandoText(typing.NamedTuple): + at: str + text: typing.List[str] + percentage: int = 100 + + +PlandoTextsFromAnyType = typing.Union[ + typing.Iterable[typing.Union[typing.Mapping[str, typing.Any], PlandoText, typing.Any]], typing.Any +] + + +class PlandoTexts(Option[typing.List[PlandoText]], VerifyKeys): + default = () + supports_weighting = False + display_name = "Plando Texts" + + def __init__(self, value: typing.Iterable[PlandoText]) -> None: + self.value = list(deepcopy(value)) + super().__init__() + + def verify(self, world: typing.Type[World], player_name: str, plando_options: "PlandoOptions") -> None: + from BaseClasses import PlandoOptions + if self.value and not (PlandoOptions.texts & plando_options): + # plando is disabled but plando options were given so overwrite the options + self.value = [] + logging.warning(f"The plando texts module is turned off, " + f"so text for {player_name} will be ignored.") + + @classmethod + def from_any(cls, data: PlandoTextsFromAnyType) -> Self: + texts: typing.List[PlandoText] = [] + if isinstance(data, typing.Iterable): + for text in data: + if isinstance(text, typing.Mapping): + if random.random() < float(text.get("percentage", 100)/100): + at = text.get("at", None) + if at is not None: + given_text = text.get("text", []) + if isinstance(given_text, str): + given_text = [given_text] + texts.append(PlandoText( + at, + given_text, + text.get("percentage", 100) + )) + elif isinstance(text, PlandoText): + if random.random() < float(text.percentage/100): + texts.append(text) + else: + raise Exception(f"Cannot create plando text from non-dictionary type, got {type(text)}") + cls.verify_keys([text.at for text in texts]) + return cls(texts) + else: + raise NotImplementedError(f"Cannot Convert from non-list, got {type(data)}") + + @classmethod + def get_option_name(cls, value: typing.List[PlandoText]) -> str: + return str({text.at: " ".join(text.text) for text in value}) + + def __iter__(self) -> typing.Iterator[PlandoText]: + yield from self.value + + def __getitem__(self, index: typing.SupportsIndex) -> PlandoText: + return self.value.__getitem__(index) + + def __len__(self) -> int: + return self.value.__len__() + + +class ConnectionsMeta(AssembleOptions): + def __new__(mcs, name: str, bases: tuple[type, ...], attrs: dict[str, typing.Any]): + if name != "PlandoConnections": + assert "entrances" in attrs, f"Please define valid entrances for {name}" + attrs["entrances"] = frozenset((connection.lower() for connection in attrs["entrances"])) + assert "exits" in attrs, f"Please define valid exits for {name}" + attrs["exits"] = frozenset((connection.lower() for connection in attrs["exits"])) + if "__doc__" not in attrs: + attrs["__doc__"] = PlandoConnections.__doc__ + cls = super().__new__(mcs, name, bases, attrs) + return cls + + +class PlandoConnection(typing.NamedTuple): + class Direction: + entrance = "entrance" + exit = "exit" + both = "both" + + entrance: str + exit: str + direction: typing.Literal["entrance", "exit", "both"] # TODO: convert Direction to StrEnum once 3.8 is dropped + percentage: int = 100 + + +PlandoConFromAnyType = typing.Union[ + typing.Iterable[typing.Union[typing.Mapping[str, typing.Any], PlandoConnection, typing.Any]], typing.Any +] + + +class PlandoConnections(Option[typing.List[PlandoConnection]], metaclass=ConnectionsMeta): + """Generic connections plando. Format is: + - entrance: "Entrance Name" + exit: "Exit Name" + direction: "Direction" + percentage: 100 + Direction must be one of 'entrance', 'exit', or 'both', and defaults to 'both' if omitted. + Percentage is an integer from 1 to 100, and defaults to 100 when omitted.""" + + display_name = "Plando Connections" + + default = () + supports_weighting = False + + entrances: typing.ClassVar[typing.AbstractSet[str]] + exits: typing.ClassVar[typing.AbstractSet[str]] + + duplicate_exits: bool = False + """Whether or not exits should be allowed to be duplicate.""" + + def __init__(self, value: typing.Iterable[PlandoConnection]): + self.value = list(deepcopy(value)) + super(PlandoConnections, self).__init__() + + @classmethod + def validate_entrance_name(cls, entrance: str) -> bool: + return entrance.lower() in cls.entrances + + @classmethod + def validate_exit_name(cls, exit: str) -> bool: + return exit.lower() in cls.exits + + @classmethod + def can_connect(cls, entrance: str, exit: str) -> bool: + """Checks that a given entrance can connect to a given exit. + By default, this will always return true unless overridden.""" + return True + + @classmethod + def validate_plando_connections(cls, connections: typing.Iterable[PlandoConnection]) -> None: + used_entrances: typing.List[str] = [] + used_exits: typing.List[str] = [] + for connection in connections: + entrance = connection.entrance + exit = connection.exit + direction = connection.direction + if direction not in (PlandoConnection.Direction.entrance, + PlandoConnection.Direction.exit, + PlandoConnection.Direction.both): + raise ValueError(f"Unknown direction: {direction}") + if entrance in used_entrances: + raise ValueError(f"Duplicate Entrance {entrance} not allowed.") + if not cls.duplicate_exits and exit in used_exits: + raise ValueError(f"Duplicate Exit {exit} not allowed.") + used_entrances.append(entrance) + used_exits.append(exit) + if not cls.validate_entrance_name(entrance): + raise ValueError(f"{entrance.title()} is not a valid entrance.") + if not cls.validate_exit_name(exit): + raise ValueError(f"{exit.title()} is not a valid exit.") + if not cls.can_connect(entrance, exit): + raise ValueError(f"Connection between {entrance.title()} and {exit.title()} is invalid.") + + @classmethod + def from_any(cls, data: PlandoConFromAnyType) -> Self: + if not isinstance(data, typing.Iterable): + raise Exception(f"Cannot create plando connections from non-List value, got {type(data)}.") + + value: typing.List[PlandoConnection] = [] + for connection in data: + if isinstance(connection, typing.Mapping): + percentage = connection.get("percentage", 100) + if random.random() < float(percentage / 100): + entrance = connection.get("entrance", None) + if is_iterable_except_str(entrance): + entrance = random.choice(sorted(entrance)) + exit = connection.get("exit", None) + if is_iterable_except_str(exit): + exit = random.choice(sorted(exit)) + direction = connection.get("direction", "both") + + if not entrance or not exit: + raise Exception("Plando connection must have an entrance and an exit.") + value.append(PlandoConnection( + entrance, + exit, + direction, + percentage + )) + elif isinstance(connection, PlandoConnection): + if random.random() < float(connection.percentage / 100): + value.append(connection) + else: + raise Exception(f"Cannot create connection from non-Dict type, got {type(connection)}.") + cls.validate_plando_connections(value) + return cls(value) + + def verify(self, world: typing.Type[World], player_name: str, plando_options: "PlandoOptions") -> None: + from BaseClasses import PlandoOptions + if self.value and not (PlandoOptions.connections & plando_options): + # plando is disabled but plando options were given so overwrite the options + self.value = [] + logging.warning(f"The plando connections module is turned off, " + f"so connections for {player_name} will be ignored.") + + @classmethod + def get_option_name(cls, value: typing.List[PlandoConnection]) -> str: + return ", ".join(["%s %s %s" % (connection.entrance, + "<=>" if connection.direction == PlandoConnection.Direction.both else + "<=" if connection.direction == PlandoConnection.Direction.exit else + "=>", + connection.exit) for connection in value]) + + def __getitem__(self, index: typing.SupportsIndex) -> PlandoConnection: + return self.value.__getitem__(index) + + def __iter__(self) -> typing.Iterator[PlandoConnection]: + yield from self.value + + def __len__(self) -> int: + return len(self.value) + + class Accessibility(Choice): """Set rules for reachability of your items/locations. Locations: ensure everything can be reached and acquired. @@ -946,8 +1133,10 @@ class Accessibility(Choice): class ProgressionBalancing(NamedRange): - """A system that can move progression earlier, to try and prevent the player from getting stuck and bored early. - A lower setting means more getting stuck. A higher setting means less getting stuck.""" + """ + A system that can move progression earlier, to try and prevent the player from getting stuck and bored early. + A lower setting means more getting stuck. A higher setting means less getting stuck. + """ default = 50 range_start = 0 range_end = 99 @@ -984,7 +1173,7 @@ class CommonOptions(metaclass=OptionsMetaProperty): def as_dict(self, *option_names: str, casing: str = "snake") -> typing.Dict[str, typing.Any]: """ Returns a dictionary of [str, Option.value] - + :param option_names: names of the options to return :param casing: case of the keys to return. Supports `snake`, `camel`, `pascal`, `kebab` """ @@ -1020,7 +1209,7 @@ class LocalItems(ItemSet): class NonLocalItems(ItemSet): """Forces these items to be outside their native world.""" - display_name = "Not Local Items" + display_name = "Non-local Items" class StartInventory(ItemDict): @@ -1083,7 +1272,8 @@ class ItemLinks(OptionList): ]) @staticmethod - def verify_items(items: typing.List[str], item_link: str, pool_name: str, world, allow_item_groups: bool = True) -> typing.Set: + def verify_items(items: typing.List[str], item_link: str, pool_name: str, world, + allow_item_groups: bool = True) -> typing.Set: pool = set() for item_name in items: if item_name not in world.item_names and (not allow_item_groups or item_name not in world.item_name_groups): @@ -1160,7 +1350,47 @@ class DeathLinkMixin: death_link: DeathLink -def generate_yaml_templates(target_folder: typing.Union[str, "pathlib.Path"], generate_hidden: bool = True): +class OptionGroup(typing.NamedTuple): + """Define a grouping of options.""" + name: str + """Name of the group to categorize these options in for display on the WebHost and in generated YAMLS.""" + options: typing.List[typing.Type[Option[typing.Any]]] + """Options to be in the defined group.""" + start_collapsed: bool = False + """Whether the group will start collapsed on the WebHost options pages.""" + + +item_and_loc_options = [LocalItems, NonLocalItems, StartInventory, StartInventoryPool, StartHints, + StartLocationHints, ExcludeLocations, PriorityLocations, ItemLinks] +""" +Options that are always populated in "Item & Location Options" Option Group. Cannot be moved to another group. +If desired, a custom "Item & Location Options" Option Group can be defined, but only for adding additional options to +it. +""" + + +def get_option_groups(world: typing.Type[World], visibility_level: Visibility = Visibility.template) -> typing.Dict[ + str, typing.Dict[str, typing.Type[Option[typing.Any]]]]: + """Generates and returns a dictionary for the option groups of a specified world.""" + option_groups = {option: option_group.name + for option_group in world.web.option_groups + for option in option_group.options} + # add a default option group for uncategorized options to get thrown into + ordered_groups = ["Game Options"] + [ordered_groups.append(group) for group in option_groups.values() if group not in ordered_groups] + grouped_options = {group: {} for group in ordered_groups} + for option_name, option in world.options_dataclass.type_hints.items(): + if visibility_level & option.visibility: + grouped_options[option_groups.get(option, "Game Options")][option_name] = option + + # if the world doesn't have any ungrouped options, this group will be empty so just remove it + if not grouped_options["Game Options"]: + del grouped_options["Game Options"] + + return grouped_options + + +def generate_yaml_templates(target_folder: typing.Union[str, "pathlib.Path"], generate_hidden: bool = True) -> None: import os import yaml @@ -1198,15 +1428,11 @@ def dictify_range(option: Range): for game_name, world in AutoWorldRegister.world_types.items(): if not world.hidden or generate_hidden: - all_options: typing.Dict[str, AssembleOptions] = { - option_name: option for option_name, option in world.options_dataclass.type_hints.items() - if option.visibility & Visibility.template - } - + grouped_options = get_option_groups(world) with open(local_path("data", "options.yaml")) as f: file_data = f.read() res = Template(file_data).render( - options=all_options, + option_groups=grouped_options, __version__=__version__, game=game_name, yaml_dump=yaml.dump, dictify_range=dictify_range, ) diff --git a/README.md b/README.md index cbfdf75f05b7..cebd4f7e7529 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # [Archipelago](https://archipelago.gg) ![Discord Shield](https://discordapp.com/api/guilds/731205301247803413/widget.png?style=shield) | [Install](https://github.com/ArchipelagoMW/Archipelago/releases) -Archipelago provides a generic framework for developing multiworld capability for game randomizers. In all cases, presently, Archipelago is also the randomizer itself. +Archipelago provides a generic framework for developing multiworld capability for game randomizers. In all cases, +presently, Archipelago is also the randomizer itself. Currently, the following games are supported: + * The Legend of Zelda: A Link to the Past * Factorio * Minecraft @@ -65,6 +67,11 @@ Currently, the following games are supported: * Castlevania 64 * A Short Hike * Yoshi's Island +* Mario & Luigi: Superstar Saga +* Bomb Rush Cyberfunk +* Aquaria +* Yu-Gi-Oh! Ultimate Masters: World Championship Tournament 2006 +* A Hat in Time For setup and instructions check out our [tutorials page](https://archipelago.gg/tutorial/). Downloads can be found at [Releases](https://github.com/ArchipelagoMW/Archipelago/releases), including compiled @@ -72,36 +79,57 @@ windows binaries. ## History -Archipelago is built upon a strong legacy of brilliant hobbyists. We want to honor that legacy by showing it here. The repositories which Archipelago is built upon, inspired by, or otherwise owes its gratitude to are: +Archipelago is built upon a strong legacy of brilliant hobbyists. We want to honor that legacy by showing it here. +The repositories which Archipelago is built upon, inspired by, or otherwise owes its gratitude to are: * [bonta0's MultiWorld](https://github.com/Bonta0/ALttPEntranceRandomizer/tree/multiworld_31) * [AmazingAmpharos' Entrance Randomizer](https://github.com/AmazingAmpharos/ALttPEntranceRandomizer) * [VT Web Randomizer](https://github.com/sporchia/alttp_vt_randomizer) * [Dessyreqt's alttprandomizer](https://github.com/Dessyreqt/alttprandomizer) -* [Zarby89's](https://github.com/Ijwu/Enemizer/commits?author=Zarby89) and [sosuke3's](https://github.com/Ijwu/Enemizer/commits?author=sosuke3) contributions to Enemizer, which make the vast majority of Enemizer contributions. +* [Zarby89's](https://github.com/Ijwu/Enemizer/commits?author=Zarby89) + and [sosuke3's](https://github.com/Ijwu/Enemizer/commits?author=sosuke3) contributions to Enemizer, which make up the + vast majority of Enemizer contributions. -We recognize that there is a strong community of incredibly smart people that have come before us and helped pave the path. Just because one person's name may be in a repository title does not mean that only one person made that project happen. We can't hope to perfectly cover every single contribution that lead up to Archipelago but we hope to honor them fairly. +We recognize that there is a strong community of incredibly smart people that have come before us and helped pave the +path. Just because one person's name may be in a repository title does not mean that only one person made that project +happen. We can't hope to perfectly cover every single contribution that lead up to Archipelago, but we hope to honor +them fairly. ### Path to the Archipelago -Archipelago was directly forked from bonta0's `multiworld_31` branch of ALttPEntranceRandomizer (this project has a long legacy of its own, please check it out linked above) on January 12, 2020. The repository was then named to _MultiWorld-Utilities_ to better encompass its intended function. As Archipelago matured, then known as "Berserker's MultiWorld" by some, we found it necessary to transform our repository into a root level repository (as opposed to a 'forked repo') and change the name (which came later) to better reflect our project. + +Archipelago was directly forked from bonta0's `multiworld_31` branch of ALttPEntranceRandomizer (this project has a +long legacy of its own, please check it out linked above) on January 12, 2020. The repository was then named to +_MultiWorld-Utilities_ to better encompass its intended function. As Archipelago matured, then known as +"Berserker's MultiWorld" by some, we found it necessary to transform our repository into a root level repository +(as opposed to a 'forked repo') and change the name (which came later) to better reflect our project. ## Running Archipelago -For most people, all you need to do is head over to the [releases](https://github.com/ArchipelagoMW/Archipelago/releases) page then download and run the appropriate installer, or AppImage for Linux-based systems. -If you are a developer or are running on a platform with no compiled releases available, please see our doc on [running Archipelago from source](docs/running%20from%20source.md). +For most people, all you need to do is head over to +the [releases page](https://github.com/ArchipelagoMW/Archipelago/releases), then download and run the appropriate +installer, or AppImage for Linux-based systems. + +If you are a developer or are running on a platform with no compiled releases available, please see our doc on +[running Archipelago from source](docs/running%20from%20source.md). ## Related Repositories -This project makes use of multiple other projects. We wouldn't be here without these other repositories and the contributions of their developers, past and present. + +This project makes use of multiple other projects. We wouldn't be here without these other repositories and the +contributions of their developers, past and present. * [z3randomizer](https://github.com/ArchipelagoMW/z3randomizer) * [Enemizer](https://github.com/Ijwu/Enemizer) * [Ocarina of Time Randomizer](https://github.com/TestRunnerSRL/OoT-Randomizer) ## Contributing -For contribution guidelines, please see our [Contributing doc.](/docs/contributing.md) + +To contribute to Archipelago, including the WebHost, core program, or by adding a new game, see our +[Contributing guidelines](/docs/contributing.md). ## FAQ -For Frequently asked questions, please see the website's [FAQ Page.](https://archipelago.gg/faq/en/) + +For Frequently asked questions, please see the website's [FAQ Page](https://archipelago.gg/faq/en/). ## Code of Conduct -Please refer to our [code of conduct.](/docs/code_of_conduct.md) + +Please refer to our [code of conduct](/docs/code_of_conduct.md). diff --git a/SNIClient.py b/SNIClient.py index 9fdddc99a3c3..222ed54f5cc5 100644 --- a/SNIClient.py +++ b/SNIClient.py @@ -565,7 +565,7 @@ async def snes_write(ctx: SNIContext, write_list: typing.List[typing.Tuple[int, PutAddress_Request: SNESRequest = {"Opcode": "PutAddress", "Operands": [], 'Space': 'SNES'} try: for address, data in write_list: - PutAddress_Request['Operands'] = [hex(address)[2:], hex(min(len(data), 256))[2:]] + PutAddress_Request['Operands'] = [hex(address)[2:], hex(len(data))[2:]] if ctx.snes_socket is not None: await ctx.snes_socket.send(dumps(PutAddress_Request)) await ctx.snes_socket.send(data) diff --git a/UndertaleClient.py b/UndertaleClient.py index e1538ce81d2e..cdc21c561ab8 100644 --- a/UndertaleClient.py +++ b/UndertaleClient.py @@ -247,8 +247,8 @@ async def process_undertale_cmd(ctx: UndertaleContext, cmd: str, args: dict): with open(os.path.join(ctx.save_game_folder, filename), "w") as f: toDraw = "" for i in range(20): - if i < len(str(ctx.item_names[l.item])): - toDraw += str(ctx.item_names[l.item])[i] + if i < len(str(ctx.item_names.lookup_in_slot(l.item))): + toDraw += str(ctx.item_names.lookup_in_slot(l.item))[i] else: break f.write(toDraw) diff --git a/Utils.py b/Utils.py index 141b1dc7f8c6..f89330cf7c65 100644 --- a/Utils.py +++ b/Utils.py @@ -46,7 +46,7 @@ def as_simple_string(self) -> str: return ".".join(str(item) for item in self) -__version__ = "0.4.6" +__version__ = "0.5.0" version_tuple = tuplize_version(__version__) is_linux = sys.platform.startswith("linux") @@ -101,8 +101,7 @@ def cache_self1(function: typing.Callable[[S, T], RetType]) -> typing.Callable[[ @functools.wraps(function) def wrap(self: S, arg: T) -> RetType: - cache: Optional[Dict[T, RetType]] = typing.cast(Optional[Dict[T, RetType]], - getattr(self, cache_name, None)) + cache: Optional[Dict[T, RetType]] = getattr(self, cache_name, None) if cache is None: res = function(self, arg) setattr(self, cache_name, {arg: res}) @@ -209,10 +208,11 @@ def output_path(*path: str) -> str: def open_file(filename: typing.Union[str, "pathlib.Path"]) -> None: if is_windows: - os.startfile(filename) + os.startfile(filename) # type: ignore else: from shutil import which open_command = which("open") if is_macos else (which("xdg-open") or which("gnome-open") or which("kde-open")) + assert open_command, "Didn't find program for open_file! Please report this together with system details." subprocess.call([open_command, filename]) @@ -300,21 +300,21 @@ def get_options() -> Settings: return get_settings() -def persistent_store(category: str, key: typing.Any, value: typing.Any): +def persistent_store(category: str, key: str, value: typing.Any): path = user_path("_persistent_storage.yaml") - storage: dict = persistent_load() - category = storage.setdefault(category, {}) - category[key] = value + storage = persistent_load() + category_dict = storage.setdefault(category, {}) + category_dict[key] = value with open(path, "wt") as f: f.write(dump(storage, Dumper=Dumper)) -def persistent_load() -> typing.Dict[str, dict]: - storage = getattr(persistent_load, "storage", None) +def persistent_load() -> Dict[str, Dict[str, Any]]: + storage: Union[Dict[str, Dict[str, Any]], None] = getattr(persistent_load, "storage", None) if storage: return storage path = user_path("_persistent_storage.yaml") - storage: dict = {} + storage = {} if os.path.exists(path): try: with open(path, "r") as f: @@ -323,7 +323,7 @@ def persistent_load() -> typing.Dict[str, dict]: logging.debug(f"Could not read store: {e}") if storage is None: storage = {} - persistent_load.storage = storage + setattr(persistent_load, "storage", storage) return storage @@ -365,6 +365,7 @@ def store_data_package_for_checksum(game: str, data: typing.Dict[str, Any]) -> N except Exception as e: logging.debug(f"Could not store data package: {e}") + def get_default_adjuster_settings(game_name: str) -> Namespace: import LttPAdjuster adjuster_settings = Namespace() @@ -383,7 +384,9 @@ def get_adjuster_settings(game_name: str) -> Namespace: default_settings = get_default_adjuster_settings(game_name) # Fill in any arguments from the argparser that we haven't seen before - return Namespace(**vars(adjuster_settings), **{k:v for k,v in vars(default_settings).items() if k not in vars(adjuster_settings)}) + return Namespace(**vars(adjuster_settings), **{ + k: v for k, v in vars(default_settings).items() if k not in vars(adjuster_settings) + }) @cache_argsless @@ -407,13 +410,13 @@ def get_unique_identifier(): class RestrictedUnpickler(pickle.Unpickler): generic_properties_module: Optional[object] - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: super(RestrictedUnpickler, self).__init__(*args, **kwargs) self.options_module = importlib.import_module("Options") self.net_utils_module = importlib.import_module("NetUtils") self.generic_properties_module = None - def find_class(self, module, name): + def find_class(self, module: str, name: str) -> type: if module == "builtins" and name in safe_builtins: return getattr(builtins, name) # used by MultiServer -> savegame/multidata @@ -437,7 +440,7 @@ def find_class(self, module, name): raise pickle.UnpicklingError(f"global '{module}.{name}' is forbidden") -def restricted_loads(s): +def restricted_loads(s: bytes) -> Any: """Helper function analogous to pickle.loads().""" return RestrictedUnpickler(io.BytesIO(s)).load() @@ -455,6 +458,15 @@ class KeyedDefaultDict(collections.defaultdict): """defaultdict variant that uses the missing key as argument to default_factory""" default_factory: typing.Callable[[typing.Any], typing.Any] + def __init__(self, + default_factory: typing.Callable[[Any], Any] = None, + seq: typing.Union[typing.Mapping, typing.Iterable, None] = None, + **kwargs): + if seq is not None: + super().__init__(default_factory, seq, **kwargs) + else: + super().__init__(default_factory, **kwargs) + def __missing__(self, key): self[key] = value = self.default_factory(key) return value @@ -493,7 +505,7 @@ def init_logging(name: str, loglevel: typing.Union[str, int] = logging.INFO, wri file_handler.setFormatter(logging.Formatter(log_format)) class Filter(logging.Filter): - def __init__(self, filter_name, condition): + def __init__(self, filter_name: str, condition: typing.Callable[[logging.LogRecord], bool]) -> None: super().__init__(filter_name) self.condition = condition @@ -541,10 +553,11 @@ def _cleanup(): f"Archipelago ({__version__}) logging initialized" f" on {platform.platform()}" f" running Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" + f"{' (frozen)' if is_frozen() else ''}" ) -def stream_input(stream, queue): +def stream_input(stream: typing.TextIO, queue: "asyncio.Queue[str]"): def queuer(): while 1: try: @@ -572,7 +585,7 @@ class VersionException(Exception): pass -def chaining_prefix(index: int, labels: typing.Tuple[str]) -> str: +def chaining_prefix(index: int, labels: typing.Sequence[str]) -> str: text = "" max_label = len(labels) - 1 while index > max_label: @@ -595,7 +608,7 @@ def format_SI_prefix(value, power=1000, power_labels=("", "k", "M", "G", "T", "P return f"{value.quantize(decimal.Decimal('1.00'))} {chaining_prefix(n, power_labels)}" -def get_fuzzy_results(input_word: str, wordlist: typing.Sequence[str], limit: typing.Optional[int] = None) \ +def get_fuzzy_results(input_word: str, word_list: typing.Collection[str], limit: typing.Optional[int] = None) \ -> typing.List[typing.Tuple[str, int]]: import jellyfish @@ -603,21 +616,55 @@ def get_fuzzy_ratio(word1: str, word2: str) -> float: return (1 - jellyfish.damerau_levenshtein_distance(word1.lower(), word2.lower()) / max(len(word1), len(word2))) - limit: int = limit if limit else len(wordlist) + limit = limit if limit else len(word_list) return list( map( lambda container: (container[0], int(container[1]*100)), # convert up to limit to int % sorted( - map(lambda candidate: - (candidate, get_fuzzy_ratio(input_word, candidate)), - wordlist), + map(lambda candidate: (candidate, get_fuzzy_ratio(input_word, candidate)), word_list), key=lambda element: element[1], - reverse=True)[0:limit] + reverse=True + )[0:limit] ) ) -def open_filename(title: str, filetypes: typing.Sequence[typing.Tuple[str, typing.Sequence[str]]], suggest: str = "") \ +def get_intended_text(input_text: str, possible_answers) -> typing.Tuple[str, bool, str]: + picks = get_fuzzy_results(input_text, possible_answers, limit=2) + if len(picks) > 1: + dif = picks[0][1] - picks[1][1] + if picks[0][1] == 100: + return picks[0][0], True, "Perfect Match" + elif picks[0][1] < 75: + return picks[0][0], False, f"Didn't find something that closely matches '{input_text}', " \ + f"did you mean '{picks[0][0]}'? ({picks[0][1]}% sure)" + elif dif > 5: + return picks[0][0], True, "Close Match" + else: + return picks[0][0], False, f"Too many close matches for '{input_text}', " \ + f"did you mean '{picks[0][0]}'? ({picks[0][1]}% sure)" + else: + if picks[0][1] > 90: + return picks[0][0], True, "Only Option Match" + else: + return picks[0][0], False, f"Didn't find something that closely matches '{input_text}', " \ + f"did you mean '{picks[0][0]}'? ({picks[0][1]}% sure)" + + +def get_input_text_from_response(text: str, command: str) -> typing.Optional[str]: + if "did you mean " in text: + for question in ("Didn't find something that closely matches", + "Too many close matches"): + if text.startswith(question): + name = get_text_between(text, "did you mean '", + "'? (") + return f"!{command} {name}" + elif text.startswith("Missing: "): + return text.replace("Missing: ", "!hint_location ") + return None + + +def open_filename(title: str, filetypes: typing.Iterable[typing.Tuple[str, typing.Iterable[str]]], suggest: str = "") \ -> typing.Optional[str]: logging.info(f"Opening file input dialog for {title}.") @@ -734,7 +781,7 @@ def is_kivy_running(): root.update() -def title_sorted(data: typing.Sequence, key=None, ignore: typing.Set = frozenset(("a", "the"))): +def title_sorted(data: typing.Iterable, key=None, ignore: typing.AbstractSet[str] = frozenset(("a", "the"))): """Sorts a sequence of text ignoring typical articles like "a" or "the" in the beginning.""" def sorter(element: Union[str, Dict[str, Any]]) -> str: if (not isinstance(element, str)): @@ -788,7 +835,7 @@ class DeprecateDict(dict): log_message: str should_error: bool - def __init__(self, message, error: bool = False) -> None: + def __init__(self, message: str, error: bool = False) -> None: self.log_message = message self.should_error = error super().__init__() diff --git a/WargrooveClient.py b/WargrooveClient.py index 77180502cefc..c5fdeb3532f5 100644 --- a/WargrooveClient.py +++ b/WargrooveClient.py @@ -176,7 +176,7 @@ def on_package(self, cmd: str, args: dict): if not os.path.isfile(path): open(path, 'w').close() # Announcing commander unlocks - item_name = self.item_names[network_item.item] + item_name = self.item_names.lookup_in_slot(network_item.item) if item_name in faction_table.keys(): for commander in faction_table[item_name]: logger.info(f"{commander.name} has been unlocked!") @@ -197,7 +197,7 @@ def on_package(self, cmd: str, args: dict): open(print_path, 'w').close() with open(print_path, 'w') as f: f.write("Received " + - self.item_names[network_item.item] + + self.item_names.lookup_in_slot(network_item.item) + " from " + self.player_names[network_item.player]) f.close() @@ -342,7 +342,7 @@ def update_commander_data(self): faction_items = 0 faction_item_names = [faction + ' Commanders' for faction in faction_table.keys()] for network_item in self.items_received: - if self.item_names[network_item.item] in faction_item_names: + if self.item_names.lookup_in_slot(network_item.item) in faction_item_names: faction_items += 1 starting_groove = (faction_items - 1) * self.starting_groove_multiplier # Must be an integer larger than 0 diff --git a/WebHost.py b/WebHost.py index 8ccf6b68c2ee..afacd6288ec2 100644 --- a/WebHost.py +++ b/WebHost.py @@ -12,6 +12,9 @@ import Utils import settings +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 settings.no_gui = True configpath = os.path.abspath("config.yaml") @@ -19,7 +22,7 @@ configpath = os.path.abspath(Utils.user_path('config.yaml')) -def get_app(): +def get_app() -> "Flask": from WebHostLib import register, cache, app as raw_app from WebHostLib.models import db @@ -117,7 +120,7 @@ def create_ordered_tutorials_file() -> typing.List[typing.Dict[str, typing.Any]] logging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO) from WebHostLib.lttpsprites import update_sprites_lttp - from WebHostLib.autolauncher import autohost, autogen + from WebHostLib.autolauncher import autohost, autogen, stop from WebHostLib.options import create as create_options_files try: @@ -138,3 +141,11 @@ def create_ordered_tutorials_file() -> typing.List[typing.Dict[str, typing.Any]] else: from waitress import serve serve(app, port=app.config["PORT"], threads=app.config["WAITRESS_THREADS"]) + else: + from time import sleep + try: + while True: + sleep(1) # wait for process to be killed + except (SystemExit, KeyboardInterrupt): + pass + stop() # stop worker threads diff --git a/WebHostLib/__init__.py b/WebHostLib/__init__.py index 69314c334ee5..fdf3037fe015 100644 --- a/WebHostLib/__init__.py +++ b/WebHostLib/__init__.py @@ -23,6 +23,7 @@ app.config["SELFHOST"] = True # application process is in charge of running the websites app.config["GENERATORS"] = 8 # maximum concurrent world gens +app.config["HOSTERS"] = 8 # maximum concurrent room hosters app.config["SELFLAUNCH"] = True # application process is in charge of launching Rooms. app.config["SELFLAUNCHCERT"] = None # can point to a SSL Certificate to encrypt Room websocket connections app.config["SELFLAUNCHKEY"] = None # can point to a SSL Certificate Key to encrypt Room websocket connections @@ -83,6 +84,6 @@ def register(): from WebHostLib.customserver import run_server_process # to trigger app routing picking up on it - from . import tracker, upload, landing, check, generate, downloads, api, stats, misc, robots + from . import tracker, upload, landing, check, generate, downloads, api, stats, misc, robots, options app.register_blueprint(api.api_endpoints) diff --git a/WebHostLib/api/__init__.py b/WebHostLib/api/__init__.py index cfdbe25ff2fe..4003243a281d 100644 --- a/WebHostLib/api/__init__.py +++ b/WebHostLib/api/__init__.py @@ -5,7 +5,6 @@ from flask import Blueprint, abort, url_for import worlds.Files -from .. import cache from ..models import Room, Seed api_endpoints = Blueprint('api', __name__, url_prefix="/api") @@ -49,30 +48,4 @@ def supports_apdeltapatch(game: str): } -@api_endpoints.route('/datapackage') -@cache.cached() -def get_datapackage(): - from worlds import network_data_package - return network_data_package - - -@api_endpoints.route('/datapackage_version') -@cache.cached() -def get_datapackage_versions(): - from worlds import AutoWorldRegister - - version_package = {game: world.data_version for game, world in AutoWorldRegister.world_types.items()} - return version_package - - -@api_endpoints.route('/datapackage_checksum') -@cache.cached() -def get_datapackage_checksums(): - from worlds import network_data_package - version_package = { - game: game_data["checksum"] for game, game_data in network_data_package["games"].items() - } - return version_package - - -from . import generate, user # trigger registration +from . import generate, user, datapackage # trigger registration diff --git a/WebHostLib/api/datapackage.py b/WebHostLib/api/datapackage.py new file mode 100644 index 000000000000..3fb472d95dfd --- /dev/null +++ b/WebHostLib/api/datapackage.py @@ -0,0 +1,32 @@ +from flask import abort + +from Utils import restricted_loads +from WebHostLib import cache +from WebHostLib.models import GameDataPackage +from . import api_endpoints + + +@api_endpoints.route('/datapackage') +@cache.cached() +def get_datapackage(): + from worlds import network_data_package + return network_data_package + + +@api_endpoints.route('/datapackage/') +@cache.memoize(timeout=3600) +def get_datapackage_by_checksum(checksum: str): + package = GameDataPackage.get(checksum=checksum) + if package: + return restricted_loads(package.data) + return abort(404) + + +@api_endpoints.route('/datapackage_checksum') +@cache.cached() +def get_datapackage_checksums(): + from worlds import network_data_package + version_package = { + game: game_data["checksum"] for game, game_data in network_data_package["games"].items() + } + return version_package diff --git a/WebHostLib/autolauncher.py b/WebHostLib/autolauncher.py index 7254dd46e136..08a1309ebc73 100644 --- a/WebHostLib/autolauncher.py +++ b/WebHostLib/autolauncher.py @@ -3,26 +3,25 @@ import json import logging import multiprocessing -import threading -import time import typing -from uuid import UUID from datetime import timedelta, datetime +from threading import Event, Thread +from uuid import UUID from pony.orm import db_session, select, commit from Utils import restricted_loads from .locker import Locker, AlreadyRunningException +_stop_event = Event() -def launch_room(room: Room, config: dict): - # requires db_session! - if room.last_activity >= datetime.utcnow() - timedelta(seconds=room.timeout): - multiworld = multiworlds.get(room.id, None) - if not multiworld: - multiworld = MultiworldInstance(room, config) - multiworld.start() +def stop(): + """Stops previously launched threads""" + global _stop_event + stop_event = _stop_event + _stop_event = Event() # new event for new threads + stop_event.set() def handle_generation_success(seed_id): @@ -59,39 +58,50 @@ def init_db(pony_config: dict): db.generate_mapping() +def cleanup(): + """delete unowned user-content""" + with db_session: + # >>> bool(uuid.UUID(int=0)) + # True + rooms = Room.select(lambda room: room.owner == UUID(int=0)).delete(bulk=True) + seeds = Seed.select(lambda seed: seed.owner == UUID(int=0) and not seed.rooms).delete(bulk=True) + slots = Slot.select(lambda slot: not slot.seed).delete(bulk=True) + # Command gets deleted by ponyorm Cascade Delete, as Room is Required + if rooms or seeds or slots: + logging.info(f"{rooms} Rooms, {seeds} Seeds and {slots} Slots have been deleted.") + + def autohost(config: dict): def keep_running(): + stop_event = _stop_event try: with Locker("autohost"): - # delete unowned user-content - with db_session: - # >>> bool(uuid.UUID(int=0)) - # True - rooms = Room.select(lambda room: room.owner == UUID(int=0)).delete(bulk=True) - seeds = Seed.select(lambda seed: seed.owner == UUID(int=0) and not seed.rooms).delete(bulk=True) - slots = Slot.select(lambda slot: not slot.seed).delete(bulk=True) - # Command gets deleted by ponyorm Cascade Delete, as Room is Required - if rooms or seeds or slots: - logging.info(f"{rooms} Rooms, {seeds} Seeds and {slots} Slots have been deleted.") - run_guardian() - while 1: - time.sleep(0.1) + cleanup() + hosters = [] + for x in range(config["HOSTERS"]): + hoster = MultiworldInstance(config, x) + hosters.append(hoster) + hoster.start() + + while not stop_event.wait(0.1): with db_session: rooms = select( room for room in Room if room.last_activity >= datetime.utcnow() - timedelta(days=3)) for room in rooms: - launch_room(room, config) + # we have to filter twice, as the per-room timeout can't currently be PonyORM transpiled. + if room.last_activity >= datetime.utcnow() - timedelta(seconds=room.timeout + 5): + hosters[room.id.int % len(hosters)].start_room(room.id) except AlreadyRunningException: logging.info("Autohost reports as already running, not starting another.") - import threading - threading.Thread(target=keep_running, name="AP_Autohost").start() + Thread(target=keep_running, name="AP_Autohost").start() def autogen(config: dict): def keep_running(): + stop_event = _stop_event try: with Locker("autogen"): @@ -112,8 +122,7 @@ def keep_running(): commit() select(generation for generation in Generation if generation.state == STATE_ERROR).delete() - while 1: - time.sleep(0.1) + while not stop_event.wait(0.1): with db_session: # for update locks the database row(s) during transaction, preventing writes from elsewhere to_start = select( @@ -124,37 +133,45 @@ def keep_running(): except AlreadyRunningException: logging.info("Autogen reports as already running, not starting another.") - import threading - threading.Thread(target=keep_running, name="AP_Autogen").start() + Thread(target=keep_running, name="AP_Autogen").start() multiworlds: typing.Dict[type(Room.id), MultiworldInstance] = {} class MultiworldInstance(): - def __init__(self, room: Room, config: dict): - self.room_id = room.id + def __init__(self, config: dict, id: int): + self.room_ids = set() self.process: typing.Optional[multiprocessing.Process] = None - with guardian_lock: - multiworlds[self.room_id] = self self.ponyconfig = config["PONY"] self.cert = config["SELFLAUNCHCERT"] self.key = config["SELFLAUNCHKEY"] self.host = config["HOST_ADDRESS"] + self.rooms_to_start = multiprocessing.Queue() + self.rooms_shutting_down = multiprocessing.Queue() + self.name = f"MultiHoster{id}" def start(self): if self.process and self.process.is_alive(): return False - logging.info(f"Spinning up {self.room_id}") process = multiprocessing.Process(group=None, target=run_server_process, - args=(self.room_id, self.ponyconfig, get_static_server_data(), - self.cert, self.key, self.host), - name="MultiHost") + args=(self.name, self.ponyconfig, get_static_server_data(), + self.cert, self.key, self.host, + self.rooms_to_start, self.rooms_shutting_down), + name=self.name) process.start() - # bind after start to prevent thread sync issues with guardian. self.process = process + def start_room(self, room_id): + while not self.rooms_shutting_down.empty(): + self.room_ids.remove(self.rooms_shutting_down.get(block=True, timeout=None)) + if room_id in self.room_ids: + pass # should already be hosted currently. + else: + self.room_ids.add(room_id) + self.rooms_to_start.put(room_id) + def stop(self): if self.process: self.process.terminate() @@ -168,40 +185,6 @@ def collect(self): self.process = None -guardian = None -guardian_lock = threading.Lock() - - -def run_guardian(): - global guardian - global multiworlds - with guardian_lock: - if not guardian: - try: - import resource - except ModuleNotFoundError: - pass # unix only module - else: - # Each Server is another file handle, so request as many as we can from the system - file_limit = resource.getrlimit(resource.RLIMIT_NOFILE)[1] - # set soft limit to hard limit - resource.setrlimit(resource.RLIMIT_NOFILE, (file_limit, file_limit)) - - def guard(): - while 1: - time.sleep(1) - done = [] - with guardian_lock: - for key, instance in multiworlds.items(): - if instance.done(): - instance.collect() - done.append(key) - for key in done: - del (multiworlds[key]) - - guardian = threading.Thread(name="Guardian", target=guard) - - from .models import Room, Generation, STATE_QUEUED, STATE_STARTED, STATE_ERROR, db, Seed, Slot from .customserver import run_server_process, get_static_server_data from .generate import gen_game diff --git a/WebHostLib/customserver.py b/WebHostLib/customserver.py index fb3b314753cf..9f70165b61e5 100644 --- a/WebHostLib/customserver.py +++ b/WebHostLib/customserver.py @@ -5,6 +5,7 @@ import datetime import functools import logging +import multiprocessing import pickle import random import socket @@ -53,17 +54,19 @@ def _cmd_video(self, platform: str, user: str): class DBCommandProcessor(ServerCommandProcessor): def output(self, text: str): - logging.info(text) + self.ctx.logger.info(text) class WebHostContext(Context): room_id: int - def __init__(self, static_server_data: dict): + def __init__(self, static_server_data: dict, logger: logging.Logger): # static server data is used during _load_game_data to load required data, # without needing to import worlds system, which takes quite a bit of memory self.static_server_data = static_server_data - super(WebHostContext, self).__init__("", 0, "", "", 1, 40, True, "enabled", "enabled", "enabled", 0, 2) + super(WebHostContext, self).__init__("", 0, "", "", 1, + 40, True, "enabled", "enabled", + "enabled", 0, 2, logger=logger) del self.static_server_data self.main_loop = asyncio.get_running_loop() self.video = {} @@ -71,6 +74,7 @@ def __init__(self, static_server_data: dict): def _load_game_data(self): for key, value in self.static_server_data.items(): + # NOTE: attributes are mutable and shared, so they will have to be copied before being modified setattr(self, key, value) self.non_hintable_names = collections.defaultdict(frozenset, self.non_hintable_names) @@ -98,18 +102,37 @@ def load(self, room_id: int): multidata = self.decompress(room.seed.multidata) game_data_packages = {} + + static_gamespackage = self.gamespackage # this is shared across all rooms + static_item_name_groups = self.item_name_groups + static_location_name_groups = self.location_name_groups + self.gamespackage = {"Archipelago": static_gamespackage.get("Archipelago", {})} # this may be modified by _load + self.item_name_groups = {"Archipelago": static_item_name_groups.get("Archipelago", {})} + self.location_name_groups = {"Archipelago": static_location_name_groups.get("Archipelago", {})} + for game in list(multidata.get("datapackage", {})): game_data = multidata["datapackage"][game] if "checksum" in game_data: - if self.gamespackage.get(game, {}).get("checksum") == game_data["checksum"]: - # non-custom. remove from multidata + if static_gamespackage.get(game, {}).get("checksum") == game_data["checksum"]: + # non-custom. remove from multidata and use static data # games package could be dropped from static data once all rooms embed data package del multidata["datapackage"][game] else: row = GameDataPackage.get(checksum=game_data["checksum"]) if row: # None if rolled on >= 0.3.9 but uploaded to <= 0.3.8. multidata should be complete game_data_packages[game] = Utils.restricted_loads(row.data) - + continue + else: + self.logger.warning(f"Did not find game_data_package for {game}: {game_data['checksum']}") + self.gamespackage[game] = static_gamespackage.get(game, {}) + self.item_name_groups[game] = static_item_name_groups.get(game, {}) + self.location_name_groups[game] = static_location_name_groups.get(game, {}) + + if not game_data_packages: + # all static -> use the static dicts directly + self.gamespackage = static_gamespackage + self.item_name_groups = static_item_name_groups + self.location_name_groups = static_location_name_groups return self._load(multidata, game_data_packages, True) @db_session @@ -119,7 +142,7 @@ def init_save(self, enabled: bool = True): savegame_data = Room.get(id=self.room_id).multisave if savegame_data: self.set_save(restricted_loads(Room.get(id=self.room_id).multisave)) - self._start_async_saving() + self._start_async_saving(atexit_save=False) threading.Thread(target=self.listen_to_db_commands, daemon=True).start() @db_session @@ -145,86 +168,176 @@ def get_random_port(): def get_static_server_data() -> dict: import worlds data = { - "non_hintable_names": {}, - "gamespackage": worlds.network_data_package["games"], - "item_name_groups": {world_name: world.item_name_groups for world_name, world in - worlds.AutoWorldRegister.world_types.items()}, - "location_name_groups": {world_name: world.location_name_groups for world_name, world in - worlds.AutoWorldRegister.world_types.items()}, + "non_hintable_names": { + world_name: world.hint_blacklist + for world_name, world in worlds.AutoWorldRegister.world_types.items() + }, + "gamespackage": { + world_name: { + key: value + for key, value in game_package.items() + if key not in ("item_name_groups", "location_name_groups") + } + for world_name, game_package in worlds.network_data_package["games"].items() + }, + "item_name_groups": { + world_name: world.item_name_groups + for world_name, world in worlds.AutoWorldRegister.world_types.items() + }, + "location_name_groups": { + world_name: world.location_name_groups + for world_name, world in worlds.AutoWorldRegister.world_types.items() + }, } - for world_name, world in worlds.AutoWorldRegister.world_types.items(): - data["non_hintable_names"][world_name] = world.hint_blacklist - return data -def run_server_process(room_id, ponyconfig: dict, static_server_data: dict, +def set_up_logging(room_id) -> logging.Logger: + import os + # logger setup + logger = logging.getLogger(f"RoomLogger {room_id}") + + # this *should* be empty, but just in case. + for handler in logger.handlers[:]: + logger.removeHandler(handler) + handler.close() + + file_handler = logging.FileHandler( + os.path.join(Utils.user_path("logs"), f"{room_id}.txt"), + "a", + encoding="utf-8-sig") + file_handler.setFormatter(logging.Formatter("[%(asctime)s]: %(message)s")) + logger.setLevel(logging.INFO) + logger.addHandler(file_handler) + return logger + + +def run_server_process(name: str, ponyconfig: dict, static_server_data: dict, cert_file: typing.Optional[str], cert_key_file: typing.Optional[str], - host: str): + host: str, rooms_to_run: multiprocessing.Queue, rooms_shutting_down: multiprocessing.Queue): + Utils.init_logging(name) + try: + import resource + except ModuleNotFoundError: + pass # unix only module + else: + # Each Server is another file handle, so request as many as we can from the system + file_limit = resource.getrlimit(resource.RLIMIT_NOFILE)[1] + # set soft limit to hard limit + resource.setrlimit(resource.RLIMIT_NOFILE, (file_limit, file_limit)) + del resource, file_limit + # establish DB connection for multidata and multisave db.bind(**ponyconfig) db.generate_mapping(check_tables=False) - async def main(): - if "worlds" in sys.modules: - raise Exception("Worlds system should not be loaded in the custom server.") - - import gc - Utils.init_logging(str(room_id), write_mode="a") - ctx = WebHostContext(static_server_data) - ctx.load(room_id) - ctx.init_save() - ssl_context = load_server_cert(cert_file, cert_key_file) if cert_file else None - gc.collect() # free intermediate objects used during setup - try: - ctx.server = websockets.serve(functools.partial(server, ctx=ctx), ctx.host, ctx.port, ssl=ssl_context) - - await ctx.server - except OSError: # likely port in use - ctx.server = websockets.serve(functools.partial(server, ctx=ctx), ctx.host, 0, ssl=ssl_context) - - await ctx.server - port = 0 - for wssocket in ctx.server.ws_server.sockets: - socketname = wssocket.getsockname() - if wssocket.family == socket.AF_INET6: - # Prefer IPv4, as most users seem to not have working ipv6 support - if not port: - port = socketname[1] - elif wssocket.family == socket.AF_INET: - port = socketname[1] - if port: - logging.info(f'Hosting game at {host}:{port}') - with db_session: - room = Room.get(id=ctx.room_id) - room.last_port = port - else: - logging.exception("Could not determine port. Likely hosting failure.") - with db_session: - ctx.auto_shutdown = Room.get(id=room_id).timeout - ctx.shutdown_task = asyncio.create_task(auto_shutdown(ctx, [])) - await ctx.shutdown_task - - # ensure auto launch is on the same page in regard to room activity. - with db_session: - room: Room = Room.get(id=ctx.room_id) - room.last_activity = datetime.datetime.utcnow() - datetime.timedelta(seconds=room.timeout + 60) - - logging.info("Shutting down") - - with Locker(room_id): - try: - asyncio.run(main()) - except (KeyboardInterrupt, SystemExit): - with db_session: - room = Room.get(id=room_id) - # ensure the Room does not spin up again on its own, minute of safety buffer - room.last_activity = datetime.datetime.utcnow() - datetime.timedelta(minutes=1, seconds=room.timeout) - except Exception: - with db_session: - room = Room.get(id=room_id) - room.last_port = -1 - # ensure the Room does not spin up again on its own, minute of safety buffer - room.last_activity = datetime.datetime.utcnow() - datetime.timedelta(minutes=1, seconds=room.timeout) - raise + if "worlds" in sys.modules: + raise Exception("Worlds system should not be loaded in the custom server.") + + import gc + ssl_context = load_server_cert(cert_file, cert_key_file) if cert_file else None + del cert_file, cert_key_file, ponyconfig + gc.collect() # free intermediate objects used during setup + + loop = asyncio.get_event_loop() + + async def start_room(room_id): + with Locker(f"RoomLocker {room_id}"): + try: + logger = set_up_logging(room_id) + ctx = WebHostContext(static_server_data, logger) + ctx.load(room_id) + ctx.init_save() + try: + ctx.server = websockets.serve( + functools.partial(server, ctx=ctx), ctx.host, ctx.port, ssl=ssl_context) + + await ctx.server + except OSError: # likely port in use + ctx.server = websockets.serve( + functools.partial(server, ctx=ctx), ctx.host, 0, ssl=ssl_context) + + await ctx.server + port = 0 + for wssocket in ctx.server.ws_server.sockets: + socketname = wssocket.getsockname() + if wssocket.family == socket.AF_INET6: + # Prefer IPv4, as most users seem to not have working ipv6 support + if not port: + port = socketname[1] + elif wssocket.family == socket.AF_INET: + port = socketname[1] + if port: + ctx.logger.info(f'Hosting game at {host}:{port}') + with db_session: + room = Room.get(id=ctx.room_id) + room.last_port = port + else: + ctx.logger.exception("Could not determine port. Likely hosting failure.") + with db_session: + ctx.auto_shutdown = Room.get(id=room_id).timeout + if ctx.saving: + setattr(asyncio.current_task(), "save", lambda: ctx._save(True)) + ctx.shutdown_task = asyncio.create_task(auto_shutdown(ctx, [])) + await ctx.shutdown_task + + except (KeyboardInterrupt, SystemExit): + if ctx.saving: + ctx._save() + setattr(asyncio.current_task(), "save", None) + except Exception as e: + with db_session: + room = Room.get(id=room_id) + room.last_port = -1 + logger.exception(e) + raise + else: + if ctx.saving: + ctx._save() + setattr(asyncio.current_task(), "save", None) + finally: + try: + ctx.save_dirty = False # make sure the saving thread does not write to DB after final wakeup + ctx.exit_event.set() # make sure the saving thread stops at some point + # NOTE: async saving should probably be an async task and could be merged with shutdown_task + with (db_session): + # ensure the Room does not spin up again on its own, minute of safety buffer + room = Room.get(id=room_id) + room.last_activity = datetime.datetime.utcnow() - \ + datetime.timedelta(minutes=1, seconds=room.timeout) + logging.info(f"Shutting down room {room_id} on {name}.") + finally: + await asyncio.sleep(5) + rooms_shutting_down.put(room_id) + + class Starter(threading.Thread): + _tasks: typing.List[asyncio.Future] + + def __init__(self): + super().__init__() + self._tasks = [] + + def _done(self, task: asyncio.Future): + self._tasks.remove(task) + task.result() + + def run(self): + while 1: + next_room = rooms_to_run.get(block=True, timeout=None) + task = asyncio.run_coroutine_threadsafe(start_room(next_room), loop) + self._tasks.append(task) + task.add_done_callback(self._done) + logging.info(f"Starting room {next_room} on {name}.") + + starter = Starter() + starter.daemon = True + starter.start() + try: + loop.run_forever() + finally: + # save all tasks that want to be saved during shutdown + for task in asyncio.all_tasks(loop): + save: typing.Optional[typing.Callable[[], typing.Any]] = getattr(task, "save", None) + if save: + save() diff --git a/WebHostLib/generate.py b/WebHostLib/generate.py index ee1ce591ee84..a12dc0f4ae14 100644 --- a/WebHostLib/generate.py +++ b/WebHostLib/generate.py @@ -6,7 +6,7 @@ import tempfile import zipfile from collections import Counter -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, Union, Set from flask import flash, redirect, render_template, request, session, url_for from pony.orm import commit, db_session @@ -16,6 +16,7 @@ from Main import main as ERmain from Utils import __version__ from WebHostLib import app +from settings import ServerOptions, GeneratorOptions from worlds.alttp.EntranceRandomizer import parse_arguments from .check import get_yaml_data, roll_options from .models import Generation, STATE_ERROR, STATE_QUEUED, Seed, UUID @@ -23,25 +24,22 @@ def get_meta(options_source: dict, race: bool = False) -> Dict[str, Union[List[str], Dict[str, Any]]]: - plando_options = { - options_source.get("plando_bosses", ""), - options_source.get("plando_items", ""), - options_source.get("plando_connections", ""), - options_source.get("plando_texts", "") - } - plando_options -= {""} + plando_options: Set[str] = set() + for substr in ("bosses", "items", "connections", "texts"): + if options_source.get(f"plando_{substr}", substr in GeneratorOptions.plando_options): + plando_options.add(substr) server_options = { - "hint_cost": int(options_source.get("hint_cost", 10)), - "release_mode": options_source.get("release_mode", "goal"), - "remaining_mode": options_source.get("remaining_mode", "disabled"), - "collect_mode": options_source.get("collect_mode", "disabled"), - "item_cheat": bool(int(options_source.get("item_cheat", 1))), + "hint_cost": int(options_source.get("hint_cost", ServerOptions.hint_cost)), + "release_mode": options_source.get("release_mode", ServerOptions.release_mode), + "remaining_mode": options_source.get("remaining_mode", ServerOptions.remaining_mode), + "collect_mode": options_source.get("collect_mode", ServerOptions.collect_mode), + "item_cheat": bool(int(options_source.get("item_cheat", not ServerOptions.disable_item_cheat))), "server_password": options_source.get("server_password", None), } generator_options = { - "spoiler": int(options_source.get("spoiler", 0)), - "race": race + "spoiler": int(options_source.get("spoiler", GeneratorOptions.spoiler)), + "race": race, } if race: @@ -70,35 +68,39 @@ def generate(race=False): flash(options) else: meta = get_meta(request.form, race) - results, gen_options = roll_options(options, set(meta["plando_options"])) - - if any(type(result) == str for result in results.values()): - return render_template("checkResult.html", results=results) - elif len(gen_options) > app.config["MAX_ROLL"]: - flash(f"Sorry, generating of multiworlds is limited to {app.config['MAX_ROLL']} players. " - f"If you have a larger group, please generate it yourself and upload it.") - elif len(gen_options) >= app.config["JOB_THRESHOLD"]: - gen = Generation( - options=pickle.dumps({name: vars(options) for name, options in gen_options.items()}), - # convert to json compatible - meta=json.dumps(meta), - state=STATE_QUEUED, - owner=session["_id"]) - commit() + return start_generation(options, meta) + + return render_template("generate.html", race=race, version=__version__) - return redirect(url_for("wait_seed", seed=gen.id)) - else: - try: - seed_id = gen_game({name: vars(options) for name, options in gen_options.items()}, - meta=meta, owner=session["_id"].int) - except BaseException as e: - from .autolauncher import handle_generation_failure - handle_generation_failure(e) - return render_template("seedError.html", seed_error=(e.__class__.__name__ + ": " + str(e))) - return redirect(url_for("view_seed", seed=seed_id)) +def start_generation(options: Dict[str, Union[dict, str]], meta: Dict[str, Any]): + results, gen_options = roll_options(options, set(meta["plando_options"])) + + if any(type(result) == str for result in results.values()): + return render_template("checkResult.html", results=results) + elif len(gen_options) > app.config["MAX_ROLL"]: + flash(f"Sorry, generating of multiworlds is limited to {app.config['MAX_ROLL']} players. " + f"If you have a larger group, please generate it yourself and upload it.") + elif len(gen_options) >= app.config["JOB_THRESHOLD"]: + gen = Generation( + options=pickle.dumps({name: vars(options) for name, options in gen_options.items()}), + # convert to json compatible + meta=json.dumps(meta), + state=STATE_QUEUED, + owner=session["_id"]) + commit() + + return redirect(url_for("wait_seed", seed=gen.id)) + else: + try: + seed_id = gen_game({name: vars(options) for name, options in gen_options.items()}, + meta=meta, owner=session["_id"].int) + except BaseException as e: + from .autolauncher import handle_generation_failure + handle_generation_failure(e) + return render_template("seedError.html", seed_error=(e.__class__.__name__ + ": " + str(e))) - return render_template("generate.html", race=race, version=__version__) + return redirect(url_for("view_seed", seed=seed_id)) def gen_game(gen_options: dict, meta: Optional[Dict[str, Any]] = None, owner=None, sid=None): diff --git a/WebHostLib/misc.py b/WebHostLib/misc.py index ec461e7d47bd..5072f113bd54 100644 --- a/WebHostLib/misc.py +++ b/WebHostLib/misc.py @@ -37,25 +37,6 @@ def start_playing(): return render_template(f"startPlaying.html") -# TODO for back compat. remove around 0.4.5 -@app.route("/weighted-settings") -def weighted_settings(): - return redirect("weighted-options", 301) - - -@app.route("/weighted-options") -@cache.cached() -def weighted_options(): - return render_template("weighted-options.html") - - -# Player options pages -@app.route("/games//player-options") -@cache.cached() -def player_options(game: str): - return render_template("player-options.html", game=game, theme=get_world_theme(game)) - - # Game Info Pages @app.route('/games//info/') @cache.cached() @@ -150,6 +131,7 @@ def host_room(room: UUID): if cmd: Command(room=room, commandtext=cmd) commit() + return redirect(url_for("host_room", room=room.id)) now = datetime.datetime.utcnow() # indicate that the page should reload to get the assigned port diff --git a/WebHostLib/options.py b/WebHostLib/options.py index b3fd8d612ac0..53c3a6151b82 100644 --- a/WebHostLib/options.py +++ b/WebHostLib/options.py @@ -1,205 +1,257 @@ +import collections.abc import json -import logging import os -import typing +from textwrap import dedent +from typing import Dict, Union + +import yaml +from flask import redirect, render_template, request, Response import Options from Utils import local_path from worlds.AutoWorld import AutoWorldRegister - -handled_in_js = {"start_inventory", "local_items", "non_local_items", "start_hints", "start_location_hints", - "exclude_locations", "priority_locations"} +from . import app, cache +from .generate import get_meta -def create(): +def create() -> None: target_folder = local_path("WebHostLib", "static", "generated") yaml_folder = os.path.join(target_folder, "configs") Options.generate_yaml_templates(yaml_folder) - def get_html_doc(option_type: type(Options.Option)) -> str: - if not option_type.__doc__: - return "Please document me!" - return "\n".join(line.strip() for line in option_type.__doc__.split("\n")).strip() - - weighted_options = { - "baseOptions": { - "description": "Generated by https://archipelago.gg/", - "name": "", - "game": {}, - }, - "games": {}, - } - - for game_name, world in AutoWorldRegister.world_types.items(): - - all_options: typing.Dict[str, Options.AssembleOptions] = world.options_dataclass.type_hints - - # Generate JSON files for player-options pages - player_options = { - "baseOptions": { - "description": f"Generated by https://archipelago.gg/ for {game_name}", - "game": game_name, - "name": "", - }, - } - game_options = {} - visible: typing.Set[str] = set() - visible_weighted: typing.Set[str] = set() - - for option_name, option in all_options.items(): - if option.visibility & Options.Visibility.simple_ui: - visible.add(option_name) - if option.visibility & Options.Visibility.complex_ui: - visible_weighted.add(option_name) - - if option_name in handled_in_js: - pass - - elif issubclass(option, Options.Choice) or issubclass(option, Options.Toggle): - game_options[option_name] = this_option = { - "type": "select", - "displayName": option.display_name if hasattr(option, "display_name") else option_name, - "description": get_html_doc(option), - "defaultValue": None, - "options": [] - } - - for sub_option_id, sub_option_name in option.name_lookup.items(): - if sub_option_name != "random": - this_option["options"].append({ - "name": option.get_option_name(sub_option_id), - "value": sub_option_name, - }) - if sub_option_id == option.default: - this_option["defaultValue"] = sub_option_name - - if not this_option["defaultValue"]: - this_option["defaultValue"] = "random" - - elif issubclass(option, Options.Range): - game_options[option_name] = { - "type": "range", - "displayName": option.display_name if hasattr(option, "display_name") else option_name, - "description": get_html_doc(option), - "defaultValue": option.default if hasattr( - option, "default") and option.default != "random" else option.range_start, - "min": option.range_start, - "max": option.range_end, - } - - if issubclass(option, Options.NamedRange): - game_options[option_name]["type"] = 'named_range' - game_options[option_name]["value_names"] = {} - for key, val in option.special_range_names.items(): - game_options[option_name]["value_names"][key] = val - - elif issubclass(option, Options.ItemSet): - game_options[option_name] = { - "type": "items-list", - "displayName": option.display_name if hasattr(option, "display_name") else option_name, - "description": get_html_doc(option), - "defaultValue": list(option.default) - } - - elif issubclass(option, Options.LocationSet): - game_options[option_name] = { - "type": "locations-list", - "displayName": option.display_name if hasattr(option, "display_name") else option_name, - "description": get_html_doc(option), - "defaultValue": list(option.default) - } - - elif issubclass(option, Options.VerifyKeys) and not issubclass(option, Options.OptionDict): - if option.valid_keys: - game_options[option_name] = { - "type": "custom-list", - "displayName": option.display_name if hasattr(option, "display_name") else option_name, - "description": get_html_doc(option), - "options": list(option.valid_keys), - "defaultValue": list(option.default) if hasattr(option, "default") else [] - } +def get_world_theme(game_name: str) -> str: + if game_name in AutoWorldRegister.world_types: + return AutoWorldRegister.world_types[game_name].web.theme + return 'grass' + + +def render_options_page(template: str, world_name: str, is_complex: bool = False) -> Union[Response, str]: + world = AutoWorldRegister.world_types[world_name] + if world.hidden or world.web.options_page is False: + return redirect("games") + visibility_flag = Options.Visibility.complex_ui if is_complex else Options.Visibility.simple_ui + + start_collapsed = {"Game Options": False} + for group in world.web.option_groups: + start_collapsed[group.name] = group.start_collapsed + + return render_template( + template, + world_name=world_name, + world=world, + option_groups=Options.get_option_groups(world, visibility_level=visibility_flag), + start_collapsed=start_collapsed, + issubclass=issubclass, + Options=Options, + theme=get_world_theme(world_name), + ) + + +def generate_game(options: Dict[str, Union[dict, str]]) -> Union[Response, str]: + from .generate import start_generation + return start_generation(options, get_meta({})) + + +def send_yaml(player_name: str, formatted_options: dict) -> Response: + response = Response(yaml.dump(formatted_options, sort_keys=False)) + response.headers["Content-Type"] = "text/yaml" + response.headers["Content-Disposition"] = f"attachment; filename={player_name}.yaml" + return response + + +@app.template_filter("dedent") +def filter_dedent(text: str) -> str: + return dedent(text).strip("\n ") + + +@app.template_test("ordered") +def test_ordered(obj): + return isinstance(obj, collections.abc.Sequence) + + +@app.route("/games//option-presets", methods=["GET"]) +@cache.cached() +def option_presets(game: str) -> Response: + world = AutoWorldRegister.world_types[game] + + presets = {} + for preset_name, preset in world.web.options_presets.items(): + presets[preset_name] = {} + for preset_option_name, preset_option in preset.items(): + if preset_option == "random": + presets[preset_name][preset_option_name] = preset_option + continue + + option = world.options_dataclass.type_hints[preset_option_name].from_any(preset_option) + if isinstance(option, Options.NamedRange) and isinstance(preset_option, str): + assert preset_option in option.special_range_names, \ + f"Invalid preset value '{preset_option}' for '{preset_option_name}' in '{preset_name}'. " \ + f"Expected {option.special_range_names.keys()} or {option.range_start}-{option.range_end}." + + presets[preset_name][preset_option_name] = option.value + elif isinstance(option, (Options.Range, Options.OptionSet, Options.OptionList, Options.ItemDict)): + presets[preset_name][preset_option_name] = option.value + elif isinstance(preset_option, str): + # Ensure the option value is valid for Choice and Toggle options + assert option.name_lookup[option.value] == preset_option, \ + f"Invalid option value '{preset_option}' for '{preset_option_name}' in preset '{preset_name}'. " \ + f"Values must not be resolved to a different option via option.from_text (or an alias)." + # Use the name of the option + presets[preset_name][preset_option_name] = option.current_key + else: + # Use the name of the option + presets[preset_name][preset_option_name] = option.current_key + + class SetEncoder(json.JSONEncoder): + def default(self, obj): + from collections.abc import Set + if isinstance(obj, Set): + return list(obj) + return json.JSONEncoder.default(self, obj) + + json_data = json.dumps(presets, cls=SetEncoder) + response = Response(json_data) + response.headers["Content-Type"] = "application/json" + return response + + +@app.route("/weighted-options") +def weighted_options_old(): + return redirect("games", 301) + + +@app.route("/games//weighted-options") +@cache.cached() +def weighted_options(game: str): + return render_options_page("weightedOptions/weightedOptions.html", game, is_complex=True) + +@app.route("/games//generate-weighted-yaml", methods=["POST"]) +def generate_weighted_yaml(game: str): + if request.method == "POST": + intent_generate = False + options = {} + + for key, val in request.form.items(): + if "||" not in key: + if len(str(val)) == 0: + continue + + options[key] = val else: - logging.debug(f"{option} not exported to Web Options.") - - player_options["presetOptions"] = {} - for preset_name, preset in world.web.options_presets.items(): - player_options["presetOptions"][preset_name] = {} - for option_name, option_value in preset.items(): - # Random range type settings are not valid. - assert (not str(option_value).startswith("random-")), \ - f"Invalid preset value '{option_value}' for '{option_name}' in '{preset_name}'. Special random " \ - f"values are not supported for presets." - - # Normal random is supported, but needs to be handled explicitly. - if option_value == "random": - player_options["presetOptions"][preset_name][option_name] = option_value + if int(val) == 0: continue - option = world.options_dataclass.type_hints[option_name].from_any(option_value) - if isinstance(option, Options.NamedRange) and isinstance(option_value, str): - assert option_value in option.special_range_names, \ - f"Invalid preset value '{option_value}' for '{option_name}' in '{preset_name}'. " \ - f"Expected {option.special_range_names.keys()} or {option.range_start}-{option.range_end}." - - # Still use the true value for the option, not the name. - player_options["presetOptions"][preset_name][option_name] = option.value - elif isinstance(option, Options.Range): - player_options["presetOptions"][preset_name][option_name] = option.value - elif isinstance(option_value, str): - # For Choice and Toggle options, the value should be the name of the option. This is to prevent - # setting a preset for an option with an overridden from_text method that would normally be okay, - # but would not be okay for the webhost's current implementation of player options UI. - assert option.name_lookup[option.value] == option_value, \ - f"Invalid option value '{option_value}' for '{option_name}' in preset '{preset_name}'. " \ - f"Values must not be resolved to a different option via option.from_text (or an alias)." - player_options["presetOptions"][preset_name][option_name] = option.current_key - else: - # int and bool values are fine, just resolve them to the current key for webhost. - player_options["presetOptions"][preset_name][option_name] = option.current_key - - os.makedirs(os.path.join(target_folder, 'player-options'), exist_ok=True) - - filtered_player_options = player_options - filtered_player_options["gameOptions"] = { - option_name: option_data for option_name, option_data in game_options.items() - if option_name in visible + [option, setting] = key.split("||") + options.setdefault(option, {})[setting] = int(val) + + # Error checking + if "name" not in options: + return "Player name is required." + + # Remove POST data irrelevant to YAML + if "intent-generate" in options: + intent_generate = True + del options["intent-generate"] + if "intent-export" in options: + del options["intent-export"] + + # Properly format YAML output + player_name = options["name"] + del options["name"] + + formatted_options = { + "name": player_name, + "game": game, + "description": f"Generated by https://archipelago.gg/ for {game}", + game: options, } - with open(os.path.join(target_folder, 'player-options', game_name + ".json"), "w") as f: - json.dump(filtered_player_options, f, indent=2, separators=(',', ': ')) + if intent_generate: + return generate_game({player_name: formatted_options}) + + else: + return send_yaml(player_name, formatted_options) - filtered_player_options["gameOptions"] = { - option_name: option_data for option_name, option_data in game_options.items() - if option_name in visible_weighted + +# Player options pages +@app.route("/games//player-options") +@cache.cached() +def player_options(game: str): + return render_options_page("playerOptions/playerOptions.html", game, is_complex=False) + + +# YAML generator for player-options +@app.route("/games//generate-yaml", methods=["POST"]) +def generate_yaml(game: str): + if request.method == "POST": + options = {} + intent_generate = False + for key, val in request.form.items(multi=True): + if key in options: + if not isinstance(options[key], list): + options[key] = [options[key]] + options[key].append(val) + else: + options[key] = val + + for key, val in options.copy().items(): + key_parts = key.rsplit("||", 2) + # Detect and build ItemDict options from their name pattern + if key_parts[-1] == "qty": + if key_parts[0] not in options: + options[key_parts[0]] = {} + if val != "0": + options[key_parts[0]][key_parts[1]] = int(val) + del options[key] + + # Detect keys which end with -custom, indicating a TextChoice with a possible custom value + elif key_parts[-1].endswith("-custom"): + if val: + options[key_parts[-1][:-7]] = val + + del options[key] + + # Detect random-* keys and set their options accordingly + for key, val in options.copy().items(): + if key.startswith("random-"): + options[key.removeprefix("random-")] = "random" + del options[key] + + # Error checking + if not options["name"]: + return "Player name is required." + + # Remove POST data irrelevant to YAML + preset_name = 'default' + if "intent-generate" in options: + intent_generate = True + del options["intent-generate"] + if "intent-export" in options: + del options["intent-export"] + if "game-options-preset" in options: + preset_name = options["game-options-preset"] + del options["game-options-preset"] + + # Properly format YAML output + player_name = options["name"] + del options["name"] + + description = f"Generated by https://archipelago.gg/ for {game}" + if preset_name != 'default' and preset_name != 'custom': + description += f" using {preset_name} preset" + + formatted_options = { + "name": player_name, + "game": game, + "description": description, + game: options, } - if not world.hidden and world.web.options_page is True: - # Add the random option to Choice, TextChoice, and Toggle options - for option in filtered_player_options["gameOptions"].values(): - if option["type"] == "select": - option["options"].append({"name": "Random", "value": "random"}) - - if not option["defaultValue"]: - option["defaultValue"] = "random" - - weighted_options["baseOptions"]["game"][game_name] = 0 - weighted_options["games"][game_name] = { - "gameSettings": filtered_player_options["gameOptions"], - "gameItems": tuple(world.item_names), - "gameItemGroups": [ - group for group in world.item_name_groups.keys() if group != "Everything" - ], - "gameItemDescriptions": world.item_descriptions, - "gameLocations": tuple(world.location_names), - "gameLocationGroups": [ - group for group in world.location_name_groups.keys() if group != "Everywhere" - ], - "gameLocationDescriptions": world.location_descriptions, - } - - with open(os.path.join(target_folder, 'weighted-options.json'), "w") as f: - json.dump(weighted_options, f, indent=2, separators=(',', ': ')) + if intent_generate: + return generate_game({player_name: formatted_options}) + else: + return send_yaml(player_name, formatted_options) diff --git a/WebHostLib/requirements.txt b/WebHostLib/requirements.txt index 62707d78cf1f..3452c9d416db 100644 --- a/WebHostLib/requirements.txt +++ b/WebHostLib/requirements.txt @@ -1,9 +1,10 @@ -flask>=3.0.0 +flask>=3.0.3 +werkzeug>=3.0.3 pony>=0.7.17 -waitress>=2.1.2 -Flask-Caching>=2.1.0 -Flask-Compress>=1.14 -Flask-Limiter>=3.5.0 +waitress>=3.0.0 +Flask-Caching>=2.3.0 +Flask-Compress>=1.15 +Flask-Limiter>=3.7.0 bokeh>=3.1.1; python_version <= '3.8' -bokeh>=3.3.2; python_version >= '3.9' -markupsafe>=2.1.3 +bokeh>=3.4.1; python_version >= '3.9' +markupsafe>=2.1.5 diff --git a/WebHostLib/static/assets/player-options.js b/WebHostLib/static/assets/player-options.js deleted file mode 100644 index 92cd6c43f3cc..000000000000 --- a/WebHostLib/static/assets/player-options.js +++ /dev/null @@ -1,523 +0,0 @@ -let gameName = null; - -window.addEventListener('load', () => { - gameName = document.getElementById('player-options').getAttribute('data-game'); - - // Update game name on page - document.getElementById('game-name').innerText = gameName; - - fetchOptionData().then((results) => { - let optionHash = localStorage.getItem(`${gameName}-hash`); - if (!optionHash) { - // If no hash data has been set before, set it now - optionHash = md5(JSON.stringify(results)); - localStorage.setItem(`${gameName}-hash`, optionHash); - localStorage.removeItem(gameName); - } - - if (optionHash !== md5(JSON.stringify(results))) { - showUserMessage( - 'Your options are out of date! Click here to update them! Be aware this will reset them all to default.' - ); - document.getElementById('user-message').addEventListener('click', resetOptions); - } - - // Page setup - createDefaultOptions(results); - buildUI(results); - adjustHeaderWidth(); - - // Event listeners - document.getElementById('export-options').addEventListener('click', () => exportOptions()); - document.getElementById('generate-race').addEventListener('click', () => generateGame(true)); - document.getElementById('generate-game').addEventListener('click', () => generateGame()); - - // Name input field - const playerOptions = JSON.parse(localStorage.getItem(gameName)); - const nameInput = document.getElementById('player-name'); - nameInput.addEventListener('keyup', (event) => updateBaseOption(event)); - nameInput.value = playerOptions.name; - - // Presets - const presetSelect = document.getElementById('game-options-preset'); - presetSelect.addEventListener('change', (event) => setPresets(results, event.target.value)); - for (const preset in results['presetOptions']) { - const presetOption = document.createElement('option'); - presetOption.innerText = preset; - presetSelect.appendChild(presetOption); - } - presetSelect.value = localStorage.getItem(`${gameName}-preset`); - results['presetOptions']['__default'] = {}; - }).catch((e) => { - console.error(e); - const url = new URL(window.location.href); - window.location.replace(`${url.protocol}//${url.hostname}/page-not-found`); - }) -}); - -const resetOptions = () => { - localStorage.removeItem(gameName); - localStorage.removeItem(`${gameName}-hash`); - localStorage.removeItem(`${gameName}-preset`); - window.location.reload(); -}; - -const fetchOptionData = () => new Promise((resolve, reject) => { - const ajax = new XMLHttpRequest(); - ajax.onreadystatechange = () => { - if (ajax.readyState !== 4) { return; } - if (ajax.status !== 200) { - reject(ajax.responseText); - return; - } - try{ resolve(JSON.parse(ajax.responseText)); } - catch(error){ reject(error); } - }; - ajax.open('GET', `${window.location.origin}/static/generated/player-options/${gameName}.json`, true); - ajax.send(); -}); - -const createDefaultOptions = (optionData) => { - if (!localStorage.getItem(gameName)) { - const newOptions = { - [gameName]: {}, - }; - for (let baseOption of Object.keys(optionData.baseOptions)){ - newOptions[baseOption] = optionData.baseOptions[baseOption]; - } - for (let gameOption of Object.keys(optionData.gameOptions)){ - newOptions[gameName][gameOption] = optionData.gameOptions[gameOption].defaultValue; - } - localStorage.setItem(gameName, JSON.stringify(newOptions)); - } - - if (!localStorage.getItem(`${gameName}-preset`)) { - localStorage.setItem(`${gameName}-preset`, '__default'); - } -}; - -const buildUI = (optionData) => { - // Game Options - const leftGameOpts = {}; - const rightGameOpts = {}; - Object.keys(optionData.gameOptions).forEach((key, index) => { - if (index < Object.keys(optionData.gameOptions).length / 2) { - leftGameOpts[key] = optionData.gameOptions[key]; - } else { - rightGameOpts[key] = optionData.gameOptions[key]; - } - }); - document.getElementById('game-options-left').appendChild(buildOptionsTable(leftGameOpts)); - document.getElementById('game-options-right').appendChild(buildOptionsTable(rightGameOpts)); -}; - -const buildOptionsTable = (options, romOpts = false) => { - const currentOptions = JSON.parse(localStorage.getItem(gameName)); - const table = document.createElement('table'); - const tbody = document.createElement('tbody'); - - Object.keys(options).forEach((option) => { - const tr = document.createElement('tr'); - - // td Left - const tdl = document.createElement('td'); - const label = document.createElement('label'); - label.textContent = `${options[option].displayName}: `; - label.setAttribute('for', option); - - const questionSpan = document.createElement('span'); - questionSpan.classList.add('interactive'); - questionSpan.setAttribute('data-tooltip', options[option].description); - questionSpan.innerText = '(?)'; - - label.appendChild(questionSpan); - tdl.appendChild(label); - tr.appendChild(tdl); - - // td Right - const tdr = document.createElement('td'); - let element = null; - - const randomButton = document.createElement('button'); - - switch(options[option].type) { - case 'select': - element = document.createElement('div'); - element.classList.add('select-container'); - let select = document.createElement('select'); - select.setAttribute('id', option); - select.setAttribute('data-key', option); - if (romOpts) { select.setAttribute('data-romOpt', '1'); } - options[option].options.forEach((opt) => { - const optionElement = document.createElement('option'); - optionElement.setAttribute('value', opt.value); - optionElement.innerText = opt.name; - - if ((isNaN(currentOptions[gameName][option]) && - (parseInt(opt.value, 10) === parseInt(currentOptions[gameName][option]))) || - (opt.value === currentOptions[gameName][option])) - { - optionElement.selected = true; - } - select.appendChild(optionElement); - }); - select.addEventListener('change', (event) => updateGameOption(event.target)); - element.appendChild(select); - - // Randomize button - randomButton.innerText = '🎲'; - randomButton.classList.add('randomize-button'); - randomButton.setAttribute('data-key', option); - randomButton.setAttribute('data-tooltip', 'Toggle randomization for this option!'); - randomButton.addEventListener('click', (event) => toggleRandomize(event, select)); - if (currentOptions[gameName][option] === 'random') { - randomButton.classList.add('active'); - select.disabled = true; - } - - element.appendChild(randomButton); - break; - - case 'range': - element = document.createElement('div'); - element.classList.add('range-container'); - - let range = document.createElement('input'); - range.setAttribute('id', option); - range.setAttribute('type', 'range'); - range.setAttribute('data-key', option); - range.setAttribute('min', options[option].min); - range.setAttribute('max', options[option].max); - range.value = currentOptions[gameName][option]; - range.addEventListener('change', (event) => { - document.getElementById(`${option}-value`).innerText = event.target.value; - updateGameOption(event.target); - }); - element.appendChild(range); - - let rangeVal = document.createElement('span'); - rangeVal.classList.add('range-value'); - rangeVal.setAttribute('id', `${option}-value`); - rangeVal.innerText = currentOptions[gameName][option] !== 'random' ? - currentOptions[gameName][option] : options[option].defaultValue; - element.appendChild(rangeVal); - - // Randomize button - randomButton.innerText = '🎲'; - randomButton.classList.add('randomize-button'); - randomButton.setAttribute('data-key', option); - randomButton.setAttribute('data-tooltip', 'Toggle randomization for this option!'); - randomButton.addEventListener('click', (event) => toggleRandomize(event, range)); - if (currentOptions[gameName][option] === 'random') { - randomButton.classList.add('active'); - range.disabled = true; - } - - element.appendChild(randomButton); - break; - - case 'named_range': - element = document.createElement('div'); - element.classList.add('named-range-container'); - - // Build the select element - let namedRangeSelect = document.createElement('select'); - namedRangeSelect.setAttribute('data-key', option); - Object.keys(options[option].value_names).forEach((presetName) => { - let presetOption = document.createElement('option'); - presetOption.innerText = presetName; - presetOption.value = options[option].value_names[presetName]; - const words = presetOption.innerText.split('_'); - for (let i = 0; i < words.length; i++) { - words[i] = words[i][0].toUpperCase() + words[i].substring(1); - } - presetOption.innerText = words.join(' '); - namedRangeSelect.appendChild(presetOption); - }); - let customOption = document.createElement('option'); - customOption.innerText = 'Custom'; - customOption.value = 'custom'; - customOption.selected = true; - namedRangeSelect.appendChild(customOption); - if (Object.values(options[option].value_names).includes(Number(currentOptions[gameName][option]))) { - namedRangeSelect.value = Number(currentOptions[gameName][option]); - } - - // Build range element - let namedRangeWrapper = document.createElement('div'); - namedRangeWrapper.classList.add('named-range-wrapper'); - let namedRange = document.createElement('input'); - namedRange.setAttribute('type', 'range'); - namedRange.setAttribute('data-key', option); - namedRange.setAttribute('min', options[option].min); - namedRange.setAttribute('max', options[option].max); - namedRange.value = currentOptions[gameName][option]; - - // Build rage value element - let namedRangeVal = document.createElement('span'); - namedRangeVal.classList.add('range-value'); - namedRangeVal.setAttribute('id', `${option}-value`); - namedRangeVal.innerText = currentOptions[gameName][option] !== 'random' ? - currentOptions[gameName][option] : options[option].defaultValue; - - // Configure select event listener - namedRangeSelect.addEventListener('change', (event) => { - if (event.target.value === 'custom') { return; } - - // Update range slider - namedRange.value = event.target.value; - document.getElementById(`${option}-value`).innerText = event.target.value; - updateGameOption(event.target); - }); - - // Configure range event handler - namedRange.addEventListener('change', (event) => { - // Update select element - namedRangeSelect.value = - (Object.values(options[option].value_names).includes(parseInt(event.target.value))) ? - parseInt(event.target.value) : 'custom'; - document.getElementById(`${option}-value`).innerText = event.target.value; - updateGameOption(event.target); - }); - - element.appendChild(namedRangeSelect); - namedRangeWrapper.appendChild(namedRange); - namedRangeWrapper.appendChild(namedRangeVal); - element.appendChild(namedRangeWrapper); - - // Randomize button - randomButton.innerText = '🎲'; - randomButton.classList.add('randomize-button'); - randomButton.setAttribute('data-key', option); - randomButton.setAttribute('data-tooltip', 'Toggle randomization for this option!'); - randomButton.addEventListener('click', (event) => toggleRandomize( - event, namedRange, namedRangeSelect) - ); - if (currentOptions[gameName][option] === 'random') { - randomButton.classList.add('active'); - namedRange.disabled = true; - namedRangeSelect.disabled = true; - } - - namedRangeWrapper.appendChild(randomButton); - break; - - default: - console.error(`Ignoring unknown option type: ${options[option].type} with name ${option}`); - return; - } - - tdr.appendChild(element); - tr.appendChild(tdr); - tbody.appendChild(tr); - }); - - table.appendChild(tbody); - return table; -}; - -const setPresets = (optionsData, presetName) => { - const defaults = optionsData['gameOptions']; - const preset = optionsData['presetOptions'][presetName]; - - localStorage.setItem(`${gameName}-preset`, presetName); - - if (!preset) { - console.error(`No presets defined for preset name: '${presetName}'`); - return; - } - - const updateOptionElement = (option, presetValue) => { - const optionElement = document.querySelector(`#${option}[data-key='${option}']`); - const randomElement = document.querySelector(`.randomize-button[data-key='${option}']`); - - if (presetValue === 'random') { - randomElement.classList.add('active'); - optionElement.disabled = true; - updateGameOption(randomElement, false); - } else { - optionElement.value = presetValue; - randomElement.classList.remove('active'); - optionElement.disabled = undefined; - updateGameOption(optionElement, false); - } - }; - - for (const option in defaults) { - let presetValue = preset[option]; - if (presetValue === undefined) { - // Using the default value if not set in presets. - presetValue = defaults[option]['defaultValue']; - } - - switch (defaults[option].type) { - case 'range': - const numberElement = document.querySelector(`#${option}-value`); - if (presetValue === 'random') { - numberElement.innerText = defaults[option]['defaultValue'] === 'random' - ? defaults[option]['min'] // A fallback so we don't print 'random' in the UI. - : defaults[option]['defaultValue']; - } else { - numberElement.innerText = presetValue; - } - - updateOptionElement(option, presetValue); - break; - - case 'select': { - updateOptionElement(option, presetValue); - break; - } - - case 'named_range': { - const selectElement = document.querySelector(`select[data-key='${option}']`); - const rangeElement = document.querySelector(`input[data-key='${option}']`); - const randomElement = document.querySelector(`.randomize-button[data-key='${option}']`); - - if (presetValue === 'random') { - randomElement.classList.add('active'); - selectElement.disabled = true; - rangeElement.disabled = true; - updateGameOption(randomElement, false); - } else { - rangeElement.value = presetValue; - selectElement.value = Object.values(defaults[option]['value_names']).includes(parseInt(presetValue)) ? - parseInt(presetValue) : 'custom'; - document.getElementById(`${option}-value`).innerText = presetValue; - - randomElement.classList.remove('active'); - selectElement.disabled = undefined; - rangeElement.disabled = undefined; - updateGameOption(rangeElement, false); - } - break; - } - - default: - console.warn(`Ignoring preset value for unknown option type: ${defaults[option].type} with name ${option}`); - break; - } - } -}; - -const toggleRandomize = (event, inputElement, optionalSelectElement = null) => { - const active = event.target.classList.contains('active'); - const randomButton = event.target; - - if (active) { - randomButton.classList.remove('active'); - inputElement.disabled = undefined; - if (optionalSelectElement) { - optionalSelectElement.disabled = undefined; - } - } else { - randomButton.classList.add('active'); - inputElement.disabled = true; - if (optionalSelectElement) { - optionalSelectElement.disabled = true; - } - } - updateGameOption(active ? inputElement : randomButton); -}; - -const updateBaseOption = (event) => { - const options = JSON.parse(localStorage.getItem(gameName)); - options[event.target.getAttribute('data-key')] = isNaN(event.target.value) ? - event.target.value : parseInt(event.target.value); - localStorage.setItem(gameName, JSON.stringify(options)); -}; - -const updateGameOption = (optionElement, toggleCustomPreset = true) => { - const options = JSON.parse(localStorage.getItem(gameName)); - - if (toggleCustomPreset) { - localStorage.setItem(`${gameName}-preset`, '__custom'); - const presetElement = document.getElementById('game-options-preset'); - presetElement.value = '__custom'; - } - - if (optionElement.classList.contains('randomize-button')) { - // If the event passed in is the randomize button, then we know what we must do. - options[gameName][optionElement.getAttribute('data-key')] = 'random'; - } else { - options[gameName][optionElement.getAttribute('data-key')] = isNaN(optionElement.value) ? - optionElement.value : parseInt(optionElement.value, 10); - } - - localStorage.setItem(gameName, JSON.stringify(options)); -}; - -const exportOptions = () => { - const options = JSON.parse(localStorage.getItem(gameName)); - const preset = localStorage.getItem(`${gameName}-preset`); - switch (preset) { - case '__default': - options['description'] = `Generated by https://archipelago.gg with the default preset.`; - break; - - case '__custom': - options['description'] = `Generated by https://archipelago.gg.`; - break; - - default: - options['description'] = `Generated by https://archipelago.gg with the ${preset} preset.`; - } - - if (!options.name || options.name.toString().trim().length === 0) { - return showUserMessage('You must enter a player name!'); - } - const yamlText = jsyaml.safeDump(options, { noCompatMode: true }).replaceAll(/'(\d+)':/g, (x, y) => `${y}:`); - download(`${document.getElementById('player-name').value}.yaml`, yamlText); -}; - -/** Create an anchor and trigger a download of a text file. */ -const download = (filename, text) => { - const downloadLink = document.createElement('a'); - downloadLink.setAttribute('href','data:text/yaml;charset=utf-8,'+ encodeURIComponent(text)) - downloadLink.setAttribute('download', filename); - downloadLink.style.display = 'none'; - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); -}; - -const generateGame = (raceMode = false) => { - const options = JSON.parse(localStorage.getItem(gameName)); - if (!options.name || options.name.toLowerCase() === 'player' || options.name.trim().length === 0) { - return showUserMessage('You must enter a player name!'); - } - - axios.post('/api/generate', { - weights: { player: options }, - presetData: { player: options }, - playerCount: 1, - spoiler: 3, - race: raceMode ? '1' : '0', - }).then((response) => { - window.location.href = response.data.url; - }).catch((error) => { - let userMessage = 'Something went wrong and your game could not be generated.'; - if (error.response.data.text) { - userMessage += ' ' + error.response.data.text; - } - showUserMessage(userMessage); - console.error(error); - }); -}; - -const showUserMessage = (message) => { - const userMessage = document.getElementById('user-message'); - userMessage.innerText = message; - userMessage.classList.add('visible'); - window.scrollTo(0, 0); - userMessage.addEventListener('click', () => { - userMessage.classList.remove('visible'); - userMessage.addEventListener('click', hideUserMessage); - }); -}; - -const hideUserMessage = () => { - const userMessage = document.getElementById('user-message'); - userMessage.classList.remove('visible'); - userMessage.removeEventListener('click', hideUserMessage); -}; diff --git a/WebHostLib/static/assets/playerOptions.js b/WebHostLib/static/assets/playerOptions.js new file mode 100644 index 000000000000..d0f2e388c2a6 --- /dev/null +++ b/WebHostLib/static/assets/playerOptions.js @@ -0,0 +1,335 @@ +let presets = {}; + +window.addEventListener('load', async () => { + // Load settings from localStorage, if available + loadSettings(); + + // Fetch presets if available + await fetchPresets(); + + // Handle changes to range inputs + document.querySelectorAll('input[type=range]').forEach((range) => { + const optionName = range.getAttribute('id'); + range.addEventListener('change', () => { + document.getElementById(`${optionName}-value`).innerText = range.value; + + // Handle updating named range selects to "custom" if appropriate + const select = document.querySelector(`select[data-option-name=${optionName}]`); + if (select) { + let updated = false; + select?.childNodes.forEach((option) => { + if (option.value === range.value) { + select.value = range.value; + updated = true; + } + }); + if (!updated) { + select.value = 'custom'; + } + } + }); + }); + + // Handle changes to named range selects + document.querySelectorAll('.named-range-container select').forEach((select) => { + const optionName = select.getAttribute('data-option-name'); + select.addEventListener('change', (evt) => { + document.getElementById(optionName).value = evt.target.value; + document.getElementById(`${optionName}-value`).innerText = evt.target.value; + }); + }); + + // Handle changes to randomize checkboxes + document.querySelectorAll('.randomize-checkbox').forEach((checkbox) => { + const optionName = checkbox.getAttribute('data-option-name'); + checkbox.addEventListener('change', () => { + const optionInput = document.getElementById(optionName); + const namedRangeSelect = document.querySelector(`select[data-option-name=${optionName}]`); + const customInput = document.getElementById(`${optionName}-custom`); + if (checkbox.checked) { + optionInput.setAttribute('disabled', '1'); + namedRangeSelect?.setAttribute('disabled', '1'); + if (customInput) { + customInput.setAttribute('disabled', '1'); + } + } else { + optionInput.removeAttribute('disabled'); + namedRangeSelect?.removeAttribute('disabled'); + if (customInput) { + customInput.removeAttribute('disabled'); + } + } + }); + }); + + // Handle changes to TextChoice input[type=text] + document.querySelectorAll('.text-choice-container input[type=text]').forEach((input) => { + const optionName = input.getAttribute('data-option-name'); + input.addEventListener('input', () => { + const select = document.getElementById(optionName); + const optionValues = []; + select.childNodes.forEach((option) => optionValues.push(option.value)); + select.value = (optionValues.includes(input.value)) ? input.value : 'custom'; + }); + }); + + // Handle changes to TextChoice select + document.querySelectorAll('.text-choice-container select').forEach((select) => { + const optionName = select.getAttribute('id'); + select.addEventListener('change', () => { + document.getElementById(`${optionName}-custom`).value = ''; + }); + }); + + // Update the "Option Preset" select to read "custom" when changes are made to relevant inputs + const presetSelect = document.getElementById('game-options-preset'); + document.querySelectorAll('input, select').forEach((input) => { + if ( // Ignore inputs which have no effect on yaml generation + (input.id === 'player-name') || + (input.id === 'game-options-preset') || + (input.classList.contains('group-toggle')) || + (input.type === 'submit') + ) { + return; + } + input.addEventListener('change', () => { + presetSelect.value = 'custom'; + }); + }); + + // Handle changes to presets select + document.getElementById('game-options-preset').addEventListener('change', choosePreset); + + // Save settings to localStorage when form is submitted + document.getElementById('options-form').addEventListener('submit', (evt) => { + const playerName = document.getElementById('player-name'); + if (!playerName.value.trim()) { + evt.preventDefault(); + window.scrollTo(0, 0); + showUserMessage('You must enter a player name!'); + } + + saveSettings(); + }); +}); + +// Save all settings to localStorage +const saveSettings = () => { + const options = { + inputs: {}, + checkboxes: {}, + }; + document.querySelectorAll('input, select').forEach((input) => { + if (input.type === 'submit') { + // Ignore submit inputs + } + else if (input.type === 'checkbox') { + options.checkboxes[input.id] = input.checked; + } + else { + options.inputs[input.id] = input.value + } + }); + const game = document.getElementById('player-options').getAttribute('data-game'); + localStorage.setItem(game, JSON.stringify(options)); +}; + +// Load all options from localStorage +const loadSettings = () => { + const game = document.getElementById('player-options').getAttribute('data-game'); + + const options = JSON.parse(localStorage.getItem(game)); + if (options) { + if (!options.inputs || !options.checkboxes) { + localStorage.removeItem(game); + return; + } + + // Restore value-based inputs and selects + Object.keys(options.inputs).forEach((key) => { + try{ + document.getElementById(key).value = options.inputs[key]; + const rangeValue = document.getElementById(`${key}-value`); + if (rangeValue) { + rangeValue.innerText = options.inputs[key]; + } + } catch (err) { + console.error(`Unable to restore value to input with id ${key}`); + } + }); + + // Restore checkboxes + Object.keys(options.checkboxes).forEach((key) => { + try{ + if (options.checkboxes[key]) { + document.getElementById(key).setAttribute('checked', '1'); + } + } catch (err) { + console.error(`Unable to restore value to input with id ${key}`); + } + }); + } + + // Ensure any input for which the randomize checkbox is checked by default, the relevant inputs are disabled + document.querySelectorAll('.randomize-checkbox').forEach((checkbox) => { + const optionName = checkbox.getAttribute('data-option-name'); + if (checkbox.checked) { + const input = document.getElementById(optionName); + if (input) { + input.setAttribute('disabled', '1'); + } + const customInput = document.getElementById(`${optionName}-custom`); + if (customInput) { + customInput.setAttribute('disabled', '1'); + } + } + }); +}; + +/** + * Fetch the preset data for this game and apply the presets if localStorage indicates one was previously chosen + * @returns {Promise} + */ +const fetchPresets = async () => { + const response = await fetch('option-presets'); + presets = await response.json(); + const presetSelect = document.getElementById('game-options-preset'); + presetSelect.removeAttribute('disabled'); + + const game = document.getElementById('player-options').getAttribute('data-game'); + const presetToApply = localStorage.getItem(`${game}-preset`); + const playerName = localStorage.getItem(`${game}-player`); + if (presetToApply) { + localStorage.removeItem(`${game}-preset`); + presetSelect.value = presetToApply; + applyPresets(presetToApply); + } + + if (playerName) { + document.getElementById('player-name').value = playerName; + localStorage.removeItem(`${game}-player`); + } +}; + +/** + * Clear the localStorage for this game and set a preset to be loaded upon page reload + * @param evt + */ +const choosePreset = (evt) => { + if (evt.target.value === 'custom') { return; } + + const game = document.getElementById('player-options').getAttribute('data-game'); + localStorage.removeItem(game); + + localStorage.setItem(`${game}-player`, document.getElementById('player-name').value); + if (evt.target.value !== 'default') { + localStorage.setItem(`${game}-preset`, evt.target.value); + } + + document.querySelectorAll('#options-form input, #options-form select').forEach((input) => { + if (input.id === 'player-name') { return; } + input.removeAttribute('value'); + }); + + window.location.replace(window.location.href); +}; + +const applyPresets = (presetName) => { + // Ignore the "default" preset, because it gets set automatically by Jinja + if (presetName === 'default') { + saveSettings(); + return; + } + + if (!presets[presetName]) { + console.error(`Unknown preset ${presetName} chosen`); + return; + } + + const preset = presets[presetName]; + Object.keys(preset).forEach((optionName) => { + const optionValue = preset[optionName]; + + // Handle List and Set options + if (Array.isArray(optionValue)) { + document.querySelectorAll(`input[type=checkbox][name=${optionName}]`).forEach((checkbox) => { + if (optionValue.includes(checkbox.value)) { + checkbox.setAttribute('checked', '1'); + } else { + checkbox.removeAttribute('checked'); + } + }); + return; + } + + // Handle Dict options + if (typeof(optionValue) === 'object' && optionValue !== null) { + const itemNames = Object.keys(optionValue); + document.querySelectorAll(`input[type=number][data-option-name=${optionName}]`).forEach((input) => { + const itemName = input.getAttribute('data-item-name'); + input.value = (itemNames.includes(itemName)) ? optionValue[itemName] : 0 + }); + return; + } + + // Identify all possible elements + const normalInput = document.getElementById(optionName); + const customInput = document.getElementById(`${optionName}-custom`); + const rangeValue = document.getElementById(`${optionName}-value`); + const randomizeInput = document.getElementById(`random-${optionName}`); + const namedRangeSelect = document.getElementById(`${optionName}-select`); + + // It is possible for named ranges to use name of a value rather than the value itself. This is accounted for here + let trueValue = optionValue; + if (namedRangeSelect) { + namedRangeSelect.querySelectorAll('option').forEach((opt) => { + if (opt.innerText.startsWith(optionValue)) { + trueValue = opt.value; + } + }); + namedRangeSelect.value = trueValue; + } + + // Handle options whose presets are "random" + if (optionValue === 'random') { + normalInput.setAttribute('disabled', '1'); + randomizeInput.setAttribute('checked', '1'); + if (customInput) { + customInput.setAttribute('disabled', '1'); + } + if (rangeValue) { + rangeValue.innerText = normalInput.value; + } + if (namedRangeSelect) { + namedRangeSelect.setAttribute('disabled', '1'); + } + return; + } + + // Handle normal (text, number, select, etc.) and custom inputs (custom inputs exist with TextChoice only) + normalInput.value = trueValue; + normalInput.removeAttribute('disabled'); + randomizeInput.removeAttribute('checked'); + if (customInput) { + document.getElementById(`${optionName}-custom`).removeAttribute('disabled'); + } + if (rangeValue) { + rangeValue.innerText = trueValue; + } + }); + + saveSettings(); +}; + +const showUserMessage = (text) => { + const userMessage = document.getElementById('user-message'); + userMessage.innerText = text; + userMessage.addEventListener('click', hideUserMessage); + userMessage.style.display = 'block'; +}; + +const hideUserMessage = () => { + const userMessage = document.getElementById('user-message'); + userMessage.removeEventListener('click', hideUserMessage); + userMessage.style.display = 'none'; +}; diff --git a/WebHostLib/static/assets/supportedGames.js b/WebHostLib/static/assets/supportedGames.js index 56eb15b5e580..b692db9283d2 100644 --- a/WebHostLib/static/assets/supportedGames.js +++ b/WebHostLib/static/assets/supportedGames.js @@ -1,18 +1,16 @@ window.addEventListener('load', () => { // Add toggle listener to all elements with .collapse-toggle - const toggleButtons = document.querySelectorAll('.collapse-toggle'); - toggleButtons.forEach((e) => e.addEventListener('click', toggleCollapse)); + const toggleButtons = document.querySelectorAll('details'); // Handle game filter input const gameSearch = document.getElementById('game-search'); gameSearch.value = ''; gameSearch.addEventListener('input', (evt) => { if (!evt.target.value.trim()) { - // If input is empty, display all collapsed games + // If input is empty, display all games as collapsed return toggleButtons.forEach((header) => { header.style.display = null; - header.firstElementChild.innerText = '▶'; - header.nextElementSibling.classList.add('collapsed'); + header.removeAttribute('open'); }); } @@ -21,12 +19,10 @@ window.addEventListener('load', () => { // If the game name includes the search string, display the game. If not, hide it if (header.getAttribute('data-game').toLowerCase().includes(evt.target.value.toLowerCase())) { header.style.display = null; - header.firstElementChild.innerText = '▼'; - header.nextElementSibling.classList.remove('collapsed'); + header.setAttribute('open', '1'); } else { header.style.display = 'none'; - header.firstElementChild.innerText = '▶'; - header.nextElementSibling.classList.add('collapsed'); + header.removeAttribute('open'); } }); }); @@ -35,30 +31,14 @@ window.addEventListener('load', () => { document.getElementById('collapse-all').addEventListener('click', collapseAll); }); -const toggleCollapse = (evt) => { - const gameArrow = evt.target.firstElementChild; - const gameInfo = evt.target.nextElementSibling; - if (gameInfo.classList.contains('collapsed')) { - gameArrow.innerText = '▼'; - gameInfo.classList.remove('collapsed'); - } else { - gameArrow.innerText = '▶'; - gameInfo.classList.add('collapsed'); - } -}; - const expandAll = () => { - document.querySelectorAll('.collapse-toggle').forEach((header) => { - if (header.style.display === 'none') { return; } - header.firstElementChild.innerText = '▼'; - header.nextElementSibling.classList.remove('collapsed'); + document.querySelectorAll('details').forEach((detail) => { + detail.setAttribute('open', '1'); }); }; const collapseAll = () => { - document.querySelectorAll('.collapse-toggle').forEach((header) => { - if (header.style.display === 'none') { return; } - header.firstElementChild.innerText = '▶'; - header.nextElementSibling.classList.add('collapsed'); + document.querySelectorAll('details').forEach((detail) => { + detail.removeAttribute('open'); }); }; diff --git a/WebHostLib/static/assets/trackerCommon.js b/WebHostLib/static/assets/trackerCommon.js index b8e089ece5d3..6324837b2816 100644 --- a/WebHostLib/static/assets/trackerCommon.js +++ b/WebHostLib/static/assets/trackerCommon.js @@ -27,7 +27,7 @@ const adjustTableHeight = () => { * @returns {string} */ const secondsToHours = (seconds) => { - let hours = Math.floor(seconds / 3600); + let hours = Math.floor(seconds / 3600); let minutes = Math.floor((seconds - (hours * 3600)) / 60).toString().padStart(2, '0'); return `${hours}:${minutes}`; }; @@ -38,18 +38,18 @@ window.addEventListener('load', () => { info: false, dom: "t", stateSave: true, - stateSaveCallback: function(settings, data) { + stateSaveCallback: function (settings, data) { delete data.search; localStorage.setItem(`DataTables_${settings.sInstance}_/tracker`, JSON.stringify(data)); }, - stateLoadCallback: function(settings) { + stateLoadCallback: function (settings) { return JSON.parse(localStorage.getItem(`DataTables_${settings.sInstance}_/tracker`)); }, - footerCallback: function(tfoot, data, start, end, display) { + footerCallback: function (tfoot, data, start, end, display) { if (tfoot) { const activityData = this.api().column('lastActivity:name').data().toArray().filter(x => !isNaN(x)); Array.from(tfoot?.children).find(td => td.classList.contains('last-activity')).innerText = - (activityData.length) ? secondsToHours(Math.min(...activityData)) : 'None'; + (activityData.length) ? secondsToHours(Math.min(...activityData)) : 'None'; } }, columnDefs: [ @@ -123,49 +123,64 @@ window.addEventListener('load', () => { event.preventDefault(); } }); - const tracker = document.getElementById('tracker-wrapper').getAttribute('data-tracker'); - const target_second = document.getElementById('tracker-wrapper').getAttribute('data-second') + 3; + const target_second = parseInt(document.getElementById('tracker-wrapper').getAttribute('data-second')) + 3; + console.log("Target second of refresh: " + target_second); - function getSleepTimeSeconds(){ + function getSleepTimeSeconds() { // -40 % 60 is -40, which is absolutely wrong and should burn var sleepSeconds = (((target_second - new Date().getSeconds()) % 60) + 60) % 60; return sleepSeconds || 60; } + let update_on_view = false; const update = () => { - const target = $("
"); - console.log("Updating Tracker..."); - target.load(location.href, function (response, status) { - if (status === "success") { - target.find(".table").each(function (i, new_table) { - const new_trs = $(new_table).find("tbody>tr"); - const footer_tr = $(new_table).find("tfoot>tr"); - const old_table = tables.eq(i); - const topscroll = $(old_table.settings()[0].nScrollBody).scrollTop(); - const leftscroll = $(old_table.settings()[0].nScrollBody).scrollLeft(); - old_table.clear(); - if (footer_tr.length) { - $(old_table.table).find("tfoot").html(footer_tr); - } - old_table.rows.add(new_trs); - old_table.draw(); - $(old_table.settings()[0].nScrollBody).scrollTop(topscroll); - $(old_table.settings()[0].nScrollBody).scrollLeft(leftscroll); - }); - $("#multi-stream-link").replaceWith(target.find("#multi-stream-link")); - } else { - console.log("Failed to connect to Server, in order to update Table Data."); - console.log(response); - } - }) - setTimeout(update, getSleepTimeSeconds()*1000); + if (document.hidden) { + console.log("Document reporting as not visible, not updating Tracker..."); + update_on_view = true; + } else { + update_on_view = false; + const target = $("
"); + console.log("Updating Tracker..."); + target.load(location.href, function (response, status) { + if (status === "success") { + target.find(".table").each(function (i, new_table) { + const new_trs = $(new_table).find("tbody>tr"); + const footer_tr = $(new_table).find("tfoot>tr"); + const old_table = tables.eq(i); + const topscroll = $(old_table.settings()[0].nScrollBody).scrollTop(); + const leftscroll = $(old_table.settings()[0].nScrollBody).scrollLeft(); + old_table.clear(); + if (footer_tr.length) { + $(old_table.table).find("tfoot").html(footer_tr); + } + old_table.rows.add(new_trs); + old_table.draw(); + $(old_table.settings()[0].nScrollBody).scrollTop(topscroll); + $(old_table.settings()[0].nScrollBody).scrollLeft(leftscroll); + }); + $("#multi-stream-link").replaceWith(target.find("#multi-stream-link")); + } else { + console.log("Failed to connect to Server, in order to update Table Data."); + console.log(response); + } + }) + } + updater = setTimeout(update, getSleepTimeSeconds() * 1000); } - setTimeout(update, getSleepTimeSeconds()*1000); + let updater = setTimeout(update, getSleepTimeSeconds() * 1000); window.addEventListener('resize', () => { adjustTableHeight(); tables.draw(); }); + window.addEventListener('visibilitychange', () => { + if (!document.hidden && update_on_view) { + console.log("Page became visible, tracker should be refreshed."); + clearTimeout(updater); + update(); + } + }); + adjustTableHeight(); }); diff --git a/WebHostLib/static/assets/weighted-options.js b/WebHostLib/static/assets/weighted-options.js deleted file mode 100644 index 80f8efd1d7de..000000000000 --- a/WebHostLib/static/assets/weighted-options.js +++ /dev/null @@ -1,1190 +0,0 @@ -window.addEventListener('load', () => { - fetchSettingData().then((data) => { - let settingHash = localStorage.getItem('weighted-settings-hash'); - if (!settingHash) { - // If no hash data has been set before, set it now - settingHash = md5(JSON.stringify(data)); - localStorage.setItem('weighted-settings-hash', settingHash); - localStorage.removeItem('weighted-settings'); - } - - if (settingHash !== md5(JSON.stringify(data))) { - const userMessage = document.getElementById('user-message'); - userMessage.innerText = "Your settings are out of date! Click here to update them! Be aware this will reset " + - "them all to default."; - userMessage.classList.add('visible'); - userMessage.addEventListener('click', resetSettings); - } - - // Page setup - const settings = new WeightedSettings(data); - settings.buildUI(); - settings.updateVisibleGames(); - adjustHeaderWidth(); - - // Event listeners - document.getElementById('export-options').addEventListener('click', () => settings.export()); - document.getElementById('generate-race').addEventListener('click', () => settings.generateGame(true)); - document.getElementById('generate-game').addEventListener('click', () => settings.generateGame()); - - // Name input field - const nameInput = document.getElementById('player-name'); - nameInput.setAttribute('data-type', 'data'); - nameInput.setAttribute('data-setting', 'name'); - nameInput.addEventListener('keyup', (evt) => settings.updateBaseSetting(evt)); - nameInput.value = settings.current.name; - }); -}); - -const resetSettings = () => { - localStorage.removeItem('weighted-settings'); - localStorage.removeItem('weighted-settings-hash') - window.location.reload(); -}; - -const fetchSettingData = () => new Promise((resolve, reject) => { - fetch(new Request(`${window.location.origin}/static/generated/weighted-options.json`)).then((response) => { - try{ response.json().then((jsonObj) => resolve(jsonObj)); } - catch(error){ reject(error); } - }); -}); - -/// The weighted settings across all games. -class WeightedSettings { - // The data from the server describing the types of settings available for - // each game, as a JSON-safe blob. - data; - - // The settings chosen by the user as they'd appear in the YAML file, stored - // to and retrieved from local storage. - current; - - // A record mapping game names to the associated GameSettings. - games; - - constructor(data) { - this.data = data; - this.current = JSON.parse(localStorage.getItem('weighted-settings')); - this.games = Object.keys(this.data.games).map((game) => new GameSettings(this, game)); - if (this.current) { return; } - - this.current = {}; - - // Transfer base options directly - for (let baseOption of Object.keys(this.data.baseOptions)){ - this.current[baseOption] = this.data.baseOptions[baseOption]; - } - - // Set options per game - for (let game of Object.keys(this.data.games)) { - // Initialize game object - this.current[game] = {}; - - // Transfer game settings - for (let gameSetting of Object.keys(this.data.games[game].gameSettings)){ - this.current[game][gameSetting] = {}; - - const setting = this.data.games[game].gameSettings[gameSetting]; - switch(setting.type){ - case 'select': - setting.options.forEach((option) => { - this.current[game][gameSetting][option.value] = - (setting.hasOwnProperty('defaultValue') && setting.defaultValue === option.value) ? 25 : 0; - }); - break; - case 'range': - case 'named_range': - this.current[game][gameSetting]['random'] = 0; - this.current[game][gameSetting]['random-low'] = 0; - this.current[game][gameSetting]['random-middle'] = 0; - this.current[game][gameSetting]['random-high'] = 0; - if (setting.hasOwnProperty('defaultValue')) { - this.current[game][gameSetting][setting.defaultValue] = 25; - } else { - this.current[game][gameSetting][setting.min] = 25; - } - break; - - case 'items-list': - case 'locations-list': - case 'custom-list': - this.current[game][gameSetting] = setting.defaultValue; - break; - - default: - console.error(`Unknown setting type for ${game} setting ${gameSetting}: ${setting.type}`); - } - } - - this.current[game].start_inventory = {}; - this.current[game].exclude_locations = []; - this.current[game].priority_locations = []; - this.current[game].local_items = []; - this.current[game].non_local_items = []; - this.current[game].start_hints = []; - this.current[game].start_location_hints = []; - } - - this.save(); - } - - // Saves the current settings to local storage. - save() { - localStorage.setItem('weighted-settings', JSON.stringify(this.current)); - } - - buildUI() { - // Build the game-choice div - this.#buildGameChoice(); - - const gamesWrapper = document.getElementById('games-wrapper'); - this.games.forEach((game) => { - gamesWrapper.appendChild(game.buildUI()); - }); - } - - #buildGameChoice() { - const gameChoiceDiv = document.getElementById('game-choice'); - const h2 = document.createElement('h2'); - h2.innerText = 'Game Select'; - gameChoiceDiv.appendChild(h2); - - const gameSelectDescription = document.createElement('p'); - gameSelectDescription.classList.add('setting-description'); - gameSelectDescription.innerText = 'Choose which games you might be required to play.'; - gameChoiceDiv.appendChild(gameSelectDescription); - - const hintText = document.createElement('p'); - hintText.classList.add('hint-text'); - hintText.innerText = 'If a game\'s value is greater than zero, you can click it\'s name to jump ' + - 'to that section.' - gameChoiceDiv.appendChild(hintText); - - // Build the game choice table - const table = document.createElement('table'); - const tbody = document.createElement('tbody'); - - Object.keys(this.data.games).forEach((game) => { - const tr = document.createElement('tr'); - const tdLeft = document.createElement('td'); - tdLeft.classList.add('td-left'); - const span = document.createElement('span'); - span.innerText = game; - span.setAttribute('id', `${game}-game-option`) - tdLeft.appendChild(span); - tr.appendChild(tdLeft); - - const tdMiddle = document.createElement('td'); - tdMiddle.classList.add('td-middle'); - const range = document.createElement('input'); - range.setAttribute('type', 'range'); - range.setAttribute('min', 0); - range.setAttribute('max', 50); - range.setAttribute('data-type', 'weight'); - range.setAttribute('data-setting', 'game'); - range.setAttribute('data-option', game); - range.value = this.current.game[game]; - range.addEventListener('change', (evt) => { - this.updateBaseSetting(evt); - this.updateVisibleGames(); // Show or hide games based on the new settings - }); - tdMiddle.appendChild(range); - tr.appendChild(tdMiddle); - - const tdRight = document.createElement('td'); - tdRight.setAttribute('id', `game-${game}`) - tdRight.classList.add('td-right'); - tdRight.innerText = range.value; - tr.appendChild(tdRight); - tbody.appendChild(tr); - }); - - table.appendChild(tbody); - gameChoiceDiv.appendChild(table); - } - - // Verifies that `this.settings` meets all the requirements for world - // generation, normalizes it for serialization, and returns the result. - #validateSettings() { - const settings = structuredClone(this.current); - const userMessage = document.getElementById('user-message'); - let errorMessage = null; - - // User must choose a name for their file - if ( - !settings.name || - settings.name.toString().trim().length === 0 || - settings.name.toString().toLowerCase().trim() === 'player' - ) { - userMessage.innerText = 'You forgot to set your player name at the top of the page!'; - userMessage.classList.add('visible'); - userMessage.scrollIntoView({ - behavior: 'smooth', - block: 'start', - }); - return; - } - - // Clean up the settings output - Object.keys(settings.game).forEach((game) => { - // Remove any disabled games - if (settings.game[game] === 0) { - delete settings.game[game]; - delete settings[game]; - return; - } - - Object.keys(settings[game]).forEach((setting) => { - // Remove any disabled options - Object.keys(settings[game][setting]).forEach((option) => { - if (settings[game][setting][option] === 0) { - delete settings[game][setting][option]; - } - }); - - if ( - Object.keys(settings[game][setting]).length === 0 && - !Array.isArray(settings[game][setting]) && - setting !== 'start_inventory' - ) { - errorMessage = `${game} // ${setting} has no values above zero!`; - } - - // Remove weights from options with only one possibility - if ( - Object.keys(settings[game][setting]).length === 1 && - !Array.isArray(settings[game][setting]) && - setting !== 'start_inventory' - ) { - settings[game][setting] = Object.keys(settings[game][setting])[0]; - } - - // Remove empty arrays - else if ( - ['exclude_locations', 'priority_locations', 'local_items', - 'non_local_items', 'start_hints', 'start_location_hints'].includes(setting) && - settings[game][setting].length === 0 - ) { - delete settings[game][setting]; - } - - // Remove empty start inventory - else if ( - setting === 'start_inventory' && - Object.keys(settings[game]['start_inventory']).length === 0 - ) { - delete settings[game]['start_inventory']; - } - }); - }); - - if (Object.keys(settings.game).length === 0) { - errorMessage = 'You have not chosen a game to play!'; - } - - // Remove weights if there is only one game - else if (Object.keys(settings.game).length === 1) { - settings.game = Object.keys(settings.game)[0]; - } - - // If an error occurred, alert the user and do not export the file - if (errorMessage) { - userMessage.innerText = errorMessage; - userMessage.classList.add('visible'); - userMessage.scrollIntoView({ - behavior: 'smooth', - block: 'start', - }); - return; - } - - // If no error occurred, hide the user message if it is visible - userMessage.classList.remove('visible'); - return settings; - } - - updateVisibleGames() { - Object.entries(this.current.game).forEach(([game, weight]) => { - const gameDiv = document.getElementById(`${game}-div`); - const gameOption = document.getElementById(`${game}-game-option`); - if (parseInt(weight, 10) > 0) { - gameDiv.classList.remove('invisible'); - gameOption.classList.add('jump-link'); - gameOption.addEventListener('click', () => { - const gameDiv = document.getElementById(`${game}-div`); - if (gameDiv.classList.contains('invisible')) { return; } - gameDiv.scrollIntoView({ - behavior: 'smooth', - block: 'start', - }); - }); - } else { - gameDiv.classList.add('invisible'); - gameOption.classList.remove('jump-link'); - } - }); - } - - updateBaseSetting(event) { - const setting = event.target.getAttribute('data-setting'); - const option = event.target.getAttribute('data-option'); - const type = event.target.getAttribute('data-type'); - - switch(type){ - case 'weight': - this.current[setting][option] = isNaN(event.target.value) ? event.target.value : parseInt(event.target.value, 10); - document.getElementById(`${setting}-${option}`).innerText = event.target.value; - break; - case 'data': - this.current[setting] = isNaN(event.target.value) ? event.target.value : parseInt(event.target.value, 10); - break; - } - - this.save(); - } - - export() { - const settings = this.#validateSettings(); - if (!settings) { return; } - - const yamlText = jsyaml.safeDump(settings, { noCompatMode: true }).replaceAll(/'(\d+)':/g, (x, y) => `${y}:`); - download(`${document.getElementById('player-name').value}.yaml`, yamlText); - } - - generateGame(raceMode = false) { - const settings = this.#validateSettings(); - if (!settings) { return; } - - axios.post('/api/generate', { - weights: { player: JSON.stringify(settings) }, - presetData: { player: JSON.stringify(settings) }, - playerCount: 1, - spoiler: 3, - race: raceMode ? '1' : '0', - }).then((response) => { - window.location.href = response.data.url; - }).catch((error) => { - const userMessage = document.getElementById('user-message'); - userMessage.innerText = 'Something went wrong and your game could not be generated.'; - if (error.response.data.text) { - userMessage.innerText += ' ' + error.response.data.text; - } - userMessage.classList.add('visible'); - userMessage.scrollIntoView({ - behavior: 'smooth', - block: 'start', - }); - console.error(error); - }); - } -} - -// Settings for an individual game. -class GameSettings { - // The WeightedSettings that contains this game's settings. Used to save - // settings after editing. - #allSettings; - - // The name of this game. - name; - - // The data from the server describing the types of settings available for - // this game, as a JSON-safe blob. - get data() { - return this.#allSettings.data.games[this.name]; - } - - // The settings chosen by the user as they'd appear in the YAML file, stored - // to and retrieved from local storage. - get current() { - return this.#allSettings.current[this.name]; - } - - constructor(allSettings, name) { - this.#allSettings = allSettings; - this.name = name; - } - - // Builds and returns the settings UI for this game. - buildUI() { - // Create game div, invisible by default - const gameDiv = document.createElement('div'); - gameDiv.setAttribute('id', `${this.name}-div`); - gameDiv.classList.add('game-div'); - gameDiv.classList.add('invisible'); - - const gameHeader = document.createElement('h2'); - gameHeader.innerText = this.name; - gameDiv.appendChild(gameHeader); - - const collapseButton = document.createElement('a'); - collapseButton.innerText = '(Collapse)'; - gameDiv.appendChild(collapseButton); - - const expandButton = document.createElement('a'); - expandButton.innerText = '(Expand)'; - expandButton.classList.add('invisible'); - gameDiv.appendChild(expandButton); - - // Sort items and locations alphabetically. - this.data.gameItems.sort(); - this.data.gameLocations.sort(); - - const weightedSettingsDiv = this.#buildWeightedSettingsDiv(); - gameDiv.appendChild(weightedSettingsDiv); - - const itemPoolDiv = this.#buildItemPoolDiv(); - gameDiv.appendChild(itemPoolDiv); - - const hintsDiv = this.#buildHintsDiv(); - gameDiv.appendChild(hintsDiv); - - const locationsDiv = this.#buildPriorityExclusionDiv(); - gameDiv.appendChild(locationsDiv); - - collapseButton.addEventListener('click', () => { - collapseButton.classList.add('invisible'); - weightedSettingsDiv.classList.add('invisible'); - itemPoolDiv.classList.add('invisible'); - hintsDiv.classList.add('invisible'); - locationsDiv.classList.add('invisible'); - expandButton.classList.remove('invisible'); - }); - - expandButton.addEventListener('click', () => { - collapseButton.classList.remove('invisible'); - weightedSettingsDiv.classList.remove('invisible'); - itemPoolDiv.classList.remove('invisible'); - hintsDiv.classList.remove('invisible'); - locationsDiv.classList.remove('invisible'); - expandButton.classList.add('invisible'); - }); - - return gameDiv; - } - - #buildWeightedSettingsDiv() { - const settingsWrapper = document.createElement('div'); - settingsWrapper.classList.add('settings-wrapper'); - - Object.keys(this.data.gameSettings).forEach((settingName) => { - const setting = this.data.gameSettings[settingName]; - const settingWrapper = document.createElement('div'); - settingWrapper.classList.add('setting-wrapper'); - - const settingNameHeader = document.createElement('h4'); - settingNameHeader.innerText = setting.displayName; - settingWrapper.appendChild(settingNameHeader); - - const settingDescription = document.createElement('p'); - settingDescription.classList.add('setting-description'); - settingDescription.innerText = setting.description.replace(/(\n)/g, ' '); - settingWrapper.appendChild(settingDescription); - - switch(setting.type){ - case 'select': - const optionTable = document.createElement('table'); - const tbody = document.createElement('tbody'); - - // Add a weight range for each option - setting.options.forEach((option) => { - const tr = document.createElement('tr'); - const tdLeft = document.createElement('td'); - tdLeft.classList.add('td-left'); - tdLeft.innerText = option.name; - tr.appendChild(tdLeft); - - const tdMiddle = document.createElement('td'); - tdMiddle.classList.add('td-middle'); - const range = document.createElement('input'); - range.setAttribute('type', 'range'); - range.setAttribute('data-game', this.name); - range.setAttribute('data-setting', settingName); - range.setAttribute('data-option', option.value); - range.setAttribute('data-type', setting.type); - range.setAttribute('min', 0); - range.setAttribute('max', 50); - range.addEventListener('change', (evt) => this.#updateRangeSetting(evt)); - range.value = this.current[settingName][option.value]; - tdMiddle.appendChild(range); - tr.appendChild(tdMiddle); - - const tdRight = document.createElement('td'); - tdRight.setAttribute('id', `${this.name}-${settingName}-${option.value}`); - tdRight.classList.add('td-right'); - tdRight.innerText = range.value; - tr.appendChild(tdRight); - - tbody.appendChild(tr); - }); - - optionTable.appendChild(tbody); - settingWrapper.appendChild(optionTable); - break; - - case 'range': - case 'named_range': - const rangeTable = document.createElement('table'); - const rangeTbody = document.createElement('tbody'); - - const hintText = document.createElement('p'); - hintText.classList.add('hint-text'); - hintText.innerHTML = 'This is a range option. You may enter a valid numerical value in the text box ' + - `below, then press the "Add" button to add a weight for it.

Accepted values:
` + - `Normal range: ${setting.min} - ${setting.max}`; - - const acceptedValuesOutsideRange = []; - if (setting.hasOwnProperty('value_names')) { - Object.keys(setting.value_names).forEach((specialName) => { - if ( - (setting.value_names[specialName] < setting.min) || - (setting.value_names[specialName] > setting.max) - ) { - hintText.innerHTML += `
${specialName}: ${setting.value_names[specialName]}`; - acceptedValuesOutsideRange.push(setting.value_names[specialName]); - } - }); - - hintText.innerHTML += '

Certain values have special meaning:'; - Object.keys(setting.value_names).forEach((specialName) => { - hintText.innerHTML += `
${specialName}: ${setting.value_names[specialName]}`; - }); - } - - settingWrapper.appendChild(hintText); - - const addOptionDiv = document.createElement('div'); - addOptionDiv.classList.add('add-option-div'); - const optionInput = document.createElement('input'); - optionInput.setAttribute('id', `${this.name}-${settingName}-option`); - let placeholderText = `${setting.min} - ${setting.max}`; - acceptedValuesOutsideRange.forEach((aVal) => placeholderText += `, ${aVal}`); - optionInput.setAttribute('placeholder', placeholderText); - addOptionDiv.appendChild(optionInput); - const addOptionButton = document.createElement('button'); - addOptionButton.innerText = 'Add'; - addOptionDiv.appendChild(addOptionButton); - settingWrapper.appendChild(addOptionDiv); - optionInput.addEventListener('keydown', (evt) => { - if (evt.key === 'Enter') { addOptionButton.dispatchEvent(new Event('click')); } - }); - - addOptionButton.addEventListener('click', () => { - const optionInput = document.getElementById(`${this.name}-${settingName}-option`); - let option = optionInput.value; - if (!option || !option.trim()) { return; } - option = parseInt(option, 10); - - let optionAcceptable = false; - if ((option >= setting.min) && (option <= setting.max)) { - optionAcceptable = true; - } - if (setting.hasOwnProperty('value_names') && Object.values(setting.value_names).includes(option)){ - optionAcceptable = true; - } - if (!optionAcceptable) { return; } - - optionInput.value = ''; - if (document.getElementById(`${this.name}-${settingName}-${option}-range`)) { return; } - - const tr = document.createElement('tr'); - const tdLeft = document.createElement('td'); - tdLeft.classList.add('td-left'); - tdLeft.innerText = option; - if ( - setting.hasOwnProperty('value_names') && - Object.values(setting.value_names).includes(parseInt(option, 10)) - ) { - const optionName = Object.keys(setting.value_names).find( - (key) => setting.value_names[key] === parseInt(option, 10) - ); - tdLeft.innerText += ` [${optionName}]`; - } - tr.appendChild(tdLeft); - - const tdMiddle = document.createElement('td'); - tdMiddle.classList.add('td-middle'); - const range = document.createElement('input'); - range.setAttribute('type', 'range'); - range.setAttribute('id', `${this.name}-${settingName}-${option}-range`); - range.setAttribute('data-game', this.name); - range.setAttribute('data-setting', settingName); - range.setAttribute('data-option', option); - range.setAttribute('min', 0); - range.setAttribute('max', 50); - range.addEventListener('change', (evt) => this.#updateRangeSetting(evt)); - range.value = this.current[settingName][parseInt(option, 10)]; - tdMiddle.appendChild(range); - tr.appendChild(tdMiddle); - - const tdRight = document.createElement('td'); - tdRight.setAttribute('id', `${this.name}-${settingName}-${option}`) - tdRight.classList.add('td-right'); - tdRight.innerText = range.value; - tr.appendChild(tdRight); - - const tdDelete = document.createElement('td'); - tdDelete.classList.add('td-delete'); - const deleteButton = document.createElement('span'); - deleteButton.classList.add('range-option-delete'); - deleteButton.innerText = '❌'; - deleteButton.addEventListener('click', () => { - range.value = 0; - range.dispatchEvent(new Event('change')); - rangeTbody.removeChild(tr); - }); - tdDelete.appendChild(deleteButton); - tr.appendChild(tdDelete); - - rangeTbody.appendChild(tr); - - // Save new option to settings - range.dispatchEvent(new Event('change')); - }); - - Object.keys(this.current[settingName]).forEach((option) => { - // These options are statically generated below, and should always appear even if they are deleted - // from localStorage - if (['random', 'random-low', 'random-middle', 'random-high'].includes(option)) { return; } - - const tr = document.createElement('tr'); - const tdLeft = document.createElement('td'); - tdLeft.classList.add('td-left'); - tdLeft.innerText = option; - if ( - setting.hasOwnProperty('value_names') && - Object.values(setting.value_names).includes(parseInt(option, 10)) - ) { - const optionName = Object.keys(setting.value_names).find( - (key) => setting.value_names[key] === parseInt(option, 10) - ); - tdLeft.innerText += ` [${optionName}]`; - } - tr.appendChild(tdLeft); - - const tdMiddle = document.createElement('td'); - tdMiddle.classList.add('td-middle'); - const range = document.createElement('input'); - range.setAttribute('type', 'range'); - range.setAttribute('id', `${this.name}-${settingName}-${option}-range`); - range.setAttribute('data-game', this.name); - range.setAttribute('data-setting', settingName); - range.setAttribute('data-option', option); - range.setAttribute('min', 0); - range.setAttribute('max', 50); - range.addEventListener('change', (evt) => this.#updateRangeSetting(evt)); - range.value = this.current[settingName][parseInt(option, 10)]; - tdMiddle.appendChild(range); - tr.appendChild(tdMiddle); - - const tdRight = document.createElement('td'); - tdRight.setAttribute('id', `${this.name}-${settingName}-${option}`) - tdRight.classList.add('td-right'); - tdRight.innerText = range.value; - tr.appendChild(tdRight); - - const tdDelete = document.createElement('td'); - tdDelete.classList.add('td-delete'); - const deleteButton = document.createElement('span'); - deleteButton.classList.add('range-option-delete'); - deleteButton.innerText = '❌'; - deleteButton.addEventListener('click', () => { - range.value = 0; - const changeEvent = new Event('change'); - changeEvent.action = 'rangeDelete'; - range.dispatchEvent(changeEvent); - rangeTbody.removeChild(tr); - }); - tdDelete.appendChild(deleteButton); - tr.appendChild(tdDelete); - - rangeTbody.appendChild(tr); - }); - - ['random', 'random-low', 'random-middle', 'random-high'].forEach((option) => { - const tr = document.createElement('tr'); - const tdLeft = document.createElement('td'); - tdLeft.classList.add('td-left'); - switch(option){ - case 'random': - tdLeft.innerText = 'Random'; - break; - case 'random-low': - tdLeft.innerText = "Random (Low)"; - break; - case 'random-middle': - tdLeft.innerText = 'Random (Middle)'; - break; - case 'random-high': - tdLeft.innerText = "Random (High)"; - break; - } - tr.appendChild(tdLeft); - - const tdMiddle = document.createElement('td'); - tdMiddle.classList.add('td-middle'); - const range = document.createElement('input'); - range.setAttribute('type', 'range'); - range.setAttribute('id', `${this.name}-${settingName}-${option}-range`); - range.setAttribute('data-game', this.name); - range.setAttribute('data-setting', settingName); - range.setAttribute('data-option', option); - range.setAttribute('min', 0); - range.setAttribute('max', 50); - range.addEventListener('change', (evt) => this.#updateRangeSetting(evt)); - range.value = this.current[settingName][option]; - tdMiddle.appendChild(range); - tr.appendChild(tdMiddle); - - const tdRight = document.createElement('td'); - tdRight.setAttribute('id', `${this.name}-${settingName}-${option}`) - tdRight.classList.add('td-right'); - tdRight.innerText = range.value; - tr.appendChild(tdRight); - rangeTbody.appendChild(tr); - }); - - rangeTable.appendChild(rangeTbody); - settingWrapper.appendChild(rangeTable); - break; - - case 'items-list': - const itemsList = this.#buildItemsDiv(settingName); - settingWrapper.appendChild(itemsList); - break; - - case 'locations-list': - const locationsList = this.#buildLocationsDiv(settingName); - settingWrapper.appendChild(locationsList); - break; - - case 'custom-list': - const customList = this.#buildListDiv(settingName, this.data.gameSettings[settingName].options); - settingWrapper.appendChild(customList); - break; - - default: - console.error(`Unknown setting type for ${this.name} setting ${settingName}: ${setting.type}`); - return; - } - - settingsWrapper.appendChild(settingWrapper); - }); - - return settingsWrapper; - } - - #buildItemPoolDiv() { - const itemsDiv = document.createElement('div'); - itemsDiv.classList.add('items-div'); - - const itemsDivHeader = document.createElement('h3'); - itemsDivHeader.innerText = 'Item Pool'; - itemsDiv.appendChild(itemsDivHeader); - - const itemsDescription = document.createElement('p'); - itemsDescription.classList.add('setting-description'); - itemsDescription.innerText = 'Choose if you would like to start with items, or control if they are placed in ' + - 'your seed or someone else\'s.'; - itemsDiv.appendChild(itemsDescription); - - const itemsHint = document.createElement('p'); - itemsHint.classList.add('hint-text'); - itemsHint.innerText = 'Drag and drop items from one box to another.'; - itemsDiv.appendChild(itemsHint); - - const itemsWrapper = document.createElement('div'); - itemsWrapper.classList.add('items-wrapper'); - - const itemDragoverHandler = (evt) => evt.preventDefault(); - const itemDropHandler = (evt) => this.#itemDropHandler(evt); - - // Create container divs for each category - const availableItemsWrapper = document.createElement('div'); - availableItemsWrapper.classList.add('item-set-wrapper'); - availableItemsWrapper.innerText = 'Available Items'; - const availableItems = document.createElement('div'); - availableItems.classList.add('item-container'); - availableItems.setAttribute('id', `${this.name}-available_items`); - availableItems.addEventListener('dragover', itemDragoverHandler); - availableItems.addEventListener('drop', itemDropHandler); - - const startInventoryWrapper = document.createElement('div'); - startInventoryWrapper.classList.add('item-set-wrapper'); - startInventoryWrapper.innerText = 'Start Inventory'; - const startInventory = document.createElement('div'); - startInventory.classList.add('item-container'); - startInventory.setAttribute('id', `${this.name}-start_inventory`); - startInventory.setAttribute('data-setting', 'start_inventory'); - startInventory.addEventListener('dragover', itemDragoverHandler); - startInventory.addEventListener('drop', itemDropHandler); - - const localItemsWrapper = document.createElement('div'); - localItemsWrapper.classList.add('item-set-wrapper'); - localItemsWrapper.innerText = 'Local Items'; - const localItems = document.createElement('div'); - localItems.classList.add('item-container'); - localItems.setAttribute('id', `${this.name}-local_items`); - localItems.setAttribute('data-setting', 'local_items') - localItems.addEventListener('dragover', itemDragoverHandler); - localItems.addEventListener('drop', itemDropHandler); - - const nonLocalItemsWrapper = document.createElement('div'); - nonLocalItemsWrapper.classList.add('item-set-wrapper'); - nonLocalItemsWrapper.innerText = 'Non-Local Items'; - const nonLocalItems = document.createElement('div'); - nonLocalItems.classList.add('item-container'); - nonLocalItems.setAttribute('id', `${this.name}-non_local_items`); - nonLocalItems.setAttribute('data-setting', 'non_local_items'); - nonLocalItems.addEventListener('dragover', itemDragoverHandler); - nonLocalItems.addEventListener('drop', itemDropHandler); - - // Populate the divs - this.data.gameItems.forEach((item) => { - if (Object.keys(this.current.start_inventory).includes(item)){ - const itemDiv = this.#buildItemQtyDiv(item); - itemDiv.setAttribute('data-setting', 'start_inventory'); - startInventory.appendChild(itemDiv); - } else if (this.current.local_items.includes(item)) { - const itemDiv = this.#buildItemDiv(item); - itemDiv.setAttribute('data-setting', 'local_items'); - localItems.appendChild(itemDiv); - } else if (this.current.non_local_items.includes(item)) { - const itemDiv = this.#buildItemDiv(item); - itemDiv.setAttribute('data-setting', 'non_local_items'); - nonLocalItems.appendChild(itemDiv); - } else { - const itemDiv = this.#buildItemDiv(item); - availableItems.appendChild(itemDiv); - } - }); - - availableItemsWrapper.appendChild(availableItems); - startInventoryWrapper.appendChild(startInventory); - localItemsWrapper.appendChild(localItems); - nonLocalItemsWrapper.appendChild(nonLocalItems); - itemsWrapper.appendChild(availableItemsWrapper); - itemsWrapper.appendChild(startInventoryWrapper); - itemsWrapper.appendChild(localItemsWrapper); - itemsWrapper.appendChild(nonLocalItemsWrapper); - itemsDiv.appendChild(itemsWrapper); - return itemsDiv; - } - - #buildItemDiv(item) { - const itemDiv = document.createElement('div'); - itemDiv.classList.add('item-div'); - itemDiv.setAttribute('id', `${this.name}-${item}`); - itemDiv.setAttribute('data-game', this.name); - itemDiv.setAttribute('data-item', item); - itemDiv.setAttribute('draggable', 'true'); - itemDiv.innerText = item; - itemDiv.addEventListener('dragstart', (evt) => { - evt.dataTransfer.setData('text/plain', itemDiv.getAttribute('id')); - }); - return itemDiv; - } - - #buildItemQtyDiv(item) { - const itemQtyDiv = document.createElement('div'); - itemQtyDiv.classList.add('item-qty-div'); - itemQtyDiv.setAttribute('id', `${this.name}-${item}`); - itemQtyDiv.setAttribute('data-game', this.name); - itemQtyDiv.setAttribute('data-item', item); - itemQtyDiv.setAttribute('draggable', 'true'); - itemQtyDiv.innerText = item; - - const inputWrapper = document.createElement('div'); - inputWrapper.classList.add('item-qty-input-wrapper') - - const itemQty = document.createElement('input'); - itemQty.setAttribute('value', this.current.start_inventory.hasOwnProperty(item) ? - this.current.start_inventory[item] : '1'); - itemQty.setAttribute('data-game', this.name); - itemQty.setAttribute('data-setting', 'start_inventory'); - itemQty.setAttribute('data-option', item); - itemQty.setAttribute('maxlength', '3'); - itemQty.addEventListener('keyup', (evt) => { - evt.target.value = isNaN(parseInt(evt.target.value)) ? 0 : parseInt(evt.target.value); - this.#updateItemSetting(evt); - }); - inputWrapper.appendChild(itemQty); - itemQtyDiv.appendChild(inputWrapper); - - itemQtyDiv.addEventListener('dragstart', (evt) => { - evt.dataTransfer.setData('text/plain', itemQtyDiv.getAttribute('id')); - }); - return itemQtyDiv; - } - - #itemDropHandler(evt) { - evt.preventDefault(); - const sourceId = evt.dataTransfer.getData('text/plain'); - const sourceDiv = document.getElementById(sourceId); - - const item = sourceDiv.getAttribute('data-item'); - - const oldSetting = sourceDiv.hasAttribute('data-setting') ? sourceDiv.getAttribute('data-setting') : null; - const newSetting = evt.target.hasAttribute('data-setting') ? evt.target.getAttribute('data-setting') : null; - - const itemDiv = newSetting === 'start_inventory' ? this.#buildItemQtyDiv(item) : this.#buildItemDiv(item); - - if (oldSetting) { - if (oldSetting === 'start_inventory') { - if (this.current[oldSetting].hasOwnProperty(item)) { - delete this.current[oldSetting][item]; - } - } else { - if (this.current[oldSetting].includes(item)) { - this.current[oldSetting].splice(this.current[oldSetting].indexOf(item), 1); - } - } - } - - if (newSetting) { - itemDiv.setAttribute('data-setting', newSetting); - document.getElementById(`${this.name}-${newSetting}`).appendChild(itemDiv); - if (newSetting === 'start_inventory') { - this.current[newSetting][item] = 1; - } else { - if (!this.current[newSetting].includes(item)){ - this.current[newSetting].push(item); - } - } - } else { - // No setting was assigned, this item has been removed from the settings - document.getElementById(`${this.name}-available_items`).appendChild(itemDiv); - } - - // Remove the source drag object - sourceDiv.parentElement.removeChild(sourceDiv); - - // Save the updated settings - this.save(); - } - - #buildHintsDiv() { - const hintsDiv = document.createElement('div'); - hintsDiv.classList.add('hints-div'); - const hintsHeader = document.createElement('h3'); - hintsHeader.innerText = 'Item & Location Hints'; - hintsDiv.appendChild(hintsHeader); - const hintsDescription = document.createElement('p'); - hintsDescription.classList.add('setting-description'); - hintsDescription.innerText = 'Choose any items or locations to begin the game with the knowledge of where those ' + - ' items are, or what those locations contain.'; - hintsDiv.appendChild(hintsDescription); - - const itemHintsContainer = document.createElement('div'); - itemHintsContainer.classList.add('hints-container'); - - // Item Hints - const itemHintsWrapper = document.createElement('div'); - itemHintsWrapper.classList.add('hints-wrapper'); - itemHintsWrapper.innerText = 'Starting Item Hints'; - - const itemHintsDiv = this.#buildItemsDiv('start_hints'); - itemHintsWrapper.appendChild(itemHintsDiv); - itemHintsContainer.appendChild(itemHintsWrapper); - - // Starting Location Hints - const locationHintsWrapper = document.createElement('div'); - locationHintsWrapper.classList.add('hints-wrapper'); - locationHintsWrapper.innerText = 'Starting Location Hints'; - - const locationHintsDiv = this.#buildLocationsDiv('start_location_hints'); - locationHintsWrapper.appendChild(locationHintsDiv); - itemHintsContainer.appendChild(locationHintsWrapper); - - hintsDiv.appendChild(itemHintsContainer); - return hintsDiv; - } - - #buildPriorityExclusionDiv() { - const locationsDiv = document.createElement('div'); - locationsDiv.classList.add('locations-div'); - const locationsHeader = document.createElement('h3'); - locationsHeader.innerText = 'Priority & Exclusion Locations'; - locationsDiv.appendChild(locationsHeader); - const locationsDescription = document.createElement('p'); - locationsDescription.classList.add('setting-description'); - locationsDescription.innerText = 'Priority locations guarantee a progression item will be placed there while ' + - 'excluded locations will not contain progression or useful items.'; - locationsDiv.appendChild(locationsDescription); - - const locationsContainer = document.createElement('div'); - locationsContainer.classList.add('locations-container'); - - // Priority Locations - const priorityLocationsWrapper = document.createElement('div'); - priorityLocationsWrapper.classList.add('locations-wrapper'); - priorityLocationsWrapper.innerText = 'Priority Locations'; - - const priorityLocationsDiv = this.#buildLocationsDiv('priority_locations'); - priorityLocationsWrapper.appendChild(priorityLocationsDiv); - locationsContainer.appendChild(priorityLocationsWrapper); - - // Exclude Locations - const excludeLocationsWrapper = document.createElement('div'); - excludeLocationsWrapper.classList.add('locations-wrapper'); - excludeLocationsWrapper.innerText = 'Exclude Locations'; - - const excludeLocationsDiv = this.#buildLocationsDiv('exclude_locations'); - excludeLocationsWrapper.appendChild(excludeLocationsDiv); - locationsContainer.appendChild(excludeLocationsWrapper); - - locationsDiv.appendChild(locationsContainer); - return locationsDiv; - } - - // Builds a div for a setting whose value is a list of locations. - #buildLocationsDiv(setting) { - return this.#buildListDiv(setting, this.data.gameLocations, { - groups: this.data.gameLocationGroups, - descriptions: this.data.gameLocationDescriptions, - }); - } - - // Builds a div for a setting whose value is a list of items. - #buildItemsDiv(setting) { - return this.#buildListDiv(setting, this.data.gameItems, { - groups: this.data.gameItemGroups, - descriptions: this.data.gameItemDescriptions - }); - } - - // Builds a div for a setting named `setting` with a list value that can - // contain `items`. - // - // The `groups` option can be a list of additional options for this list - // (usually `item_name_groups` or `location_name_groups`) that are displayed - // in a special section at the top of the list. - // - // The `descriptions` option can be a map from item names or group names to - // descriptions for the user's benefit. - #buildListDiv(setting, items, {groups = [], descriptions = {}} = {}) { - const div = document.createElement('div'); - div.classList.add('simple-list'); - - groups.forEach((group) => { - const row = this.#addListRow(setting, group, descriptions[group]); - div.appendChild(row); - }); - - if (groups.length > 0) { - div.appendChild(document.createElement('hr')); - } - - items.forEach((item) => { - const row = this.#addListRow(setting, item, descriptions[item]); - div.appendChild(row); - }); - - return div; - } - - // Builds and returns a row for a list of checkboxes. - // - // If `help` is passed, it's displayed as a help tooltip for this list item. - #addListRow(setting, item, help = undefined) { - const row = document.createElement('div'); - row.classList.add('list-row'); - - const label = document.createElement('label'); - label.setAttribute('for', `${this.name}-${setting}-${item}`); - - const checkbox = document.createElement('input'); - checkbox.setAttribute('type', 'checkbox'); - checkbox.setAttribute('id', `${this.name}-${setting}-${item}`); - checkbox.setAttribute('data-game', this.name); - checkbox.setAttribute('data-setting', setting); - checkbox.setAttribute('data-option', item); - if (this.current[setting].includes(item)) { - checkbox.setAttribute('checked', '1'); - } - checkbox.addEventListener('change', (evt) => this.#updateListSetting(evt)); - label.appendChild(checkbox); - - const name = document.createElement('span'); - name.innerText = item; - - if (help) { - const helpSpan = document.createElement('span'); - helpSpan.classList.add('interactive'); - helpSpan.setAttribute('data-tooltip', help); - helpSpan.innerText = '(?)'; - name.innerText += ' '; - name.appendChild(helpSpan); - - // Put the first 7 tooltips below their rows. CSS tooltips in scrolling - // containers can't be visible outside those containers, so this helps - // ensure they won't be pushed out the top. - if (helpSpan.parentNode.childNodes.length < 7) { - helpSpan.classList.add('tooltip-bottom'); - } - } - - label.appendChild(name); - - row.appendChild(label); - return row; - } - - #updateRangeSetting(evt) { - const setting = evt.target.getAttribute('data-setting'); - const option = evt.target.getAttribute('data-option'); - document.getElementById(`${this.name}-${setting}-${option}`).innerText = evt.target.value; - if (evt.action && evt.action === 'rangeDelete') { - delete this.current[setting][option]; - } else { - this.current[setting][option] = parseInt(evt.target.value, 10); - } - this.save(); - } - - #updateListSetting(evt) { - const setting = evt.target.getAttribute('data-setting'); - const option = evt.target.getAttribute('data-option'); - - if (evt.target.checked) { - // If the option is to be enabled and it is already enabled, do nothing - if (this.current[setting].includes(option)) { return; } - - this.current[setting].push(option); - } else { - // If the option is to be disabled and it is already disabled, do nothing - if (!this.current[setting].includes(option)) { return; } - - this.current[setting].splice(this.current[setting].indexOf(option), 1); - } - this.save(); - } - - #updateItemSetting(evt) { - const setting = evt.target.getAttribute('data-setting'); - const option = evt.target.getAttribute('data-option'); - if (setting === 'start_inventory') { - this.current[setting][option] = evt.target.value.trim() ? parseInt(evt.target.value) : 0; - } else { - this.current[setting][option] = isNaN(evt.target.value) ? - evt.target.value : parseInt(evt.target.value, 10); - } - this.save(); - } - - // Saves the current settings to local storage. - save() { - this.#allSettings.save(); - } -} - -/** Create an anchor and trigger a download of a text file. */ -const download = (filename, text) => { - const downloadLink = document.createElement('a'); - downloadLink.setAttribute('href','data:text/yaml;charset=utf-8,'+ encodeURIComponent(text)) - downloadLink.setAttribute('download', filename); - downloadLink.style.display = 'none'; - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); -}; diff --git a/WebHostLib/static/assets/weightedOptions.js b/WebHostLib/static/assets/weightedOptions.js new file mode 100644 index 000000000000..0417ab174b0e --- /dev/null +++ b/WebHostLib/static/assets/weightedOptions.js @@ -0,0 +1,223 @@ +let deletedOptions = {}; + +window.addEventListener('load', () => { + const worldName = document.querySelector('#weighted-options').getAttribute('data-game'); + + // Generic change listener. Detecting unique qualities and acting on them here reduces initial JS initialisation time + // and handles dynamically created elements + document.addEventListener('change', (evt) => { + // Handle updates to range inputs + if (evt.target.type === 'range') { + // Update span containing range value. All ranges have a corresponding `{rangeId}-value` span + document.getElementById(`${evt.target.id}-value`).innerText = evt.target.value; + + // If the changed option was the name of a game, determine whether to show or hide that game's div + if (evt.target.id.startsWith('game||')) { + const gameName = evt.target.id.split('||')[1]; + const gameDiv = document.getElementById(`${gameName}-container`); + if (evt.target.value > 0) { + gameDiv.classList.remove('hidden'); + } else { + gameDiv.classList.add('hidden'); + } + } + } + }); + + // Generic click listener + document.addEventListener('click', (evt) => { + // Handle creating new rows for Range options + if (evt.target.classList.contains('add-range-option-button')) { + const optionName = evt.target.getAttribute('data-option'); + addRangeRow(optionName); + } + + // Handle deleting range rows + if (evt.target.classList.contains('range-option-delete')) { + const targetRow = document.querySelector(`tr[data-row="${evt.target.getAttribute('data-target')}"]`); + setDeletedOption( + targetRow.getAttribute('data-option-name'), + targetRow.getAttribute('data-value'), + ); + targetRow.parentElement.removeChild(targetRow); + } + }); + + // Listen for enter presses on inputs intended to add range rows + document.addEventListener('keydown', (evt) => { + if (evt.key === 'Enter') { + evt.preventDefault(); + } + + if (evt.key === 'Enter' && evt.target.classList.contains('range-option-value')) { + const optionName = evt.target.getAttribute('data-option'); + addRangeRow(optionName); + } + }); + + // Detect form submission + document.getElementById('weighted-options-form').addEventListener('submit', (evt) => { + // Save data to localStorage + const weightedOptions = {}; + document.querySelectorAll('input[name]').forEach((input) => { + const keys = input.getAttribute('name').split('||'); + + // Determine keys + const optionName = keys[0] ?? null; + const subOption = keys[1] ?? null; + + // Ensure keys exist + if (!weightedOptions[optionName]) { weightedOptions[optionName] = {}; } + if (subOption && !weightedOptions[optionName][subOption]) { + weightedOptions[optionName][subOption] = null; + } + + if (subOption) { return weightedOptions[optionName][subOption] = determineValue(input); } + if (optionName) { return weightedOptions[optionName] = determineValue(input); } + }); + + localStorage.setItem(`${worldName}-weights`, JSON.stringify(weightedOptions)); + localStorage.setItem(`${worldName}-deletedOptions`, JSON.stringify(deletedOptions)); + }); + + // Remove all deleted values as specified by localStorage + deletedOptions = JSON.parse(localStorage.getItem(`${worldName}-deletedOptions`) || '{}'); + Object.keys(deletedOptions).forEach((optionName) => { + deletedOptions[optionName].forEach((value) => { + const targetRow = document.querySelector(`tr[data-row="${value}-row"]`); + targetRow.parentElement.removeChild(targetRow); + }); + }); + + // Populate all settings from localStorage on page initialisation + const previousSettingsJson = localStorage.getItem(`${worldName}-weights`); + if (previousSettingsJson) { + const previousSettings = JSON.parse(previousSettingsJson); + Object.keys(previousSettings).forEach((option) => { + if (typeof previousSettings[option] === 'string') { + return document.querySelector(`input[name="${option}"]`).value = previousSettings[option]; + } + + Object.keys(previousSettings[option]).forEach((value) => { + const input = document.querySelector(`input[name="${option}||${value}"]`); + if (!input?.type) { + return console.error(`Unable to populate option with name ${option}||${value}.`); + } + + switch (input.type) { + case 'checkbox': + input.checked = (parseInt(previousSettings[option][value], 10) === 1); + break; + case 'range': + input.value = parseInt(previousSettings[option][value], 10); + break; + case 'number': + input.value = previousSettings[option][value].toString(); + break; + default: + console.error(`Found unsupported input type: ${input.type}`); + } + }); + }); + } +}); + +const addRangeRow = (optionName) => { + const inputQuery = `input[type=number][data-option="${optionName}"].range-option-value`; + const inputTarget = document.querySelector(inputQuery); + const newValue = inputTarget.value; + if (!/^-?\d+$/.test(newValue)) { + alert('Range values must be a positive or negative integer!'); + return; + } + inputTarget.value = ''; + const tBody = document.querySelector(`table[data-option="${optionName}"].range-rows tbody`); + const tr = document.createElement('tr'); + tr.setAttribute('data-row', `${optionName}-${newValue}-row`); + tr.setAttribute('data-option-name', optionName); + tr.setAttribute('data-value', newValue); + const tdLeft = document.createElement('td'); + tdLeft.classList.add('td-left'); + const label = document.createElement('label'); + label.setAttribute('for', `${optionName}||${newValue}`); + label.innerText = newValue.toString(); + tdLeft.appendChild(label); + tr.appendChild(tdLeft); + const tdMiddle = document.createElement('td'); + tdMiddle.classList.add('td-middle'); + const range = document.createElement('input'); + range.setAttribute('type', 'range'); + range.setAttribute('min', '0'); + range.setAttribute('max', '50'); + range.setAttribute('value', '0'); + range.setAttribute('id', `${optionName}||${newValue}`); + range.setAttribute('name', `${optionName}||${newValue}`); + tdMiddle.appendChild(range); + tr.appendChild(tdMiddle); + const tdRight = document.createElement('td'); + tdRight.classList.add('td-right'); + const valueSpan = document.createElement('span'); + valueSpan.setAttribute('id', `${optionName}||${newValue}-value`); + valueSpan.innerText = '0'; + tdRight.appendChild(valueSpan); + tr.appendChild(tdRight); + const tdDelete = document.createElement('td'); + const deleteSpan = document.createElement('span'); + deleteSpan.classList.add('range-option-delete'); + deleteSpan.classList.add('js-required'); + deleteSpan.setAttribute('data-target', `${optionName}-${newValue}-row`); + deleteSpan.innerText = '❌'; + tdDelete.appendChild(deleteSpan); + tr.appendChild(tdDelete); + tBody.appendChild(tr); + + // Remove this option from the set of deleted options if it exists + unsetDeletedOption(optionName, newValue); +}; + +/** + * Determines the value of an input element, or returns a 1 or 0 if the element is a checkbox + * + * @param {object} input - The input element. + * @returns {number} The value of the input element. + */ +const determineValue = (input) => { + switch (input.type) { + case 'checkbox': + return (input.checked ? 1 : 0); + case 'range': + return parseInt(input.value, 10); + default: + return input.value; + } +}; + +/** + * Sets the deleted option value for a given world and option name. + * If the world or option does not exist, it creates the necessary entries. + * + * @param {string} optionName - The name of the option. + * @param {*} value - The value to be set for the deleted option. + * @returns {void} + */ +const setDeletedOption = (optionName, value) => { + deletedOptions[optionName] = deletedOptions[optionName] || []; + deletedOptions[optionName].push(`${optionName}-${value}`); +}; + +/** + * Removes a specific value from the deletedOptions object. + * + * @param {string} optionName - The name of the option. + * @param {*} value - The value to be removed + * @returns {void} + */ +const unsetDeletedOption = (optionName, value) => { + if (!deletedOptions.hasOwnProperty(optionName)) { return; } + if (deletedOptions[optionName].includes(`${optionName}-${value}`)) { + deletedOptions[optionName].splice(deletedOptions[optionName].indexOf(`${optionName}-${value}`), 1); + } + if (deletedOptions[optionName].length === 0) { + delete deletedOptions[optionName]; + } +}; diff --git a/WebHostLib/static/styles/globalStyles.css b/WebHostLib/static/styles/globalStyles.css index a787b0c6570a..1a0144830e7c 100644 --- a/WebHostLib/static/styles/globalStyles.css +++ b/WebHostLib/static/styles/globalStyles.css @@ -44,7 +44,7 @@ a{ font-family: LexendDeca-Regular, sans-serif; } -button{ +button, input[type=submit]{ font-weight: 500; font-size: 0.9rem; padding: 10px 17px 11px 16px; /* top right bottom left */ @@ -57,7 +57,7 @@ button{ cursor: pointer; } -button:active{ +button:active, input[type=submit]:active{ border-right: 1px solid rgba(0, 0, 0, 0.5); border-bottom: 1px solid rgba(0, 0, 0, 0.5); padding-right: 16px; @@ -66,11 +66,11 @@ button:active{ margin-bottom: 2px; } -button.button-grass{ +button.button-grass, input[type=submit].button-grass{ border: 1px solid black; } -button.button-dirt{ +button.button-dirt, input[type=submit].button-dirt{ border: 1px solid black; } @@ -111,4 +111,4 @@ h5, h6{ .interactive{ color: #ffef00; -} \ No newline at end of file +} diff --git a/WebHostLib/static/styles/markdown.css b/WebHostLib/static/styles/markdown.css index dce135588e5f..e0165b7489ef 100644 --- a/WebHostLib/static/styles/markdown.css +++ b/WebHostLib/static/styles/markdown.css @@ -23,7 +23,7 @@ .markdown a{} -.markdown h1{ +.markdown h1, .markdown details summary.h1{ font-size: 52px; font-weight: normal; font-family: LondrinaSolid-Regular, sans-serif; @@ -33,7 +33,7 @@ text-shadow: 1px 1px 4px #000000; } -.markdown h2{ +.markdown h2, .markdown details summary.h2{ font-size: 38px; font-weight: normal; font-family: LondrinaSolid-Light, sans-serif; @@ -45,7 +45,7 @@ text-shadow: 1px 1px 2px #000000; } -.markdown h3{ +.markdown h3, .markdown details summary.h3{ font-size: 26px; font-family: LexendDeca-Regular, sans-serif; text-transform: none; @@ -55,7 +55,7 @@ margin-bottom: 0.5rem; } -.markdown h4{ +.markdown h4, .markdown details summary.h4{ font-family: LexendDeca-Regular, sans-serif; text-transform: none; font-size: 24px; @@ -63,21 +63,21 @@ margin-bottom: 24px; } -.markdown h5{ +.markdown h5, .markdown details summary.h5{ font-family: LexendDeca-Regular, sans-serif; text-transform: none; font-size: 22px; cursor: pointer; } -.markdown h6{ +.markdown h6, .markdown details summary.h6{ font-family: LexendDeca-Regular, sans-serif; text-transform: none; font-size: 20px; cursor: pointer;; } -.markdown h4, .markdown h5,.markdown h6{ +.markdown h4, .markdown h5, .markdown h6{ margin-bottom: 0.5rem; } diff --git a/WebHostLib/static/styles/player-options.css b/WebHostLib/static/styles/player-options.css deleted file mode 100644 index cc2d5e2de5ce..000000000000 --- a/WebHostLib/static/styles/player-options.css +++ /dev/null @@ -1,244 +0,0 @@ -html{ - background-image: url('../static/backgrounds/grass.png'); - background-repeat: repeat; - background-size: 650px 650px; -} - -#player-options{ - box-sizing: border-box; - max-width: 1024px; - margin-left: auto; - margin-right: auto; - background-color: rgba(0, 0, 0, 0.15); - border-radius: 8px; - padding: 1rem; - color: #eeffeb; -} - -#player-options #player-options-button-row{ - display: flex; - flex-direction: row; - justify-content: space-between; - margin-top: 15px; -} - -#player-options code{ - background-color: #d9cd8e; - border-radius: 4px; - padding-left: 0.25rem; - padding-right: 0.25rem; - color: #000000; -} - -#player-options #user-message{ - display: none; - width: calc(100% - 8px); - background-color: #ffe86b; - border-radius: 4px; - color: #000000; - padding: 4px; - text-align: center; -} - -#player-options #user-message.visible{ - display: block; - cursor: pointer; -} - -#player-options h1{ - font-size: 2.5rem; - font-weight: normal; - width: 100%; - margin-bottom: 0.5rem; - text-shadow: 1px 1px 4px #000000; -} - -#player-options h2{ - font-size: 40px; - font-weight: normal; - width: 100%; - margin-bottom: 0.5rem; - text-transform: lowercase; - text-shadow: 1px 1px 2px #000000; -} - -#player-options h3, #player-options h4, #player-options h5, #player-options h6{ - text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); -} - -#player-options input:not([type]){ - border: 1px solid #000000; - padding: 3px; - border-radius: 3px; - min-width: 150px; -} - -#player-options input:not([type]):focus{ - border: 1px solid #ffffff; -} - -#player-options select{ - border: 1px solid #000000; - padding: 3px; - border-radius: 3px; - min-width: 150px; - background-color: #ffffff; -} - -#player-options #game-options, #player-options #rom-options{ - display: flex; - flex-direction: row; -} - -#player-options #meta-options { - display: flex; - justify-content: space-between; - gap: 20px; - padding: 3px; -} - -#player-options div { - display: flex; - flex-grow: 1; -} - -#player-options #meta-options label { - display: inline-block; - min-width: 180px; - flex-grow: 1; -} - -#player-options #meta-options input, -#player-options #meta-options select { - box-sizing: border-box; - min-width: 150px; - width: 50%; -} - -#player-options .left, #player-options .right{ - flex-grow: 1; -} - -#player-options .left{ - margin-right: 10px; -} - -#player-options .right{ - margin-left: 10px; -} - -#player-options table{ - margin-bottom: 30px; - width: 100%; -} - -#player-options table .select-container{ - display: flex; - flex-direction: row; -} - -#player-options table .select-container select{ - min-width: 200px; - flex-grow: 1; -} - -#player-options table select:disabled{ - background-color: lightgray; -} - -#player-options table .range-container{ - display: flex; - flex-direction: row; -} - -#player-options table .range-container input[type=range]{ - flex-grow: 1; -} - -#player-options table .range-value{ - min-width: 20px; - margin-left: 0.25rem; -} - -#player-options table .named-range-container{ - display: flex; - flex-direction: column; -} - -#player-options table .named-range-wrapper{ - display: flex; - flex-direction: row; - margin-top: 0.25rem; -} - -#player-options table .named-range-wrapper input[type=range]{ - flex-grow: 1; -} - -#player-options table .randomize-button { - max-height: 24px; - line-height: 16px; - padding: 2px 8px; - margin: 0 0 0 0.25rem; - font-size: 12px; - border: 1px solid black; - border-radius: 3px; -} - -#player-options table .randomize-button.active { - background-color: #ffef00; /* Same as .interactive in globalStyles.css */ -} - -#player-options table .randomize-button[data-tooltip]::after { - left: unset; - right: 0; -} - -#player-options table label{ - display: block; - min-width: 200px; - margin-right: 4px; - cursor: default; -} - -#player-options th, #player-options td{ - border: none; - padding: 3px; - font-size: 17px; - vertical-align: top; -} - -@media all and (max-width: 1024px) { - #player-options { - border-radius: 0; - } - - #player-options #meta-options { - flex-direction: column; - justify-content: flex-start; - gap: 6px; - } - - #player-options #game-options{ - justify-content: flex-start; - flex-wrap: wrap; - } - - #player-options .left, - #player-options .right { - margin: 0; - } - - #game-options table { - margin-bottom: 0; - } - - #game-options table label{ - display: block; - min-width: 200px; - } - - #game-options table tr td { - width: 50%; - } -} diff --git a/WebHostLib/static/styles/playerOptions/playerOptions.css b/WebHostLib/static/styles/playerOptions/playerOptions.css new file mode 100644 index 000000000000..56c9263d3330 --- /dev/null +++ b/WebHostLib/static/styles/playerOptions/playerOptions.css @@ -0,0 +1,310 @@ +@import "../markdown.css"; +html { + background-image: url("../../static/backgrounds/grass.png"); + background-repeat: repeat; + background-size: 650px 650px; + overflow-x: hidden; +} + +#player-options { + box-sizing: border-box; + max-width: 1024px; + margin-left: auto; + margin-right: auto; + background-color: rgba(0, 0, 0, 0.15); + border-radius: 8px; + padding: 1rem; + color: #eeffeb; + word-break: break-word; +} +#player-options #player-options-header h1 { + margin-bottom: 0; + padding-bottom: 0; +} +#player-options #player-options-header h1:nth-child(2) { + font-size: 1.4rem; + margin-top: -8px; + margin-bottom: 0.5rem; +} +#player-options .js-warning-banner { + width: calc(100% - 1rem); + padding: 0.5rem; + border-radius: 4px; + background-color: #f3f309; + color: #000000; + margin-bottom: 0.5rem; + text-align: center; +} +#player-options .group-container { + padding: 0; + margin: 0; +} +#player-options .group-container h2 { + user-select: none; + cursor: unset; +} +#player-options .group-container h2 label { + cursor: pointer; +} +#player-options #player-options-button-row { + display: flex; + flex-direction: row; + justify-content: space-between; + margin-top: 15px; +} +#player-options #user-message { + display: none; + width: calc(100% - 8px); + background-color: #ffe86b; + border-radius: 4px; + color: #000000; + padding: 4px; + text-align: center; + cursor: pointer; +} +#player-options h1 { + font-size: 2.5rem; + font-weight: normal; + width: 100%; + margin-bottom: 0.5rem; + text-shadow: 1px 1px 4px #000000; +} +#player-options h2 { + font-size: 40px; + font-weight: normal; + width: 100%; + margin-bottom: 0.5rem; + text-transform: lowercase; + text-shadow: 1px 1px 2px #000000; +} +#player-options h3, #player-options h4, #player-options h5, #player-options h6 { + text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); +} +#player-options input:not([type]) { + border: 1px solid #000000; + padding: 3px; + border-radius: 3px; + min-width: 150px; +} +#player-options input:not([type]):focus { + border: 1px solid #ffffff; +} +#player-options select { + border: 1px solid #000000; + padding: 3px; + border-radius: 3px; + min-width: 150px; + background-color: #ffffff; + text-overflow: ellipsis; +} +#player-options .game-options { + display: flex; + flex-direction: row; +} +#player-options .game-options .left, #player-options .game-options .right { + display: grid; + grid-template-columns: 12rem auto; + grid-row-gap: 0.5rem; + grid-auto-rows: min-content; + align-items: start; + min-width: 480px; + width: 50%; +} +#player-options #meta-options { + display: flex; + justify-content: space-between; + gap: 20px; + padding: 3px; +} +#player-options #meta-options input, #player-options #meta-options select { + box-sizing: border-box; + width: 200px; +} +#player-options .left, #player-options .right { + flex-grow: 1; + margin-bottom: 0.5rem; +} +#player-options .left { + margin-right: 20px; +} +#player-options .select-container { + display: flex; + flex-direction: row; + max-width: 270px; +} +#player-options .select-container select { + min-width: 200px; + flex-grow: 1; +} +#player-options .select-container select:disabled { + background-color: lightgray; +} +#player-options .range-container { + display: flex; + flex-direction: row; + max-width: 270px; +} +#player-options .range-container input[type=range] { + flex-grow: 1; +} +#player-options .range-container .range-value { + min-width: 20px; + margin-left: 0.25rem; +} +#player-options .named-range-container { + display: flex; + flex-direction: column; + max-width: 270px; +} +#player-options .named-range-container .named-range-wrapper { + display: flex; + flex-direction: row; + margin-top: 0.25rem; +} +#player-options .named-range-container .named-range-wrapper input[type=range] { + flex-grow: 1; +} +#player-options .free-text-container { + display: flex; + flex-direction: column; + max-width: 270px; +} +#player-options .free-text-container input[type=text] { + flex-grow: 1; +} +#player-options .text-choice-container { + display: flex; + flex-direction: column; + max-width: 270px; +} +#player-options .text-choice-container .text-choice-wrapper { + display: flex; + flex-direction: row; + margin-bottom: 0.25rem; +} +#player-options .text-choice-container .text-choice-wrapper select { + flex-grow: 1; +} +#player-options .option-container { + display: flex; + flex-direction: column; + background-color: rgba(0, 0, 0, 0.25); + border: 1px solid rgba(20, 20, 20, 0.25); + border-radius: 3px; + color: #ffffff; + max-height: 10rem; + min-width: 14.5rem; + overflow-y: auto; + padding-right: 0.25rem; + padding-left: 0.25rem; +} +#player-options .option-container .option-divider { + width: 100%; + height: 2px; + background-color: rgba(20, 20, 20, 0.25); + margin-top: 0.125rem; + margin-bottom: 0.125rem; +} +#player-options .option-container .option-entry { + display: flex; + flex-direction: row; + align-items: flex-start; + margin-bottom: 0.125rem; + margin-top: 0.125rem; + user-select: none; +} +#player-options .option-container .option-entry:hover { + background-color: rgba(20, 20, 20, 0.25); +} +#player-options .option-container .option-entry input[type=checkbox] { + margin-right: 0.25rem; +} +#player-options .option-container .option-entry input[type=number] { + max-width: 1.5rem; + max-height: 1rem; + margin-left: 0.125rem; + text-align: center; + /* Hide arrows on input[type=number] fields */ + -moz-appearance: textfield; +} +#player-options .option-container .option-entry input[type=number]::-webkit-outer-spin-button, #player-options .option-container .option-entry input[type=number]::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +#player-options .option-container .option-entry label { + flex-grow: 1; + margin-right: 0; + min-width: unset; + display: unset; +} +#player-options .randomize-button { + display: flex; + flex-direction: column; + justify-content: center; + height: 22px; + max-width: 30px; + margin: 0 0 0 0.25rem; + font-size: 14px; + border: 1px solid black; + border-radius: 3px; + background-color: #d3d3d3; + user-select: none; +} +#player-options .randomize-button:hover { + background-color: #c0c0c0; + cursor: pointer; +} +#player-options .randomize-button label { + line-height: 22px; + padding-left: 5px; + padding-right: 2px; + margin-right: 4px; + width: 100%; + height: 100%; + min-width: unset; +} +#player-options .randomize-button label:hover { + cursor: pointer; +} +#player-options .randomize-button input[type=checkbox] { + display: none; +} +#player-options .randomize-button:has(input[type=checkbox]:checked) { + background-color: #ffef00; /* Same as .interactive in globalStyles.css */ +} +#player-options .randomize-button:has(input[type=checkbox]:checked):hover { + background-color: #eedd27; +} +#player-options .randomize-button[data-tooltip]::after { + left: unset; + right: 0; +} +#player-options label { + display: block; + margin-right: 4px; + cursor: default; + word-break: break-word; +} +#player-options th, #player-options td { + border: none; + padding: 3px; + font-size: 17px; + vertical-align: top; +} + +@media all and (max-width: 1024px) { + #player-options { + border-radius: 0; + } + #player-options #meta-options { + flex-direction: column; + justify-content: flex-start; + gap: 6px; + } + #player-options .game-options { + justify-content: flex-start; + flex-wrap: wrap; + } +} + +/*# sourceMappingURL=playerOptions.css.map */ diff --git a/WebHostLib/static/styles/playerOptions/playerOptions.css.map b/WebHostLib/static/styles/playerOptions/playerOptions.css.map new file mode 100644 index 000000000000..6797b88c7bfe --- /dev/null +++ b/WebHostLib/static/styles/playerOptions/playerOptions.css.map @@ -0,0 +1 @@ +{"version":3,"sourceRoot":"","sources":["playerOptions.scss"],"names":[],"mappings":"AAAQ;AAER;EACI;EACA;EACA;EACA;;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGI;EACI;EACA;;AAGJ;EACI;EACA;EACA;;AAIR;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;;AAEA;EACI;EACA;;AAEA;EACI;;AAKZ;EACI;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;;AAGJ;EACI;EACA;EACA;EACA;;AAEA;EACI;;AAIR;EACI;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;;AAEA;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AAIR;EACI;EACA;EACA;EACA;;AAEA;EACI;EACA;;AAIR;EACI;EACA;;AAGJ;EACI;;AAGJ;EACI;EACA;EACA;;AAEA;EACI;EACA;;AAEA;EACI;;AAKZ;EACI;EACA;EACA;;AAEA;EACI;;AAGJ;EACI;EACA;;AAIR;EACI;EACA;EACA;;AAEA;EACI;EACA;EACA;;AAEA;EACI;;AAKZ;EACI;EACA;EACA;;AAEA;EACI;;AAIR;EACI;EACA;EACA;;AAEA;EACI;EACA;EACA;;AAEA;EACI;;AAKZ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;;AAGJ;EACI;;AAGJ;EACI;EACA;EACA;EACA;AAEA;EACA;;AACA;EACI;EACA;;AAIR;EACI;EACA;EACA;EACA;;AAKZ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AACA;EACI;;AAIR;EACI;;AAGJ;EACI;;AAEA;EACI;;AAIR;EACI;EACA;;AAIR;EACI;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;;;AAIR;EACI;IACI;;EAEA;IACI;IACA;IACA;;EAGJ;IACI;IACA","file":"playerOptions.css"} \ No newline at end of file diff --git a/WebHostLib/static/styles/playerOptions/playerOptions.scss b/WebHostLib/static/styles/playerOptions/playerOptions.scss new file mode 100644 index 000000000000..06bde759d263 --- /dev/null +++ b/WebHostLib/static/styles/playerOptions/playerOptions.scss @@ -0,0 +1,364 @@ +@import "../markdown.css"; + +html{ + background-image: url('../../static/backgrounds/grass.png'); + background-repeat: repeat; + background-size: 650px 650px; + overflow-x: hidden; +} + +#player-options{ + box-sizing: border-box; + max-width: 1024px; + margin-left: auto; + margin-right: auto; + background-color: rgba(0, 0, 0, 0.15); + border-radius: 8px; + padding: 1rem; + color: #eeffeb; + word-break: break-word; + + #player-options-header{ + h1{ + margin-bottom: 0; + padding-bottom: 0; + } + + h1:nth-child(2){ + font-size: 1.4rem; + margin-top: -8px; + margin-bottom: 0.5rem; + } + } + + .js-warning-banner{ + width: calc(100% - 1rem); + padding: 0.5rem; + border-radius: 4px; + background-color: #f3f309; + color: #000000; + margin-bottom: 0.5rem; + text-align: center; + } + + .group-container{ + padding: 0; + margin: 0; + + h2{ + user-select: none; + cursor: unset; + + label{ + cursor: pointer; + } + } + } + + #player-options-button-row{ + display: flex; + flex-direction: row; + justify-content: space-between; + margin-top: 15px; + } + + #user-message{ + display: none; + width: calc(100% - 8px); + background-color: #ffe86b; + border-radius: 4px; + color: #000000; + padding: 4px; + text-align: center; + cursor: pointer; + } + + h1{ + font-size: 2.5rem; + font-weight: normal; + width: 100%; + margin-bottom: 0.5rem; + text-shadow: 1px 1px 4px #000000; + } + + h2{ + font-size: 40px; + font-weight: normal; + width: 100%; + margin-bottom: 0.5rem; + text-transform: lowercase; + text-shadow: 1px 1px 2px #000000; + } + + h3, h4, h5, h6{ + text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); + } + + input:not([type]){ + border: 1px solid #000000; + padding: 3px; + border-radius: 3px; + min-width: 150px; + + &:focus{ + border: 1px solid #ffffff; + } + } + + select{ + border: 1px solid #000000; + padding: 3px; + border-radius: 3px; + min-width: 150px; + background-color: #ffffff; + text-overflow: ellipsis; + } + + .game-options{ + display: flex; + flex-direction: row; + + .left, .right{ + display: grid; + grid-template-columns: 12rem auto; + grid-row-gap: 0.5rem; + grid-auto-rows: min-content; + align-items: start; + min-width: 480px; + width: 50%; + } + } + + #meta-options{ + display: flex; + justify-content: space-between; + gap: 20px; + padding: 3px; + + input, select{ + box-sizing: border-box; + width: 200px; + } + } + + .left, .right{ + flex-grow: 1; + margin-bottom: 0.5rem; + } + + .left{ + margin-right: 20px; + } + + .select-container{ + display: flex; + flex-direction: row; + max-width: 270px; + + select{ + min-width: 200px; + flex-grow: 1; + + &:disabled{ + background-color: lightgray; + } + } + } + + .range-container{ + display: flex; + flex-direction: row; + max-width: 270px; + + input[type=range]{ + flex-grow: 1; + } + + .range-value{ + min-width: 20px; + margin-left: 0.25rem; + } + } + + .named-range-container{ + display: flex; + flex-direction: column; + max-width: 270px; + + .named-range-wrapper{ + display: flex; + flex-direction: row; + margin-top: 0.25rem; + + input[type=range]{ + flex-grow: 1; + } + } + } + + .free-text-container{ + display: flex; + flex-direction: column; + max-width: 270px; + + input[type=text]{ + flex-grow: 1; + } + } + + .text-choice-container{ + display: flex; + flex-direction: column; + max-width: 270px; + + .text-choice-wrapper{ + display: flex; + flex-direction: row; + margin-bottom: 0.25rem; + + select{ + flex-grow: 1; + } + } + } + + .option-container{ + display: flex; + flex-direction: column; + background-color: rgba(0, 0, 0, 0.25); + border: 1px solid rgba(20, 20, 20, 0.25); + border-radius: 3px; + color: #ffffff; + max-height: 10rem; + min-width: 14.5rem; + overflow-y: auto; + padding-right: 0.25rem; + padding-left: 0.25rem; + + .option-divider{ + width: 100%; + height: 2px; + background-color: rgba(20, 20, 20, 0.25); + margin-top: 0.125rem; + margin-bottom: 0.125rem; + } + + .option-entry{ + display: flex; + flex-direction: row; + align-items: flex-start; + margin-bottom: 0.125rem; + margin-top: 0.125rem; + user-select: none; + + &:hover{ + background-color: rgba(20, 20, 20, 0.25); + } + + input[type=checkbox]{ + margin-right: 0.25rem; + } + + input[type=number]{ + max-width: 1.5rem; + max-height: 1rem; + margin-left: 0.125rem; + text-align: center; + + /* Hide arrows on input[type=number] fields */ + -moz-appearance: textfield; + &::-webkit-outer-spin-button, &::-webkit-inner-spin-button{ + -webkit-appearance: none; + margin: 0; + } + } + + label{ + flex-grow: 1; + margin-right: 0; + min-width: unset; + display: unset; + } + } + } + + .randomize-button{ + display: flex; + flex-direction: column; + justify-content: center; + height: 22px; + max-width: 30px; + margin: 0 0 0 0.25rem; + font-size: 14px; + border: 1px solid black; + border-radius: 3px; + background-color: #d3d3d3; + user-select: none; + + &:hover{ + background-color: #c0c0c0; + cursor: pointer; + } + + label{ + line-height: 22px; + padding-left: 5px; + padding-right: 2px; + margin-right: 4px; + width: 100%; + height: 100%; + min-width: unset; + &:hover{ + cursor: pointer; + } + } + + input[type=checkbox]{ + display: none; + } + + &:has(input[type=checkbox]:checked){ + background-color: #ffef00; /* Same as .interactive in globalStyles.css */ + + &:hover{ + background-color: #eedd27; + } + } + + &[data-tooltip]::after{ + left: unset; + right: 0; + } + } + + label{ + display: block; + margin-right: 4px; + cursor: default; + word-break: break-word; + } + + th, td{ + border: none; + padding: 3px; + font-size: 17px; + vertical-align: top; + } +} + +@media all and (max-width: 1024px) { + #player-options { + border-radius: 0; + + #meta-options { + flex-direction: column; + justify-content: flex-start; + gap: 6px; + } + + .game-options{ + justify-content: flex-start; + flex-wrap: wrap; + } + } +} diff --git a/WebHostLib/static/styles/supportedGames.css b/WebHostLib/static/styles/supportedGames.css index 7396daa95404..ab12f320716b 100644 --- a/WebHostLib/static/styles/supportedGames.css +++ b/WebHostLib/static/styles/supportedGames.css @@ -8,30 +8,15 @@ cursor: unset; } -#games h1{ +#games h1, #games details summary.h1{ font-size: 60px; cursor: unset; } -#games h2{ +#games h2, #games details summary.h2{ color: #93dcff; margin-bottom: 2px; -} - -#games .collapse-toggle{ - cursor: pointer; -} - -#games h2 .collapse-arrow{ - font-size: 20px; - display: inline-block; /* make vertical-align work */ - padding-bottom: 9px; - vertical-align: middle; - padding-right: 8px; -} - -#games p.collapsed{ - display: none; + text-transform: none; } #games a{ diff --git a/WebHostLib/static/styles/tooltip.css b/WebHostLib/static/styles/tooltip.css index 7cd8463f64a4..02992b188bc9 100644 --- a/WebHostLib/static/styles/tooltip.css +++ b/WebHostLib/static/styles/tooltip.css @@ -42,6 +42,7 @@ give it one of the following classes: tooltip-left, tooltip-right, tooltip-top, [data-tooltip]:hover:before, [data-tooltip]:hover:after, .tooltip:hover:before, .tooltip:hover:after{ visibility: visible; opacity: 1; + word-break: break-word; } /** Directional arrow styles */ diff --git a/WebHostLib/static/styles/weighted-options.css b/WebHostLib/static/styles/weighted-options.css deleted file mode 100644 index 8a66ca237015..000000000000 --- a/WebHostLib/static/styles/weighted-options.css +++ /dev/null @@ -1,315 +0,0 @@ -html{ - background-image: url('../static/backgrounds/grass.png'); - background-repeat: repeat; - background-size: 650px 650px; - scroll-padding-top: 90px; -} - -#weighted-settings{ - max-width: 1000px; - margin-left: auto; - margin-right: auto; - background-color: rgba(0, 0, 0, 0.15); - border-radius: 8px; - padding: 1rem; - color: #eeffeb; -} - -#weighted-settings #games-wrapper{ - width: 100%; -} - -#weighted-settings .setting-wrapper{ - width: 100%; - margin-bottom: 2rem; -} - -#weighted-settings .setting-wrapper .add-option-div{ - display: flex; - flex-direction: row; - justify-content: flex-start; - margin-bottom: 1rem; -} - -#weighted-settings .setting-wrapper .add-option-div button{ - width: auto; - height: auto; - margin: 0 0 0 0.15rem; - padding: 0 0.25rem; - border-radius: 4px; - cursor: default; -} - -#weighted-settings .setting-wrapper .add-option-div button:active{ - margin-bottom: 1px; -} - -#weighted-settings p.setting-description{ - margin: 0 0 1rem; -} - -#weighted-settings p.hint-text{ - margin: 0 0 1rem; - font-style: italic; -} - -#weighted-settings .jump-link{ - color: #ffef00; - cursor: pointer; - text-decoration: underline; -} - -#weighted-settings table{ - width: 100%; -} - -#weighted-settings table th, #weighted-settings table td{ - border: none; -} - -#weighted-settings table td{ - padding: 5px; -} - -#weighted-settings table .td-left{ - font-family: LexendDeca-Regular, sans-serif; - padding-right: 1rem; - width: 200px; -} - -#weighted-settings table .td-middle{ - display: flex; - flex-direction: column; - justify-content: space-evenly; - padding-right: 1rem; -} - -#weighted-settings table .td-right{ - width: 4rem; - text-align: right; -} - -#weighted-settings table .td-delete{ - width: 50px; - text-align: right; -} - -#weighted-settings table .range-option-delete{ - cursor: pointer; -} - -#weighted-settings .items-wrapper{ - display: flex; - flex-direction: row; - justify-content: space-between; -} - -#weighted-settings .items-div h3{ - margin-bottom: 0.5rem; -} - -#weighted-settings .items-wrapper .item-set-wrapper{ - width: 24%; - font-weight: bold; -} - -#weighted-settings .item-container{ - border: 1px solid #ffffff; - border-radius: 2px; - width: 100%; - height: 300px; - overflow-y: auto; - overflow-x: hidden; - margin-top: 0.125rem; - font-weight: normal; -} - -#weighted-settings .item-container .item-div{ - padding: 0.125rem 0.5rem; - cursor: pointer; -} - -#weighted-settings .item-container .item-div:hover{ - background-color: rgba(0, 0, 0, 0.1); -} - -#weighted-settings .item-container .item-qty-div{ - display: flex; - flex-direction: row; - justify-content: space-between; - padding: 0.125rem 0.5rem; - cursor: pointer; -} - -#weighted-settings .item-container .item-qty-div .item-qty-input-wrapper{ - display: flex; - flex-direction: column; - justify-content: space-around; -} - -#weighted-settings .item-container .item-qty-div input{ - min-width: unset; - width: 1.5rem; - text-align: center; -} - -#weighted-settings .item-container .item-qty-div:hover{ - background-color: rgba(0, 0, 0, 0.1); -} - -#weighted-settings .hints-div, #weighted-settings .locations-div{ - margin-top: 2rem; -} - -#weighted-settings .hints-div h3, #weighted-settings .locations-div h3{ - margin-bottom: 0.5rem; -} - -#weighted-settings .hints-container, #weighted-settings .locations-container{ - display: flex; - flex-direction: row; - justify-content: space-between; -} - -#weighted-settings .hints-wrapper, #weighted-settings .locations-wrapper{ - width: calc(50% - 0.5rem); - font-weight: bold; -} - -#weighted-settings .hints-wrapper .simple-list, #weighted-settings .locations-wrapper .simple-list{ - margin-top: 0.25rem; - height: 300px; - font-weight: normal; -} - -#weighted-settings #weighted-settings-button-row{ - display: flex; - flex-direction: row; - justify-content: space-between; - margin-top: 15px; -} - -#weighted-settings code{ - background-color: #d9cd8e; - border-radius: 4px; - padding-left: 0.25rem; - padding-right: 0.25rem; - color: #000000; -} - -#weighted-settings #user-message{ - display: none; - width: calc(100% - 8px); - background-color: #ffe86b; - border-radius: 4px; - color: #000000; - padding: 4px; - text-align: center; -} - -#weighted-settings #user-message.visible{ - display: block; - cursor: pointer; -} - -#weighted-settings h1{ - font-size: 2.5rem; - font-weight: normal; - border-bottom: 1px solid #ffffff; - width: 100%; - margin-bottom: 0.5rem; - color: #ffffff; - text-shadow: 1px 1px 4px #000000; -} - -#weighted-settings h2{ - font-size: 2rem; - font-weight: normal; - border-bottom: 1px solid #ffffff; - width: 100%; - margin-bottom: 0.5rem; - color: #ffe993; - text-transform: none; - text-shadow: 1px 1px 2px #000000; -} - -#weighted-settings h3, #weighted-settings h4, #weighted-settings h5, #weighted-settings h6{ - color: #ffffff; - text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); - text-transform: none; -} - -#weighted-settings a{ - color: #ffef00; - cursor: pointer; -} - -#weighted-settings input:not([type]){ - border: 1px solid #000000; - padding: 3px; - border-radius: 3px; - min-width: 150px; -} - -#weighted-settings input:not([type]):focus{ - border: 1px solid #ffffff; -} - -#weighted-settings select{ - border: 1px solid #000000; - padding: 3px; - border-radius: 3px; - min-width: 150px; - background-color: #ffffff; -} - -#weighted-settings .game-options, #weighted-settings .rom-options{ - display: flex; - flex-direction: column; -} - -#weighted-settings .simple-list{ - display: flex; - flex-direction: column; - - max-height: 300px; - overflow-y: auto; - border: 1px solid #ffffff; - border-radius: 4px; -} - -#weighted-settings .simple-list .list-row label{ - display: block; - width: calc(100% - 0.5rem); - padding: 0.0625rem 0.25rem; -} - -#weighted-settings .simple-list .list-row label:hover{ - background-color: rgba(0, 0, 0, 0.1); -} - -#weighted-settings .simple-list .list-row label input[type=checkbox]{ - margin-right: 0.5rem; -} - -#weighted-settings .simple-list hr{ - width: calc(100% - 2px); - margin: 2px auto; - border-bottom: 1px solid rgb(255 255 255 / 0.6); -} - -#weighted-settings .invisible{ - display: none; -} - -@media all and (max-width: 1000px), all and (orientation: portrait){ - #weighted-settings .game-options{ - justify-content: flex-start; - flex-wrap: wrap; - } - - #game-options table label{ - display: block; - min-width: 200px; - } -} diff --git a/WebHostLib/static/styles/weightedOptions/weightedOptions.css b/WebHostLib/static/styles/weightedOptions/weightedOptions.css new file mode 100644 index 000000000000..3cfc6d24992d --- /dev/null +++ b/WebHostLib/static/styles/weightedOptions/weightedOptions.css @@ -0,0 +1,232 @@ +html { + background-image: url("../../static/backgrounds/grass.png"); + background-repeat: repeat; + background-size: 650px 650px; + scroll-padding-top: 90px; +} + +#weighted-options { + max-width: 1000px; + margin-left: auto; + margin-right: auto; + background-color: rgba(0, 0, 0, 0.15); + border-radius: 8px; + padding: 1rem; + color: #eeffeb; +} +#weighted-options #weighted-options-header h1 { + margin-bottom: 0; + padding-bottom: 0; +} +#weighted-options #weighted-options-header h1:nth-child(2) { + font-size: 1.4rem; + margin-top: -8px; + margin-bottom: 0.5rem; +} +#weighted-options .js-warning-banner { + width: calc(100% - 1rem); + padding: 0.5rem; + border-radius: 4px; + background-color: #f3f309; + color: #000000; + margin-bottom: 0.5rem; + text-align: center; +} +#weighted-options .option-wrapper { + width: 100%; + margin-bottom: 2rem; +} +#weighted-options .option-wrapper .add-option-div { + display: flex; + flex-direction: row; + justify-content: flex-start; + margin-bottom: 1rem; +} +#weighted-options .option-wrapper .add-option-div button { + width: auto; + height: auto; + margin: 0 0 0 0.15rem; + padding: 0 0.25rem; + border-radius: 4px; + cursor: default; +} +#weighted-options .option-wrapper .add-option-div button:active { + margin-bottom: 1px; +} +#weighted-options p.option-description { + margin: 0 0 1rem; +} +#weighted-options p.hint-text { + margin: 0 0 1rem; + font-style: italic; +} +#weighted-options table { + width: 100%; + margin-top: 0.5rem; + margin-bottom: 1.5rem; +} +#weighted-options table th, #weighted-options table td { + border: none; +} +#weighted-options table td { + padding: 5px; +} +#weighted-options table .td-left { + font-family: LexendDeca-Regular, sans-serif; + padding-right: 1rem; + width: 200px; +} +#weighted-options table .td-middle { + display: flex; + flex-direction: column; + justify-content: space-evenly; + padding-right: 1rem; +} +#weighted-options table .td-right { + width: 4rem; + text-align: right; +} +#weighted-options table .td-delete { + width: 50px; + text-align: right; +} +#weighted-options table .range-option-delete { + cursor: pointer; +} +#weighted-options #weighted-options-button-row { + display: flex; + flex-direction: row; + justify-content: space-between; + margin-top: 15px; +} +#weighted-options #user-message { + display: none; + width: calc(100% - 8px); + background-color: #ffe86b; + border-radius: 4px; + color: #000000; + padding: 4px; + text-align: center; +} +#weighted-options #user-message.visible { + display: block; + cursor: pointer; +} +#weighted-options h1 { + font-size: 2.5rem; + font-weight: normal; + width: 100%; + margin-bottom: 0.5rem; + color: #ffffff; + text-shadow: 1px 1px 4px #000000; +} +#weighted-options h2, #weighted-options details summary.h2 { + font-size: 2rem; + font-weight: normal; + border-bottom: 1px solid #ffffff; + width: 100%; + margin-bottom: 0.5rem; + color: #ffe993; + text-transform: none; + text-shadow: 1px 1px 2px #000000; +} +#weighted-options h3, #weighted-options h4, #weighted-options h5, #weighted-options h6 { + color: #ffffff; + text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); + text-transform: none; + cursor: unset; +} +#weighted-options h3.option-group-header { + margin-top: 0.75rem; + font-weight: bold; +} +#weighted-options a { + color: #ffef00; + cursor: pointer; +} +#weighted-options input:not([type]) { + border: 1px solid #000000; + padding: 3px; + border-radius: 3px; + min-width: 150px; +} +#weighted-options input:not([type]):focus { + border: 1px solid #ffffff; +} +#weighted-options .invisible { + display: none; +} +#weighted-options .unsupported-option { + margin-top: 0.5rem; +} +#weighted-options .set-container, #weighted-options .dict-container, #weighted-options .list-container { + display: flex; + flex-direction: column; + background-color: rgba(0, 0, 0, 0.25); + border: 1px solid rgba(20, 20, 20, 0.25); + border-radius: 3px; + color: #ffffff; + max-height: 15rem; + min-width: 14.5rem; + overflow-y: auto; + padding-right: 0.25rem; + padding-left: 0.25rem; + margin-top: 0.5rem; +} +#weighted-options .set-container .divider, #weighted-options .dict-container .divider, #weighted-options .list-container .divider { + width: 100%; + height: 2px; + background-color: rgba(20, 20, 20, 0.25); + margin-top: 0.125rem; + margin-bottom: 0.125rem; +} +#weighted-options .set-container .set-entry, #weighted-options .set-container .dict-entry, #weighted-options .set-container .list-entry, #weighted-options .dict-container .set-entry, #weighted-options .dict-container .dict-entry, #weighted-options .dict-container .list-entry, #weighted-options .list-container .set-entry, #weighted-options .list-container .dict-entry, #weighted-options .list-container .list-entry { + display: flex; + flex-direction: row; + align-items: flex-start; + padding-bottom: 0.25rem; + padding-top: 0.25rem; + user-select: none; + line-height: 1rem; +} +#weighted-options .set-container .set-entry:hover, #weighted-options .set-container .dict-entry:hover, #weighted-options .set-container .list-entry:hover, #weighted-options .dict-container .set-entry:hover, #weighted-options .dict-container .dict-entry:hover, #weighted-options .dict-container .list-entry:hover, #weighted-options .list-container .set-entry:hover, #weighted-options .list-container .dict-entry:hover, #weighted-options .list-container .list-entry:hover { + background-color: rgba(20, 20, 20, 0.25); +} +#weighted-options .set-container .set-entry input[type=checkbox], #weighted-options .set-container .dict-entry input[type=checkbox], #weighted-options .set-container .list-entry input[type=checkbox], #weighted-options .dict-container .set-entry input[type=checkbox], #weighted-options .dict-container .dict-entry input[type=checkbox], #weighted-options .dict-container .list-entry input[type=checkbox], #weighted-options .list-container .set-entry input[type=checkbox], #weighted-options .list-container .dict-entry input[type=checkbox], #weighted-options .list-container .list-entry input[type=checkbox] { + margin-right: 0.25rem; +} +#weighted-options .set-container .set-entry input[type=number], #weighted-options .set-container .dict-entry input[type=number], #weighted-options .set-container .list-entry input[type=number], #weighted-options .dict-container .set-entry input[type=number], #weighted-options .dict-container .dict-entry input[type=number], #weighted-options .dict-container .list-entry input[type=number], #weighted-options .list-container .set-entry input[type=number], #weighted-options .list-container .dict-entry input[type=number], #weighted-options .list-container .list-entry input[type=number] { + max-width: 1.5rem; + max-height: 1rem; + margin-left: 0.125rem; + text-align: center; + /* Hide arrows on input[type=number] fields */ + -moz-appearance: textfield; +} +#weighted-options .set-container .set-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .set-container .set-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .set-container .dict-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .set-container .dict-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .set-container .list-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .set-container .list-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .dict-container .set-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .dict-container .set-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .dict-container .dict-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .dict-container .dict-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .dict-container .list-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .dict-container .list-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .list-container .set-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .list-container .set-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .list-container .dict-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .list-container .dict-entry input[type=number]::-webkit-inner-spin-button, #weighted-options .list-container .list-entry input[type=number]::-webkit-outer-spin-button, #weighted-options .list-container .list-entry input[type=number]::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +#weighted-options .set-container .set-entry label, #weighted-options .set-container .dict-entry label, #weighted-options .set-container .list-entry label, #weighted-options .dict-container .set-entry label, #weighted-options .dict-container .dict-entry label, #weighted-options .dict-container .list-entry label, #weighted-options .list-container .set-entry label, #weighted-options .list-container .dict-entry label, #weighted-options .list-container .list-entry label { + flex-grow: 1; + margin-right: 0; + min-width: unset; + display: unset; +} + +.hidden { + display: none; +} + +@media all and (max-width: 1000px), all and (orientation: portrait) { + #weighted-options .game-options { + justify-content: flex-start; + flex-wrap: wrap; + } + #game-options table label { + display: block; + min-width: 200px; + } +} + +/*# sourceMappingURL=weightedOptions.css.map */ diff --git a/WebHostLib/static/styles/weightedOptions/weightedOptions.css.map b/WebHostLib/static/styles/weightedOptions/weightedOptions.css.map new file mode 100644 index 000000000000..7c57cde01506 --- /dev/null +++ b/WebHostLib/static/styles/weightedOptions/weightedOptions.css.map @@ -0,0 +1 @@ +{"version":3,"sourceRoot":"","sources":["weightedOptions.scss"],"names":[],"mappings":"AAAA;EACI;EACA;EACA;EACA;;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AAGI;EACI;EACA;;AAGJ;EACI;EACA;EACA;;AAIR;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;;AAEA;EACI;EACA;EACA;EACA;;AAEA;EACI;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;;AAOZ;EACI;;AAGJ;EACI;EACA;;AAIR;EACI;EACA;EACA;;AAEA;EACI;;AAGJ;EACI;;AAGJ;EACI;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;;AAGJ;EACI;EACA;;AAGJ;EACI;EACA;;AAGJ;EACI;;AAIR;EACI;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;EACA;;AAIR;EACI;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;;AAIA;EACI;EACA;;AAIR;EACI;EACA;;AAGJ;EACI;EACA;EACA;EACA;;AAEA;EACI;;AAIR;EACI;;AAGJ;EACI;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;EACA;EACA;EACA;EACA;;AAGJ;EACI;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACI;;AAGJ;EACI;;AAGJ;EACI;EACA;EACA;EACA;AAEA;EACA;;AACA;EACI;EACA;;AAIR;EACI;EACA;EACA;EACA;;;AAMhB;EACI;;;AAGJ;EACI;IACI;IACA;;EAGJ;IACI;IACA","file":"weightedOptions.css"} \ No newline at end of file diff --git a/WebHostLib/static/styles/weightedOptions/weightedOptions.scss b/WebHostLib/static/styles/weightedOptions/weightedOptions.scss new file mode 100644 index 000000000000..7ff3a2c3722e --- /dev/null +++ b/WebHostLib/static/styles/weightedOptions/weightedOptions.scss @@ -0,0 +1,274 @@ +html{ + background-image: url('../../static/backgrounds/grass.png'); + background-repeat: repeat; + background-size: 650px 650px; + scroll-padding-top: 90px; +} + +#weighted-options{ + max-width: 1000px; + margin-left: auto; + margin-right: auto; + background-color: rgba(0, 0, 0, 0.15); + border-radius: 8px; + padding: 1rem; + color: #eeffeb; + + #weighted-options-header{ + h1{ + margin-bottom: 0; + padding-bottom: 0; + } + + h1:nth-child(2){ + font-size: 1.4rem; + margin-top: -8px; + margin-bottom: 0.5rem; + } + } + + .js-warning-banner{ + width: calc(100% - 1rem); + padding: 0.5rem; + border-radius: 4px; + background-color: #f3f309; + color: #000000; + margin-bottom: 0.5rem; + text-align: center; + } + + .option-wrapper{ + width: 100%; + margin-bottom: 2rem; + + .add-option-div{ + display: flex; + flex-direction: row; + justify-content: flex-start; + margin-bottom: 1rem; + + button{ + width: auto; + height: auto; + margin: 0 0 0 0.15rem; + padding: 0 0.25rem; + border-radius: 4px; + cursor: default; + + &:active{ + margin-bottom: 1px; + } + } + } + } + + p{ + &.option-description{ + margin: 0 0 1rem; + } + + &.hint-text{ + margin: 0 0 1rem; + font-style: italic; + }; + } + + table{ + width: 100%; + margin-top: 0.5rem; + margin-bottom: 1.5rem; + + th, td{ + border: none; + } + + td{ + padding: 5px; + } + + .td-left{ + font-family: LexendDeca-Regular, sans-serif; + padding-right: 1rem; + width: 200px; + } + + .td-middle{ + display: flex; + flex-direction: column; + justify-content: space-evenly; + padding-right: 1rem; + } + + .td-right{ + width: 4rem; + text-align: right; + } + + .td-delete{ + width: 50px; + text-align: right; + } + + .range-option-delete{ + cursor: pointer; + } + } + + #weighted-options-button-row{ + display: flex; + flex-direction: row; + justify-content: space-between; + margin-top: 15px; + } + + #user-message{ + display: none; + width: calc(100% - 8px); + background-color: #ffe86b; + border-radius: 4px; + color: #000000; + padding: 4px; + text-align: center; + + &.visible{ + display: block; + cursor: pointer; + } + } + + h1{ + font-size: 2.5rem; + font-weight: normal; + width: 100%; + margin-bottom: 0.5rem; + color: #ffffff; + text-shadow: 1px 1px 4px #000000; + } + + h2, details summary.h2{ + font-size: 2rem; + font-weight: normal; + border-bottom: 1px solid #ffffff; + width: 100%; + margin-bottom: 0.5rem; + color: #ffe993; + text-transform: none; + text-shadow: 1px 1px 2px #000000; + } + + h3, h4, h5, h6{ + color: #ffffff; + text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); + text-transform: none; + cursor: unset; + } + + h3{ + &.option-group-header{ + margin-top: 0.75rem; + font-weight: bold; + } + } + + a{ + color: #ffef00; + cursor: pointer; + } + + input:not([type]){ + border: 1px solid #000000; + padding: 3px; + border-radius: 3px; + min-width: 150px; + + &:focus{ + border: 1px solid #ffffff; + } + } + + .invisible{ + display: none; + } + + .unsupported-option{ + margin-top: 0.5rem; + } + + .set-container, .dict-container, .list-container{ + display: flex; + flex-direction: column; + background-color: rgba(0, 0, 0, 0.25); + border: 1px solid rgba(20, 20, 20, 0.25); + border-radius: 3px; + color: #ffffff; + max-height: 15rem; + min-width: 14.5rem; + overflow-y: auto; + padding-right: 0.25rem; + padding-left: 0.25rem; + margin-top: 0.5rem; + + .divider{ + width: 100%; + height: 2px; + background-color: rgba(20, 20, 20, 0.25); + margin-top: 0.125rem; + margin-bottom: 0.125rem; + } + + .set-entry, .dict-entry, .list-entry{ + display: flex; + flex-direction: row; + align-items: flex-start; + padding-bottom: 0.25rem; + padding-top: 0.25rem; + user-select: none; + line-height: 1rem; + + &:hover{ + background-color: rgba(20, 20, 20, 0.25); + } + + input[type=checkbox]{ + margin-right: 0.25rem; + } + + input[type=number]{ + max-width: 1.5rem; + max-height: 1rem; + margin-left: 0.125rem; + text-align: center; + + /* Hide arrows on input[type=number] fields */ + -moz-appearance: textfield; + &::-webkit-outer-spin-button, &::-webkit-inner-spin-button{ + -webkit-appearance: none; + margin: 0; + } + } + + label{ + flex-grow: 1; + margin-right: 0; + min-width: unset; + display: unset; + } + } + } +} + +.hidden{ + display: none; +} + +@media all and (max-width: 1000px), all and (orientation: portrait){ + #weighted-options .game-options{ + justify-content: flex-start; + flex-wrap: wrap; + } + + #game-options table label{ + display: block; + min-width: 200px; + } +} diff --git a/WebHostLib/templates/hostRoom.html b/WebHostLib/templates/hostRoom.html index 2981c41452f0..2bbfe4ad0169 100644 --- a/WebHostLib/templates/hostRoom.html +++ b/WebHostLib/templates/hostRoom.html @@ -24,7 +24,8 @@
{% endif %} {% if room.tracker %} - This room has a Multiworld Tracker enabled. + This room has a Multiworld Tracker + and a Sphere Tracker enabled.
{% endif %} The server for this room will be paused after {{ room.timeout//60//60 }} hours of inactivity. diff --git a/WebHostLib/templates/multispheretracker.html b/WebHostLib/templates/multispheretracker.html new file mode 100644 index 000000000000..a86697498396 --- /dev/null +++ b/WebHostLib/templates/multispheretracker.html @@ -0,0 +1,72 @@ +{% extends "tablepage.html" %} +{% block head %} + {{ super() }} + Multiworld Sphere Tracker + + +{% endblock %} + +{% block body %} + {% include "header/dirtHeader.html" %} + +
+
+ + +
+ {% if tracker_data.get_spheres() %} + This tracker lists already found locations by their logical access sphere. + It ignores items that cannot be sent + and will therefore differ from the sphere numbers in the spoiler playthrough. + This tracker will automatically update itself periodically. + {% else %} + This Multiworld has no Sphere data, likely due to being too old, cannot display data. + {% endif %} +
+
+ +
+ {%- for team, players in tracker_data.get_all_players().items() %} +
+ + + + + {#- Mimicking hint table header for familiarity. #} + + + + + + + + + {%- for sphere in tracker_data.get_spheres() %} + {%- set current_sphere = loop.index %} + {%- for player, sphere_location_ids in sphere.items() %} + {%- set checked_locations = tracker_data.get_player_checked_locations(team, player) %} + {%- set finder_game = tracker_data.get_player_game(team, player) %} + {%- set player_location_data = tracker_data.get_player_locations(team, player) %} + {%- for location_id in sphere_location_ids.intersection(checked_locations) %} + + {%- set item_id, receiver, item_flags = player_location_data[location_id] %} + {%- set receiver_game = tracker_data.get_player_game(team, receiver) %} + + + + + + + + {%- endfor %} + + {%- endfor %} + {%- endfor %} + +
SphereFinderReceiverItemLocationGame
{{ current_sphere }}{{ tracker_data.get_player_name(team, player) }}{{ tracker_data.get_player_name(team, receiver) }}{{ tracker_data.item_id_to_name[receiver_game][item_id] }}{{ tracker_data.location_id_to_name[finder_game][location_id] }}{{ finder_game }}
+
+ + {%- endfor -%} +
+
+{% endblock %} diff --git a/WebHostLib/templates/multitracker.html b/WebHostLib/templates/multitracker.html index b16d4714ec6a..1b371b1229e5 100644 --- a/WebHostLib/templates/multitracker.html +++ b/WebHostLib/templates/multitracker.html @@ -10,7 +10,7 @@ {% include "header/dirtHeader.html" %} {% include "multitrackerNavigation.html" %} -
+
diff --git a/WebHostLib/templates/ootTracker.html b/WebHostLib/templates/ootTracker.html deleted file mode 100644 index ea7a6d5a4c30..000000000000 --- a/WebHostLib/templates/ootTracker.html +++ /dev/null @@ -1,180 +0,0 @@ - - - - {{ player_name }}'s Tracker - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
{{ hookshot_length }}
-
-
-
- -
{{ bottle_count if bottle_count > 0 else '' }}
-
-
-
- -
{{ wallet_size }}
-
-
-
- -
Zelda
-
-
-
- -
Epona
-
-
-
- -
Saria
-
-
-
- -
Sun
-
-
-
- -
Time
-
-
-
- -
Storms
-
-
-
- -
{{ token_count }}
-
-
-
- -
Min
-
-
-
- -
Bol
-
-
-
- -
Ser
-
-
-
- -
Req
-
-
-
- -
Noc
-
-
-
- -
Pre
-
-
-
- -
{{ piece_count if piece_count > 0 else '' }}
-
-
- - - - - - - - {% for area in checks_done %} - - - - - - - - {% for location in location_info[area] %} - - - - - - - {% endfor %} - - {% endfor %} -
Items
{{ area }} {{'▼' if area != 'Total'}}{{ small_key_counts.get(area, '-') }}{{ boss_key_counts.get(area, '-') }}{{ checks_done[area] }} / {{ checks_in_area[area] }}
{{ location }}{{ '✔' if location_info[area][location] else '' }}
-
- - diff --git a/WebHostLib/templates/player-options.html b/WebHostLib/templates/player-options.html deleted file mode 100644 index 4c749752882a..000000000000 --- a/WebHostLib/templates/player-options.html +++ /dev/null @@ -1,62 +0,0 @@ -{% extends 'pageWrapper.html' %} - -{% block head %} - {{ game }} Options - - - - - - -{% endblock %} - -{% block body %} - {% include 'header/'+theme+'Header.html' %} -
-
-

Player Options

-

Choose the options you would like to play with! You may generate a single-player game from this page, - or download an options file you can use to participate in a MultiWorld.

- -

- A more advanced options configuration for all games can be found on the - Weighted options page. -
- 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. -

- -
-
- - -
-
- - -
- -
- -

Game Options

-
-
-
-
- -
- - - -
-
-{% endblock %} diff --git a/WebHostLib/templates/playerOptions/macros.html b/WebHostLib/templates/playerOptions/macros.html new file mode 100644 index 000000000000..b34ac79a029e --- /dev/null +++ b/WebHostLib/templates/playerOptions/macros.html @@ -0,0 +1,210 @@ +{% macro Toggle(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ + {{ RandomizeButton(option_name, option) }} +
+{% endmacro %} + +{% macro Choice(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ + {{ RandomizeButton(option_name, option) }} +
+{% endmacro %} + +{% macro Range(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ + + {{ option.default | default(option.range_start) if option.default != "random" else option.range_start }} + + {{ RandomizeButton(option_name, option) }} +
+{% endmacro %} + +{% macro NamedRange(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ +
+ + + {{ option.default | default(option.range_start) if option.default != "random" else option.range_start }} + + {{ RandomizeButton(option_name, option) }} +
+
+{% endmacro %} + +{% macro FreeText(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ +
+{% endmacro %} + +{% macro TextChoice(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+
+ + {{ RandomizeButton(option_name, option) }} +
+ +
+{% endmacro %} + +{% macro ItemDict(option_name, option, world) %} + {{ OptionTitle(option_name, option) }} +
+ {% for item_name in (option.valid_keys|sort if (option.valid_keys|length > 0) else world.item_names|sort) %} +
+ + +
+ {% endfor %} +
+{% endmacro %} + +{% macro OptionList(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ {% for key in (option.valid_keys if option.valid_keys is ordered else option.valid_keys|sort) %} +
+ + +
+ {% endfor %} +
+{% endmacro %} + +{% macro LocationSet(option_name, option, world) %} + {{ OptionTitle(option_name, option) }} +
+ {% for group_name in world.location_name_groups.keys()|sort %} + {% if group_name != "Everywhere" %} +
+ + +
+ {% endif %} + {% endfor %} + {% if world.location_name_groups.keys()|length > 1 %} +
 
+ {% endif %} + {% for location_name in (option.valid_keys|sort if (option.valid_keys|length > 0) else world.location_names|sort) %} +
+ + +
+ {% endfor %} +
+{% endmacro %} + +{% macro ItemSet(option_name, option, world) %} + {{ OptionTitle(option_name, option) }} +
+ {% for group_name in world.item_name_groups.keys()|sort %} + {% if group_name != "Everything" %} +
+ + +
+ {% endif %} + {% endfor %} + {% if world.item_name_groups.keys()|length > 1 %} +
 
+ {% endif %} + {% for item_name in (option.valid_keys|sort if (option.valid_keys|length > 0) else world.item_names|sort) %} +
+ + +
+ {% endfor %} +
+{% endmacro %} + +{% macro OptionSet(option_name, option) %} + {{ OptionTitle(option_name, option) }} +
+ {% for key in (option.valid_keys if option.valid_keys is ordered else option.valid_keys|sort) %} +
+ + +
+ {% endfor %} +
+{% endmacro %} + +{% macro OptionTitle(option_name, option) %} + +{% endmacro %} + +{% macro RandomizeButton(option_name, option) %} +
+ +
+{% endmacro %} diff --git a/WebHostLib/templates/playerOptions/playerOptions.html b/WebHostLib/templates/playerOptions/playerOptions.html new file mode 100644 index 000000000000..2506cf9619e6 --- /dev/null +++ b/WebHostLib/templates/playerOptions/playerOptions.html @@ -0,0 +1,166 @@ +{% extends 'pageWrapper.html' %} +{% import 'playerOptions/macros.html' as inputs %} + +{% block head %} + {{ world_name }} Options + + + + + + +{% endblock %} + +{% block body %} + {% include 'header/'+theme+'Header.html' %} +
+ + +
{{ message }}
+ +
+

{{ world_name }}

+

Player Options

+
+

Choose the options you would like to play with! You may generate a single-player game from this page, + or download an options file you can use to participate in a MultiWorld.

+ +

+ A more advanced options configuration for all games can be found on the + Weighted options page. +
+ 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. +

+ +
+
+
+ + +
+
+ + +
+
+ +
+ {% for group_name, group_options in option_groups.items() %} +
+ {{ group_name }} +
+
+ {% for option_name, option in group_options.items() %} + {% if loop.index <= (loop.length / 2)|round(0,"ceil") %} + {% if issubclass(option, Options.Toggle) %} + {{ inputs.Toggle(option_name, option) }} + + {% elif issubclass(option, Options.TextChoice) %} + {{ inputs.TextChoice(option_name, option) }} + + {% elif issubclass(option, Options.Choice) %} + {{ inputs.Choice(option_name, option) }} + + {% elif issubclass(option, Options.NamedRange) %} + {{ inputs.NamedRange(option_name, option) }} + + {% elif issubclass(option, Options.Range) %} + {{ inputs.Range(option_name, option) }} + + {% elif issubclass(option, Options.FreeText) %} + {{ inputs.FreeText(option_name, option) }} + + {% elif issubclass(option, Options.ItemDict) and option.verify_item_name %} + {{ inputs.ItemDict(option_name, option, world) }} + + {% elif issubclass(option, Options.OptionList) and option.valid_keys %} + {{ inputs.OptionList(option_name, option) }} + + {% elif issubclass(option, Options.LocationSet) and option.verify_location_name %} + {{ inputs.LocationSet(option_name, option, world) }} + + {% elif issubclass(option, Options.ItemSet) and option.verify_item_name %} + {{ inputs.ItemSet(option_name, option, world) }} + + {% elif issubclass(option, Options.OptionSet) and option.valid_keys %} + {{ inputs.OptionSet(option_name, option) }} + + {% endif %} + {% endif %} + {% endfor %} +
+
+ {% for option_name, option in group_options.items() %} + {% if loop.index > (loop.length / 2)|round(0,"ceil") %} + {% if issubclass(option, Options.Toggle) %} + {{ inputs.Toggle(option_name, option) }} + + {% elif issubclass(option, Options.TextChoice) %} + {{ inputs.TextChoice(option_name, option) }} + + {% elif issubclass(option, Options.Choice) %} + {{ inputs.Choice(option_name, option) }} + + {% elif issubclass(option, Options.NamedRange) %} + {{ inputs.NamedRange(option_name, option) }} + + {% elif issubclass(option, Options.Range) %} + {{ inputs.Range(option_name, option) }} + + {% elif issubclass(option, Options.FreeText) %} + {{ inputs.FreeText(option_name, option) }} + + {% elif issubclass(option, Options.ItemDict) and option.verify_item_name %} + {{ inputs.ItemDict(option_name, option, world) }} + + {% elif issubclass(option, Options.OptionList) and option.valid_keys %} + {{ inputs.OptionList(option_name, option) }} + + {% elif issubclass(option, Options.LocationSet) and option.verify_location_name %} + {{ inputs.LocationSet(option_name, option, world) }} + + {% elif issubclass(option, Options.ItemSet) and option.verify_item_name %} + {{ inputs.ItemSet(option_name, option, world) }} + + {% elif issubclass(option, Options.OptionSet) and option.valid_keys %} + {{ inputs.OptionSet(option_name, option) }} + + {% endif %} + {% endif %} + {% endfor %} +
+
+
+ {% endfor %} +
+ +
+ + +
+
+
+{% endblock %} diff --git a/WebHostLib/templates/siteMap.html b/WebHostLib/templates/siteMap.html index 231ec83e2420..cdd6ad45eb27 100644 --- a/WebHostLib/templates/siteMap.html +++ b/WebHostLib/templates/siteMap.html @@ -24,7 +24,6 @@

Base Pages

  • Supported Games Page
  • Tutorials Page
  • User Content
  • -
  • Weighted Options Page
  • Game Statistics
  • Glossary
  • @@ -50,8 +49,12 @@

    Game Options Pages

    diff --git a/WebHostLib/templates/supportedGames.html b/WebHostLib/templates/supportedGames.html index 6666323c9387..b3f20d293543 100644 --- a/WebHostLib/templates/supportedGames.html +++ b/WebHostLib/templates/supportedGames.html @@ -41,28 +41,28 @@

    Currently Supported Games

    {% for game_name in worlds | title_sorted %} {% set world = worlds[game_name] %} -

    - {{ game_name }} -

    -
    + {{ game_name }} {{ world.__doc__ | default("No description provided.", true) }}
    Game Page {% if world.web.tutorials %} | - Setup Guides + Setup Guides {% endif %} {% if world.web.options_page is string %} | - Options Page + Options Page (External Link) {% elif world.web.options_page %} | Options Page + | + Advanced Options {% endif %} {% if world.web.bug_report_page %} | Report a Bug {% endif %} -

    +
    {% endfor %}
    {% endblock %} diff --git a/WebHostLib/templates/weighted-options.html b/WebHostLib/templates/weighted-options.html deleted file mode 100644 index 032a4eeb905c..000000000000 --- a/WebHostLib/templates/weighted-options.html +++ /dev/null @@ -1,48 +0,0 @@ -{% extends 'pageWrapper.html' %} - -{% block head %} - {{ game }} Options - - - - - - -{% endblock %} - -{% block body %} - {% include 'header/grassHeader.html' %} -
    -
    -

    Weighted Options

    -

    Weighted options allow you to choose how likely a particular option is to be used in game generation. - The higher an option is weighted, the more likely the option will be chosen. Think of them like - entries in a raffle.

    - -

    Choose the games and options you would like to play with! You may generate a single-player game from - this page, or download an options file you can use to participate in a MultiWorld.

    - -

    A list of all games you have generated can be found on the User Content - page.

    - -


    - -

    - -
    - -
    - - -
    - -
    - -
    - - - -
    -
    -{% endblock %} diff --git a/WebHostLib/templates/weightedOptions/macros.html b/WebHostLib/templates/weightedOptions/macros.html new file mode 100644 index 000000000000..55a56e32851d --- /dev/null +++ b/WebHostLib/templates/weightedOptions/macros.html @@ -0,0 +1,264 @@ +{% macro Toggle(option_name, option) %} + + + {{ RangeRow(option_name, option, "No", "false", False, "true" if option.default else "false") }} + {{ RangeRow(option_name, option, "Yes", "true", False, "true" if option.default else "false") }} + {{ RandomRow(option_name, option) }} + +
    +{% endmacro %} + +{% macro DefaultOnToggle(option_name, option) %} + + {{ Toggle(option_name, option) }} +{% endmacro %} + +{% macro Choice(option_name, option) %} + + + {% for id, name in option.name_lookup.items() %} + {% if name != 'random' %} + {% if option.default != 'random' %} + {{ RangeRow(option_name, option, option.get_option_name(id), name, False, name if option.get_option_name(option.default)|lower == name else None) }} + {% else %} + {{ RangeRow(option_name, option, option.get_option_name(id), name) }} + {% endif %} + {% endif %} + {% endfor %} + {{ RandomRow(option_name, option) }} + +
    +{% endmacro %} + +{% macro Range(option_name, option) %} +
    + This is a range option. +

    + Accepted values:
    + Normal range: {{ option.range_start }} - {{ option.range_end }} + {% if option.special_range_names %} +

    + The following values have special meanings, and may fall outside the normal range. +
      + {% for name, value in option.special_range_names.items() %} +
    • {{ value }}: {{ name }}
    • + {% endfor %} +
    + {% endif %} +
    + + +
    +
    + + + {{ RangeRow(option_name, option, option.range_start, option.range_start, True) }} + {% if 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) }} + {{ RandomRows(option_name, option) }} + +
    +{% endmacro %} + +{% macro NamedRange(option_name, option) %} + + {{ Range(option_name, option) }} +{% endmacro %} + +{% macro FreeText(option_name, option) %} +
    + This option allows custom values only. Please enter your desired values below. +
    + + +
    + + + {% if option.default %} + {{ RangeRow(option_name, option, option.default, option.default) }} + {% endif %} + +
    +
    +{% endmacro %} + +{% macro TextChoice(option_name, option) %} +
    + Custom values are also allowed for this option. To create one, enter it into the input box below. +
    + + +
    +
    + + + {% for id, name in option.name_lookup.items() %} + {% if name != 'random' %} + {% if option.default != 'random' %} + {{ RangeRow(option_name, option, option.get_option_name(id), name, False, name if option.get_option_name(option.default)|lower == name else None) }} + {% else %} + {{ RangeRow(option_name, option, option.get_option_name(id), name) }} + {% endif %} + {% endif %} + {% endfor %} + {{ RandomRow(option_name, option) }} + +
    +{% endmacro %} + +{% macro PlandoBosses(option_name, option) %} + + {{ TextChoice(option_name, option) }} +{% endmacro %} + +{% macro ItemDict(option_name, option, world) %} +
    + {% for item_name in (option.valid_keys|sort if (option.valid_keys|length > 0) else world.item_names|sort) %} +
    + + +
    + {% endfor %} +
    +{% endmacro %} + +{% macro OptionList(option_name, option) %} +
    + {% for key in (option.valid_keys if option.valid_keys is ordered else option.valid_keys|sort) %} +
    + + +
    + {% endfor %} +
    +{% endmacro %} + +{% macro LocationSet(option_name, option, world) %} +
    + {% for group_name in world.location_name_groups.keys()|sort %} + {% if group_name != "Everywhere" %} +
    + + +
    + {% endif %} + {% endfor %} + {% if world.location_name_groups.keys()|length > 1 %} +
     
    + {% endif %} + {% for location_name in (option.valid_keys|sort if (option.valid_keys|length > 0) else world.location_names|sort) %} +
    + + +
    + {% endfor %} +
    +{% endmacro %} + +{% macro ItemSet(option_name, option, world) %} +
    + {% for group_name in world.item_name_groups.keys()|sort %} + {% if group_name != "Everything" %} +
    + + +
    + {% endif %} + {% endfor %} + {% if world.item_name_groups.keys()|length > 1 %} +
     
    + {% endif %} + {% for item_name in (option.valid_keys|sort if (option.valid_keys|length > 0) else world.item_names|sort) %} +
    + + +
    + {% endfor %} +
    +{% endmacro %} + +{% macro OptionSet(option_name, option) %} +
    + {% for key in (option.valid_keys if option.valid_keys is ordered else option.valid_keys|sort) %} +
    + + +
    + {% endfor %} +
    +{% endmacro %} + +{% macro OptionTitleTd(option_name, value) %} + + + +{% endmacro %} + +{% macro RandomRow(option_name, option, extra_column=False) %} + {{ RangeRow(option_name, option, "Random", "random") }} +{% endmacro %} + +{% macro RandomRows(option_name, option, extra_column=False) %} + {% for key, value in {"Random": "random", "Random (Low)": "random-low", "Random (Middle)": "random-middle", "Random (High)": "random-high"}.items() %} + {{ RangeRow(option_name, option, key, value) }} + {% endfor %} +{% endmacro %} + +{% macro RangeRow(option_name, option, display_value, value, can_delete=False, default_override=None) %} + + + + + + + + + + {% if option.default == value or default_override == value %} + 25 + {% else %} + 0 + {% endif %} + + + {% if can_delete %} + + + ❌ + + + {% else %} + + {% endif %} + +{% endmacro %} diff --git a/WebHostLib/templates/weightedOptions/weightedOptions.html b/WebHostLib/templates/weightedOptions/weightedOptions.html new file mode 100644 index 000000000000..b3aefd483535 --- /dev/null +++ b/WebHostLib/templates/weightedOptions/weightedOptions.html @@ -0,0 +1,119 @@ +{% extends 'pageWrapper.html' %} +{% import 'weightedOptions/macros.html' as inputs %} + +{% block head %} + {{ world_name }} Weighted Options + + + + +{% endblock %} + +{% block body %} + {% include 'header/'+theme+'Header.html' %} +
    + + +
    + +
    +

    {{ world_name }}

    +

    Weighted Options

    +
    + +
    + +

    Weighted options allow you to choose how likely a particular option's value is to be used in game + generation. The higher a value is weighted, the more likely the option will be chosen. Think of them like + entries in a raffle.

    + +

    Choose the options you would like to play with! You may generate a single-player game from + this page, or download an options file you can use to participate in a MultiWorld.

    + +

    A list of all games you have generated can be found on the User Content + page.

    + + +


    + +

    + +
    + {% for group_name, group_options in option_groups.items() %} +
    + {{ group_name }} + {% for option_name, option in group_options.items() %} +
    +

    {{ option.display_name|default(option_name) }}

    +
    + {{ option.__doc__ }} +
    + {% if issubclass(option, Options.Toggle) %} + {{ inputs.Toggle(option_name, option) }} + + {% elif issubclass(option, Options.DefaultOnToggle) %} + {{ inputs.DefaultOnToggle(option_name, option) }} + + {% elif issubclass(option, Options.PlandoBosses) %} + {{ inputs.PlandoBosses(option_name, option) }} + + {% elif issubclass(option, Options.TextChoice) %} + {{ inputs.TextChoice(option_name, option) }} + + {% elif issubclass(option, Options.Choice) %} + {{ inputs.Choice(option_name, option) }} + + {% elif issubclass(option, Options.NamedRange) %} + {{ inputs.NamedRange(option_name, option) }} + + {% elif issubclass(option, Options.Range) %} + {{ inputs.Range(option_name, option) }} + + {% elif issubclass(option, Options.FreeText) %} + {{ inputs.FreeText(option_name, option) }} + + {% elif issubclass(option, Options.ItemDict) and option.verify_item_name %} + {{ inputs.ItemDict(option_name, option, world) }} + + {% elif issubclass(option, Options.OptionList) and option.valid_keys %} + {{ inputs.OptionList(option_name, option) }} + + {% elif issubclass(option, Options.LocationSet) and option.verify_location_name %} + {{ inputs.LocationSet(option_name, option, world) }} + + {% elif issubclass(option, Options.ItemSet) and option.verify_item_name %} + {{ inputs.ItemSet(option_name, option, world) }} + + {% elif issubclass(option, Options.OptionSet) and option.valid_keys %} + {{ inputs.OptionSet(option_name, option) }} + + {% else %} +
    + This option is not supported. Please edit your .yaml file manually. +
    + + {% endif %} +
    + {% endfor %} +
    + {% endfor %} +
    + +
    + + +
    +
    +
    +{% endblock %} diff --git a/WebHostLib/tracker.py b/WebHostLib/tracker.py index fd233da131e7..36ebaacbcb0b 100644 --- a/WebHostLib/tracker.py +++ b/WebHostLib/tracker.py @@ -3,8 +3,9 @@ from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Set, Tuple, NamedTuple, Counter from uuid import UUID +from email.utils import parsedate_to_datetime -from flask import render_template +from flask import render_template, make_response, Response, request from werkzeug.exceptions import abort from MultiServer import Context, get_saving_second @@ -291,47 +292,47 @@ def get_room_videos(self) -> Dict[TeamPlayer, Tuple[str, str]]: return video_feeds + @_cache_results + def get_spheres(self) -> List[List[int]]: + """ each sphere is { player: { location_id, ... } } """ + return self._multidata.get("spheres", []) -@app.route("/tracker///") -def get_player_tracker(tracker: UUID, tracked_team: int, tracked_player: int, generic: bool = False) -> str: - key = f"{tracker}_{tracked_team}_{tracked_player}_{generic}" - tracker_page = cache.get(key) - if tracker_page: - return tracker_page - timeout, tracker_page = get_timeout_and_tracker(tracker, tracked_team, tracked_player, generic) - cache.set(key, tracker_page, timeout) - return tracker_page +def _process_if_request_valid(incoming_request, room: Optional[Room]) -> Optional[Response]: + if not room: + abort(404) + if_modified = incoming_request.headers.get("If-Modified-Since", None) + if if_modified: + if_modified = parsedate_to_datetime(if_modified) + # if_modified has less precision than last_activity, so we bring them to same precision + if if_modified >= room.last_activity.replace(microsecond=0): + return make_response("", 304) -@app.route("/generic_tracker///") -def get_generic_game_tracker(tracker: UUID, tracked_team: int, tracked_player: int) -> str: - return get_player_tracker(tracker, tracked_team, tracked_player, True) +@app.route("/tracker///") +def get_player_tracker(tracker: UUID, tracked_team: int, tracked_player: int, generic: bool = False) -> Response: + key = f"{tracker}_{tracked_team}_{tracked_player}_{generic}" + response: Optional[Response] = cache.get(key) + if response: + return response -@app.route("/tracker/", defaults={"game": "Generic"}) -@app.route("/tracker//") -@cache.memoize(timeout=TRACKER_CACHE_TIMEOUT_IN_SECONDS) -def get_multiworld_tracker(tracker: UUID, game: str): # Room must exist. room = Room.get(tracker=tracker) - if not room: - abort(404) - tracker_data = TrackerData(room) - enabled_trackers = list(get_enabled_multiworld_trackers(room).keys()) - if game not in _multiworld_trackers: - return render_generic_multiworld_tracker(tracker_data, enabled_trackers) + response = _process_if_request_valid(request, room) + if response: + return response - return _multiworld_trackers[game](tracker_data, enabled_trackers) + timeout, last_modified, tracker_page = get_timeout_and_player_tracker(room, tracked_team, tracked_player, generic) + response = make_response(tracker_page) + response.last_modified = last_modified + cache.set(key, response, timeout) + return response -def get_timeout_and_tracker(tracker: UUID, tracked_team: int, tracked_player: int, generic: bool) -> Tuple[int, str]: - # Room must exist. - room = Room.get(tracker=tracker) - if not room: - abort(404) - +def get_timeout_and_player_tracker(room: Room, tracked_team: int, tracked_player: int, generic: bool)\ + -> Tuple[int, datetime.datetime, str]: tracker_data = TrackerData(room) # Load and render the game-specific player tracker, or fallback to generic tracker if none exists. @@ -341,7 +342,48 @@ def get_timeout_and_tracker(tracker: UUID, tracked_team: int, tracked_player: in else: tracker = render_generic_tracker(tracker_data, tracked_team, tracked_player) - return (tracker_data.get_room_saving_second() - datetime.datetime.now().second) % 60 or 60, tracker + return ((tracker_data.get_room_saving_second() - datetime.datetime.now().second) + % TRACKER_CACHE_TIMEOUT_IN_SECONDS or TRACKER_CACHE_TIMEOUT_IN_SECONDS, room.last_activity, tracker) + + +@app.route("/generic_tracker///") +def get_generic_game_tracker(tracker: UUID, tracked_team: int, tracked_player: int) -> Response: + return get_player_tracker(tracker, tracked_team, tracked_player, True) + + +@app.route("/tracker/", defaults={"game": "Generic"}) +@app.route("/tracker//") +def get_multiworld_tracker(tracker: UUID, game: str) -> Response: + key = f"{tracker}_{game}" + response: Optional[Response] = cache.get(key) + if response: + return response + + # Room must exist. + room = Room.get(tracker=tracker) + + response = _process_if_request_valid(request, room) + if response: + return response + + timeout, last_modified, tracker_page = get_timeout_and_multiworld_tracker(room, game) + response = make_response(tracker_page) + response.last_modified = last_modified + cache.set(key, response, timeout) + return response + + +def get_timeout_and_multiworld_tracker(room: Room, game: str)\ + -> Tuple[int, datetime.datetime, str]: + tracker_data = TrackerData(room) + enabled_trackers = list(get_enabled_multiworld_trackers(room).keys()) + if game in _multiworld_trackers: + tracker = _multiworld_trackers[game](tracker_data, enabled_trackers) + else: + tracker = render_generic_multiworld_tracker(tracker_data, enabled_trackers) + + return ((tracker_data.get_room_saving_second() - datetime.datetime.now().second) + % TRACKER_CACHE_TIMEOUT_IN_SECONDS or TRACKER_CACHE_TIMEOUT_IN_SECONDS, room.last_activity, tracker) def get_enabled_multiworld_trackers(room: Room) -> Dict[str, Callable]: @@ -411,9 +453,30 @@ def render_generic_multiworld_tracker(tracker_data: TrackerData, enabled_tracker videos=tracker_data.get_room_videos(), item_id_to_name=tracker_data.item_id_to_name, location_id_to_name=tracker_data.location_id_to_name, + saving_second=tracker_data.get_room_saving_second(), ) +def render_generic_multiworld_sphere_tracker(tracker_data: TrackerData) -> str: + return render_template( + "multispheretracker.html", + room=tracker_data.room, + tracker_data=tracker_data, + ) + + +@app.route("/sphere_tracker/") +@cache.memoize(timeout=TRACKER_CACHE_TIMEOUT_IN_SECONDS) +def get_multiworld_sphere_tracker(tracker: UUID): + # Room must exist. + room = Room.get(tracker=tracker) + if not room: + abort(404) + + tracker_data = TrackerData(room) + return render_generic_multiworld_sphere_tracker(tracker_data) + + # TODO: This is a temporary solution until a proper Tracker API can be implemented for tracker templates and data to # live in their respective world folders. diff --git a/Zelda1Client.py b/Zelda1Client.py index cd76a0a5ca78..6d7af0a94dcf 100644 --- a/Zelda1Client.py +++ b/Zelda1Client.py @@ -152,7 +152,7 @@ def get_payload(ctx: ZeldaContext): def reconcile_shops(ctx: ZeldaContext): - checked_location_names = [ctx.location_names[location] for location in ctx.checked_locations] + checked_location_names = [ctx.location_names.lookup_in_slot(location) for location in ctx.checked_locations] shops = [location for location in checked_location_names if "Shop" in location] left_slots = [shop for shop in shops if "Left" in shop] middle_slots = [shop for shop in shops if "Middle" in shop] @@ -190,7 +190,7 @@ async def parse_locations(locations_array, ctx: ZeldaContext, force: bool, zone= locations_checked = [] location = None for location in ctx.missing_locations: - location_name = ctx.location_names[location] + location_name = ctx.location_names.lookup_in_slot(location) if location_name in Locations.overworld_locations and zone == "overworld": status = locations_array[Locations.major_location_offsets[location_name]] diff --git a/data/client.kv b/data/client.kv index bf98fa151770..dc8a5c9c9d72 100644 --- a/data/client.kv +++ b/data/client.kv @@ -13,6 +13,7 @@ plum: "AF99EF" # typically progression item salmon: "FA8072" # typically trap item white: "FFFFFF" # not used, if you want to change the generic text color change color in Label + orange: "FF7700" # Used for command echo