Jak and Daxter: Implement New Game (#3291)

* Jak 1: Initial commit: Cell Locations, Items, and Regions modeled.

* Jak 1: Wrote Regions, Rules, init. Untested.

* Jak 1: Fixed mistakes, need better understanding of Entrances.

* Jak 1: Fixed bugs, refactored Regions, added missing Special Checks. First spoiler log generated.

* Jak 1: Add Scout Fly Locations, code and style cleanup.

* Jak 1: Add Scout Flies to Regions.

* Jak 1: Add version info.

* Jak 1: Reduced code smell.

* Jak 1: Fixed UT bugs, added Free The Sages as Locations.

* Jak 1: Refactor ID scheme to better fit game's scheme. Add more subregions and rules, but still missing one-way Entrances.

* Jak 1: Add some one-ways, adjust scout fly offset.

* Jak 1: Found Scout Fly ID's for first 4 maps.

* Jak 1: Add more scout fly ID's, refactor game/AP ID translation for easier reading and code reuse.

* Jak 1: Fixed a few things. Four maps to go.

* Jak 1: Last of the scout flies mapped!

* Jak 1: simplify citadel sages logic.

* Jak 1: WebWorld setup, some documentation.

* Jak 1: Initial checkin of Client. Removed the colon from the game name.

* Jak 1: Refactored client into components, working on async communication between the client and the game.

* Jak 1: In tandem with new ArchipelaGOAL memory structure, define read_memory.

* Jak 1: There's magic in the air...

* Jak 1: Fixed bug translating scout fly ID's.

* Jak 1: Make the REPL a little more verbose, easier to debug.

* Jak 1: Did you know Snowy Mountain had such specific unlock requirements? I didn't.

* Jak 1: Update Documentation.

* Jak 1: Simplify user interaction with agents, make process more robust/less dependent on order of ops.

* Jak 1: Simplified startup process, updated docs, prayed.

* Jak 1: quick fix to settings.

* Jak and Daxter: Implement New Game (#1)

* Jak 1: Initial commit: Cell Locations, Items, and Regions modeled.

* Jak 1: Wrote Regions, Rules, init. Untested.

* Jak 1: Fixed mistakes, need better understanding of Entrances.

* Jak 1: Fixed bugs, refactored Regions, added missing Special Checks. First spoiler log generated.

* Jak 1: Add Scout Fly Locations, code and style cleanup.

* Jak 1: Add Scout Flies to Regions.

* Jak 1: Add version info.

* Jak 1: Reduced code smell.

* Jak 1: Fixed UT bugs, added Free The Sages as Locations.

* Jak 1: Refactor ID scheme to better fit game's scheme. Add more subregions and rules, but still missing one-way Entrances.

* Jak 1: Add some one-ways, adjust scout fly offset.

* Jak 1: Found Scout Fly ID's for first 4 maps.

* Jak 1: Add more scout fly ID's, refactor game/AP ID translation for easier reading and code reuse.

* Jak 1: Fixed a few things. Four maps to go.

* Jak 1: Last of the scout flies mapped!

* Jak 1: simplify citadel sages logic.

* Jak 1: WebWorld setup, some documentation.

* Jak 1: Initial checkin of Client. Removed the colon from the game name.

* Jak 1: Refactored client into components, working on async communication between the client and the game.

* Jak 1: In tandem with new ArchipelaGOAL memory structure, define read_memory.

* Jak 1: There's magic in the air...

* Jak 1: Fixed bug translating scout fly ID's.

* Jak 1: Make the REPL a little more verbose, easier to debug.

* Jak 1: Did you know Snowy Mountain had such specific unlock requirements? I didn't.

* Jak 1: Update Documentation.

* Jak 1: Simplify user interaction with agents, make process more robust/less dependent on order of ops.

* Jak 1: Simplified startup process, updated docs, prayed.

* Jak 1: quick fix to settings.

* Jak and Daxter: Genericize Items, Update Scout Fly logic, Add Victory Condition. (#3)

* Jak 1: Update to 0.4.6. Decouple locations from items, support filler items.

* Jak 1: Total revamp of Items. This is where everything broke.

* Jak 1: Decouple 7 scout fly checks from normal checks, update regions/rules for orb counts/traders.

* Jak 1: correct regions/rules, account for sequential oracle/miner locations.

* Jak 1: make nicer strings.

* Jak 1: Add logic for finished game. First full run complete!

* Jak 1: update group names.

* Jak and Daxter - Gondola, Pontoons, Rules, Regions, and Client Update

* Jak 1: Overhaul of regions, rules, and special locations. Updated game info page.

* Jak 1: Preparations for Alpha. Reintroducing automatic startup in client. Updating docs, readme, codeowners.

* Alpha Updates (#15)

* Jak 1: Consolidate client into apworld, create launcher icon, improve setup docs.

* Jak 1: Update setup guide.

* Jak 1: Load title screen, save states of in/outboxes.

* Logging Update (#16)

* Jak 1: Separate info and debug logs.

* Jak 1: Update world info to refer to Archipelago Options menu.

* Deathlink (#18)

* Jak 1: Implement Deathlink. TODO: make it optional...

* Jak 1: Issue a proper send-event for deathlink deaths.

* Jak 1: Added cause of death to deathlink, fixed typo.

* Jak 1: Make Deathlink toggleable.

* Jak 1: Added player name to death text, added zoomer/flut/fishing text, simplified GOAL call for deathlink.

* Jak 1: Fix death text in client logger.

* Move Randomizer (#26)

* Finally remove debug-segment text, update Python imports to relative paths.

* HUGE refactor to Regions/Rules to support move rando, first hub area coded.

* More refactoring.

* Another refactor - may squash.

* Fix some Rules, reuse some code by returning key regions from build_regions.

* More regions added. A couple of TODOs.

* Fixed trade logic, added LPC regions.

* Added Spider, Snowy, Boggy. Fixed Misty's orbs.

* Fix circular import, assert orb counts per level, fix a few naming errors.

* Citadel added, missing locs and connections fixed. First move rando seed generated.

* Add Move Rando to Options class.

* Fixed rules for prerequisite moves.

* Implement client functionality for move rando, add blurbs to game info page.

* Fix wrong address for cache checks.

* Fix byte alignment of offsets, refactor read_memory for better code reuse.

* Refactor memory offsets and add some unit tests.

* Make green eco the filler item, also define a maximum ID. Fix Boggy tether locations.

* Move rando fixes (#29)

* Fix virtual regions in Snowy. Fix some GMC problems.

* Fix Deathlink on sunken slides.

* Removed unncessary code causing build failure.

* Orbsanity (#32)

* My big dumb shortcut: a 2000 item array.

* A better idea: bundle orbs as a numerical option and make array variable size.

* Have Item/Region generation respect the chosen Orbsanity bundle size. Fix trade logic.

* Separate Global/Local Orbsanity options. TODO - re-introduce orb factory for per-level option.

* Per-level Orbsanity implemented w/ orb bundle factory.

* Implement Orbsanity for client, fix some things up for regions.

* Fix location name/id mappings.

* Fix client orb collection on connection.

* Fix minor Deathlink bug, add Update instructions.

* Finishing Touches (#36)

* Set up connector level thresholds, completion goal choices.

* Send AP sender/recipient info to game via client.

* Slight refactors.

* Refactor option checking, add DataStorage handling of traded orbs.

* Update instructions to change order of load/connect.

* Add Option check to ensure enough Locations exist for Cell Count thresholds. Fix Final Door region.

* Need some height move to get LPC sunken chamber cell.

* Rename completion_condition to jak_completion_condition (#41)

* The Afterparty (#42)

* Fixes to Jak client, rules, options, and more.

* Post-rebase fixes.

* Remove orbsanity reset code, optimize game text in client.

* More game text optimization.

* Added more specific troubleshooting/setup instructions.

* Add known issue about large releases taking time. (Dodge 6,666th commit.)

* Remove "Bundle of", Add location name groups, set better default RootDirectory for new players.

* Make orb trade amounts configurable, make orbsanity defaults more reasonable.

* Add HUD info to doc.

* Exempt's Code Review Updates (#43)

* Round 1 of code review updates, the easy stuff.

* Factor options checking away from region/rule creation.

* Code review updates round 2, more complex stuff.

* Code review updates round 3: the mental health annihilator

* Code review updates part 4: redemption.

* More code review feedback, simplifying code, etc.

* Added a host.yaml option to override friendly limits, plus a couple of code review updates.

* Added singleplayer limits, player names to enforcement rules.

* Updated friendly limits to be more strict, optimized recalculate logic.

* Today's the big day Jak: updates docs for mod support in OpenGOAL Launcher

* Rearranged and clarified some instructions, ADDED PATH-SPACE FIX TO CLIENT.

* Fix deathlink reset stalls on a busy client. (#47)

* Jak & Daxter Client : queue game text messages to get items faster during release (#48)

* queue game text messages to write them during the main_tick function and empty the message queue faster during release

* wrap comment for code style character limit

Co-authored-by: massimilianodelliubaldini <8584296+massimilianodelliubaldini@users.noreply.github.com>

* remove useless blank line

Co-authored-by: massimilianodelliubaldini <8584296+massimilianodelliubaldini@users.noreply.github.com>

* whitespace code style

Co-authored-by: massimilianodelliubaldini <8584296+massimilianodelliubaldini@users.noreply.github.com>

* Move JsonMessageData dataclass outside of ReplClient class for code clarity

---------

Co-authored-by: massimilianodelliubaldini <8584296+massimilianodelliubaldini@users.noreply.github.com>

* Item Classifications (and REPL fixes) (#49)

* Changes to item classifications

* Bugfixes to power cell thresholds.

* Fix bugs in item_type_helper.

* Refactor 100 cell door to pass unit tests.

* Quick fix to ReplClient.

* Not so quick fix to ReplClient.

* Display friendly limits in options tooltips.

* Use math.ceil like a normal person.

* Missed a space.

* Fix non-accessibility due to bad orb calculation.

* Updated documentation.

* More Options, More Docs, More Tests (#51)

* Reorder cell counts, require punch for Klaww.

* Friendlier friendly friendlies.

* Removed custom_worlds references from docs/setup guide, focused OpenGOAL Launcher language.

* Increased breadth of unit tests.

* Clean imports of unit tests.

* Create OptionGroups.

* Fix region rule bug with Punch for Klaww.

* Include Punch For Klaww in slot data.

* Update worlds/jakanddaxter/__init__.py

Co-authored-by: Scipio Wright <scipiowright@gmail.com>

* Temper and Harden Text Client (#52)

* Provide config path so OpenGOAL can use mod-specific saves and settings.

* Add versioning to MemoryReader. Harden the client against user errors.

* Updated comments.

* Add Deathlink as a "statement of intent" to the YAML. Small updates to client.

* Revert deathlink changes.

* Update error message.

* Added color markup to log messages printed in text client.

* Separate loggers by agent, write markup to GUI and non-markup to disk simultaneously.

* Refactor MemoryReader callbacks from main_tick to constructor.

* Make callback names more... informative.

* Give users explicit instructions in error messages.

* Stellar Messaging (#54)

* Use new ap-messenger functions for text writing.

* Remove Powershell requirement, bump memory version to 3.

* Error message update w/ instructions for game crash.

* Create no console window for gk.

* ISO Data Enhancement (#58)

* Add iso-path as argument to GOAL compiler.

# Conflicts:
#	worlds/jakanddaxter/Client.py

* More resilient handling of iso_path.

* Fixed scout fly ID mismatches.

* Corrected iso_data subpath.

* Update memory version to 4.

* Docs update for iso_data.

* Auto Detect OpenGOAL Install (#63)

* Auto detect OpenGOAL install path. Also fix Deathlink on server connection.

* Updated docs, add instructions to error messages.

* Slight tweak to error text.

* J&D : add per region location groups (#64)

* add per region power cells location group

* add per region scout flies location group

* add per zone orb bundle groups
(I'm not particularly happy about this code, but I figured doing it this way was the point of least friction/duplication)

* guess who forgot 9 very important characters in each line of the last commit

* Rearrange location group names, quick fix to client error handling.

* Fix pycharm warnings.

* Fix more pycharm warnings.

* Light cleanup: fix icons, add bug report page, remove py 3.8 code.

* Update worlds/jakanddaxter/Options.py

Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com>

* Update worlds/jakanddaxter/Options.py

Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com>

* Update worlds/jakanddaxter/Options.py

Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com>

* Update worlds/jakanddaxter/Options.py

Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com>

* Code review updates on comments, tooltips, and type hints.

* Update type hint for lists in regions.

* Missed todo removal.

* More type hint updates.

* Small region updates for location accessibility, small updates to world guide and README.md.

* Add GMC scout fly location group.

* Improved sanitization of game text.

* Traps 2 (#70)

* Add trap items, relevant options, and citadel orb caches.

* Update REPL to send traps to game.

* Fix item counter.

* Allow player to select which traps to use.

* Fix host.yaml doc strings, ap-setup-options typing, bump memory version to 5.

* Alter some trap names.

* Update world doc.

* Add health trap.

* Added 3 more trap types.

* Protect against empty trap list.

* Reword traps paragraph in world doc.

* Another update to trap paragraph.

* Concisify trap option docstring.

* Timestamp on game log file.

* Update client to handle waiting on title screen.

* Send slot name and seed to game.

* Use self.random instead.

* Update setup doc for new title screen.

* Quick clarification of orb caches in world doc.

* Sanitize slot info earlier.

* Added to and improved unit tests.

* Light cleanup on world.

* Optimizations to movement rules, docs: known issues update.

* Quick fixes for beta 0.5.0 release: template options and LPC logic.

* Quick fix to spoiler counts.

* Reorganize world guide for faster navigation.

* Fix links.

* Update HUD section.

* Found a way to render apostrophes in item names.

* March Refactors (#77)

* Reorg imports, small fix to Rock Village movement.

* Fix wait-on-title message never going to ready message.

* Colorama init fix.

* Swap trap list for a dictionary of trap weights.

* The more laws, the less justice.

* Quick readability update.

* Have memory reader provide instructions for slow booting games.

* Revert some things.

* Update setup_en.md

* Update HUD mode lingo for combined msgs.

* Remade launcher icon, sized correctly.

* I don't know why I can't be satisfied with things.

* Apply suggestions from Scipio

Co-authored-by: Scipio Wright <scipiowright@gmail.com>

* Properly use the settings API instead of Utils.

* Newline on requirements.txt.

* Add __init__ files for frozen builds.

* Replace an ap_inform function with a CommonClient built-in.

* Resize icon to match kivymd expected size.

* First round of Treble code reviews.

* Second round of Treble code reviews.

* Third round of Treble code reviews.

* Missed an unncessary if condition.

* Missed unnecessary comments.

* Fourth round of Treble code reviews.

* Switch trap dictionary to OptionCounter.

* Use existing slot name/seed from network protocol.

* Violet code review updates.

* Violet code review updates part 2.

* Refactor to avoid floating imports (Violet part 3).

* Found a few more valid characters for messaging.

* Move tests out of init, add colon to game name (now that it's safe).

* But don't include those chars for file text.

* Implement Vi suggestion on webhost-capable friendly limits.

* Revert "Implement Vi suggestion on webhost-capable friendly limits."

This reverts commit 2d012b7f4a9a4c13985ecd7303bb1fc646831c86.

* Rename all files for PEP8.

* Refactor how maximums work on webhost.

* Fix rogue UT.

* Don't rush.

* Fix client post-PEP8.

---------

Co-authored-by: Justus Lind <DeamonHunter@users.noreply.github.com>
Co-authored-by: Romain BERNARD <30secondstodraw@gmail.com>
Co-authored-by: Scipio Wright <scipiowright@gmail.com>
Co-authored-by: Nicholas Saylor <79181893+nicholassaylor@users.noreply.github.com>
This commit is contained in:
massimilianodelliubaldini
2025-05-21 08:12:27 -04:00
committed by GitHub
parent 7f4bf71807
commit 3069deb019
51 changed files with 6213 additions and 0 deletions

View File

@@ -80,6 +80,7 @@ Currently, the following games are supported:
* Inscryption
* Civilization VI
* The Legend of Zelda: The Wind Waker
* Jak and Daxter: The Precursor Legacy
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

View File

@@ -87,6 +87,9 @@
# Inscryption
/worlds/inscryption/ @DrBibop @Glowbuzz
# Jak and Daxter: The Precursor Legacy
/worlds/jakanddaxter/ @massimilianodelliubaldini
# Kirby's Dream Land 3
/worlds/kdl3/ @Silvris

View File

@@ -0,0 +1,504 @@
# Python standard libraries
from collections import defaultdict
from math import ceil
from typing import Any, ClassVar, Callable, Union, cast
# Archipelago imports
import settings
from worlds.AutoWorld import World, WebWorld
from worlds.LauncherComponents import components, Component, launch_subprocess, Type, icon_paths
from BaseClasses import (Item,
ItemClassification as ItemClass,
Tutorial,
CollectionState)
from Options import OptionGroup
# Jak imports
from . import options
from .game_id import jak1_id, jak1_name, jak1_max
from .items import (JakAndDaxterItem,
OrbAssoc,
item_table,
cell_item_table,
scout_item_table,
special_item_table,
move_item_table,
orb_item_table,
trap_item_table)
from .levels import level_table, level_table_with_global
from .locations import (JakAndDaxterLocation,
location_table,
cell_location_table,
scout_location_table,
special_location_table,
cache_location_table,
orb_location_table)
from .regions import create_regions
from .rules import (enforce_multiplayer_limits,
enforce_singleplayer_limits,
verify_orb_trade_amounts,
set_orb_trade_rule)
from .locs import (cell_locations as cells,
scout_locations as scouts,
special_locations as specials,
orb_cache_locations as caches,
orb_locations as orbs)
from .regs.region_base import JakAndDaxterRegion
def launch_client():
from . import client
launch_subprocess(client.launch, name="JakAndDaxterClient")
components.append(Component("Jak and Daxter Client",
func=launch_client,
component_type=Type.CLIENT,
icon="precursor_orb"))
icon_paths["precursor_orb"] = f"ap:{__name__}/icons/precursor_orb.png"
class JakAndDaxterSettings(settings.Group):
class RootDirectory(settings.UserFolderPath):
"""Path to folder containing the ArchipelaGOAL mod executables (gk.exe and goalc.exe).
Ensure this path contains forward slashes (/) only. This setting only applies if
Auto Detect Root Directory is set to false."""
description = "ArchipelaGOAL Root Directory"
class AutoDetectRootDirectory(settings.Bool):
"""Attempt to find the OpenGOAL installation and the mod executables (gk.exe and goalc.exe)
automatically. If set to true, the ArchipelaGOAL Root Directory setting is ignored."""
description = "ArchipelaGOAL Auto Detect Root Directory"
class EnforceFriendlyOptions(settings.Bool):
"""Enforce friendly player options in both single and multiplayer seeds. Disabling this allows for
more disruptive and challenging options, but may impact seed generation. Use at your own risk!"""
description = "ArchipelaGOAL Enforce Friendly Options"
root_directory: RootDirectory = RootDirectory(
"%programfiles%/OpenGOAL-Launcher/features/jak1/mods/JakMods/archipelagoal")
# Don't ever change these type hints again.
auto_detect_root_directory: Union[AutoDetectRootDirectory, bool] = True
enforce_friendly_options: Union[EnforceFriendlyOptions, bool] = True
class JakAndDaxterWebWorld(WebWorld):
setup_en = Tutorial(
"Multiworld Setup Guide",
"A guide to setting up ArchipelaGOAL (Archipelago on OpenGOAL).",
"English",
"setup_en.md",
"setup/en",
["markustulliuscicero"]
)
tutorials = [setup_en]
bug_report_page = "https://github.com/ArchipelaGOAL/Archipelago/issues"
option_groups = [
OptionGroup("Orbsanity", [
options.EnableOrbsanity,
options.GlobalOrbsanityBundleSize,
options.PerLevelOrbsanityBundleSize,
]),
OptionGroup("Power Cell Counts", [
options.EnableOrderedCellCounts,
options.FireCanyonCellCount,
options.MountainPassCellCount,
options.LavaTubeCellCount,
]),
OptionGroup("Orb Trade Counts", [
options.CitizenOrbTradeAmount,
options.OracleOrbTradeAmount,
]),
OptionGroup("Traps", [
options.FillerPowerCellsReplacedWithTraps,
options.FillerOrbBundlesReplacedWithTraps,
options.TrapEffectDuration,
options.TrapWeights,
]),
]
class JakAndDaxterWorld(World):
"""
Jak and Daxter: The Precursor Legacy is a 2001 action platformer developed by Naughty Dog
for the PlayStation 2. The game follows the eponymous protagonists, a young boy named Jak
and his friend Daxter, who has been transformed into an ottsel. With the help of Samos
the Sage of Green Eco and his daughter Keira, the pair travel north in search of a cure for Daxter,
discovering artifacts created by an ancient race known as the Precursors along the way. When the
rogue sages Gol and Maia Acheron plan to flood the world with Dark Eco, they must stop their evil plan
and save the world.
"""
# ID, name, version
game = jak1_name
required_client_version = (0, 5, 0)
# Options
settings: ClassVar[JakAndDaxterSettings]
options_dataclass = options.JakAndDaxterOptions
options: options.JakAndDaxterOptions
# Web world
web = JakAndDaxterWebWorld()
# Stored as {ID: Name} pairs, these must now be swapped to {Name: ID} pairs.
# Remember, the game ID and various offsets for each item type have already been calculated.
item_name_to_id = {name: k for k, name in item_table.items()}
location_name_to_id = {name: k for k, name in location_table.items()}
item_name_groups = {
"Power Cells": set(cell_item_table.values()),
"Scout Flies": set(scout_item_table.values()),
"Specials": set(special_item_table.values()),
"Moves": set(move_item_table.values()),
"Precursor Orbs": set(orb_item_table.values()),
"Traps": set(trap_item_table.values()),
}
location_name_groups = {
"Power Cells": set(cell_location_table.values()),
"Power Cells - GR": set(cells.locGR_cellTable.values()),
"Power Cells - SV": set(cells.locSV_cellTable.values()),
"Power Cells - FJ": set(cells.locFJ_cellTable.values()),
"Power Cells - SB": set(cells.locSB_cellTable.values()),
"Power Cells - MI": set(cells.locMI_cellTable.values()),
"Power Cells - FC": set(cells.locFC_cellTable.values()),
"Power Cells - RV": set(cells.locRV_cellTable.values()),
"Power Cells - PB": set(cells.locPB_cellTable.values()),
"Power Cells - LPC": set(cells.locLPC_cellTable.values()),
"Power Cells - BS": set(cells.locBS_cellTable.values()),
"Power Cells - MP": set(cells.locMP_cellTable.values()),
"Power Cells - VC": set(cells.locVC_cellTable.values()),
"Power Cells - SC": set(cells.locSC_cellTable.values()),
"Power Cells - SM": set(cells.locSM_cellTable.values()),
"Power Cells - LT": set(cells.locLT_cellTable.values()),
"Power Cells - GMC": set(cells.locGMC_cellTable.values()),
"Scout Flies": set(scout_location_table.values()),
"Scout Flies - GR": set(scouts.locGR_scoutTable.values()),
"Scout Flies - SV": set(scouts.locSV_scoutTable.values()),
"Scout Flies - FJ": set(scouts.locFJ_scoutTable.values()),
"Scout Flies - SB": set(scouts.locSB_scoutTable.values()),
"Scout Flies - MI": set(scouts.locMI_scoutTable.values()),
"Scout Flies - FC": set(scouts.locFC_scoutTable.values()),
"Scout Flies - RV": set(scouts.locRV_scoutTable.values()),
"Scout Flies - PB": set(scouts.locPB_scoutTable.values()),
"Scout Flies - LPC": set(scouts.locLPC_scoutTable.values()),
"Scout Flies - BS": set(scouts.locBS_scoutTable.values()),
"Scout Flies - MP": set(scouts.locMP_scoutTable.values()),
"Scout Flies - VC": set(scouts.locVC_scoutTable.values()),
"Scout Flies - SC": set(scouts.locSC_scoutTable.values()),
"Scout Flies - SM": set(scouts.locSM_scoutTable.values()),
"Scout Flies - LT": set(scouts.locLT_scoutTable.values()),
"Scout Flies - GMC": set(scouts.locGMC_scoutTable.values()),
"Specials": set(special_location_table.values()),
"Orb Caches": set(cache_location_table.values()),
"Precursor Orbs": set(orb_location_table.values()),
"Precursor Orbs - GR": set(orbs.locGR_orbBundleTable.values()),
"Precursor Orbs - SV": set(orbs.locSV_orbBundleTable.values()),
"Precursor Orbs - FJ": set(orbs.locFJ_orbBundleTable.values()),
"Precursor Orbs - SB": set(orbs.locSB_orbBundleTable.values()),
"Precursor Orbs - MI": set(orbs.locMI_orbBundleTable.values()),
"Precursor Orbs - FC": set(orbs.locFC_orbBundleTable.values()),
"Precursor Orbs - RV": set(orbs.locRV_orbBundleTable.values()),
"Precursor Orbs - PB": set(orbs.locPB_orbBundleTable.values()),
"Precursor Orbs - LPC": set(orbs.locLPC_orbBundleTable.values()),
"Precursor Orbs - BS": set(orbs.locBS_orbBundleTable.values()),
"Precursor Orbs - MP": set(orbs.locMP_orbBundleTable.values()),
"Precursor Orbs - VC": set(orbs.locVC_orbBundleTable.values()),
"Precursor Orbs - SC": set(orbs.locSC_orbBundleTable.values()),
"Precursor Orbs - SM": set(orbs.locSM_orbBundleTable.values()),
"Precursor Orbs - LT": set(orbs.locLT_orbBundleTable.values()),
"Precursor Orbs - GMC": set(orbs.locGMC_orbBundleTable.values()),
"Trades": {location_table[cells.to_ap_id(k)] for k in
{11, 12, 31, 32, 33, 96, 97, 98, 99, 13, 14, 34, 35, 100, 101}},
"'Free 7 Scout Flies' Power Cells": set(cells.loc7SF_cellTable.values()),
}
# These functions and variables are Options-driven, keep them as instance variables here so that we don't clog up
# the seed generation routines with options checking. So we set these once, and then just use them as needed.
can_trade: Callable[[CollectionState, int, int | None], bool]
total_orbs: int = 2000
orb_bundle_item_name: str = ""
orb_bundle_size: int = 0
total_trade_orbs: int = 0
total_prog_orb_bundles: int = 0
total_trap_orb_bundles: int = 0
total_filler_orb_bundles: int = 0
total_power_cells: int = 101
total_prog_cells: int = 0
total_trap_cells: int = 0
total_filler_cells: int = 0
power_cell_thresholds: list[int]
power_cell_thresholds_minus_one: list[int]
trap_weights: tuple[list[str], list[int]]
# Store these dictionaries for speed improvements.
level_to_regions: dict[str, list[JakAndDaxterRegion]] # Contains all levels and regions.
level_to_orb_regions: dict[str, list[JakAndDaxterRegion]] # Contains only regions which contain orbs.
# Handles various options validation, rules enforcement, and caching of important information.
def generate_early(self) -> None:
# Initialize the level-region dictionary.
self.level_to_regions = defaultdict(list)
self.level_to_orb_regions = defaultdict(list)
# Cache the power cell threshold values for quicker reference.
self.power_cell_thresholds = [
self.options.fire_canyon_cell_count.value,
self.options.mountain_pass_cell_count.value,
self.options.lava_tube_cell_count.value,
100, # The 100 Power Cell Door.
]
# Order the thresholds ascending and set the options values to the new order.
if self.options.enable_ordered_cell_counts:
self.power_cell_thresholds.sort()
self.options.fire_canyon_cell_count.value = self.power_cell_thresholds[0]
self.options.mountain_pass_cell_count.value = self.power_cell_thresholds[1]
self.options.lava_tube_cell_count.value = self.power_cell_thresholds[2]
# Store this for remove function.
self.power_cell_thresholds_minus_one = [x - 1 for x in self.power_cell_thresholds]
# For the fairness of other players in a multiworld game, enforce some friendly limitations on our options,
# so we don't cause chaos during seed generation. These friendly limits should **guarantee** a successful gen.
# We would have done this earlier, but we needed to sort the power cell thresholds first.
enforce_friendly_options = self.settings.enforce_friendly_options
if enforce_friendly_options:
if self.multiworld.players > 1:
enforce_multiplayer_limits(self)
else:
enforce_singleplayer_limits(self)
# Calculate the number of power cells needed for full region access, the number being replaced by traps,
# and the number of remaining filler.
if self.options.jak_completion_condition == options.CompletionCondition.option_open_100_cell_door:
self.total_prog_cells = 100
else:
self.total_prog_cells = max(self.power_cell_thresholds[:3])
non_prog_cells = self.total_power_cells - self.total_prog_cells
self.total_trap_cells = min(self.options.filler_power_cells_replaced_with_traps.value, non_prog_cells)
self.options.filler_power_cells_replaced_with_traps.value = self.total_trap_cells
self.total_filler_cells = non_prog_cells - self.total_trap_cells
# Verify that we didn't overload the trade amounts with more orbs than exist in the world.
# This is easy to do by accident even in a singleplayer world.
self.total_trade_orbs = (9 * self.options.citizen_orb_trade_amount) + (6 * self.options.oracle_orb_trade_amount)
verify_orb_trade_amounts(self)
# Cache the orb bundle size and item name for quicker reference.
if self.options.enable_orbsanity == options.EnableOrbsanity.option_per_level:
self.orb_bundle_size = self.options.level_orbsanity_bundle_size.value
self.orb_bundle_item_name = orb_item_table[self.orb_bundle_size]
elif self.options.enable_orbsanity == options.EnableOrbsanity.option_global:
self.orb_bundle_size = self.options.global_orbsanity_bundle_size.value
self.orb_bundle_item_name = orb_item_table[self.orb_bundle_size]
else:
self.orb_bundle_size = 0
self.orb_bundle_item_name = ""
# Calculate the number of orb bundles needed for trades, the number being replaced by traps,
# and the number of remaining filler. If Orbsanity is off, default values of 0 will prevail for all.
if self.orb_bundle_size > 0:
total_orb_bundles = self.total_orbs // self.orb_bundle_size
self.total_prog_orb_bundles = ceil(self.total_trade_orbs / self.orb_bundle_size)
non_prog_orb_bundles = total_orb_bundles - self.total_prog_orb_bundles
self.total_trap_orb_bundles = min(self.options.filler_orb_bundles_replaced_with_traps.value,
non_prog_orb_bundles)
self.options.filler_orb_bundles_replaced_with_traps.value = self.total_trap_orb_bundles
self.total_filler_orb_bundles = non_prog_orb_bundles - self.total_trap_orb_bundles
else:
self.options.filler_orb_bundles_replaced_with_traps.value = 0
self.trap_weights = self.options.trap_weights.weights_pair
# Options drive which trade rules to use, so they need to be setup before we create_regions.
set_orb_trade_rule(self)
# This will also set Locations, Location access rules, Region access rules, etc.
def create_regions(self) -> None:
create_regions(self)
# Don't forget to add the created regions to the multiworld!
for level in self.level_to_regions:
self.multiworld.regions.extend(self.level_to_regions[level])
# As a lazy measure, let's also fill level_to_orb_regions here.
# This should help speed up orbsanity calculations.
self.level_to_orb_regions[level] = [reg for reg in self.level_to_regions[level] if reg.orb_count > 0]
# from Utils import visualize_regions
# visualize_regions(self.multiworld.get_region("Menu", self.player), "jakanddaxter.puml")
def item_data_helper(self, item: int) -> list[tuple[int, ItemClass, OrbAssoc, int]]:
"""
Helper function to reuse some nasty if/else trees. This outputs a list of pairs of item count and class.
For instance, not all 101 power cells need to be marked progression if you only need 72 to beat the game.
So we will have 72 Progression Power Cells, and 29 Filler Power Cells.
"""
data: list[tuple[int, ItemClass, OrbAssoc, int]] = []
# Make N Power Cells. We only want AP's Progression Fill routine to handle the amount of cells we need
# to reach the furthest possible region. Even for early completion goals, all areas in the game must be
# reachable or generation will fail. TODO - Option-driven region creation would be an enormous refactor.
if item in range(jak1_id, jak1_id + scouts.fly_offset):
data.append((self.total_prog_cells, ItemClass.progression_skip_balancing, OrbAssoc.IS_POWER_CELL, 0))
data.append((self.total_filler_cells, ItemClass.filler, OrbAssoc.IS_POWER_CELL, 0))
# Make 7 Scout Flies per level.
elif item in range(jak1_id + scouts.fly_offset, jak1_id + specials.special_offset):
data.append((7, ItemClass.progression_skip_balancing, OrbAssoc.NEVER_UNLOCKS_ORBS, 0))
# Make only 1 of each Special Item.
elif item in range(jak1_id + specials.special_offset, jak1_id + caches.orb_cache_offset):
data.append((1, ItemClass.progression | ItemClass.useful, OrbAssoc.ALWAYS_UNLOCKS_ORBS, 0))
# Make only 1 of each Move Item.
elif item in range(jak1_id + caches.orb_cache_offset, jak1_id + orbs.orb_offset):
data.append((1, ItemClass.progression | ItemClass.useful, OrbAssoc.ALWAYS_UNLOCKS_ORBS, 0))
# Make N Precursor Orb bundles. Like Power Cells, only a fraction of these will be marked as Progression
# with the remainder as Filler, but they are still entirely fungible. See collect function for why these
# are OrbAssoc.NEVER_UNLOCKS_ORBS.
elif item in range(jak1_id + orbs.orb_offset, jak1_max - max(trap_item_table)):
data.append((self.total_prog_orb_bundles, ItemClass.progression_skip_balancing,
OrbAssoc.NEVER_UNLOCKS_ORBS, self.orb_bundle_size))
data.append((self.total_filler_orb_bundles, ItemClass.filler,
OrbAssoc.NEVER_UNLOCKS_ORBS, self.orb_bundle_size))
# We will manually create trap items as needed.
elif item in range(jak1_max - max(trap_item_table), jak1_max):
data.append((0, ItemClass.trap, OrbAssoc.NEVER_UNLOCKS_ORBS, 0))
# We will manually create filler items as needed.
elif item == jak1_max:
data.append((0, ItemClass.filler, OrbAssoc.NEVER_UNLOCKS_ORBS, 0))
# If we try to make items with ID's higher than we've defined, something has gone wrong.
else:
raise KeyError(f"Tried to fill item pool with unknown ID {item}.")
return data
def create_items(self) -> None:
items_made: int = 0
for item_name in self.item_name_to_id:
item_id = self.item_name_to_id[item_name]
# Handle Move Randomizer option.
# If it is OFF, put all moves in your starting inventory instead of the item pool,
# then fill the item pool with a corresponding amount of filler items.
if item_name in self.item_name_groups["Moves"] and not self.options.enable_move_randomizer:
self.multiworld.push_precollected(self.create_item(item_name))
self.multiworld.itempool.append(self.create_filler())
items_made += 1
continue
# Handle Orbsanity option.
# If it is OFF, don't add any orb bundles to the item pool, period.
# If it is ON, don't add any orb bundles that don't match the chosen option.
if (item_name in self.item_name_groups["Precursor Orbs"]
and (self.options.enable_orbsanity == options.EnableOrbsanity.option_off
or item_name != self.orb_bundle_item_name)):
continue
# Skip Traps for now.
if item_name in self.item_name_groups["Traps"]:
continue
# In almost every other scenario, do this. Not all items with the same name will have the same item class.
data = self.item_data_helper(item_id)
for (count, classification, orb_assoc, orb_amount) in data:
self.multiworld.itempool += [JakAndDaxterItem(item_name, classification, item_id,
self.player, orb_assoc, orb_amount)
for _ in range(count)]
items_made += count
# Handle Traps (for real).
# Manually fill the item pool with a weighted assortment of trap items, equal to the sum of
# total_trap_cells + total_trap_orb_bundles. Only do this if one or more traps have weights > 0.
names, weights = self.trap_weights
if sum(weights):
total_traps = self.total_trap_cells + self.total_trap_orb_bundles
trap_list = self.random.choices(names, weights=weights, k=total_traps)
self.multiworld.itempool += [self.create_item(trap_name) for trap_name in trap_list]
items_made += total_traps
# Handle Unfilled Locations.
# Add an amount of filler items equal to the number of locations yet to be filled.
# This is the final set of items we will add to the pool.
all_regions = self.multiworld.get_regions(self.player)
total_locations = sum(reg.location_count for reg in cast(list[JakAndDaxterRegion], all_regions))
total_filler = total_locations - items_made
self.multiworld.itempool += [self.create_filler() for _ in range(total_filler)]
def create_item(self, name: str) -> Item:
item_id = self.item_name_to_id[name]
# Use first tuple (will likely be the most important).
_, classification, orb_assoc, orb_amount = self.item_data_helper(item_id)[0]
return JakAndDaxterItem(name, classification, item_id, self.player, orb_assoc, orb_amount)
def get_filler_item_name(self) -> str:
return "Green Eco Pill"
def collect(self, state: CollectionState, item: JakAndDaxterItem) -> bool:
change = super().collect(state, item)
if change:
# Orbsanity as an option is no-factor to these conditions. Matching the item name implies Orbsanity is ON,
# so we don't need to check the option. When Orbsanity is OFF, there won't even be any orb bundle items
# to collect.
# Orb items do not intrinsically unlock anything that contains more Reachable Orbs, so they do not need to
# set the cache to stale. They just change how many orbs you have to trade with.
if item.orb_amount > 0:
state.prog_items[self.player]["Tradeable Orbs"] += self.orb_bundle_size # Give a bundle of Trade Orbs
# Power Cells DO unlock new regions that contain more Reachable Orbs - the connector levels and new
# hub levels - BUT they only do that when you have a number of them equal to one of the threshold values.
elif (item.orb_assoc == OrbAssoc.ALWAYS_UNLOCKS_ORBS
or (item.orb_assoc == OrbAssoc.IS_POWER_CELL
and state.count("Power Cell", self.player) in self.power_cell_thresholds)):
state.prog_items[self.player]["Reachable Orbs Fresh"] = False
# However, every other item that does not have an appropriate OrbAssoc that changes the CollectionState
# should NOT set the cache to stale, because they did not make it possible to reach more orb locations
# (level unlocks, region unlocks, etc.).
return change
def remove(self, state: CollectionState, item: JakAndDaxterItem) -> bool:
change = super().remove(state, item)
if change:
# Do the same thing we did in collect, except subtract trade orbs instead of add.
if item.orb_amount > 0:
state.prog_items[self.player]["Tradeable Orbs"] -= self.orb_bundle_size # Take a bundle of Trade Orbs
# Ditto Power Cells, but check thresholds - 1, because we potentially crossed the threshold in the opposite
# direction. E.g. we've removed the 20th power cell, our count is now 19, so we should stale the cache.
elif (item.orb_assoc == OrbAssoc.ALWAYS_UNLOCKS_ORBS
or (item.orb_assoc == OrbAssoc.IS_POWER_CELL
and state.count("Power Cell", self.player) in self.power_cell_thresholds_minus_one)):
state.prog_items[self.player]["Reachable Orbs Fresh"] = False
return change
def fill_slot_data(self) -> dict[str, Any]:
options_dict = self.options.as_dict("enable_move_randomizer",
"enable_orbsanity",
"global_orbsanity_bundle_size",
"level_orbsanity_bundle_size",
"fire_canyon_cell_count",
"mountain_pass_cell_count",
"lava_tube_cell_count",
"citizen_orb_trade_amount",
"oracle_orb_trade_amount",
"filler_power_cells_replaced_with_traps",
"filler_orb_bundles_replaced_with_traps",
"trap_effect_duration",
"trap_weights",
"jak_completion_condition",
"require_punch_for_klaww",
)
return options_dict

View File

View File

@@ -0,0 +1,489 @@
import logging
import random
import struct
from typing import ByteString, Callable
import json
import pymem
from pymem import pattern
from pymem.exception import ProcessNotFound, ProcessError, MemoryReadError, WinAPIError
from dataclasses import dataclass
from ..locs import (orb_locations as orbs,
cell_locations as cells,
scout_locations as flies,
special_locations as specials,
orb_cache_locations as caches)
logger = logging.getLogger("MemoryReader")
# Some helpful constants.
sizeof_uint64 = 8
sizeof_uint32 = 4
sizeof_uint8 = 1
sizeof_float = 4
# *****************************************************************************
# **** This number must match (-> *ap-info-jak1* version) in ap-struct.gc! ****
# *****************************************************************************
expected_memory_version = 5
# IMPORTANT: OpenGOAL memory structures are particular about the alignment, in memory, of member elements according to
# their size in bits. The address for an N-bit field must be divisible by N. Use this class to define the memory offsets
# of important values in the struct. It will also do the byte alignment properly for you.
# See https://opengoal.dev/docs/reference/type_system/#arrays
@dataclass
class OffsetFactory:
current_offset: int = 0
def define(self, size: int, length: int = 1) -> int:
# If necessary, align current_offset to the current size first.
bytes_to_alignment = self.current_offset % size
if bytes_to_alignment != 0:
self.current_offset += (size - bytes_to_alignment)
# Increment current_offset so the next definition can be made.
offset_to_use = self.current_offset
self.current_offset += (size * length)
return offset_to_use
# Start defining important memory address offsets here. They must be in the same order, have the same sizes, and have
# the same lengths, as defined in `ap-info-jak1`.
offsets = OffsetFactory()
# Cell, Buzzer, and Special information.
next_cell_index_offset = offsets.define(sizeof_uint64)
next_buzzer_index_offset = offsets.define(sizeof_uint64)
next_special_index_offset = offsets.define(sizeof_uint64)
cells_checked_offset = offsets.define(sizeof_uint32, 101)
buzzers_checked_offset = offsets.define(sizeof_uint32, 112)
specials_checked_offset = offsets.define(sizeof_uint32, 32)
buzzers_received_offset = offsets.define(sizeof_uint8, 16)
specials_received_offset = offsets.define(sizeof_uint8, 32)
# Deathlink information.
death_count_offset = offsets.define(sizeof_uint32)
death_cause_offset = offsets.define(sizeof_uint8)
deathlink_enabled_offset = offsets.define(sizeof_uint8)
# Move Rando information.
next_orb_cache_index_offset = offsets.define(sizeof_uint64)
orb_caches_checked_offset = offsets.define(sizeof_uint32, 16)
moves_received_offset = offsets.define(sizeof_uint8, 16)
moverando_enabled_offset = offsets.define(sizeof_uint8)
# Orbsanity information.
orbsanity_option_offset = offsets.define(sizeof_uint8)
orbsanity_bundle_offset = offsets.define(sizeof_uint32)
collected_bundle_offset = offsets.define(sizeof_uint32, 17)
# Progression and Completion information.
fire_canyon_unlock_offset = offsets.define(sizeof_float)
mountain_pass_unlock_offset = offsets.define(sizeof_float)
lava_tube_unlock_offset = offsets.define(sizeof_float)
citizen_orb_amount_offset = offsets.define(sizeof_float)
oracle_orb_amount_offset = offsets.define(sizeof_float)
completion_goal_offset = offsets.define(sizeof_uint8)
completed_offset = offsets.define(sizeof_uint8)
# Text to display in the HUD (32 char max per string).
their_item_name_offset = offsets.define(sizeof_uint8, 32)
their_item_owner_offset = offsets.define(sizeof_uint8, 32)
my_item_name_offset = offsets.define(sizeof_uint8, 32)
my_item_finder_offset = offsets.define(sizeof_uint8, 32)
# Version of the memory struct, to cut down on mod/apworld version mismatches.
memory_version_offset = offsets.define(sizeof_uint32)
# Connection status to AP server (not the game!)
server_connection_offset = offsets.define(sizeof_uint8)
slot_name_offset = offsets.define(sizeof_uint8, 16)
slot_seed_offset = offsets.define(sizeof_uint8, 8)
# Trap information.
trap_duration_offset = offsets.define(sizeof_float)
# The End.
end_marker_offset = offsets.define(sizeof_uint8, 4)
# Can't believe this is easier to do in GOAL than Python but that's how it be sometimes.
def as_float(value: int) -> int:
return int(struct.unpack('f', value.to_bytes(sizeof_float, "little"))[0])
# "Jak" to be replaced by player name in the Client.
def autopsy(cause: int) -> str:
if cause in [1, 2, 3, 4]:
return random.choice(["Jak said goodnight.",
"Jak stepped into the light.",
"Jak gave Daxter his insect collection.",
"Jak did not follow Step 1."])
if cause == 5:
return "Jak fell into an endless pit."
if cause == 6:
return "Jak drowned in the spicy water."
if cause == 7:
return "Jak tried to tackle a Lurker Shark."
if cause == 8:
return "Jak hit 500 degrees."
if cause == 9:
return "Jak took a bath in a pool of dark eco."
if cause == 10:
return "Jak got bombarded with flaming 30-ton boulders."
if cause == 11:
return "Jak hit 800 degrees."
if cause == 12:
return "Jak ceased to be."
if cause == 13:
return "Jak got eaten by the dark eco plant."
if cause == 14:
return "Jak burned up."
if cause == 15:
return "Jak hit the ground hard."
if cause == 16:
return "Jak crashed the zoomer."
if cause == 17:
return "Jak got Flut Flut hurt."
if cause == 18:
return "Jak poisoned the whole darn catch."
if cause == 19:
return "Jak collided with too many obstacles."
return "Jak died."
class JakAndDaxterMemoryReader:
marker: ByteString
goal_address: int | None = None
connected: bool = False
initiated_connect: bool = False
# The memory reader just needs the game running.
gk_process: pymem.process = None
location_outbox: list[int] = []
outbox_index: int = 0
finished_game: bool = False
# Deathlink handling
deathlink_enabled: bool = False
send_deathlink: bool = False
cause_of_death: str = ""
death_count: int = 0
# Orbsanity handling
orbsanity_enabled: bool = False
orbs_paid: int = 0
# Game-related callbacks (inform the AP server of changes to game state)
inform_checked_location: Callable
inform_finished_game: Callable
inform_died: Callable
inform_toggled_deathlink: Callable
inform_traded_orbs: Callable
# Logging callbacks
# These will write to the provided logger, as well as the Client GUI with color markup.
log_error: Callable # Red
log_warn: Callable # Orange
log_success: Callable # Green
log_info: Callable # White (default)
def __init__(self,
location_check_callback: Callable,
finish_game_callback: Callable,
send_deathlink_callback: Callable,
toggle_deathlink_callback: Callable,
orb_trade_callback: Callable,
log_error_callback: Callable,
log_warn_callback: Callable,
log_success_callback: Callable,
log_info_callback: Callable,
marker: ByteString = b'UnLiStEdStRaTs_JaK1\x00'):
self.marker = marker
self.inform_checked_location = location_check_callback
self.inform_finished_game = finish_game_callback
self.inform_died = send_deathlink_callback
self.inform_toggled_deathlink = toggle_deathlink_callback
self.inform_traded_orbs = orb_trade_callback
self.log_error = log_error_callback
self.log_warn = log_warn_callback
self.log_success = log_success_callback
self.log_info = log_info_callback
async def main_tick(self):
if self.initiated_connect:
await self.connect()
self.initiated_connect = False
if self.connected:
try:
self.gk_process.read_bool(self.gk_process.base_address) # Ping to see if it's alive.
except (ProcessError, MemoryReadError, WinAPIError):
msg = (f"Error reading game memory! (Did the game crash?)\n"
f"Please close all open windows and reopen the Jak and Daxter Client "
f"from the Archipelago Launcher.\n"
f"If the game and compiler do not restart automatically, please follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Then click Advanced > Play in Debug Mode.\n"
f" Then click Advanced > Open REPL.\n"
f" Then close and reopen the Jak and Daxter Client from the Archipelago Launcher.")
self.log_error(logger, msg)
self.connected = False
else:
return
if self.connected:
# Save some state variables temporarily.
old_deathlink_enabled = self.deathlink_enabled
# Read the memory address to check the state of the game.
self.read_memory()
# Checked Locations in game. Handle the entire outbox every tick until we're up to speed.
if len(self.location_outbox) > self.outbox_index:
self.inform_checked_location(self.location_outbox)
self.save_data()
self.outbox_index += 1
if self.finished_game:
self.inform_finished_game()
if old_deathlink_enabled != self.deathlink_enabled:
self.inform_toggled_deathlink()
logger.debug("Toggled DeathLink " + ("ON" if self.deathlink_enabled else "OFF"))
if self.send_deathlink:
self.inform_died()
if self.orbs_paid > 0:
self.inform_traded_orbs(self.orbs_paid)
self.orbs_paid = 0
async def connect(self):
try:
self.gk_process = pymem.Pymem("gk.exe") # The GOAL Kernel
logger.debug("Found the gk process: " + str(self.gk_process.process_id))
except ProcessNotFound:
self.log_error(logger, "Could not find the game process.")
self.connected = False
return
# If we don't find the marker in the first loaded module, we've failed.
modules = list(self.gk_process.list_modules())
marker_address = pattern.pattern_scan_module(self.gk_process.process_handle, modules[0], self.marker)
if marker_address:
# At this address is another address that contains the struct we're looking for: the game's state.
# From here we need to add the length in bytes for the marker and 4 bytes of padding,
# and the struct address is 8 bytes long (it's an uint64).
goal_pointer = marker_address + len(self.marker) + 4
self.goal_address = int.from_bytes(self.gk_process.read_bytes(goal_pointer, sizeof_uint64),
byteorder="little",
signed=False)
logger.debug("Found the archipelago memory address: " + str(self.goal_address))
await self.verify_memory_version()
else:
self.log_error(logger, "Could not find the Archipelago marker address!")
self.connected = False
async def verify_memory_version(self):
if self.goal_address is None:
self.log_error(logger, "Could not find the Archipelago memory address!")
self.connected = False
return
memory_version: int | None = None
try:
memory_version = self.read_goal_address(memory_version_offset, sizeof_uint32)
if memory_version == expected_memory_version:
self.log_success(logger, "The Memory Reader is ready!")
self.connected = True
else:
raise MemoryReadError(memory_version_offset, sizeof_uint32)
except (ProcessError, MemoryReadError, WinAPIError):
if memory_version is None:
msg = (f"Could not find a version number in the OpenGOAL memory structure!\n"
f" Expected Version: {str(expected_memory_version)}\n"
f" Found Version: {str(memory_version)}\n"
f"Please follow these steps:\n"
f" If the game is running, try entering '/memr connect' in the client.\n"
f" You should see 'The Memory Reader is ready!'\n"
f" If that did not work, or the game is not running, run the OpenGOAL Launcher.\n"
f" Click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Then click Advanced > Play in Debug Mode.\n"
f" Try entering '/memr connect' in the client again.")
else:
msg = (f"The OpenGOAL memory structure is incompatible with the current Archipelago client!\n"
f" Expected Version: {str(expected_memory_version)}\n"
f" Found Version: {str(memory_version)}\n"
f"Please follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Click Update (if one is available).\n"
f" Click Advanced > Compile. When this is done, click Continue.\n"
f" Click Versions and verify the latest version is marked 'Active'.\n"
f" Close all launchers, games, clients, and console windows, then restart Archipelago.")
self.log_error(logger, msg)
self.connected = False
async def print_status(self):
proc_id = str(self.gk_process.process_id) if self.gk_process else "None"
last_loc = str(self.location_outbox[self.outbox_index - 1] if self.outbox_index else "None")
msg = (f"Memory Reader Status:\n"
f" Game process ID: {proc_id}\n"
f" Game state memory address: {str(self.goal_address)}\n"
f" Last location checked: {last_loc}")
await self.verify_memory_version()
self.log_info(logger, msg)
def read_memory(self) -> list[int]:
try:
# Need to grab these first and convert to floats, see below.
citizen_orb_amount = self.read_goal_address(citizen_orb_amount_offset, sizeof_float)
oracle_orb_amount = self.read_goal_address(oracle_orb_amount_offset, sizeof_float)
next_cell_index = self.read_goal_address(next_cell_index_offset, sizeof_uint64)
for k in range(0, next_cell_index):
next_cell = self.read_goal_address(cells_checked_offset + (k * sizeof_uint32), sizeof_uint32)
cell_ap_id = cells.to_ap_id(next_cell)
if cell_ap_id not in self.location_outbox:
self.location_outbox.append(cell_ap_id)
logger.debug("Checked power cell: " + str(next_cell))
# If orbsanity is ON and next_cell is one of the traders or oracles, then run a callback
# to add their amount to the DataStorage value holding our current orb trade total.
if next_cell in {11, 12, 31, 32, 33, 96, 97, 98, 99}:
citizen_orb_amount = as_float(citizen_orb_amount)
self.orbs_paid += citizen_orb_amount
logger.debug(f"Traded {citizen_orb_amount} orbs!")
if next_cell in {13, 14, 34, 35, 100, 101}:
oracle_orb_amount = as_float(oracle_orb_amount)
self.orbs_paid += oracle_orb_amount
logger.debug(f"Traded {oracle_orb_amount} orbs!")
next_buzzer_index = self.read_goal_address(next_buzzer_index_offset, sizeof_uint64)
for k in range(0, next_buzzer_index):
next_buzzer = self.read_goal_address(buzzers_checked_offset + (k * sizeof_uint32), sizeof_uint32)
buzzer_ap_id = flies.to_ap_id(next_buzzer)
if buzzer_ap_id not in self.location_outbox:
self.location_outbox.append(buzzer_ap_id)
logger.debug("Checked scout fly: " + str(next_buzzer))
next_special_index = self.read_goal_address(next_special_index_offset, sizeof_uint64)
for k in range(0, next_special_index):
next_special = self.read_goal_address(specials_checked_offset + (k * sizeof_uint32), sizeof_uint32)
special_ap_id = specials.to_ap_id(next_special)
if special_ap_id not in self.location_outbox:
self.location_outbox.append(special_ap_id)
logger.debug("Checked special: " + str(next_special))
death_count = self.read_goal_address(death_count_offset, sizeof_uint32)
death_cause = self.read_goal_address(death_cause_offset, sizeof_uint8)
if death_count > self.death_count:
self.cause_of_death = autopsy(death_cause) # The way he names his variables? Wack!
self.send_deathlink = True
self.death_count += 1
# Listen for any changes to this setting.
deathlink_flag = self.read_goal_address(deathlink_enabled_offset, sizeof_uint8)
self.deathlink_enabled = bool(deathlink_flag)
next_cache_index = self.read_goal_address(next_orb_cache_index_offset, sizeof_uint64)
for k in range(0, next_cache_index):
next_cache = self.read_goal_address(orb_caches_checked_offset + (k * sizeof_uint32), sizeof_uint32)
cache_ap_id = caches.to_ap_id(next_cache)
if cache_ap_id not in self.location_outbox:
self.location_outbox.append(cache_ap_id)
logger.debug("Checked orb cache: " + str(next_cache))
# Listen for any changes to this setting.
# moverando_flag = self.read_goal_address(moverando_enabled_offset, sizeof_uint8)
# self.moverando_enabled = bool(moverando_flag)
orbsanity_option = self.read_goal_address(orbsanity_option_offset, sizeof_uint8)
bundle_size = self.read_goal_address(orbsanity_bundle_offset, sizeof_uint32)
self.orbsanity_enabled = orbsanity_option > 0
# Per Level Orbsanity option. Only need to do this loop if we chose this setting.
if orbsanity_option == 1:
for level in range(0, 16):
collected_bundles = self.read_goal_address(collected_bundle_offset + (level * sizeof_uint32),
sizeof_uint32)
# Count up from the first bundle, by bundle size, until you reach the latest collected bundle.
# e.g. {25, 50, 75, 100, 125...}
if collected_bundles > 0:
for bundle in range(bundle_size,
bundle_size + collected_bundles, # Range max is non-inclusive.
bundle_size):
bundle_ap_id = orbs.to_ap_id(orbs.find_address(level, bundle, bundle_size))
if bundle_ap_id not in self.location_outbox:
self.location_outbox.append(bundle_ap_id)
logger.debug(f"Checked orb bundle: L{level} {bundle}")
# Global Orbsanity option. Index 16 refers to all orbs found regardless of level.
if orbsanity_option == 2:
collected_bundles = self.read_goal_address(collected_bundle_offset + (16 * sizeof_uint32),
sizeof_uint32)
if collected_bundles > 0:
for bundle in range(bundle_size,
bundle_size + collected_bundles, # Range max is non-inclusive.
bundle_size):
bundle_ap_id = orbs.to_ap_id(orbs.find_address(16, bundle, bundle_size))
if bundle_ap_id not in self.location_outbox:
self.location_outbox.append(bundle_ap_id)
logger.debug(f"Checked orb bundle: G {bundle}")
completed = self.read_goal_address(completed_offset, sizeof_uint8)
if completed > 0 and not self.finished_game:
self.finished_game = True
self.log_success(logger, "Congratulations! You finished the game!")
except (ProcessError, MemoryReadError, WinAPIError):
msg = (f"Error reading game memory! (Did the game crash?)\n"
f"Please close all open windows and reopen the Jak and Daxter Client "
f"from the Archipelago Launcher.\n"
f"If the game and compiler do not restart automatically, please follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Then click Advanced > Play in Debug Mode.\n"
f" Then click Advanced > Open REPL.\n"
f" Then close and reopen the Jak and Daxter Client from the Archipelago Launcher.")
self.log_error(logger, msg)
self.connected = False
return self.location_outbox
def read_goal_address(self, offset: int, length: int) -> int:
return int.from_bytes(
self.gk_process.read_bytes(self.goal_address + offset, length),
byteorder="little",
signed=False)
def save_data(self):
with open("jakanddaxter_location_outbox.json", "w+") as f:
dump = {
"outbox_index": self.outbox_index,
"location_outbox": self.location_outbox
}
json.dump(dump, f, indent=4)
def load_data(self):
try:
with open("jakanddaxter_location_outbox.json", "r") as f:
load = json.load(f)
self.outbox_index = load["outbox_index"]
self.location_outbox = load["location_outbox"]
except FileNotFoundError:
pass

View File

@@ -0,0 +1,527 @@
import json
import logging
import queue
import time
import struct
import random
from dataclasses import dataclass
from queue import Queue
from typing import Callable
import pymem
from pymem.exception import ProcessNotFound, ProcessError
import asyncio
from asyncio import StreamReader, StreamWriter, Lock
from NetUtils import NetworkItem
from ..game_id import jak1_id, jak1_max
from ..items import item_table, trap_item_table
from ..locs import (
orb_locations as orbs,
cell_locations as cells,
scout_locations as flies,
special_locations as specials,
orb_cache_locations as caches)
logger = logging.getLogger("ReplClient")
@dataclass
class JsonMessageData:
my_item_name: str | None = None
my_item_finder: str | None = None
their_item_name: str | None = None
their_item_owner: str | None = None
ALLOWED_CHARACTERS = frozenset({
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", " ", "!", ":", ",", ".", "/", "?", "-",
"=", "+", "'", "(", ")", "\""
})
class JakAndDaxterReplClient:
ip: str
port: int
reader: StreamReader
writer: StreamWriter
lock: Lock
connected: bool = False
initiated_connect: bool = False # Signals when user tells us to try reconnecting.
received_deathlink: bool = False
balanced_orbs: bool = False
# Variables to handle the title screen and initial game connection.
initial_item_count = -1 # Brand new games have 0 items, so initialize this to -1.
received_initial_items = False
processed_initial_items = False
# The REPL client needs the REPL/compiler process running, but that process
# also needs the game running. Therefore, the REPL client needs both running.
gk_process: pymem.process = None
goalc_process: pymem.process = None
item_inbox: dict[int, NetworkItem] = {}
inbox_index = 0
json_message_queue: Queue[JsonMessageData] = queue.Queue()
# Logging callbacks
# These will write to the provided logger, as well as the Client GUI with color markup.
log_error: Callable # Red
log_warn: Callable # Orange
log_success: Callable # Green
log_info: Callable # White (default)
def __init__(self,
log_error_callback: Callable,
log_warn_callback: Callable,
log_success_callback: Callable,
log_info_callback: Callable,
ip: str = "127.0.0.1",
port: int = 8181):
self.ip = ip
self.port = port
self.lock = asyncio.Lock()
self.log_error = log_error_callback
self.log_warn = log_warn_callback
self.log_success = log_success_callback
self.log_info = log_info_callback
async def main_tick(self):
if self.initiated_connect:
await self.connect()
self.initiated_connect = False
if self.connected:
try:
self.gk_process.read_bool(self.gk_process.base_address) # Ping to see if it's alive.
except ProcessError:
msg = (f"Error reading game memory! (Did the game crash?)\n"
f"Please close all open windows and reopen the Jak and Daxter Client "
f"from the Archipelago Launcher.\n"
f"If the game and compiler do not restart automatically, please follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Then click Advanced > Play in Debug Mode.\n"
f" Then click Advanced > Open REPL.\n"
f" Then close and reopen the Jak and Daxter Client from the Archipelago Launcher.")
self.log_error(logger, msg)
self.connected = False
try:
self.goalc_process.read_bool(self.goalc_process.base_address) # Ping to see if it's alive.
except ProcessError:
msg = (f"Error sending data to compiler! (Did the compiler crash?)\n"
f"Please close all open windows and reopen the Jak and Daxter Client "
f"from the Archipelago Launcher.\n"
f"If the game and compiler do not restart automatically, please follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Then click Advanced > Play in Debug Mode.\n"
f" Then click Advanced > Open REPL.\n"
f" Then close and reopen the Jak and Daxter Client from the Archipelago Launcher.")
self.log_error(logger, msg)
self.connected = False
else:
return
# When connecting the game to the AP server on the title screen, we may be processing items from starting
# inventory or items received in an async game. Once we have caught up to the initial count, tell the player
# that we are ready to start. New items may even come in during the title screen, so if we go over the count,
# we should still send the ready signal.
if not self.processed_initial_items:
if self.inbox_index >= self.initial_item_count >= 0:
self.processed_initial_items = True
await self.send_connection_status("ready")
# Receive Items from AP. Handle 1 item per tick.
if len(self.item_inbox) > self.inbox_index:
await self.receive_item()
await self.save_data()
self.inbox_index += 1
if self.received_deathlink:
await self.receive_deathlink()
self.received_deathlink = False
# Progressively empty the queue during each tick
# if text messages happen to be too slow we could pool dequeuing here,
# but it'd slow down the ItemReceived message during release
if not self.json_message_queue.empty():
json_txt_data = self.json_message_queue.get_nowait()
await self.write_game_text(json_txt_data)
# This helper function formats and sends `form` as a command to the REPL.
# ALL commands to the REPL should be sent using this function.
async def send_form(self, form: str, print_ok: bool = True) -> bool:
header = struct.pack("<II", len(form), 10)
async with self.lock:
self.writer.write(header + form.encode())
await self.writer.drain()
response_data = await self.reader.read(1024)
response = response_data.decode()
if "OK!" in response:
if print_ok:
logger.debug(response)
return True
else:
self.log_error(logger, f"Unexpected response from REPL: {response}")
return False
async def connect(self):
try:
self.gk_process = pymem.Pymem("gk.exe") # The GOAL Kernel
logger.debug("Found the gk process: " + str(self.gk_process.process_id))
except ProcessNotFound:
self.log_error(logger, "Could not find the game process.")
return
try:
self.goalc_process = pymem.Pymem("goalc.exe") # The GOAL Compiler and REPL
logger.debug("Found the goalc process: " + str(self.goalc_process.process_id))
except ProcessNotFound:
self.log_error(logger, "Could not find the compiler process.")
return
try:
self.reader, self.writer = await asyncio.open_connection(self.ip, self.port)
time.sleep(1)
connect_data = await self.reader.read(1024)
welcome_message = connect_data.decode()
# Should be the OpenGOAL welcome message (ignore version number).
if "Connected to OpenGOAL" and "nREPL!" in welcome_message:
logger.debug(welcome_message)
else:
self.log_error(logger,
f"Unable to connect to REPL websocket: unexpected welcome message \"{welcome_message}\"")
except ConnectionRefusedError as e:
self.log_error(logger, f"Unable to connect to REPL websocket: {e.strerror}")
return
ok_count = 0
if self.reader and self.writer:
# Have the REPL listen to the game's internal websocket.
if await self.send_form("(lt)", print_ok=False):
ok_count += 1
# Show this visual cue when compilation is started.
# It's the version number of the OpenGOAL Compiler.
if await self.send_form("(set! *debug-segment* #t)", print_ok=False):
ok_count += 1
# Start compilation. This is blocking, so nothing will happen until the REPL is done.
if await self.send_form("(mi)", print_ok=False):
ok_count += 1
# Play this audio cue when compilation is complete.
# It's the sound you hear when you press START + START to close the Options menu.
if await self.send_form("(dotimes (i 1) "
"(sound-play-by-name "
"(static-sound-name \"menu-close\") "
"(new-sound-id) 1024 0 0 (sound-group sfx) #t))", print_ok=False):
ok_count += 1
# Disable cheat-mode and debug (close the visual cues).
if await self.send_form("(set! *debug-segment* #f)", print_ok=False):
ok_count += 1
if await self.send_form("(set! *cheat-mode* #f)", print_ok=False):
ok_count += 1
# Run the retail game start sequence (while still connected with REPL).
if await self.send_form("(start \'play (get-continue-by-name *game-info* \"title-start\"))"):
ok_count += 1
# Now wait until we see the success message... 7 times.
if ok_count == 7:
self.connected = True
else:
self.connected = False
if self.connected:
self.log_success(logger, "The REPL is ready!")
async def print_status(self):
gc_proc_id = str(self.goalc_process.process_id) if self.goalc_process else "None"
gk_proc_id = str(self.gk_process.process_id) if self.gk_process else "None"
msg = (f"REPL Status:\n"
f" REPL process ID: {gc_proc_id}\n"
f" Game process ID: {gk_proc_id}\n")
try:
if self.reader and self.writer:
addr = self.writer.get_extra_info("peername")
addr = str(addr) if addr else "None"
msg += f" Game websocket: {addr}\n"
await self.send_form("(dotimes (i 1) "
"(sound-play-by-name "
"(static-sound-name \"menu-close\") "
"(new-sound-id) 1024 0 0 (sound-group sfx) #t))", print_ok=False)
except ConnectionResetError:
msg += f" Connection to the game was lost or reset!"
last_item = str(getattr(self.item_inbox[self.inbox_index], "item")) if self.inbox_index else "None"
msg += f" Last item received: {last_item}\n"
msg += f" Did you hear the success audio cue?"
self.log_info(logger, msg)
# To properly display in-game text:
# - It must be a valid character from the ALLOWED_CHARACTERS list.
# - All lowercase letters must be uppercase.
# - It must be wrapped in double quotes (for the REPL command).
# - Apostrophes must be handled specially - GOAL uses invisible ASCII character 0x12.
# I also only allotted 32 bytes to each string in OpenGOAL, so we must truncate.
@staticmethod
def sanitize_game_text(text: str) -> str:
result = "".join([c if c in ALLOWED_CHARACTERS else "?" for c in text[:32]]).upper()
result = result.replace("'", "\\c12")
return f"\"{result}\""
# Like sanitize_game_text, but the settings file will NOT allow any whitespace in the slot_name or slot_seed data.
# And don't replace any chars with "?" for good measure.
@staticmethod
def sanitize_file_text(text: str) -> str:
allowed_chars_no_extras = ALLOWED_CHARACTERS - {" ", "'", "(", ")", "\""}
result = "".join([c if c in allowed_chars_no_extras else "" for c in text[:16]]).upper()
return f"\"{result}\""
# Pushes a JsonMessageData object to the json message queue to be processed during the repl main_tick
def queue_game_text(self, my_item_name, my_item_finder, their_item_name, their_item_owner):
self.json_message_queue.put(JsonMessageData(my_item_name, my_item_finder, their_item_name, their_item_owner))
# OpenGOAL can handle both its own string datatype and C-like character pointers (charp).
async def write_game_text(self, data: JsonMessageData):
logger.debug(f"Sending info to the in-game messenger!")
body = ""
if data.my_item_name and data.my_item_finder:
body += (f" (append-messages (-> *ap-messenger* 0) \'recv "
f" {self.sanitize_game_text(data.my_item_name)} "
f" {self.sanitize_game_text(data.my_item_finder)})")
if data.their_item_name and data.their_item_owner:
body += (f" (append-messages (-> *ap-messenger* 0) \'sent "
f" {self.sanitize_game_text(data.their_item_name)} "
f" {self.sanitize_game_text(data.their_item_owner)})")
await self.send_form(f"(begin {body} (none))", print_ok=False)
async def receive_item(self):
ap_id = getattr(self.item_inbox[self.inbox_index], "item")
# Determine the type of item to receive.
if ap_id in range(jak1_id, jak1_id + flies.fly_offset):
await self.receive_power_cell(ap_id)
elif ap_id in range(jak1_id + flies.fly_offset, jak1_id + specials.special_offset):
await self.receive_scout_fly(ap_id)
elif ap_id in range(jak1_id + specials.special_offset, jak1_id + caches.orb_cache_offset):
await self.receive_special(ap_id)
elif ap_id in range(jak1_id + caches.orb_cache_offset, jak1_id + orbs.orb_offset):
await self.receive_move(ap_id)
elif ap_id in range(jak1_id + orbs.orb_offset, jak1_max - max(trap_item_table)):
await self.receive_precursor_orb(ap_id) # Ponder the orbs.
elif ap_id in range(jak1_max - max(trap_item_table), jak1_max):
await self.receive_trap(ap_id)
elif ap_id == jak1_max:
await self.receive_green_eco() # Ponder why I chose to do ID's this way.
else:
self.log_error(logger, f"Tried to receive item with unknown AP ID {ap_id}!")
async def receive_power_cell(self, ap_id: int) -> bool:
cell_id = cells.to_game_id(ap_id)
ok = await self.send_form("(send-event "
"*target* \'get-archipelago "
"(pickup-type fuel-cell) "
"(the float " + str(cell_id) + "))")
if ok:
logger.debug(f"Received a Power Cell!")
else:
self.log_error(logger, f"Unable to receive a Power Cell!")
return ok
async def receive_scout_fly(self, ap_id: int) -> bool:
fly_id = flies.to_game_id(ap_id)
ok = await self.send_form("(send-event "
"*target* \'get-archipelago "
"(pickup-type buzzer) "
"(the float " + str(fly_id) + "))")
if ok:
logger.debug(f"Received a {item_table[ap_id]}!")
else:
self.log_error(logger, f"Unable to receive a {item_table[ap_id]}!")
return ok
async def receive_special(self, ap_id: int) -> bool:
special_id = specials.to_game_id(ap_id)
ok = await self.send_form("(send-event "
"*target* \'get-archipelago "
"(pickup-type ap-special) "
"(the float " + str(special_id) + "))")
if ok:
logger.debug(f"Received special unlock {item_table[ap_id]}!")
else:
self.log_error(logger, f"Unable to receive special unlock {item_table[ap_id]}!")
return ok
async def receive_move(self, ap_id: int) -> bool:
move_id = caches.to_game_id(ap_id)
ok = await self.send_form("(send-event "
"*target* \'get-archipelago "
"(pickup-type ap-move) "
"(the float " + str(move_id) + "))")
if ok:
logger.debug(f"Received the ability to {item_table[ap_id]}!")
else:
self.log_error(logger, f"Unable to receive the ability to {item_table[ap_id]}!")
return ok
async def receive_precursor_orb(self, ap_id: int) -> bool:
orb_amount = orbs.to_game_id(ap_id)
ok = await self.send_form("(send-event "
"*target* \'get-archipelago "
"(pickup-type money) "
"(the float " + str(orb_amount) + "))")
if ok:
logger.debug(f"Received {orb_amount} Precursor orbs!")
else:
self.log_error(logger, f"Unable to receive {orb_amount} Precursor orbs!")
return ok
async def receive_trap(self, ap_id: int) -> bool:
trap_id = jak1_max - ap_id
ok = await self.send_form("(send-event "
"*target* \'get-archipelago "
"(pickup-type ap-trap) "
"(the float " + str(trap_id) + "))")
if ok:
logger.debug(f"Received a {item_table[ap_id]}!")
else:
self.log_error(logger, f"Unable to receive a {item_table[ap_id]}!")
return ok
# Green eco pills are our filler item. Use the get-pickup event instead to handle being full health.
async def receive_green_eco(self) -> bool:
ok = await self.send_form("(send-event *target* \'get-pickup (pickup-type eco-pill) (the float 1))")
if ok:
logger.debug(f"Received a green eco pill!")
else:
self.log_error(logger, f"Unable to receive a green eco pill!")
return ok
async def receive_deathlink(self) -> bool:
# Because it should at least be funny sometimes.
death_types = ["\'death",
"\'death",
"\'death",
"\'death",
"\'endlessfall",
"\'drown-death",
"\'melt",
"\'dark-eco-pool"]
chosen_death = random.choice(death_types)
ok = await self.send_form("(ap-deathlink-received! " + chosen_death + ")")
if ok:
logger.debug(f"Received deathlink signal!")
else:
self.log_error(logger, f"Unable to receive deathlink signal!")
return ok
async def subtract_traded_orbs(self, orb_count: int) -> bool:
# To protect against momentary server disconnects,
# this should only be done once per client session.
if not self.balanced_orbs:
self.balanced_orbs = True
ok = await self.send_form(f"(-! (-> *game-info* money) (the float {orb_count}))")
if ok:
logger.debug(f"Subtracting {orb_count} traded orbs!")
else:
self.log_error(logger, f"Unable to subtract {orb_count} traded orbs!")
return ok
return True
# OpenGOAL has a limit of 8 parameters per function. We've already hit this limit. So, define a new datatype
# in OpenGOAL that holds all these options, instantiate the type here, and have ap-setup-options! function take
# that instance as input.
async def setup_options(self,
os_option: int, os_bundle: int,
fc_count: int, mp_count: int,
lt_count: int, ct_amount: int,
ot_amount: int, trap_time: int,
goal_id: int, slot_name: str,
slot_seed: str) -> bool:
sanitized_name = self.sanitize_file_text(slot_name)
sanitized_seed = self.sanitize_file_text(slot_seed)
# I didn't want to have to do this with floats but GOAL's compile-time vs runtime types leave me no choice.
ok = await self.send_form(f"(ap-setup-options! (new 'static 'ap-seed-options "
f":orbsanity-option {os_option} "
f":orbsanity-bundle {os_bundle} "
f":fire-canyon-unlock {fc_count}.0 "
f":mountain-pass-unlock {mp_count}.0 "
f":lava-tube-unlock {lt_count}.0 "
f":citizen-orb-amount {ct_amount}.0 "
f":oracle-orb-amount {ot_amount}.0 "
f":trap-duration {trap_time}.0 "
f":completion-goal {goal_id} "
f":slot-name {sanitized_name} "
f":slot-seed {sanitized_seed} ))")
message = (f"Setting options: \n"
f" orbsanity Option {os_option}, orbsanity Bundle {os_bundle}, \n"
f" FC Cell Count {fc_count}, MP Cell Count {mp_count}, \n"
f" LT Cell Count {lt_count}, Citizen Orb Amt {ct_amount}, \n"
f" Oracle Orb Amt {ot_amount}, Trap Duration {trap_time}, \n"
f" Completion GOAL {goal_id}, Slot Name {sanitized_name}, \n"
f" Slot Seed {sanitized_seed}... ")
if ok:
logger.debug(message + "Success!")
else:
self.log_error(logger, message + "Failed!")
return ok
async def send_connection_status(self, status: str) -> bool:
ok = await self.send_form(f"(ap-set-connection-status! (connection-status {status}))")
if ok:
logger.debug(f"Connection Status {status} set!")
else:
self.log_error(logger, f"Connection Status {status} failed to set!")
return ok
async def save_data(self):
with open("jakanddaxter_item_inbox.json", "w+") as f:
dump = {
"inbox_index": self.inbox_index,
"item_inbox": [{
"item": self.item_inbox[k].item,
"location": self.item_inbox[k].location,
"player": self.item_inbox[k].player,
"flags": self.item_inbox[k].flags
} for k in self.item_inbox
]
}
json.dump(dump, f, indent=4)
def load_data(self):
try:
with open("jakanddaxter_item_inbox.json", "r") as f:
load = json.load(f)
self.inbox_index = load["inbox_index"]
self.item_inbox = {k: NetworkItem(
item=load["item_inbox"][k]["item"],
location=load["item_inbox"][k]["location"],
player=load["item_inbox"][k]["player"],
flags=load["item_inbox"][k]["flags"]
) for k in range(0, len(load["item_inbox"]))
}
except FileNotFoundError:
pass

View File

@@ -0,0 +1,600 @@
# Python standard libraries
import asyncio
import json
import logging
import os
import subprocess
import sys
from asyncio import Task
from datetime import datetime
from logging import Logger
from typing import Awaitable
# Misc imports
import colorama
import pymem
from pymem.exception import ProcessNotFound
# Archipelago imports
import ModuleUpdate
import Utils
from CommonClient import ClientCommandProcessor, CommonContext, server_loop, gui_enabled
from NetUtils import ClientStatus
# Jak imports
from .game_id import jak1_name
from .options import EnableOrbsanity
from .agents.memory_reader import JakAndDaxterMemoryReader
from .agents.repl_client import JakAndDaxterReplClient
from . import JakAndDaxterWorld
ModuleUpdate.update()
logger = logging.getLogger("JakClient")
all_tasks: set[Task] = set()
def create_task_log_exception(awaitable: Awaitable) -> asyncio.Task:
async def _log_exception(a):
try:
return await a
except Exception as e:
logger.exception(e)
finally:
all_tasks.remove(task)
task = asyncio.create_task(_log_exception(awaitable))
all_tasks.add(task)
return task
class JakAndDaxterClientCommandProcessor(ClientCommandProcessor):
ctx: "JakAndDaxterContext"
# The command processor is not async so long-running operations like the /repl connect command
# (which takes 10-15 seconds to compile the game) have to be requested with user-initiated flags.
# The flags are checked by the agents every main_tick.
def _cmd_repl(self, *arguments: str):
"""Sends a command to the OpenGOAL REPL. Arguments:
- connect : connect the client to the REPL (goalc).
- status : check internal status of the REPL."""
if arguments:
if arguments[0] == "connect":
self.ctx.on_log_info(logger, "This may take a bit... Wait for the success audio cue before continuing!")
self.ctx.repl.initiated_connect = True
if arguments[0] == "status":
create_task_log_exception(self.ctx.repl.print_status())
def _cmd_memr(self, *arguments: str):
"""Sends a command to the Memory Reader. Arguments:
- connect : connect the memory reader to the game process (gk).
- status : check the internal status of the Memory Reader."""
if arguments:
if arguments[0] == "connect":
self.ctx.memr.initiated_connect = True
if arguments[0] == "status":
create_task_log_exception(self.ctx.memr.print_status())
class JakAndDaxterContext(CommonContext):
game = jak1_name
items_handling = 0b111 # Full item handling
command_processor = JakAndDaxterClientCommandProcessor
# We'll need two agents working in tandem to handle two-way communication with the game.
# The REPL Client will handle the server->game direction by issuing commands directly to the running game.
# But the REPL cannot send information back to us, it only ingests information we send it.
# Luckily OpenGOAL sets up memory addresses to write to, that AutoSplit can read from, for speedrunning.
# We'll piggyback off this system with a Memory Reader, and that will handle the game->server direction.
repl: JakAndDaxterReplClient
memr: JakAndDaxterMemoryReader
# And two associated tasks, so we have handles on them.
repl_task: asyncio.Task
memr_task: asyncio.Task
# Storing some information for writing save slot identifiers.
slot_seed: str
def __init__(self, server_address: str | None, password: str | None) -> None:
self.repl = JakAndDaxterReplClient(self.on_log_error,
self.on_log_warn,
self.on_log_success,
self.on_log_info)
self.memr = JakAndDaxterMemoryReader(self.on_location_check,
self.on_finish_check,
self.on_deathlink_check,
self.on_deathlink_toggle,
self.on_orb_trade,
self.on_log_error,
self.on_log_warn,
self.on_log_success,
self.on_log_info)
# self.repl.load_data()
# self.memr.load_data()
super().__init__(server_address, password)
def run_gui(self):
from kvui import GameManager
class JakAndDaxterManager(GameManager):
logging_pairs = [
("Client", "Archipelago")
]
base_title = "Jak and Daxter ArchipelaGOAL Client"
self.ui = JakAndDaxterManager(self)
self.ui_task = asyncio.create_task(self.ui.async_run(), name="UI")
async def server_auth(self, password_requested: bool = False):
if password_requested and not self.password:
await super(JakAndDaxterContext, self).server_auth(password_requested)
await self.get_username()
self.tags = set()
await self.send_connect()
def on_package(self, cmd: str, args: dict):
if cmd == "RoomInfo":
self.slot_seed = args["seed_name"]
if cmd == "Connected":
slot_data = args["slot_data"]
orbsanity_option = slot_data["enable_orbsanity"]
if orbsanity_option == EnableOrbsanity.option_per_level:
orbsanity_bundle = slot_data["level_orbsanity_bundle_size"]
elif orbsanity_option == EnableOrbsanity.option_global:
orbsanity_bundle = slot_data["global_orbsanity_bundle_size"]
else:
orbsanity_bundle = 1
# Connected packet is unaware of starting inventory or if player is returning to an existing game.
# Set initial_item_count to 0, see below comments for more info.
if not self.repl.received_initial_items and self.repl.initial_item_count < 0:
self.repl.initial_item_count = 0
create_task_log_exception(
self.repl.setup_options(orbsanity_option,
orbsanity_bundle,
slot_data["fire_canyon_cell_count"],
slot_data["mountain_pass_cell_count"],
slot_data["lava_tube_cell_count"],
slot_data["citizen_orb_trade_amount"],
slot_data["oracle_orb_trade_amount"],
slot_data["trap_effect_duration"],
slot_data["jak_completion_condition"],
self.auth[:16], # The slot name
self.slot_seed[:8]))
# Because Orbsanity and the orb traders in the game are intrinsically linked, we need the server
# to track our trades at all times to support async play. "Retrieved" will tell us the orbs we lost,
# while "ReceivedItems" will tell us the orbs we gained. This will give us the correct balance.
if orbsanity_option in [EnableOrbsanity.option_per_level, EnableOrbsanity.option_global]:
async def get_orb_balance():
await self.send_msgs([{"cmd": "Get", "keys": [f"jakanddaxter_{self.auth}_orbs_paid"]}])
create_task_log_exception(get_orb_balance())
# Tell the server if Deathlink is enabled or disabled in the in-game options.
# This allows us to "remember" the user's choice.
self.on_deathlink_toggle()
if cmd == "Retrieved":
if f"jakanddaxter_{self.auth}_orbs_paid" in args["keys"]:
orbs_traded = args["keys"][f"jakanddaxter_{self.auth}_orbs_paid"]
orbs_traded = orbs_traded if orbs_traded is not None else 0
create_task_log_exception(self.repl.subtract_traded_orbs(orbs_traded))
if cmd == "ReceivedItems":
# If you have a starting inventory or are returning to a game where you have items, a ReceivedItems will be
# in the same network packet as Connected. This guarantees it is the first of any ReceivedItems we process.
# In this case, we should set the initial_item_count to > 0, even if already set to 0 by Connected, as well
# as the received_initial_items flag. Finally, use send_connection_status to tell the player to wait while
# we process the initial items. However, we will skip all this if there was no initial ReceivedItems and
# the REPL indicates it already handled any initial items (0 or otherwise).
if not self.repl.received_initial_items and not self.repl.processed_initial_items:
self.repl.received_initial_items = True
self.repl.initial_item_count = len(args["items"])
create_task_log_exception(self.repl.send_connection_status("wait"))
# This enumeration should run on every ReceivedItems packet,
# regardless of it being on initial connection or midway through a game.
for index, item in enumerate(args["items"], start=args["index"]):
logger.debug(f"index: {str(index)}, item: {str(item)}")
self.repl.item_inbox[index] = item
async def json_to_game_text(self, args: dict):
if "type" in args and args["type"] in {"ItemSend"}:
my_item_name: str | None = None
my_item_finder: str | None = None
their_item_name: str | None = None
their_item_owner: str | None = None
item = args["item"]
recipient = args["receiving"]
# Receiving an item from the server.
if self.slot_concerns_self(recipient):
my_item_name = self.item_names.lookup_in_game(item.item)
# Did we find it, or did someone else?
if self.slot_concerns_self(item.player):
my_item_finder = "MYSELF"
else:
my_item_finder = self.player_names[item.player]
# Sending an item to the server.
if self.slot_concerns_self(item.player):
their_item_name = self.item_names.lookup_in_slot(item.item, recipient)
# Does it belong to us, or to someone else?
if self.slot_concerns_self(recipient):
their_item_owner = "MYSELF"
else:
their_item_owner = self.player_names[recipient]
# Write to game display.
self.repl.queue_game_text(my_item_name, my_item_finder, their_item_name, their_item_owner)
# Even though N items come in as 1 ReceivedItems packet, there are still N PrintJson packets to process,
# and they all arrive before the ReceivedItems packet does. Defer processing of these packets as
# async tasks to speed up large releases of items.
def on_print_json(self, args: dict) -> None:
create_task_log_exception(self.json_to_game_text(args))
super(JakAndDaxterContext, self).on_print_json(args)
# We need to do a little more than just use CommonClient's on_deathlink.
def on_deathlink(self, data: dict):
if self.memr.deathlink_enabled:
self.repl.received_deathlink = True
super().on_deathlink(data)
# We don't need an ap_inform function because check_locations solves that need.
def on_location_check(self, location_ids: list[int]):
create_task_log_exception(self.check_locations(location_ids))
# CommonClient has no finished_game function, so we will have to craft our own. TODO - Update if that changes.
async def ap_inform_finished_game(self):
if not self.finished_game and self.memr.finished_game:
message = [{"cmd": "StatusUpdate", "status": ClientStatus.CLIENT_GOAL}]
await self.send_msgs(message)
self.finished_game = True
def on_finish_check(self):
create_task_log_exception(self.ap_inform_finished_game())
# We need to do a little more than just use CommonClient's send_death.
async def ap_inform_deathlink(self):
if self.memr.deathlink_enabled:
player = self.player_names[self.slot] if self.slot is not None else "Jak"
death_text = self.memr.cause_of_death.replace("Jak", player)
await self.send_death(death_text)
self.on_log_warn(logger, death_text)
# Reset all flags, but leave the death count alone.
self.memr.send_deathlink = False
self.memr.cause_of_death = ""
def on_deathlink_check(self):
create_task_log_exception(self.ap_inform_deathlink())
# We don't need an ap_inform function because update_death_link solves that need.
def on_deathlink_toggle(self):
create_task_log_exception(self.update_death_link(self.memr.deathlink_enabled))
# Orb trades are situations unique to Jak, so we have to craft our own function.
async def ap_inform_orb_trade(self, orbs_changed: int):
if self.memr.orbsanity_enabled:
await self.send_msgs([{"cmd": "Set",
"key": f"jakanddaxter_{self.auth}_orbs_paid",
"default": 0,
"want_reply": False,
"operations": [{"operation": "add", "value": orbs_changed}]
}])
def on_orb_trade(self, orbs_changed: int):
create_task_log_exception(self.ap_inform_orb_trade(orbs_changed))
def _markup_panels(self, msg: str, c: str = None):
color = self.jsontotextparser.color_codes[c] if c else None
message = f"[color={color}]{msg}[/color]" if c else msg
self.ui.log_panels["Archipelago"].on_message_markup(message)
self.ui.log_panels["All"].on_message_markup(message)
def on_log_error(self, lg: Logger, message: str):
lg.error(message)
if self.ui:
self._markup_panels(message, "red")
def on_log_warn(self, lg: Logger, message: str):
lg.warning(message)
if self.ui:
self._markup_panels(message, "orange")
def on_log_success(self, lg: Logger, message: str):
lg.info(message)
if self.ui:
self._markup_panels(message, "green")
def on_log_info(self, lg: Logger, message: str):
lg.info(message)
if self.ui:
self._markup_panels(message)
async def run_repl_loop(self):
while True:
await self.repl.main_tick()
await asyncio.sleep(0.1)
async def run_memr_loop(self):
while True:
await self.memr.main_tick()
await asyncio.sleep(0.1)
def find_root_directory(ctx: JakAndDaxterContext):
# The path to this file is platform-dependent.
if Utils.is_windows:
appdata = os.getenv("APPDATA")
settings_path = os.path.normpath(f"{appdata}/OpenGOAL-Launcher/settings.json")
elif Utils.is_linux:
home = os.path.expanduser("~")
settings_path = os.path.normpath(f"{home}/.config/OpenGOAL-Launcher/settings.json")
elif Utils.is_macos:
home = os.path.expanduser("~")
settings_path = os.path.normpath(f"{home}/Library/Application Support/OpenGOAL-Launcher/settings.json")
else:
ctx.on_log_error(logger, f"Unknown operating system: {sys.platform}!")
return
# Boilerplate messages that all error messages in this function should have.
err_title = "Unable to locate the ArchipelaGOAL install directory"
alt_instructions = (f"Please verify that OpenGOAL and ArchipelaGOAL are installed properly. "
f"If the problem persists, follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Features > Mods > ArchipelaGOAL.\n"
f" Then click Advanced > Open Game Data Folder.\n"
f" Go up one folder, then copy this path.\n"
f" Run the Archipelago Launcher, click Open host.yaml.\n"
f" Set the value of 'jakanddaxter_options > root_directory' to this path.\n"
f" Replace all backslashes in the path with forward slashes.\n"
f" Set the value of 'jakanddaxter_options > auto_detect_root_directory' to false, "
f"then save and close the host.yaml file.\n"
f" Close all launchers, games, clients, and console windows, then restart Archipelago.")
if not os.path.exists(settings_path):
msg = (f"{err_title}: the OpenGOAL settings file does not exist.\n"
f"{alt_instructions}")
ctx.on_log_error(logger, msg)
return
with open(settings_path, "r") as f:
load = json.load(f)
jak1_installed = load["games"]["Jak 1"]["isInstalled"]
if not jak1_installed:
msg = (f"{err_title}: The OpenGOAL Launcher is missing a normal install of Jak 1!\n"
f"{alt_instructions}")
ctx.on_log_error(logger, msg)
return
mod_sources = load["games"]["Jak 1"]["modsInstalledVersion"]
if mod_sources is None:
msg = (f"{err_title}: No mod sources have been configured in the OpenGOAL Launcher!\n"
f"{alt_instructions}")
ctx.on_log_error(logger, msg)
return
# Mods can come from multiple user-defined sources.
# Make no assumptions about where ArchipelaGOAL comes from, we should find it ourselves.
archipelagoal_source = None
for src in mod_sources:
for mod in mod_sources[src].keys():
if mod == "archipelagoal":
archipelagoal_source = src
# Using this file, we could verify the right version is installed, but we don't need to.
if archipelagoal_source is None:
msg = (f"{err_title}: The ArchipelaGOAL mod is not installed in the OpenGOAL Launcher!\n"
f"{alt_instructions}")
ctx.on_log_error(logger, msg)
return
# This is just the base OpenGOAL directory, we need to go deeper.
base_path = load["installationDir"]
mod_relative_path = f"features/jak1/mods/{archipelagoal_source}/archipelagoal"
mod_path = os.path.normpath(
os.path.join(
os.path.normpath(base_path),
os.path.normpath(mod_relative_path)))
return mod_path
async def run_game(ctx: JakAndDaxterContext):
# These may already be running. If they are not running, try to start them.
# TODO - Support other OS's. 1: Pymem is Windows-only. 2: on Linux, there's no ".exe."
gk_running = False
try:
pymem.Pymem("gk.exe") # The GOAL Kernel
gk_running = True
except ProcessNotFound:
ctx.on_log_warn(logger, "Game not running, attempting to start.")
goalc_running = False
try:
pymem.Pymem("goalc.exe") # The GOAL Compiler and REPL
goalc_running = True
except ProcessNotFound:
ctx.on_log_warn(logger, "Compiler not running, attempting to start.")
try:
auto_detect_root_directory = JakAndDaxterWorld.settings.auto_detect_root_directory
if auto_detect_root_directory:
root_path = find_root_directory(ctx)
else:
root_path = JakAndDaxterWorld.settings.root_directory
# Always trust your instincts... the user may not have entered their root_directory properly.
# We don't have to do this check if the root directory was auto-detected.
if "/" not in root_path:
msg = (f"The ArchipelaGOAL root directory contains no path. (Are you missing forward slashes?)\n"
f"Please check your host.yaml file.\n"
f"Verify the value of 'jakanddaxter_options > root_directory' is a valid existing path, "
f"and all backslashes have been replaced with forward slashes.")
ctx.on_log_error(logger, msg)
return
# Start by checking the existence of the root directory provided in the host.yaml file (or found automatically).
root_path = os.path.normpath(root_path)
if not os.path.exists(root_path):
msg = (f"The ArchipelaGOAL root directory does not exist, unable to locate the Game and Compiler.\n"
f"Please check your host.yaml file.\n"
f"If the value of 'jakanddaxter_options > auto_detect_root_directory' is true, verify that OpenGOAL "
f"is installed properly.\n"
f"If it is false, check the value of 'jakanddaxter_options > root_directory'. "
f"Verify it is a valid existing path, and all backslashes have been replaced with forward slashes.")
ctx.on_log_error(logger, msg)
return
# Now double-check the existence of the two executables we need.
gk_path = os.path.join(root_path, "gk.exe")
goalc_path = os.path.join(root_path, "goalc.exe")
if not os.path.exists(gk_path) or not os.path.exists(goalc_path):
msg = (f"The Game and Compiler could not be found in the ArchipelaGOAL root directory.\n"
f"Please check your host.yaml file.\n"
f"If the value of 'jakanddaxter_options > auto_detect_root_directory' is true, verify that OpenGOAL "
f"is installed properly.\n"
f"If it is false, check the value of 'jakanddaxter_options > root_directory'. "
f"Verify it is a valid existing path, and all backslashes have been replaced with forward slashes.")
ctx.on_log_error(logger, msg)
return
# Now we can FINALLY attempt to start the programs.
if not gk_running:
# Per-mod saves and settings are stored outside the ArchipelaGOAL root folder, so we have to traverse
# a relative path, normalize it, and pass it in as an argument to gk. This folder will be created if
# it does not exist.
config_relative_path = "../_settings/archipelagoal"
config_path = os.path.normpath(
os.path.join(
root_path,
os.path.normpath(config_relative_path)))
# The game freezes if text is inadvertently selected in the stdout/stderr data streams. Let's pipe those
# streams to a file, and let's not clutter the screen with another console window.
timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
log_path = os.path.join(Utils.user_path("logs"), f"JakAndDaxterGame_{timestamp}.txt")
log_path = os.path.normpath(log_path)
with open(log_path, "w") as log_file:
gk_process = subprocess.Popen(
[gk_path, "--game", "jak1",
"--config-path", config_path,
"--", "-v", "-boot", "-fakeiso", "-debug"],
stdout=log_file,
stderr=log_file,
creationflags=subprocess.CREATE_NO_WINDOW)
if not goalc_running:
# For the OpenGOAL Compiler, the existence of the "data" subfolder indicates you are running it from
# a built package. This subfolder is treated as its proj_path.
proj_path = os.path.join(root_path, "data")
if os.path.exists(proj_path):
# Look for "iso_data" path to automate away an oft-forgotten manual step of mod updates.
# All relative paths should start from root_path and end with "jak1".
goalc_args = []
possible_relative_paths = {
"../../../../../active/jak1/data/iso_data/jak1",
"./data/iso_data/jak1",
}
for iso_relative_path in possible_relative_paths:
iso_path = os.path.normpath(
os.path.join(
root_path,
os.path.normpath(iso_relative_path)))
if os.path.exists(iso_path):
goalc_args = [goalc_path, "--game", "jak1", "--proj-path", proj_path, "--iso-path", iso_path]
logger.debug(f"iso_data folder found: {iso_path}")
break
else:
logger.debug(f"iso_data folder not found, continuing: {iso_path}")
if not goalc_args:
msg = (f"The iso_data folder could not be found.\n"
f"Please follow these steps:\n"
f" Run the OpenGOAL Launcher, click Jak and Daxter > Advanced > Open Game Data Folder.\n"
f" Copy the iso_data folder from this location.\n"
f" Click Jak and Daxter > Features > Mods > ArchipelaGOAL > Advanced > "
f"Open Game Data Folder.\n"
f" Paste the iso_data folder in this location.\n"
f" Click Advanced > Compile. When this is done, click Continue.\n"
f" Close all launchers, games, clients, and console windows, then restart Archipelago.\n"
f"(See Setup Guide for more details.)")
ctx.on_log_error(logger, msg)
return
# The non-existence of the "data" subfolder indicates you are running it from source, as a developer.
# The compiler will traverse upward to find the project path on its own. It will also assume your
# "iso_data" folder is at the root of your repository. Therefore, we don't need any of those arguments.
else:
goalc_args = [goalc_path, "--game", "jak1"]
# This needs to be a new console. The REPL console cannot share a window with any other process.
goalc_process = subprocess.Popen(goalc_args, creationflags=subprocess.CREATE_NEW_CONSOLE)
except AttributeError as e:
if " " in e.args[0]:
# YAML keys in Host.yaml ought to contain no spaces, which means this is a much more important error.
ctx.on_log_error(logger, e.args[0])
else:
ctx.on_log_error(logger,
f"Host.yaml does not contain {e.args[0]}, unable to locate game executables.")
return
except FileNotFoundError as e:
msg = (f"The following path could not be found: {e.filename}\n"
f"Please check your host.yaml file.\n"
f"If the value of 'jakanddaxter_options > auto_detect_root_directory' is true, verify that OpenGOAL "
f"is installed properly.\n"
f"If it is false, check the value of 'jakanddaxter_options > root_directory'."
f"Verify it is a valid existing path, and all backslashes have been replaced with forward slashes.")
ctx.on_log_error(logger, msg)
return
# Auto connect the repl and memr agents. Sleep 5 because goalc takes just a little bit of time to load,
# and it's not something we can await.
ctx.on_log_info(logger, "This may take a bit... Wait for the game's title sequence before continuing!")
await asyncio.sleep(5)
ctx.repl.initiated_connect = True
ctx.memr.initiated_connect = True
async def main():
Utils.init_logging("JakAndDaxterClient", exception_logger="Client")
ctx = JakAndDaxterContext(None, None)
ctx.server_task = asyncio.create_task(server_loop(ctx), name="server loop")
ctx.repl_task = create_task_log_exception(ctx.run_repl_loop())
ctx.memr_task = create_task_log_exception(ctx.run_memr_loop())
if gui_enabled:
ctx.run_gui()
ctx.run_cli()
# Find and run the game (gk) and compiler/repl (goalc).
create_task_log_exception(run_game(ctx))
await ctx.exit_event.wait()
await ctx.shutdown()
def launch():
# use colorama to display colored text highlighting
colorama.just_fix_windows_console()
asyncio.run(main())
colorama.deinit()

View File

@@ -0,0 +1,258 @@
# Jak And Daxter (ArchipelaGOAL)
## FAQ
- [Where is the Options page?](#where-is-the-options-page)
- [What does randomization do to this game?](#what-does-randomization-do-to-this-game)
- [What are the Special Checks and how do I check them?](#what-are-the-special-checks-and-how-do-i-check-them)
- [What are the Special Items and what do they unlock?](#what-are-the-special-items-and-what-do-they-unlock)
- [How do I know which Special Items I have?](#how-do-i-know-which-special-items-i-have)
- [What is the goal of the game once randomized?](#what-is-the-goal-of-the-game-once-randomized)
- [What happens when I pick up or receive a Power Cell?](#what-happens-when-i-pick-up-or-receive-a-power-cell)
- [What happens when I pick up or receive a Scout Fly?](#what-happens-when-i-pick-up-or-receive-a-scout-fly)
- [How do I check the 'Free 7 Scout Flies' Power Cell?](#how-do-i-check-the-free-7-scout-flies-power-cell)
- [What does Death Link do?](#what-does-death-link-do)
- [What does Move Randomizer do?](#what-does-move-randomizer-do)
- [What are the movement options in Move Randomizer?](#what-are-the-movement-options-in-move-randomizer)
- [How do I know which moves I have?](#how-do-i-know-which-moves-i-have)
- [What does Orbsanity do?](#what-does-orbsanity-do)
- [What do Traps do?](#what-do-traps-do)
- [What kind of Traps are there?](#what-kind-of-traps-are-there)
- [I got soft-locked and cannot leave, how do I get out of here?](#i-got-soft-locked-and-cannot-leave-how-do-i-get-out-of-here)
- [Why did I get an Option Error when generating a seed, and how do I fix it?](#why-did-i-get-an-option-error-when-generating-a-seed-and-how-do-i-fix-it)
- [How do I check my player options in-game?](#how-do-i-check-my-player-options-in-game)
- [How does the HUD work?](#how-does-the-hud-work)
- [I think I found a bug, where should I report it?](#i-think-i-found-a-bug-where-should-i-report-it)
## Where is the options page
The [Player Options Page](../player-options) for this game contains all the options you need to configure and export
a config file.
At this time, there are several caveats and restrictions:
- Power Cells and Scout Flies are **always** randomized.
- **All** the traders in the game become in-logic checks **if and only if** you have enough Orbs to pay all of them at once.
- This is to prevent hard locks, where an item required for progression is locked behind a trade you can't afford because you spent the orbs elsewhere.
- By default, that total is 1530.
## What does randomization do to this game
The game now contains the following Location checks:
- All 101 Power Cells
- All 112 Scout Flies
- All 14 Orb Caches (collect every orb in the cache and let it close)
These may contain Items for different games, as well as different Items from within Jak and Daxter.
Additionally, several special checks and corresponding items have been added that are required to complete the game.
## What are the special checks and how do I check them
| Check Name | How To Check |
|------------------------|------------------------------------------------------------------------------|
| Fisherman's Boat | Complete the fishing minigame in Forbidden Jungle |
| Jungle Elevator | Collect the power cell at the top of the temple in Forbidden Jungle |
| Blue Eco Switch | Collect the power cell on the blue vent switch in Forbidden Jungle |
| Flut Flut | Push the egg off the cliff in Sentinel Beach and talk to the bird lady |
| Warrior's Pontoons | Talk to the Warrior in Rock Village once (you do NOT have to trade with him) |
| Snowy Mountain Gondola | Approach the gondola in Volcanic Crater |
| Yellow Eco Switch | Collect the power cell on the yellow vent switch in Snowy Mountain |
| Snowy Fort Gate | Ride the Flut Flut in Snowy Mountain and press the fort gate switch |
| Freed The Blue Sage | Free the Blue Sage in Gol and Maia's Citadel |
| Freed The Red Sage | Free the Red Sage in Gol and Maia's Citadel |
| Freed The Yellow Sage | Free the Yellow Sage in Gol and Maia's Citadel |
| Freed The Green Sage | Free the Green Sage in Gol and Maia's Citadel |
## What are the special items and what do they unlock
| Item Name | What it Unlocks |
|--------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| Fisherman's Boat | Misty Island |
| Jungle Elevator | The blue vent switch inside the temple in Forbidden Jungle |
| Blue Eco Switch | The plant boss inside the temple in Forbidden Jungle <br/> The cannon tower in Sentinel Beach |
| Flut Flut | The upper platforms in Boggy Swamp <br/> The fort gate switch in Snowy Mountain |
| Warrior's Pontoons | Boggy Swamp and Mountain Pass |
| Snowy Mountain Gondola | Snowy Mountain |
| Yellow Eco Switch | The frozen box in Snowy Mountain <br/> The shortcut in Mountain Pass |
| Snowy Fort Gate | The fort in Snowy Mountain |
| Freed The Blue Sage <br/> Freed The Red Sage <br/> Freed The Yellow Sage | The final staircase in Gol and Maia's Citadel |
| Freed The Green Sage | The final elevator in Gol and Maia's Citadel |
## How do I know which special items I have
Open the game's menu, navigate to `Options`, then `Archipelago Options`, then `Item Tracker`.
This will show you a list of all the special items in the game, ones not normally tracked as power cells or scout flies.
Gray items indicate you do not possess that item, light blue items indicate you possess that item.
## What is the goal of the game once randomized
By default, to complete the game you must defeat the Gol and Maia and stop them from opening the Dark Eco silo. In order
to reach them, you will need at least 72 Power Cells to cross the Lava Tube, as well as the four special items for
freeing the Red, Blue, Yellow, and Green Sages.
Alternatively, you can choose from a handful of other completion conditions like defeating a particular boss, crossing
a particular connector level, or opening the 100 Power Cell door after defeating the final boss. You can also customize
the thresholds for connector levels and orb trades. These options allow you to tailor the expected length and difficulty
of your run as you see fit.
## What happens when I pick up or receive a power cell
When you pick up a power cell, Jak and Daxter will perform their victory animation. Your power cell count will
NOT change. The pause menu will say "Task Completed" below the picked-up Power Cell. If your power cell was related
to one of the special checks listed above, you will automatically check that location as well - a 2 for 1 deal!
Finally, your text client will inform you what you found and who it belongs to.
When you receive a power cell, your power cell count will tick up by 1. Gameplay will otherwise continue as normal.
Finally, your text client will inform you where you received the power cell from.
## What happens when I pick up or receive a scout fly
When you pick up a scout fly, your scout fly count will NOT change. The pause menu will show you the number of
scout flies you picked up per-region, and this number will have ticked up by 1 for the region that scout fly belongs to.
Finally, your text client will inform you what you found and who it belongs to.
When you receive a scout fly, your total scout fly count will tick up by 1. The pause menu will show you the number of
scout flies you received per-region, and this number will have ticked up by 1 for the region that scout fly belongs to.
Finally, your text client will inform you where you received the scout fly from, and which one it is.
## How do I check the Free 7 Scout Flies power cell
You will automatically check this power cell when you _receive_ your 7th scout fly, NOT when you _pick up_ your 7th
scout fly. So in short:
- When you _pick up_ your 7th fly, the normal rules apply.
- When you _receive_ your 7th fly, 2 things will happen in quick succession.
- First, you will receive that scout fly, as normal.
- Second, you will immediately complete the "Free 7 Scout Flies" check, which will send out another item.
## What does Death Link do
If you enable Death Link, all the other players in your Multiworld who also have it enabled will be linked by death.
That means when Jak dies in your game, the players in with Death Link also die. Likewise, if any of the other
players with Death Link die, Jak will also die in a random, possibly spectacular fashion.
You can turn off Death Link at any time in the game by opening the game's menu and navigating to `Options`,
then `Archipelago Options`, then `Deathlink`.
## What does Move Randomizer do
If you enable Move Randomizer, most of Jak's movement set will be added to the randomized item pool, and you will need
to receive the move in order to use it (i.e. you must find it, or another player must send it to you). Some moves have
prerequisite moves that you must also have in order to use them (e.g. Crouch Jump is dependent on Crouch). Jak will only
be able to run, swim (including underwater), perform single jumps, and shoot yellow eco from his goggles ("firing from
the hip" requires Punch). Note that Flut Flut and the Zoomer will have access to their full movement sets at all times.
You can turn off Move Rando at any time in the game by opening the game's menu, navigate to `Options`,
then `Archipelago Options`, then `Move Randomizer`. This will give you access to the full movement set again.
## What are the movement options in Move Randomizer
| Move Name | Prerequisite Moves |
|-----------------|--------------------|
| Crouch | |
| Crouch Jump | Crouch |
| Crouch Uppercut | Crouch |
| Roll | |
| Roll Jump | Roll |
| Double Jump | |
| Jump Dive | |
| Jump Kick | |
| Punch | |
| Punch Uppercut | Punch |
| Kick | |
## How do I know which moves I have
Open the game's menu, navigate to `Options`, then `Archipelago Options`, then `Move Tracker`.
This will show you a list of all the moves in the game.
- Gray items indicate you do not possess that move.
- Yellow items indicate you possess that move, but you are missing its prerequisites.
- Light blue items indicate you possess that move, as well as its prerequisites.
## What does Orbsanity do
If you enable Orbsanity, bundles of Precursor Orbs will be turned into checks. Every time you collect the chosen number
of orbs, i.e. a "bundle," you will trigger another check. Likewise, the orbs will be added to the random item pool.
There are several options to change the difficulty of this challenge.
- "Per Level" Orbsanity means the bundles are for each level in the game. (Geyser Rock, Sandover Village, etc.)
- "Global" Orbsanity means orbs collected from any level count toward the next bundle.
- The options with "Bundle Size" in the name indicate how many orbs are in a bundle. This adds a number of Items
and Locations to the pool inversely proportional to the size of the bundle.
- For example, if your bundle size is 20 orbs, you will add 100 items to the pool. If your bundle size is 250 orbs,
you will add 8 items to the pool.
## What do Traps do
When creating your player YAML, you can choose to replace some of the game's extraneous Power Cells and Precursor Orbs
with traps. You can choose which traps you want to generate in your seed and how long they last. A random assortment
will then be chosen to populate the item pool.
When you receive one, you will hear a buzzer and some kind of negative effect will occur in game. These effects may be
challenging, maddening, or entertaining. When the trap duration ends, the game should return to its previous state.
Multiple traps can be active at the same time, and they may interact with each other in strange ways. If they become
too frustrating, you can lower their duration by navigating to `Options`, then `Archipelago Options`, then
`Seed Options`, then `Trap Duration`. Lowering this number to zero will disable traps entirely.
## What kind of Traps are there
| Trap Name | Effect |
|-----------------|--------------------------------------------------------------------------------|
| Trip Trap | Jak trips and falls |
| Slippery Trap | The world gains the physical properties of Snowy Mountain's ice lake |
| Gravity Trap | Jak falls to the ground faster and takes fall damage more easily |
| Camera Trap | The camera remains fixed in place no matter how far away Jak moves |
| Darkness Trap | The world gains the lighting properties of Dark Cave |
| Earthquake Trap | The world and camera shake |
| Teleport Trap | Jak immediately teleports to Samos's Hut |
| Despair Trap | The Warrior sobs profusely |
| Pacifism Trap | Jak's attacks have no effect on enemies, crates, or buttons |
| Ecoless Trap | Jak's eco is drained and he cannot collect new eco |
| Health Trap | Jak's health is set to 0 - not dead yet, but he will die to any attack or bonk |
| Ledge Trap | Jak cannot grab onto ledges |
| Zoomer Trap | Jak mounts an invisible zoomer (model loads properly depending on level) |
| Mirror Trap | The world is mirrored |
## I got soft-locked and cannot leave how do I get out of here
Open the game's menu, navigate to `Options`, then `Archipelago Options`, then `Warp To Home`.
Selecting this option will ask if you want to be teleported to Geyser Rock. From there, you can teleport back
to the nearest sage's hut to continue your journey.
## Why did I get an Option Error when generating a seed and how do I fix it
Depending on your player YAML, Jak and Daxter can have a lot of items, which can sometimes be overwhelming or
disruptive to multiworld games. There are also options that are mutually incompatible with each other, even in a solo
game. To prevent the game from disrupting multiworlds, or generating an impossible solo seed, some options have
Singleplayer and Multiplayer Minimums and Maximums, collectively called "friendly limits."
If you're generating a solo game, or your multiworld host agrees to your request, you can override those limits by
editing the `host.yaml`. In the Archipelago Launcher, click `Open host.yaml`, then search for `jakanddaxter_options`,
then search for `enforce_friendly_options`, then change this value from `true` to `false`. Disabling this allows for
more disruptive and challenging options, but it may cause seed generation to fail. **Use at your own risk!**
## How do I check my player options in-game
When you connect your text client to the Archipelago Server, the server will tell the game what options were chosen
for this seed, and the game will apply those settings automatically.
You can verify these options by navigating to `Options`, then `Archipelago Options`, then `Seed Options`. **You can open
each option to verify them, but you should NOT alter them during a run.** This may cause you to miss important
progression items and prevent you (and others) from completing the run.
## How does the HUD work
The game's normal HUD shows you how many power cells, precursor orbs, and scout flies you currently have. But if you
hold `L2 or R2` and press a direction on the D-Pad, the HUD will show you alternate modes. Here is how the HUD works:
| HUD Mode | Button Combo | What the HUD Shows | Text Messages |
|---------------|------------------------------|-----------------------------------|---------------------------------------|
| Per-Level | `L2 or R2` + `Down` | Locations Checked (in this level) | `SENT {Other Item} TO {Other Player}` |
| Global | `L2 or R2` + `Up` | Locations Checked (in the game) | `GOT {Your Item} FROM {Other Player}` |
| Normal | `L2 or R2` + `Left or Right` | Items Received | Both Sent and Got Messages |
| | | | |
| (In Any Mode) | | (If you sent an Item to Yourself) | `FOUND {Your Item}` |
In all modes, the last 3 sent/received items and the player who sent/received it will be displayed in the
bottom left corner. This will help you quickly reference information about newly received or sent items. Items in blue
are Progression (or non-Jak items), in green are Filler, and in red are Traps. You can turn this off by navigating
to `Options`, then `Archipelago Options`, then set `Item Messages` to `Off`.
## I think I found a bug where should I report it
Depending on the nature of the bug, there are a couple of different options.
* If you found a logical error in the randomizer, please create a new Issue
[here](https://github.com/ArchipelaGOAL/Archipelago/issues). Use this page if:
* An item required for progression is unreachable.
* The randomizer did not respect one of the Options you chose.
* You see a mistake, typo, etc. on this webpage.
* You see an error or stack trace appear on the text client.
* If you encountered an error in OpenGOAL, please create a new Issue
[here](https://github.com/ArchipelaGOAL/ArchipelaGOAL/issues). Use this page if:
* You encounter a crash, freeze, reset, etc. in the game.
* You fail to send Items you find in the game to the Archipelago server.
* You fail to receive Items the server sends to you.
* Your game disconnects from the server and cannot reconnect.
* You go looking for a game item that has already disappeared before you could reach it.
* Please upload your config file, spoiler log file, and any other generated logs in the Issue, so we can troubleshoot the problem.

View File

@@ -0,0 +1,182 @@
# Jak And Daxter (ArchipelaGOAL) Setup Guide
## Required Software
- A legally purchased copy of *Jak And Daxter: The Precursor Legacy.*
- [The OpenGOAL Launcher](https://opengoal.dev/)
- [The Jak and Daxter .APWORLD package](https://github.com/ArchipelaGOAL/Archipelago/releases)
At this time, this method of setup works on Windows only, but Linux support is a strong likelihood in the near future as OpenGOAL itself supports Linux.
## Installation via OpenGOAL Launcher
**You must set up a vanilla installation of Jak and Daxter before you can install mods for it.**
- Follow the installation process for the official OpenGOAL Launcher. See [here](https://opengoal.dev/docs/usage/installation).
- Follow the setup process for adding mods to the OpenGOAL Launcher. See [here](https://jakmods.dev/).
- Run the OpenGOAL Launcher (if you had it open before, close it and reopen it).
- Click the Jak and Daxter logo on the left sidebar.
- Click `Features` in the bottom right corner, then click `Mods`.
- Under `Available Mods`, click `ArchipelaGOAL`. The mod should begin installing. When it is done, click `Continue` in the bottom right corner.
- **DO NOT PLAY AN ARCHIPELAGO GAME THROUGH THE OPENGOAL LAUNCHER.** The Archipelago Client should handle everything for you.
### For NTSC versions of the game, follow these steps.
- Run the OpenGOAL Launcher (if you had it open before, close it and reopen it).
- Click the Jak and Daxter logo on the left sidebar.
- Click `Features` in the bottom right corner, then click `Mods`, then under `Installed Mods`, click `ArchipelaGOAL`.
- In the bottom right corner, click `Advanced`, then click `Compile`.
### For PAL versions of the game, follow these steps.
PAL versions of the game seem to require additional troubleshooting/setup in order to work properly.
Below are some instructions that may help.
If you see `-- Compilation Error! --` after pressing `Compile` or Launching the ArchipelaGOAL mod, try these steps.
- Remove these folders if you have them:
- `<opengoal active version directory>/iso_data`
- `<archipelagoal directory>/iso_data`
- `<archipelagoal directory>/data/iso_data`
- Place your Jak1 ISO in `<archipelagoal directory>` and rename it to `JakAndDaxter.iso`
- Type `cmd` in Windows search, right click `Command Prompt`, and pick `Run as Administrator`
- Run `cd <archipelagoal directory>`
- Then run `.\extractor.exe --extract --extract-path .\data\iso_data "JakAndDaxter.iso"`
- This command should end by saying `Uses Decompiler Config Version - ntsc_v1` or `... - pal`. Take note of this message.
- If you saw `ntsc_v1`:
- In cmd, run `.\decompiler.exe data\decompiler\config\jak1\jak1_config.jsonc --version "ntsc_v1" data\iso_data data\decompiler_out`
- If you saw `pal`:
- Rename `<archipelagoal directory>\data\iso_data\jak1` to `jak1_pal`
- Back in cmd, run `.\decompiler.exe data\decompiler\config\jak1\jak1_config.jsonc --version "pal" data\iso_data data\decompiler_out`
- Rename `<archipelagoal directory>\data\iso_data\jak1_pal` back to `jak1`
- Rename `<archipelagoal directory>\data\decompiler_out\jak1_pal` back to `jak1`
- Open a **brand new** console window and launch the compiler:
- `cd <archipelagoal directory>`
- `.\goalc.exe --user-auto --game jak1`
- From the compiler (in the same window): `(mi)`. This should compile the game. **Note that the parentheses are important.**
- **Don't close this first terminal, you will need it at the end.**
- Then, open **another brand new** console window and execute the game:
- `cd <archipelagoal directory>`
- `.\gk.exe -v --game jak1 -- -boot -fakeiso -debug`
- Finally, **from the first console still in the GOALC compiler**, connect to the game: `(lt)`.
## Updates and New Releases via OpenGOAL Launcher
If you are in the middle of an async game, and you do not want to update the mod, you do not need to do this step. The mod will only update when you tell it to.
- Run the OpenGOAL Launcher (if you had it open before, close it and reopen it).
- Click the Jak and Daxter logo on the left sidebar.
- Click `Features` in the bottom right corner, then click `Mods`, then under `Installed Mods`, click `ArchipelaGOAL`.
- Click `Update` to download and install any new updates that have been released.
- You can verify your version by clicking `Versions`. The version you are using will say `(Active)` next to it.
- **Then you must click `Advanced`, then click `Compile` to make the update take effect.**
## Starting a Game
### New Game
- Run the Archipelago Launcher.
- From the right-most list, find and click `Jak and Daxter Client`.
- 3 new windows should appear:
- The OpenGOAL compiler will launch and compile the game. They should take about 30 seconds to compile.
- You should hear a musical cue to indicate the compilation was a success. If you do not, see the Troubleshooting section.
- You can **MINIMIZE** the Compiler window, **BUT DO NOT CLOSE IT.** It is required for Archipelago and the game to communicate with each other.
- The game window itself will launch, and Jak will be standing outside Samos's Hut.
- Once compilation is complete, the title sequence will start.
- Finally, the Archipelago text client will open.
- If you see **BOTH** `The REPL is ready!` and `The Memory Reader is ready!` then that should indicate a successful startup. If you do not, see the Troubleshooting section.
- Once you see `CONNECT TO ARCHIPELAGO NOW` on the title screen, use the text client to connect to the Archipelago server. This will communicate your current settings and slot info to the game.
- If you see `RECEIVING ITEMS, PLEASE WAIT...`, the game is busy receiving items from your starting inventory, assuming you have some.
- Once you see `READY! PRESS START TO CONTINUE` on the title screen, you can press Start.
- Choose `New Game`, choose a save file, and play through the opening cutscenes.
- Once you reach Geyser Rock, the game has begun!
- You can leave Geyser Rock immediately if you so choose - just step on the warp gate button.
### Returning / Async Game
The same steps as New Game apply, with some exceptions:
- Once you reach the title screen, connect to the Archipelago server **BEFORE** you load your save file.
- This is to allow AP to give the game your current settings and all the items you had previously.
- **THESE SETTINGS AFFECT LOADING AND SAVING OF SAVE FILES, SO IT IS IMPORTANT TO DO THIS FIRST.**
- Once you see `READY! PRESS START TO CONTINUE` on the title screen, you can press Start.
- Instead of choosing `New Game` in the title menu, choose `Load Game`, then choose the save file **THAT HAS YOUR CURRENT SLOT NAME.**
- To help you find the correct save file, highlighting a save will show you that save's slot name and the first 8 digits of the multiworld seed number.
## Troubleshooting
### The Text Client Says "Unable to locate the OpenGOAL install directory"
Normally, the Archipelago client should be able to find your OpenGOAL installation automatically.
If it cannot, you may have to tell it yourself. Follow these instructions.
- Run the OpenGOAL Launcher (if you had it open before, close it and reopen it).
- Click the Jak and Daxter logo on the left sidebar.
- Click `Features` in the bottom right corner, then click `Mods`, then under `Installed Mods`, click `ArchipelaGOAL`.
- Click `Advanced` in the bottom right corner, then click `Open Game Data Folder`. You should see a new File Explorer open to that directory.
- In the File Explorer, go to the parent directory called `archipelagoal`, and you should see the `gk.exe` and `goalc.exe` executables. Copy this path.
- Run the Archipelago Launcher, then click on `Open host.yaml`. You should see a new text editor open that file.
- Search for `jakanddaxter_options`, and you will need to make 2 changes here.
- First, find the `root_directory` entry. Paste the path you noted earlier (the one containing gk.exe and goalc.exe) inside the double quotes.
- **MAKE SURE YOU CHANGE ALL BACKSLASHES `\ ` TO FORWARD SLASHES `/`.**
```yaml
root_directory: "%programfiles%/OpenGOAL-Launcher/features/jak1/mods/JakMods/archipelagoal"
```
- Second, find the `root_directory` entry. Change this to `false`. You do not need to use double quotes.
```yaml
auto_detect_root_directory: true
```
- Save the file and close it.
### The Game Fails To Load The Title Screen
You may start the game via the Text Client, but it never loads in the title screen. Check the Compiler window: you may see red and yellow errors like this.
```
-- Compilation Error! --
```
If this happens, follow these instructions. If you are using a PAL version of the game, you should skip these instructions and follow the `Special PAL Instructions` above.
- Run the OpenGOAL Launcher (if you had it open before, close it and reopen it).
- Click the Jak and Daxter logo on the left sidebar, then click `Advanced`, then click `Open Game Data Folder`. Copy the `iso_data` folder from this directory.
- Back in the OpenGOAL Launcher, click the Jak and Daxter logo on the left sidebar.
- Click `Features` in the bottom right corner, then click `Mods`, then under `Installed Mods`, click `ArchipelaGOAL`.
- In the bottom right corner, click `Advanced`, then click `Open Game Data Folder`.
- Paste the `iso_data` folder you copied earlier.
- Back in the OpenGOAL Launcher, click the Jak and Daxter logo on the left sidebar.
- Click `Features` in the bottom right corner, then click `Mods`, then under `Installed Mods`, click `ArchipelaGOAL`.
- In the bottom right corner, click `Advanced`, then click `Compile`.
### The Text Client Says "Error reading game memory!" or "Error sending data to compiler"
If at any point the text client says this, you will need to restart the **all** of these applications.
- Close all open windows: the client, the compiler, and the game.
- Run the OpenGOAL Launcher, then click `Features`, then click `Mods`, then click `ArchipelaGOAL`.
- Click `Advanced`, then click `Play in Debug Mode`.
- Click `Advanced`, then click `Open REPL`.
- Then close and reopen the Jak and Daxter Client from the Archipelago Launcher.
- Once these are done, you can enter `/repl status` and `/memr status` in the text client to verify.
### The Client Cannot Open A REPL Connection
If the client cannot open a REPL connection to the game, you may need to check the following steps:
- Ensure you are not hosting anything on ports `8181` and `8112`. Those are for the REPL (goalc) and the game (gk) respectively.
- Ensure that Windows Defender and Windows Firewall are not blocking those programs from hosting or listening on those ports.
- You can use Windows Resource Monitor to verify those ports are open when the programs are running.
- Ensure that you only opened those ports for your local network, not the wider internet.
## Known Issues
- The game needs to boot in debug mode in order to allow the compiler to connect to it. **Clicking "Play" on the mod page in the OpenGOAL Launcher will not work.**
- The Compiler console window is orphaned once you close the game - you will have to kill it manually when you stop playing.
- The console windows cannot be run as background processes due to how the REPL works, so the best we can do is minimize them.
- Orbsanity checks may show up out of order in the text client.
- Large item releases may take up to several minutes for the game to process them all. Item Messages will usually take longer to appear than Items themselves.
- In Lost Precursor City, if you die in the Color Platforms room, the game may crash after you respawn. The cause is unknown.
- Darkness Trap may cause some visual glitches on certain levels. This is temporary, and terrain and object collision are unaffected.

View File

@@ -0,0 +1,8 @@
# All Jak And Daxter Archipelago IDs must be offset by this number.
jak1_id = 741000000
# This is maximum ID we will allow.
jak1_max = jak1_id + 999999
# The name of the game.
jak1_name = "Jak and Daxter: The Precursor Legacy"

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

@@ -0,0 +1,156 @@
from enum import IntEnum
from BaseClasses import Item, ItemClassification
from .game_id import jak1_name, jak1_max
from .locs import (orb_locations as orbs,
cell_locations as cells,
scout_locations as scouts,
special_locations as specials,
orb_cache_locations as caches)
class OrbAssoc(IntEnum):
"""
Identifies an item's association to unlocking new sources of Precursor Orbs. For example, Double Jump will unlock
new orbs, but Freed the Green Sage will not. Power Cells conditionally unlock new orbs if they get you across
connector levels.
"""
NEVER_UNLOCKS_ORBS = 0
ALWAYS_UNLOCKS_ORBS = 1
IS_POWER_CELL = 2
class JakAndDaxterItem(Item):
game: str = jak1_name
orb_assoc: OrbAssoc
orb_amount: int # Only non-zero for Orb Bundle items.
def __init__(self, name: str,
classification: ItemClassification,
code: int | None,
player: int,
orb_assoc: OrbAssoc = OrbAssoc.NEVER_UNLOCKS_ORBS,
orb_amount: int = 0):
super().__init__(name, classification, code, player)
self.orb_assoc = orb_assoc
self.orb_amount = orb_amount
# Power Cells are generic, fungible, interchangeable items. Every cell is indistinguishable from every other.
cell_item_table = {
0: "Power Cell",
}
# Scout flies are interchangeable within their respective sets of 7. Notice the level name after each item.
# Also, notice that their Item ID equals their respective Power Cell's Location ID. This is necessary for
# game<->archipelago communication.
scout_item_table = {
95: "Scout Fly - Geyser Rock",
75: "Scout Fly - Sandover Village",
7: "Scout Fly - Forbidden Jungle",
20: "Scout Fly - Sentinel Beach",
28: "Scout Fly - Misty Island",
68: "Scout Fly - Fire Canyon",
76: "Scout Fly - Rock Village",
57: "Scout Fly - Precursor Basin",
49: "Scout Fly - Lost Precursor City",
43: "Scout Fly - Boggy Swamp",
88: "Scout Fly - Mountain Pass",
77: "Scout Fly - Volcanic Crater",
85: "Scout Fly - Spider Cave",
65: "Scout Fly - Snowy Mountain",
90: "Scout Fly - Lava Tube",
91: "Scout Fly - Citadel", # Had to shorten, it was >32 characters.
}
# Orbs are also generic and interchangeable.
# These items are only used by Orbsanity, and only one of these
# items will be used corresponding to the chosen bundle size.
orb_item_table = {
1: "1 Precursor Orb",
2: "2 Precursor Orbs",
4: "4 Precursor Orbs",
5: "5 Precursor Orbs",
8: "8 Precursor Orbs",
10: "10 Precursor Orbs",
16: "16 Precursor Orbs",
20: "20 Precursor Orbs",
25: "25 Precursor Orbs",
40: "40 Precursor Orbs",
50: "50 Precursor Orbs",
80: "80 Precursor Orbs",
100: "100 Precursor Orbs",
125: "125 Precursor Orbs",
200: "200 Precursor Orbs",
250: "250 Precursor Orbs",
400: "400 Precursor Orbs",
500: "500 Precursor Orbs",
1000: "1000 Precursor Orbs",
2000: "2000 Precursor Orbs",
}
# These are special items representing unique unlocks in the world. Notice that their Item ID equals their
# respective Location ID. Like scout flies, this is necessary for game<->archipelago communication.
special_item_table = {
5: "Fisherman's Boat", # Unlocks Misty Island
4: "Jungle Elevator", # Unlocks the Forbidden Jungle Temple
2: "Blue Eco Switch", # Unlocks Blue Eco Vents
17: "Flut Flut", # Unlocks Flut Flut sections in Boggy Swamp and Snowy Mountain
33: "Warrior's Pontoons", # Unlocks Boggy Swamp and everything post-Rock Village
105: "Snowy Mountain Gondola", # Unlocks Snowy Mountain
60: "Yellow Eco Switch", # Unlocks Yellow Eco Vents
63: "Snowy Fort Gate", # Unlocks the Snowy Mountain Fort
71: "Freed The Blue Sage", # 1 of 3 unlocks for the final staircase in Citadel
72: "Freed The Red Sage", # 1 of 3 unlocks for the final staircase in Citadel
73: "Freed The Yellow Sage", # 1 of 3 unlocks for the final staircase in Citadel
70: "Freed The Green Sage", # Unlocks the final boss elevator in Citadel
}
# These are the move items for move randomizer. Notice that their Item ID equals some of the Orb Cache Location ID's.
# This was 100% arbitrary. There's no reason to tie moves to orb caches except that I need a place to put them. ;_;
move_item_table = {
10344: "Crouch",
10369: "Crouch Jump",
11072: "Crouch Uppercut",
12634: "Roll",
12635: "Roll Jump",
10945: "Double Jump",
14507: "Jump Dive",
14838: "Jump Kick",
23348: "Punch",
23349: "Punch Uppercut",
23350: "Kick",
# 24038: "Orb Cache at End of Blast Furnace", # Hold onto these ID's for future use.
# 24039: "Orb Cache at End of Launch Pad Room",
# 24040: "Orb Cache at Start of Launch Pad Room",
}
# These are trap items. Their Item ID is to be subtracted from the base game ID. They do not have corresponding
# game locations because they are intended to replace other items that have been marked as filler.
trap_item_table = {
1: "Trip Trap",
2: "Slippery Trap",
3: "Gravity Trap",
4: "Camera Trap",
5: "Darkness Trap",
6: "Earthquake Trap",
7: "Teleport Trap",
8: "Despair Trap",
9: "Pacifism Trap",
10: "Ecoless Trap",
11: "Health Trap",
12: "Ledge Trap",
13: "Zoomer Trap",
14: "Mirror Trap",
}
# All Items
# While we're here, do all the ID conversions needed.
item_table = {
**{cells.to_ap_id(k): name for k, name in cell_item_table.items()},
**{scouts.to_ap_id(k): name for k, name in scout_item_table.items()},
**{specials.to_ap_id(k): name for k, name in special_item_table.items()},
**{caches.to_ap_id(k): name for k, name in move_item_table.items()},
**{orbs.to_ap_id(k): name for k, name in orb_item_table.items()},
**{jak1_max - k: name for k, name in trap_item_table.items()},
jak1_max: "Green Eco Pill" # Filler item.
}

View File

@@ -0,0 +1,76 @@
# This contains the list of levels in Jak and Daxter.
# Not to be confused with Regions - there can be multiple Regions in every Level.
level_table = {
"Geyser Rock": {
"level_index": 0,
"orbs": 50
},
"Sandover Village": {
"level_index": 1,
"orbs": 50
},
"Sentinel Beach": {
"level_index": 2,
"orbs": 150
},
"Forbidden Jungle": {
"level_index": 3,
"orbs": 150
},
"Misty Island": {
"level_index": 4,
"orbs": 150
},
"Fire Canyon": {
"level_index": 5,
"orbs": 50
},
"Rock Village": {
"level_index": 6,
"orbs": 50
},
"Lost Precursor City": {
"level_index": 7,
"orbs": 200
},
"Boggy Swamp": {
"level_index": 8,
"orbs": 200
},
"Precursor Basin": {
"level_index": 9,
"orbs": 200
},
"Mountain Pass": {
"level_index": 10,
"orbs": 50
},
"Volcanic Crater": {
"level_index": 11,
"orbs": 50
},
"Snowy Mountain": {
"level_index": 12,
"orbs": 200
},
"Spider Cave": {
"level_index": 13,
"orbs": 200
},
"Lava Tube": {
"level_index": 14,
"orbs": 50
},
"Gol and Maia's Citadel": {
"level_index": 15,
"orbs": 200
}
}
level_table_with_global = {
**level_table,
"": {
"level_index": 16, # Global
"orbs": 2000
}
}

View File

@@ -0,0 +1,66 @@
from BaseClasses import Location
from .game_id import jak1_name
from .locs import (orb_locations as orbs,
cell_locations as cells,
scout_locations as scouts,
special_locations as specials,
orb_cache_locations as caches)
class JakAndDaxterLocation(Location):
game: str = jak1_name
# Different tables for location groups.
# Each Item ID == its corresponding Location ID. While we're here, do all the ID conversions needed.
cell_location_table = {
**{cells.to_ap_id(k): name for k, name in cells.loc7SF_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locGR_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locSV_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locFJ_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locSB_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locMI_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locFC_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locRV_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locPB_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locLPC_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locBS_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locMP_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locVC_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locSC_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locSM_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locLT_cellTable.items()},
**{cells.to_ap_id(k): name for k, name in cells.locGMC_cellTable.items()},
}
scout_location_table = {
**{scouts.to_ap_id(k): name for k, name in scouts.locGR_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locSV_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locFJ_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locSB_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locMI_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locFC_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locRV_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locPB_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locLPC_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locBS_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locMP_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locVC_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locSC_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locSM_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locLT_scoutTable.items()},
**{scouts.to_ap_id(k): name for k, name in scouts.locGMC_scoutTable.items()},
}
special_location_table = {specials.to_ap_id(k): name for k, name in specials.loc_specialTable.items()}
cache_location_table = {caches.to_ap_id(k): name for k, name in caches.loc_orbCacheTable.items()}
orb_location_table = {orbs.to_ap_id(k): name for k, name in orbs.loc_orbBundleTable.items()}
# All Locations
location_table = {
**cell_location_table,
**scout_location_table,
**special_location_table,
**cache_location_table,
**orb_location_table
}

View File

View File

@@ -0,0 +1,194 @@
from ..game_id import jak1_id
# Power Cells are given ID's between 0 and 116 by the game.
# The game tracks all game-tasks as integers.
# 101 of these ID's correspond directly to power cells, but they are not
# necessarily ordered, nor are they the first 101 in the task list.
# The remaining ones are cutscenes and other events.
# These helper functions do all the math required to get information about each
# power cell and translate its ID between AP and OpenGOAL.
def to_ap_id(game_id: int) -> int:
if game_id >= jak1_id:
raise ValueError(f"Attempted to convert {game_id} to an AP ID, but it already is one.")
return jak1_id + game_id
def to_game_id(ap_id: int) -> int:
if ap_id < jak1_id:
raise ValueError(f"Attempted to convert {ap_id} to a Jak 1 ID, but it already is one.")
return ap_id - jak1_id
# The ID's you see below correspond directly to that cell's game-task ID.
# The "Free 7 Scout Flies" Power Cells will be unlocked separately from their respective levels.
loc7SF_cellTable = {
95: "GR: Free 7 Scout Flies",
75: "SV: Free 7 Scout Flies",
7: "FJ: Free 7 Scout Flies",
20: "SB: Free 7 Scout Flies",
28: "MI: Free 7 Scout Flies",
68: "FC: Free 7 Scout Flies",
76: "RV: Free 7 Scout Flies",
57: "PB: Free 7 Scout Flies",
49: "LPC: Free 7 Scout Flies",
43: "BS: Free 7 Scout Flies",
88: "MP: Free 7 Scout Flies",
77: "VC: Free 7 Scout Flies",
85: "SC: Free 7 Scout Flies",
65: "SM: Free 7 Scout Flies",
90: "LT: Free 7 Scout Flies",
91: "GMC: Free 7 Scout Flies",
}
# Geyser Rock
locGR_cellTable = {
92: "GR: Find The Cell On The Path",
93: "GR: Open The Precursor Door",
94: "GR: Climb Up The Cliff",
}
# Sandover Village
locSV_cellTable = {
11: "SV: Bring 90 Orbs To The Mayor",
12: "SV: Bring 90 Orbs to Your Uncle",
10: "SV: Herd The Yakows Into The Pen",
13: "SV: Bring 120 Orbs To The Oracle (1)",
14: "SV: Bring 120 Orbs To The Oracle (2)",
}
# Forbidden Jungle
locFJ_cellTable = {
3: "FJ: Connect The Eco Beams",
4: "FJ: Get To The Top Of The Temple",
2: "FJ: Find The Blue Vent Switch",
6: "FJ: Defeat The Dark Eco Plant",
5: "FJ: Catch 200 Pounds Of Fish",
8: "FJ: Follow The Canyon To The Sea",
9: "FJ: Open The Locked Temple Door",
}
# Sentinel Beach
locSB_cellTable = {
15: "SB: Unblock The Eco Harvesters",
17: "SB: Push The Flut Flut Egg Off The Cliff",
16: "SB: Get The Power Cell From The Pelican",
18: "SB: Chase The Seagulls",
19: "SB: Launch Up To The Cannon Tower",
21: "SB: Explore The Beach",
22: "SB: Climb The Sentinel",
}
# Misty Island
locMI_cellTable = {
23: "MI: Catch The Sculptor's Muse",
24: "MI: Climb The Lurker Ship",
26: "MI: Stop The Cannon",
25: "MI: Return To The Dark Eco Pool",
27: "MI: Destroy the Balloon Lurkers",
29: "MI: Use Zoomer To Reach Power Cell",
30: "MI: Use Blue Eco To Reach Power Cell",
}
# Fire Canyon
locFC_cellTable = {
69: "FC: Reach The End Of Fire Canyon",
}
# Rock Village
locRV_cellTable = {
31: "RV: Bring 90 Orbs To The Gambler",
32: "RV: Bring 90 Orbs To The Geologist",
33: "RV: Bring 90 Orbs To The Warrior",
34: "RV: Bring 120 Orbs To The Oracle (1)",
35: "RV: Bring 120 Orbs To The Oracle (2)",
}
# Precursor Basin
locPB_cellTable = {
54: "PB: Herd The Moles Into Their Hole",
53: "PB: Catch The Flying Lurkers",
52: "PB: Beat Record Time On The Gorge",
56: "PB: Get The Power Cell Over The Lake",
55: "PB: Cure Dark Eco Infected Plants",
58: "PB: Navigate The Purple Precursor Rings",
59: "PB: Navigate The Blue Precursor Rings",
}
# Lost Precursor City
locLPC_cellTable = {
47: "LPC: Raise The Chamber",
45: "LPC: Follow The Colored Pipes",
46: "LPC: Reach The Bottom Of The City",
48: "LPC: Quickly Cross The Dangerous Pool",
44: "LPC: Match The Platform Colors",
50: "LPC: Climb The Slide Tube",
51: "LPC: Reach The Center Of The Complex",
}
# Boggy Swamp
locBS_cellTable = {
37: "BS: Ride The Flut Flut",
36: "BS: Protect Farthy's Snacks",
38: "BS: Defeat The Lurker Ambush",
39: "BS: Break The Tethers To The Zeppelin (1)",
40: "BS: Break The Tethers To The Zeppelin (2)",
41: "BS: Break The Tethers To The Zeppelin (3)",
42: "BS: Break The Tethers To The Zeppelin (4)",
}
# Mountain Pass
locMP_cellTable = {
86: "MP: Defeat Klaww",
87: "MP: Reach The End Of The Mountain Pass",
110: "MP: Find The Hidden Power Cell",
}
# Volcanic Crater
locVC_cellTable = {
96: "VC: Bring 90 Orbs To The Miners (1)",
97: "VC: Bring 90 Orbs To The Miners (2)",
98: "VC: Bring 90 Orbs To The Miners (3)",
99: "VC: Bring 90 Orbs To The Miners (4)",
100: "VC: Bring 120 Orbs To The Oracle (1)",
101: "VC: Bring 120 Orbs To The Oracle (2)",
74: "VC: Find The Hidden Power Cell",
}
# Spider Cave
locSC_cellTable = {
78: "SC: Use Your Goggles To Shoot The Gnawing Lurkers",
79: "SC: Destroy The Dark Eco Crystals",
80: "SC: Explore The Dark Cave",
81: "SC: Climb The Giant Robot",
82: "SC: Launch To The Poles",
83: "SC: Navigate The Spider Tunnel",
84: "SC: Climb the Precursor Platforms",
}
# Snowy Mountain
locSM_cellTable = {
60: "SM: Find The Yellow Vent Switch",
61: "SM: Stop The 3 Lurker Glacier Troops",
66: "SM: Deactivate The Precursor Blockers",
67: "SM: Open The Frozen Crate",
63: "SM: Open The Lurker Fort Gate",
62: "SM: Get Through The Lurker Fort",
64: "SM: Survive The Lurker Infested Cave",
}
# Lava Tube
locLT_cellTable = {
89: "LT: Cross The Lava Tube",
}
# Gol and Maias Citadel
locGMC_cellTable = {
71: "GMC: Free The Blue Sage",
72: "GMC: Free The Red Sage",
73: "GMC: Free The Yellow Sage",
70: "GMC: Free The Green Sage",
}

View File

@@ -0,0 +1,52 @@
from ..game_id import jak1_id
# These are the locations of Orb Caches throughout the game, unlockable only with blue eco.
# They are not game collectables and thus don't have the same kinds of game ID's. They do, however, have actor ID's.
# There are a total of 14 in the game.
# When these are opened, we can execute a hook in the mod that might be able to tell us which orb cache we opened,
# by ID, and that will allow us to map a Location object to it. We'll be using these for Move Randomizer,
# where each move is "mapped" to an Orb Cache being unlocked. Obviously, they will then be randomized, but with moves
# not being considered Items by the game, we need to conjure SOME kind of Location for them, and Orb Caches is the best
# we can do.
# We can use 2^12 to offset these from special checks, just like we offset those from scout flies
# by 2^11. Special checks don't exceed an ID of (jak1_id + 2153).
orb_cache_offset = 4096
# These helper functions do all the math required to get information about each
# special check and translate its ID between AP and OpenGOAL. Similar to Scout Flies, these large numbers are not
# necessary, and we can flatten out the range in which these numbers lie.
def to_ap_id(game_id: int) -> int:
if game_id >= jak1_id:
raise ValueError(f"Attempted to convert {game_id} to an AP ID, but it already is one.")
uncompressed_id = jak1_id + orb_cache_offset + game_id # Add the offsets and the orb cache Actor ID.
return uncompressed_id - 10344 # Subtract the smallest Actor ID.
def to_game_id(ap_id: int) -> int:
if ap_id < jak1_id:
raise ValueError(f"Attempted to convert {ap_id} to a Jak 1 ID, but it already is one.")
uncompressed_id = ap_id + 10344 # Reverse process, add back the smallest Actor ID.
return uncompressed_id - jak1_id - orb_cache_offset # Subtract the offsets.
# The ID's you see below correlate to the Actor ID of each Orb Cache.
loc_orbCacheTable = {
10344: "Orb Cache in Sandover Village",
10369: "Orb Cache in Forbidden Jungle",
11072: "Orb Cache on Misty Island",
12634: "Orb Cache near Flut Flut Egg",
12635: "Orb Cache near Pelican's Nest",
10945: "Orb Cache in Rock Village",
14507: "Orb Cache in First Sunken Chamber",
14838: "Orb Cache in Second Sunken Chamber",
23348: "Orb Cache in Snowy Fort (1)",
23349: "Orb Cache in Snowy Fort (2)",
23350: "Orb Cache in Snowy Fort (3)",
24038: "Orb Cache at End of Blast Furnace",
24039: "Orb Cache at End of Launch Pad Room",
24040: "Orb Cache at Start of Launch Pad Room",
}

View File

@@ -0,0 +1,123 @@
from ..game_id import jak1_id
from ..levels import level_table_with_global
# Precursor Orbs are not necessarily given ID's by the game.
# Of the 2000 orbs (or "money") you can pick up, only 1233 are standalone ones you find in the overworld.
# We can identify them by Actor ID's, which run from 549 to 24433. Other actors reside in this range,
# so like Power Cells these are not ordered, nor contiguous, nor exclusively orbs.
# In fact, other ID's in this range belong to actors that spawn orbs when they are activated or when they die,
# like steel crates, orb caches, Spider Cave gnawers, or jumping on the Plant Boss's head. These orbs that spawn
# from parent actors DON'T have an Actor ID themselves - the parent object keeps track of how many of its orbs
# have been picked up.
# In order to deal with this mess, we're creating 2 extra functions that will create and identify Orb Locations for us.
# These will be compatible with both Global Orbsanity and Per-Level Orbsanity, allowing us to create any
# number of Locations depending on the bundle size chosen, while also guaranteeing that each has a unique address.
# We can use 2^15 to offset them from Orb Caches, because Orb Cache ID's max out at (jak1_id + 17792).
orb_offset = 32768
# These helper functions do all the math required to get information about each
# precursor orb and translate its ID between AP and OpenGOAL.
def to_ap_id(game_id: int) -> int:
if game_id >= jak1_id:
raise ValueError(f"Attempted to convert {game_id} to an AP ID, but it already is one.")
return jak1_id + orb_offset + game_id # Add the offsets and the orb Actor ID.
def to_game_id(ap_id: int) -> int:
if ap_id < jak1_id:
raise ValueError(f"Attempted to convert {ap_id} to a Jak 1 ID, but it already is one.")
return ap_id - jak1_id - orb_offset # Reverse process, subtract the offsets.
# Use this when the Memory Reader learns that you checked a specific bundle.
# Offset each level by 200 orbs (max number in any level), {200, 400, ...}
# then divide orb count by bundle size, {201, 202, ...}
# then subtract 1. {200, 201, ...}
def find_address(level_index: int, orb_count: int, bundle_size: int) -> int:
result = (level_index * 200) + (orb_count // bundle_size) - 1
return result
# Use this when assigning addresses during region generation.
def create_address(level_index: int, bundle_index: int) -> int:
result = (level_index * 200) + bundle_index
return result
# What follows is our methods of generating all the name/ID pairs for location_name_to_id.
# Remember that not every bundle will be used in the actual seed, we just need a static map of strings to ints.
locGR_orbBundleTable = {create_address(level_table_with_global["Geyser Rock"]["level_index"], index):
f"Geyser Rock Orb Bundle {index + 1}"
for index in range(level_table_with_global["Geyser Rock"]["orbs"])}
locSV_orbBundleTable = {create_address(level_table_with_global["Sandover Village"]["level_index"], index):
f"Sandover Village Orb Bundle {index + 1}"
for index in range(level_table_with_global["Sandover Village"]["orbs"])}
locFJ_orbBundleTable = {create_address(level_table_with_global["Forbidden Jungle"]["level_index"], index):
f"Forbidden Jungle Orb Bundle {index + 1}"
for index in range(level_table_with_global["Forbidden Jungle"]["orbs"])}
locSB_orbBundleTable = {create_address(level_table_with_global["Sentinel Beach"]["level_index"], index):
f"Sentinel Beach Orb Bundle {index + 1}"
for index in range(level_table_with_global["Sentinel Beach"]["orbs"])}
locMI_orbBundleTable = {create_address(level_table_with_global["Misty Island"]["level_index"], index):
f"Misty Island Orb Bundle {index + 1}"
for index in range(level_table_with_global["Misty Island"]["orbs"])}
locFC_orbBundleTable = {create_address(level_table_with_global["Fire Canyon"]["level_index"], index):
f"Fire Canyon Orb Bundle {index + 1}"
for index in range(level_table_with_global["Fire Canyon"]["orbs"])}
locRV_orbBundleTable = {create_address(level_table_with_global["Rock Village"]["level_index"], index):
f"Rock Village Orb Bundle {index + 1}"
for index in range(level_table_with_global["Rock Village"]["orbs"])}
locLPC_orbBundleTable = {create_address(level_table_with_global["Lost Precursor City"]["level_index"], index):
f"Lost Precursor City Orb Bundle {index + 1}"
for index in range(level_table_with_global["Lost Precursor City"]["orbs"])}
locBS_orbBundleTable = {create_address(level_table_with_global["Boggy Swamp"]["level_index"], index):
f"Boggy Swamp Orb Bundle {index + 1}"
for index in range(level_table_with_global["Boggy Swamp"]["orbs"])}
locPB_orbBundleTable = {create_address(level_table_with_global["Precursor Basin"]["level_index"], index):
f"Precursor Basin Orb Bundle {index + 1}"
for index in range(level_table_with_global["Precursor Basin"]["orbs"])}
locMP_orbBundleTable = {create_address(level_table_with_global["Mountain Pass"]["level_index"], index):
f"Mountain Pass Orb Bundle {index + 1}"
for index in range(level_table_with_global["Mountain Pass"]["orbs"])}
locVC_orbBundleTable = {create_address(level_table_with_global["Volcanic Crater"]["level_index"], index):
f"Volcanic Crater Orb Bundle {index + 1}"
for index in range(level_table_with_global["Volcanic Crater"]["orbs"])}
locSM_orbBundleTable = {create_address(level_table_with_global["Snowy Mountain"]["level_index"], index):
f"Snowy Mountain Orb Bundle {index + 1}"
for index in range(level_table_with_global["Snowy Mountain"]["orbs"])}
locSC_orbBundleTable = {create_address(level_table_with_global["Spider Cave"]["level_index"], index):
f"Spider Cave Orb Bundle {index + 1}"
for index in range(level_table_with_global["Spider Cave"]["orbs"])}
locLT_orbBundleTable = {create_address(level_table_with_global["Lava Tube"]["level_index"], index):
f"Lava Tube Orb Bundle {index + 1}"
for index in range(level_table_with_global["Lava Tube"]["orbs"])}
locGMC_orbBundleTable = {create_address(level_table_with_global["Gol and Maia's Citadel"]["level_index"], index):
f"Gol and Maia's Citadel Orb Bundle {index + 1}"
for index in range(level_table_with_global["Gol and Maia's Citadel"]["orbs"])}
locGlobal_orbBundleTable = {create_address(level_table_with_global[""]["level_index"], index):
f"Orb Bundle {index + 1}"
for index in range(level_table_with_global[""]["orbs"])}
loc_orbBundleTable = {
**locGR_orbBundleTable,
**locSV_orbBundleTable,
**locSB_orbBundleTable,
**locFJ_orbBundleTable,
**locMI_orbBundleTable,
**locFC_orbBundleTable,
**locRV_orbBundleTable,
**locLPC_orbBundleTable,
**locBS_orbBundleTable,
**locPB_orbBundleTable,
**locMP_orbBundleTable,
**locVC_orbBundleTable,
**locSM_orbBundleTable,
**locSC_orbBundleTable,
**locLT_orbBundleTable,
**locGMC_orbBundleTable,
**locGlobal_orbBundleTable
}

View File

@@ -0,0 +1,230 @@
from ..game_id import jak1_id
# Scout Flies are given ID's between 0 and 393311 by the game, explanation below.
# Each fly (or "buzzer") is given a unique 32-bit number broken into two 16-bit numbers.
# The lower 16 bits are the game-task ID of the power cell the fly corresponds to.
# The higher 16 bits are the index of the fly itself, from 000 (0) to 110 (6).
# Ex: The final scout fly on Geyser Rock
# 0000000000000110 0000000001011111
# ( Index: 6 ) ( Cell: 95 )
# Because flies are indexed from 0, each 0th fly's full ID == the power cell's ID.
# So we need to offset all of their ID's in order for Archipelago to separate them
# from their power cells. We can use 1024 (2^10) for this purpose, because scout flies
# only ever need 10 bits to identify themselves (3 for the index, 7 for the cell ID).
# We're also going to compress the ID by bit-shifting the fly index down to lower bits,
# keeping the scout fly ID range to a smaller set of numbers (1000 -> 2000, instead of 1 -> 400000).
fly_offset = 1024
# These helper functions do all the math required to get information about each
# scout fly and translate its ID between AP and OpenGOAL.
def to_ap_id(game_id: int) -> int:
if game_id >= jak1_id:
raise ValueError(f"Attempted to convert {game_id} to an AP ID, but it already is one.")
cell_id = get_cell_id(game_id) # Get the power cell ID from the lowest 7 bits.
buzzer_index = (game_id - cell_id) >> 9 # Get the index, bit shift it down 9 places.
compressed_id = fly_offset + buzzer_index + cell_id # Add the offset, the bit-shifted index, and the cell ID.
return jak1_id + compressed_id # Last thing: add the game's ID.
def to_game_id(ap_id: int) -> int:
if ap_id < jak1_id:
raise ValueError(f"Attempted to convert {ap_id} to a Jak 1 ID, but it already is one.")
compressed_id = ap_id - jak1_id # Reverse process. First thing: subtract the game's ID.
cell_id = get_cell_id(compressed_id) # Get the power cell ID from the lowest 7 bits.
buzzer_index = compressed_id - fly_offset - cell_id # Get the bit-shifted index.
return (buzzer_index << 9) + cell_id # Return the index to its normal place, re-add the cell ID.
# Get the power cell ID from the lowest 7 bits.
# Make sure to use this function ONLY when the input argument does NOT include jak1_id,
# because that number may flip some of the bottom 7 bits, and that will throw off this bit mask.
def get_cell_id(buzzer_id: int) -> int:
if buzzer_id >= jak1_id:
raise ValueError(f"Attempted to bit mask {buzzer_id}, but it is polluted by the game's ID {jak1_id}.")
return buzzer_id & 0b1111111
# The ID's you see below correspond directly to that fly's 32-bit ID in the game.
# I used the decompiled entity JSON's and Jak's X/Y coordinates in Debug Mode
# to determine which box ID is which location.
# Geyser Rock
locGR_scoutTable = {
95: "GR: Scout Fly On Ground, Front",
327775: "GR: Scout Fly On Ground, Back",
393311: "GR: Scout Fly On Left Ledge",
65631: "GR: Scout Fly On Right Ledge",
262239: "GR: Scout Fly On Middle Ledge, Left",
131167: "GR: Scout Fly On Middle Ledge, Right",
196703: "GR: Scout Fly On Top Ledge"
}
# Sandover Village
locSV_scoutTable = {
262219: "SV: Scout Fly In Fisherman's House",
327755: "SV: Scout Fly In Mayor's House",
131147: "SV: Scout Fly Under Bridge",
65611: "SV: Scout Fly Behind Sculptor's House",
75: "SV: Scout Fly Overlooking Farmer's House",
393291: "SV: Scout Fly Near Oracle",
196683: "SV: Scout Fly In Farmer's House"
}
# Forbidden Jungle
locFJ_scoutTable = {
393223: "FJ: Scout Fly At End Of Path",
262151: "FJ: Scout Fly On Spiral Of Stumps",
7: "FJ: Scout Fly Near Dark Eco Boxes",
196615: "FJ: Scout Fly At End Of River",
131079: "FJ: Scout Fly Behind Lurker Machine",
327687: "FJ: Scout Fly Around Temple Spire",
65543: "FJ: Scout Fly On Top Of Temple"
}
# Sentinel Beach
locSB_scoutTable = {
327700: "SB: Scout Fly At Entrance",
20: "SB: Scout Fly Overlooking Locked Boxes",
65556: "SB: Scout Fly On Path To Flut Flut",
262164: "SB: Scout Fly Under Wood Pillars",
196628: "SB: Scout Fly Overlooking Blue Eco Vent",
131092: "SB: Scout Fly Overlooking Green Eco Vents",
393236: "SB: Scout Fly On Sentinel"
}
# Misty Island
locMI_scoutTable = {
327708: "MI: Scout Fly Overlooking Entrance",
65564: "MI: Scout Fly On Ledge Near Arena Entrance",
262172: "MI: Scout Fly Near Arena Door",
28: "MI: Scout Fly On Ledge Near Arena Exit",
131100: "MI: Scout Fly On Ship",
196636: "MI: Scout Fly On Barrel Ramps",
393244: "MI: Scout Fly On Zoomer Ramps"
}
# Fire Canyon
locFC_scoutTable = {
393284: "FC: Scout Fly 1",
68: "FC: Scout Fly 2",
65604: "FC: Scout Fly 3",
196676: "FC: Scout Fly 4",
131140: "FC: Scout Fly 5",
262212: "FC: Scout Fly 6",
327748: "FC: Scout Fly 7"
}
# Rock Village
locRV_scoutTable = {
76: "RV: Scout Fly Behind Sage's Hut",
131148: "RV: Scout Fly Near Waterfall",
196684: "RV: Scout Fly Behind Geologist",
262220: "RV: Scout Fly Behind Fiery Boulder",
65612: "RV: Scout Fly On Dock",
327756: "RV: Scout Fly At Pontoon Bridge",
393292: "RV: Scout Fly At Boggy Swamp Entrance"
}
# Precursor Basin
locPB_scoutTable = {
196665: "PB: Scout Fly Overlooking Entrance",
393273: "PB: Scout Fly Near Mole Hole",
131129: "PB: Scout Fly At Purple Ring Start",
65593: "PB: Scout Fly Near Dark Eco Plant, Above",
57: "PB: Scout Fly At Blue Ring Start",
262201: "PB: Scout Fly Before Big Jump",
327737: "PB: Scout Fly Near Dark Eco Plant, Below"
}
# Lost Precursor City
locLPC_scoutTable = {
262193: "LPC: Scout Fly First Room",
131121: "LPC: Scout Fly Before Second Room",
393265: "LPC: Scout Fly Second Room, Near Orb Vent",
196657: "LPC: Scout Fly Second Room, On Path To Cell",
49: "LPC: Scout Fly Second Room, Green Pipe", # Sunken Pipe Game, special cases. See `got-buzzer?`
65585: "LPC: Scout Fly Second Room, Blue Pipe", # Sunken Pipe Game, special cases. See `got-buzzer?`
327729: "LPC: Scout Fly Across Steam Vents"
}
# Boggy Swamp
locBS_scoutTable = {
43: "BS: Scout Fly Near Entrance",
393259: "BS: Scout Fly Over First Jump Pad",
65579: "BS: Scout Fly Over Second Jump Pad",
262187: "BS: Scout Fly Across Black Swamp",
327723: "BS: Scout Fly Overlooking Flut Flut",
131115: "BS: Scout Fly On Flut Flut Platforms",
196651: "BS: Scout Fly In Field Of Boxes"
}
# Mountain Pass
locMP_scoutTable = {
88: "MP: Scout Fly 1",
65624: "MP: Scout Fly 2",
131160: "MP: Scout Fly 3",
196696: "MP: Scout Fly 4",
262232: "MP: Scout Fly 5",
327768: "MP: Scout Fly 6",
393304: "MP: Scout Fly 7"
}
# Volcanic Crater
locVC_scoutTable = {
262221: "VC: Scout Fly In Miner's Cave",
393293: "VC: Scout Fly Near Oracle",
196685: "VC: Scout Fly On Stone Platforms",
131149: "VC: Scout Fly Near Lava Tube",
77: "VC: Scout Fly At Minecart Junction",
65613: "VC: Scout Fly Near Spider Cave",
327757: "VC: Scout Fly Near Mountain Pass"
}
# Spider Cave
locSC_scoutTable = {
327765: "SC: Scout Fly Near Dark Cave Entrance",
262229: "SC: Scout Fly In Dark Cave",
393301: "SC: Scout Fly Main Cave, Overlooking Entrance",
196693: "SC: Scout Fly Main Cave, Near Dark Crystal",
131157: "SC: Scout Fly Main Cave, Near Robot Cave Entrance",
85: "SC: Scout Fly Robot Cave, At Bottom Level",
65621: "SC: Scout Fly Robot Cave, At Top Level",
}
# Snowy Mountain
locSM_scoutTable = {
65: "SM: Scout Fly Near Entrance",
327745: "SM: Scout Fly Near Frozen Box",
65601: "SM: Scout Fly Near Yellow Eco Switch",
131137: "SM: Scout Fly On Cliff near Flut Flut",
393281: "SM: Scout Fly Under Bridge To Fort",
196673: "SM: Scout Fly On Top Of Fort Tower",
262209: "SM: Scout Fly On Top Of Fort"
}
# Lava Tube
locLT_scoutTable = {
90: "LT: Scout Fly 1",
65626: "LT: Scout Fly 2",
327770: "LT: Scout Fly 3",
262234: "LT: Scout Fly 4",
131162: "LT: Scout Fly 5",
196698: "LT: Scout Fly 6",
393306: "LT: Scout Fly 7"
}
# Gol and Maias Citadel
locGMC_scoutTable = {
91: "GMC: Scout Fly At Entrance",
65627: "GMC: Scout Fly Main Room, Left of Robot",
196699: "GMC: Scout Fly Main Room, Right of Robot",
262235: "GMC: Scout Fly Before Jumping Lurkers",
393307: "GMC: Scout Fly At Blast Furnace",
131163: "GMC: Scout Fly At Launch Pad Room",
327771: "GMC: Scout Fly Top Of Rotating Tower"
}

View File

@@ -0,0 +1,51 @@
from ..game_id import jak1_id
# These are special checks that the game normally does not track. They are not game entities and thus
# don't have game ID's.
# Normally, for example, completing the fishing minigame is what gives you access to the
# fisherman's boat to get to Misty Island. The game treats completion of the fishing minigame as well as the
# power cell you receive as one and the same. The fisherman only gives you one item, a power cell.
# We're significantly altering the game logic here to decouple these concepts. First, completing the fishing minigame
# now counts as 2 Location checks. Second, the fisherman should give you a power cell (a generic item) as well as
# the "keys" to his boat (a special item). It is the "keys" that we are defining in this file, and the respective
# Item representing those keys will be defined in Items.py. These aren't real in the sense that
# they have a model and texture, they are just the logical representation of the boat unlock.
# We can use 2^11 to offset these from scout flies, just like we offset scout flies from power cells
# by 2^10. Even with the high-16 reminder bits, scout flies don't exceed an ID of (jak1_id + 1887).
special_offset = 2048
# These helper functions do all the math required to get information about each
# special check and translate its ID between AP and OpenGOAL.
def to_ap_id(game_id: int) -> int:
if game_id >= jak1_id:
raise ValueError(f"Attempted to convert {game_id} to an AP ID, but it already is one.")
return jak1_id + special_offset + game_id # Add the offsets and the orb Actor ID.
def to_game_id(ap_id: int) -> int:
if ap_id < jak1_id:
raise ValueError(f"Attempted to convert {ap_id} to a Jak 1 ID, but it already is one.")
return ap_id - jak1_id - special_offset # Reverse process, subtract the offsets.
# The ID's you see below correlate to each of their respective game-tasks, even though they are separate.
# This makes it easier for the new game logic to know what relates to what. I hope. God I hope.
loc_specialTable = {
5: "Fisherman's Boat",
4: "Jungle Elevator",
2: "Blue Eco Switch",
17: "Flut Flut",
33: "Warrior's Pontoons",
105: "Snowy Mountain Gondola",
60: "Yellow Eco Switch",
63: "Snowy Fort Gate",
71: "Freed The Blue Sage",
72: "Freed The Red Sage",
73: "Freed The Yellow Sage",
70: "Freed The Green Sage",
}

View File

@@ -0,0 +1,262 @@
from dataclasses import dataclass
from functools import cached_property
from Options import PerGameCommonOptions, StartInventoryPool, Toggle, Choice, Range, DefaultOnToggle, OptionCounter
from .items import trap_item_table
class StaticGetter:
def __init__(self, func):
self.fget = func
def __get__(self, instance, owner):
return self.fget(owner)
@StaticGetter
def determine_range_end(cls) -> int:
from . import JakAndDaxterWorld
enforce_friendly_options = JakAndDaxterWorld.settings.enforce_friendly_options
return cls.friendly_maximum if enforce_friendly_options else cls.absolute_maximum
class EnableMoveRandomizer(Toggle):
"""Include movement options as items in the randomizer. Until you find his other moves, Jak is limited to
running, swimming, single-jumping, and shooting yellow eco through his goggles.
This adds 11 items to the pool."""
display_name = "Enable Move Randomizer"
class EnableOrbsanity(Choice):
"""Include bundles of Precursor Orbs as checks. Every time you collect the chosen number of orbs, you will trigger
another check.
Per Level: bundles are for each level in the game.
Global: bundles carry over level to level.
This adds a number of Items and Locations to the pool inversely proportional to the size of the bundle.
For example, if your bundle size is 20 orbs, you will add 100 items to the pool. If your bundle size is 250 orbs,
you will add 8 items to the pool."""
display_name = "Enable Orbsanity"
option_off = 0
option_per_level = 1
option_global = 2
default = 0
class GlobalOrbsanityBundleSize(Choice):
"""The orb bundle size for Global Orbsanity. This only applies if "Enable Orbsanity" is set to "Global."
There are 2000 orbs in the game, so your bundle size must be a factor of 2000.
Multiplayer Minimum: 10
Multiplayer Maximum: 200"""
display_name = "Global Orbsanity Bundle Size"
option_1_orb = 1
option_2_orbs = 2
option_4_orbs = 4
option_5_orbs = 5
option_8_orbs = 8
option_10_orbs = 10
option_16_orbs = 16
option_20_orbs = 20
option_25_orbs = 25
option_40_orbs = 40
option_50_orbs = 50
option_80_orbs = 80
option_100_orbs = 100
option_125_orbs = 125
option_200_orbs = 200
option_250_orbs = 250
option_400_orbs = 400
option_500_orbs = 500
option_1000_orbs = 1000
option_2000_orbs = 2000
friendly_minimum = 10
friendly_maximum = 200
default = 20
class PerLevelOrbsanityBundleSize(Choice):
"""The orb bundle size for Per Level Orbsanity. This only applies if "Enable Orbsanity" is set to "Per Level."
There are 50, 150, or 200 orbs per level, so your bundle size must be a factor of 50.
Multiplayer Minimum: 10"""
display_name = "Per Level Orbsanity Bundle Size"
option_1_orb = 1
option_2_orbs = 2
option_5_orbs = 5
option_10_orbs = 10
option_25_orbs = 25
option_50_orbs = 50
friendly_minimum = 10
default = 25
class FireCanyonCellCount(Range):
"""The number of power cells you need to cross Fire Canyon. This value is restricted to a safe maximum value to
ensure valid singleplayer games and non-disruptive multiplayer games, but the host can remove this restriction by
turning off enforce_friendly_options in host.yaml."""
display_name = "Fire Canyon Cell Count"
friendly_maximum = 30
absolute_maximum = 100
range_start = 0
range_end = determine_range_end
default = 20
class MountainPassCellCount(Range):
"""The number of power cells you need to reach Klaww and cross Mountain Pass. This value is restricted to a safe
maximum value to ensure valid singleplayer games and non-disruptive multiplayer games, but the host can
remove this restriction by turning off enforce_friendly_options in host.yaml."""
display_name = "Mountain Pass Cell Count"
friendly_maximum = 60
absolute_maximum = 100
range_start = 0
range_end = determine_range_end
default = 45
class LavaTubeCellCount(Range):
"""The number of power cells you need to cross Lava Tube. This value is restricted to a safe maximum value to
ensure valid singleplayer games and non-disruptive multiplayer games, but the host can remove this restriction by
turning off enforce_friendly_options in host.yaml."""
display_name = "Lava Tube Cell Count"
friendly_maximum = 90
absolute_maximum = 100
range_start = 0
range_end = determine_range_end
default = 72
class EnableOrderedCellCounts(DefaultOnToggle):
"""Reorder the Cell Count requirements for vehicle sections to be in ascending order.
For example, if Fire Canyon Cell Count, Mountain Pass Cell Count, and Lava Tube Cell Count are 60, 30, and 40
respectively, they will be reordered to 30, 40, and 60."""
display_name = "Enable Ordered Cell Counts"
class RequirePunchForKlaww(DefaultOnToggle):
"""Force the Punch move to come before Klaww. Disabling this setting may require Jak to fight Klaww
and Gol and Maia by shooting yellow eco through his goggles. This only applies if "Enable Move Randomizer" is ON."""
display_name = "Require Punch For Klaww"
# 222 is the absolute maximum because there are 9 citizen trades and 2000 orbs to trade (2000/9 = 222).
class CitizenOrbTradeAmount(Range):
"""The number of orbs you need to trade to citizens for a power cell (Mayor, Uncle, etc.).
Along with Oracle Orb Trade Amount, this setting cannot exceed the total number of orbs in the game (2000).
The equation to determine the total number of trade orbs is (9 * Citizen Trades) + (6 * Oracle Trades).
This value is restricted to a safe maximum value to ensure valid singleplayer games and non-disruptive
multiplayer games, but the host can remove this restriction by turning off enforce_friendly_options in host.yaml."""
display_name = "Citizen Orb Trade Amount"
friendly_maximum = 120
absolute_maximum = 222
range_start = 0
range_end = determine_range_end
default = 90
# 333 is the absolute maximum because there are 6 oracle trades and 2000 orbs to trade (2000/6 = 333).
class OracleOrbTradeAmount(Range):
"""The number of orbs you need to trade to the Oracles for a power cell.
Along with Citizen Orb Trade Amount, this setting cannot exceed the total number of orbs in the game (2000).
The equation to determine the total number of trade orbs is (9 * Citizen Trades) + (6 * Oracle Trades).
This value is restricted to a safe maximum value to ensure valid singleplayer games and non-disruptive
multiplayer games, but the host can remove this restriction by turning off enforce_friendly_options in host.yaml."""
display_name = "Oracle Orb Trade Amount"
friendly_maximum = 150
absolute_maximum = 333
range_start = 0
range_end = determine_range_end
default = 120
class FillerPowerCellsReplacedWithTraps(Range):
"""
The number of filler power cells that will be replaced with traps. This does not affect the number of progression
power cells.
If this value is greater than the number of filler power cells, then they will all be replaced with traps.
"""
display_name = "Filler Power Cells Replaced With Traps"
range_start = 0
range_end = 100
default = 0
class FillerOrbBundlesReplacedWithTraps(Range):
"""
The number of filler orb bundles that will be replaced with traps. This does not affect the number of progression
orb bundles. This only applies if "Enable Orbsanity" is set to "Per Level" or "Global."
If this value is greater than the number of filler orb bundles, then they will all be replaced with traps.
"""
display_name = "Filler Orb Bundles Replaced With Traps"
range_start = 0
range_end = 2000
default = 0
class TrapEffectDuration(Range):
"""
The length of time, in seconds, that a trap effect lasts.
"""
display_name = "Trap Effect Duration"
range_start = 5
range_end = 60
default = 30
class TrapWeights(OptionCounter):
"""
The list of traps and corresponding weights that will be randomly added to the item pool. A trap with weight 10 is
twice as likely to appear as a trap with weight 5. Set a weight to 0 to prevent that trap from appearing altogether.
If all weights are 0, no traps are created, overriding the values of "Filler * Replaced With Traps."
"""
display_name = "Trap Weights"
min = 0
default = {trap: 1 for trap in trap_item_table.values()}
valid_keys = sorted({trap for trap in trap_item_table.values()})
@cached_property
def weights_pair(self) -> tuple[list[str], list[int]]:
return list(self.value.keys()), list(self.value.values())
class CompletionCondition(Choice):
"""Set the goal for completing the game."""
display_name = "Completion Condition"
option_cross_fire_canyon = 69
option_cross_mountain_pass = 87
option_cross_lava_tube = 89
option_defeat_dark_eco_plant = 6
option_defeat_klaww = 86
option_defeat_gol_and_maia = 112
option_open_100_cell_door = 116
default = 112
@dataclass
class JakAndDaxterOptions(PerGameCommonOptions):
enable_move_randomizer: EnableMoveRandomizer
enable_orbsanity: EnableOrbsanity
global_orbsanity_bundle_size: GlobalOrbsanityBundleSize
level_orbsanity_bundle_size: PerLevelOrbsanityBundleSize
fire_canyon_cell_count: FireCanyonCellCount
mountain_pass_cell_count: MountainPassCellCount
lava_tube_cell_count: LavaTubeCellCount
enable_ordered_cell_counts: EnableOrderedCellCounts
require_punch_for_klaww: RequirePunchForKlaww
citizen_orb_trade_amount: CitizenOrbTradeAmount
oracle_orb_trade_amount: OracleOrbTradeAmount
filler_power_cells_replaced_with_traps: FillerPowerCellsReplacedWithTraps
filler_orb_bundles_replaced_with_traps: FillerOrbBundlesReplacedWithTraps
trap_effect_duration: TrapEffectDuration
trap_weights: TrapWeights
jak_completion_condition: CompletionCondition
start_inventory_from_pool: StartInventoryPool

View File

@@ -0,0 +1,132 @@
import typing
from Options import OptionError
from .items import item_table
from .options import EnableOrbsanity, CompletionCondition
from .rules import can_reach_orbs_global
from .locs import cell_locations as cells, scout_locations as scouts
from .regs import (geyser_rock_regions as geyser_rock,
sandover_village_regions as sandover_village,
forbidden_jungle_regions as forbidden_jungle,
sentinel_beach_regions as sentinel_beach,
misty_island_regions as misty_island,
fire_canyon_regions as fire_canyon,
rock_village_regions as rock_village,
precursor_basin_regions as precursor_basin,
lost_precursor_city_regions as lost_precursor_city,
boggy_swamp_regions as boggy_swamp,
mountain_pass_regions as mountain_pass,
volcanic_crater_regions as volcanic_crater,
spider_cave_regions as spider_cave,
snowy_mountain_regions as snowy_mountain,
lava_tube_regions as lava_tube,
gol_and_maias_citadel_regions as gol_and_maias_citadel)
from .regs.region_base import JakAndDaxterRegion
if typing.TYPE_CHECKING:
from . import JakAndDaxterWorld
def create_regions(world: "JakAndDaxterWorld"):
multiworld = world.multiworld
options = world.options
player = world.player
# Always start with Menu.
menu = JakAndDaxterRegion("Menu", player, multiworld)
multiworld.regions.append(menu)
# Build the special "Free 7 Scout Flies" Region. This is a virtual region always accessible to Menu.
# The Locations within are automatically checked when you receive the 7th scout fly for the corresponding cell.
free7 = JakAndDaxterRegion("'Free 7 Scout Flies' Power Cells", player, multiworld)
free7.add_cell_locations(cells.loc7SF_cellTable.keys())
for scout_fly_cell in free7.locations:
# Translate from Cell AP ID to Scout AP ID using game ID as an intermediary.
scout_fly_id = scouts.to_ap_id(cells.to_game_id(typing.cast(int, scout_fly_cell.address)))
scout_fly_cell.access_rule = lambda state, flies=scout_fly_id: state.has(item_table[flies], player, 7)
multiworld.regions.append(free7)
menu.connect(free7)
# If Global Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Menu. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_global:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld)
bundle_count = 2000 // world.orb_bundle_size
for bundle_index in range(bundle_count):
# Unlike Per-Level Orbsanity, Global Orbsanity Locations always have a level_index of 16.
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(16,
bundle_index,
access_rule=lambda state, orb_amount=amount:
can_reach_orbs_global(state, player, world, orb_amount))
multiworld.regions.append(orbs)
menu.connect(orbs)
# Build all regions. Include their intra-connecting Rules, their Locations, and their Location access rules.
gr = geyser_rock.build_regions("Geyser Rock", world)
sv = sandover_village.build_regions("Sandover Village", world)
fj, fjp = forbidden_jungle.build_regions("Forbidden Jungle", world)
sb = sentinel_beach.build_regions("Sentinel Beach", world)
mi = misty_island.build_regions("Misty Island", world)
fc = fire_canyon.build_regions("Fire Canyon", world)
rv, rvp, rvc = rock_village.build_regions("Rock Village", world)
pb = precursor_basin.build_regions("Precursor Basin", world)
lpc = lost_precursor_city.build_regions("Lost Precursor City", world)
bs = boggy_swamp.build_regions("Boggy Swamp", world)
mp, mpr = mountain_pass.build_regions("Mountain Pass", world)
vc = volcanic_crater.build_regions("Volcanic Crater", world)
sc = spider_cave.build_regions("Spider Cave", world)
sm = snowy_mountain.build_regions("Snowy Mountain", world)
lt = lava_tube.build_regions("Lava Tube", world)
gmc, fb, fd = gol_and_maias_citadel.build_regions("Gol and Maia's Citadel", world)
# Configurable counts of cells for connector levels.
fc_count = options.fire_canyon_cell_count.value
mp_count = options.mountain_pass_cell_count.value
lt_count = options.lava_tube_cell_count.value
# Define the interconnecting rules.
menu.connect(gr)
gr.connect(sv) # Geyser Rock modified to let you leave at any time.
sv.connect(fj)
sv.connect(sb)
sv.connect(mi, rule=lambda state: state.has("Fisherman's Boat", player))
sv.connect(fc, rule=lambda state: state.has("Power Cell", player, fc_count)) # Normally 20.
fc.connect(rv)
rv.connect(pb)
rv.connect(lpc)
rvp.connect(bs) # rv->rvp/rvc connections defined internally by RockVillageRegions.
rvc.connect(mp, rule=lambda state: state.has("Power Cell", player, mp_count)) # Normally 45.
mpr.connect(vc) # mp->mpr connection defined internally by MountainPassRegions.
vc.connect(sc)
vc.connect(sm, rule=lambda state: state.has("Snowy Mountain Gondola", player))
vc.connect(lt, rule=lambda state: state.has("Power Cell", player, lt_count)) # Normally 72.
lt.connect(gmc) # gmc->fb connection defined internally by GolAndMaiasCitadelRegions.
# Set the completion condition.
if options.jak_completion_condition == CompletionCondition.option_cross_fire_canyon:
multiworld.completion_condition[player] = lambda state: state.can_reach(rv, "Region", player)
elif options.jak_completion_condition == CompletionCondition.option_cross_mountain_pass:
multiworld.completion_condition[player] = lambda state: state.can_reach(vc, "Region", player)
elif options.jak_completion_condition == CompletionCondition.option_cross_lava_tube:
multiworld.completion_condition[player] = lambda state: state.can_reach(gmc, "Region", player)
elif options.jak_completion_condition == CompletionCondition.option_defeat_dark_eco_plant:
multiworld.completion_condition[player] = lambda state: state.can_reach(fjp, "Region", player)
elif options.jak_completion_condition == CompletionCondition.option_defeat_klaww:
multiworld.completion_condition[player] = lambda state: state.can_reach(mp, "Region", player)
elif options.jak_completion_condition == CompletionCondition.option_defeat_gol_and_maia:
multiworld.completion_condition[player] = lambda state: state.can_reach(fb, "Region", player)
elif options.jak_completion_condition == CompletionCondition.option_open_100_cell_door:
multiworld.completion_condition[player] = lambda state: state.can_reach(fd, "Region", player)
else:
raise OptionError(f"{world.player_name}: Unknown completion goal ID "
f"({options.jak_completion_condition.value}).")

View File

View File

@@ -0,0 +1,174 @@
from BaseClasses import CollectionState
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_fight, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
# This level is full of short-medium gaps that cannot be crossed by single jump alone.
# These helper functions list out the moves that can cross all these gaps (painting with a broad brush but...)
def can_jump_farther(state: CollectionState, p: int) -> bool:
return (state.has_any(("Double Jump", "Jump Kick"), p)
or state.has_all(("Punch", "Punch Uppercut"), p))
def can_jump_higher(state: CollectionState, p: int) -> bool:
return (state.has("Double Jump", p)
or state.has_all(("Crouch", "Crouch Jump"), p)
or state.has_all(("Crouch", "Crouch Uppercut"), p)
or state.has_all(("Punch", "Punch Uppercut"), p))
# Orb crates and fly box in this area can be gotten with yellow eco and goggles.
# Start with the first yellow eco cluster near first_bats and work your way backward toward the entrance.
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 23)
main_area.add_fly_locations([43])
# Includes 4 orbs collectable with the blue eco vent.
first_bats = JakAndDaxterRegion("First Bats Area", player, multiworld, level_name, 4)
first_jump_pad = JakAndDaxterRegion("First Jump Pad", player, multiworld, level_name, 0)
first_jump_pad.add_fly_locations([393259])
# The tethers in this level are all out of order... a casual playthrough has the following order for the cell ID's:
# 42, 39, 40, 41. So that is the order we're calling "first, second, third, fourth".
# First tether cell is collectable with yellow eco and goggles.
first_tether = JakAndDaxterRegion("First Tether", player, multiworld, level_name, 7)
first_tether.add_cell_locations([42])
# This rat colony has 3 orbs on top of it, requires special movement.
first_tether_rat_colony = JakAndDaxterRegion("First Tether Rat Colony", player, multiworld, level_name, 3)
# If quick enough, combat not required.
second_jump_pad = JakAndDaxterRegion("Second Jump Pad", player, multiworld, level_name, 0)
second_jump_pad.add_fly_locations([65579])
first_pole_course = JakAndDaxterRegion("First Pole Course", player, multiworld, level_name, 28)
# You can break this tether with a yellow eco vent and goggles,
# but you can't reach the platform unless you can jump high.
second_tether = JakAndDaxterRegion("Second Tether", player, multiworld, level_name, 0)
second_tether.add_cell_locations([39], access_rule=lambda state: can_jump_higher(state, player))
# Fly and orbs are collectable with nearby blue eco cluster.
second_bats = JakAndDaxterRegion("Second Bats Area", player, multiworld, level_name, 27)
second_bats.add_fly_locations([262187], access_rule=lambda state: can_jump_farther(state, player))
third_jump_pad = JakAndDaxterRegion("Third Jump Pad (Arena)", player, multiworld, level_name, 0)
third_jump_pad.add_cell_locations([38], access_rule=lambda state: can_fight(state, player))
# The platform for the third tether might look high, but you can get a boost from the yellow eco vent.
fourth_jump_pad = JakAndDaxterRegion("Fourth Jump Pad (Third Tether)", player, multiworld, level_name, 9)
fourth_jump_pad.add_cell_locations([40])
# Orbs collectable here with yellow eco and goggles.
flut_flut_pad = JakAndDaxterRegion("Flut Flut Pad", player, multiworld, level_name, 36)
flut_flut_course = JakAndDaxterRegion("Flut Flut Course", player, multiworld, level_name, 23)
flut_flut_course.add_cell_locations([37])
flut_flut_course.add_fly_locations([327723, 131115])
# Includes some orbs on the way to the cabin, blue+yellow eco to collect.
farthy_snacks = JakAndDaxterRegion("Farthy's Snacks", player, multiworld, level_name, 7)
farthy_snacks.add_cell_locations([36])
# Scout fly in this field can be broken with yellow eco.
box_field = JakAndDaxterRegion("Field of Boxes", player, multiworld, level_name, 10)
box_field.add_fly_locations([196651])
last_tar_pit = JakAndDaxterRegion("Last Tar Pit", player, multiworld, level_name, 12)
fourth_tether = JakAndDaxterRegion("Fourth Tether", player, multiworld, level_name, 11)
fourth_tether.add_cell_locations([41], access_rule=lambda state: can_jump_higher(state, player))
main_area.connect(first_bats, rule=lambda state: can_jump_farther(state, player))
first_bats.connect(main_area)
first_bats.connect(first_jump_pad)
first_bats.connect(first_tether)
first_jump_pad.connect(first_bats)
first_tether.connect(first_bats)
first_tether.connect(first_tether_rat_colony, rule=lambda state:
(state.has_all(("Roll", "Roll Jump"), player)
or state.has_all(("Double Jump", "Jump Kick"), player)))
first_tether.connect(second_jump_pad)
first_tether.connect(first_pole_course)
first_tether_rat_colony.connect(first_tether)
second_jump_pad.connect(first_tether)
first_pole_course.connect(first_tether)
first_pole_course.connect(second_tether)
second_tether.connect(first_pole_course, rule=lambda state: can_jump_higher(state, player))
second_tether.connect(second_bats)
second_bats.connect(second_tether)
second_bats.connect(third_jump_pad)
second_bats.connect(fourth_jump_pad)
second_bats.connect(flut_flut_pad)
third_jump_pad.connect(second_bats)
fourth_jump_pad.connect(second_bats)
flut_flut_pad.connect(second_bats)
flut_flut_pad.connect(flut_flut_course, rule=lambda state: state.has("Flut Flut", player)) # Naturally.
flut_flut_pad.connect(farthy_snacks)
flut_flut_course.connect(flut_flut_pad)
farthy_snacks.connect(flut_flut_pad)
farthy_snacks.connect(box_field, rule=lambda state: can_jump_higher(state, player))
box_field.connect(farthy_snacks, rule=lambda state: can_jump_higher(state, player))
box_field.connect(last_tar_pit, rule=lambda state: can_jump_farther(state, player))
last_tar_pit.connect(box_field, rule=lambda state: can_jump_farther(state, player))
last_tar_pit.connect(fourth_tether, rule=lambda state: can_jump_farther(state, player))
fourth_tether.connect(last_tar_pit, rule=lambda state: can_jump_farther(state, player))
fourth_tether.connect(main_area) # Fall down.
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(first_bats)
world.level_to_regions[level_name].append(first_jump_pad)
world.level_to_regions[level_name].append(first_tether)
world.level_to_regions[level_name].append(first_tether_rat_colony)
world.level_to_regions[level_name].append(second_jump_pad)
world.level_to_regions[level_name].append(first_pole_course)
world.level_to_regions[level_name].append(second_tether)
world.level_to_regions[level_name].append(second_bats)
world.level_to_regions[level_name].append(third_jump_pad)
world.level_to_regions[level_name].append(fourth_jump_pad)
world.level_to_regions[level_name].append(flut_flut_pad)
world.level_to_regions[level_name].append(flut_flut_course)
world.level_to_regions[level_name].append(farthy_snacks)
world.level_to_regions[level_name].append(box_field)
world.level_to_regions[level_name].append(last_tar_pit)
world.level_to_regions[level_name].append(fourth_tether)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 200 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(8,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,38 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_reach_orbs_level
from ..locs import cell_locations as cells, scout_locations as scouts
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 50)
# Everything is accessible by making contact with the zoomer.
main_area.add_cell_locations(cells.locFC_cellTable.keys())
main_area.add_fly_locations(scouts.locFC_scoutTable.keys())
world.level_to_regions[level_name].append(main_area)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(5,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,103 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> tuple[JakAndDaxterRegion, ...]:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 25)
# You can get this scout fly by running from the blue eco vent across the temple bridge,
# falling onto the river, collecting the 3 blue clusters, using the jump pad, and running straight to the box.
main_area.add_fly_locations([393223])
lurker_machine = JakAndDaxterRegion("Lurker Machine", player, multiworld, level_name, 5)
lurker_machine.add_cell_locations([3], access_rule=lambda state: can_fight(state, player))
# This cell and this scout fly can both be gotten with the blue eco clusters near the jump pad.
lurker_machine.add_cell_locations([9])
lurker_machine.add_fly_locations([131079])
river = JakAndDaxterRegion("River", player, multiworld, level_name, 42)
# All of these can be gotten with blue eco, hitting the dark eco boxes, or by running.
river.add_cell_locations([5, 8])
river.add_fly_locations([7, 196615])
river.add_special_locations([5])
river.add_cache_locations([10369])
temple_exit = JakAndDaxterRegion("Temple Exit", player, multiworld, level_name, 12)
# This fly is too far from accessible blue eco sources.
temple_exit.add_fly_locations([262151], access_rule=lambda state: can_free_scout_flies(state, player))
temple_exterior = JakAndDaxterRegion("Temple Exterior", player, multiworld, level_name, 10)
# All of these can be gotten with blue eco and running.
temple_exterior.add_cell_locations([4])
temple_exterior.add_fly_locations([327687, 65543])
temple_exterior.add_special_locations([4])
temple_int_pre_blue = JakAndDaxterRegion("Temple Interior (Pre Blue Eco)", player, multiworld, level_name, 17)
temple_int_pre_blue.add_cell_locations([2])
temple_int_pre_blue.add_special_locations([2])
temple_int_post_blue = JakAndDaxterRegion("Temple Interior (Post Blue Eco)", player, multiworld, level_name, 39)
temple_int_post_blue.add_cell_locations([6], access_rule=lambda state: can_fight(state, player))
main_area.connect(lurker_machine) # Run and jump (tree stump platforms).
main_area.connect(river) # Jump down.
main_area.connect(temple_exit) # Run and jump (bridges).
lurker_machine.connect(main_area) # Jump down.
lurker_machine.connect(river) # Jump down.
lurker_machine.connect(temple_exterior) # Jump down (ledge).
river.connect(main_area) # Jump up (ledges near fisherman).
river.connect(lurker_machine) # Jump pad (aim toward machine).
river.connect(temple_exit) # Run and jump (trampolines).
river.connect(temple_exterior) # Jump pad (aim toward temple door).
temple_exit.connect(main_area) # Run and jump (bridges).
temple_exit.connect(river) # Jump down.
temple_exit.connect(temple_exterior) # Run and jump (bridges, dodge spikes).
# Requires Jungle Elevator.
temple_exterior.connect(temple_int_pre_blue, rule=lambda state: state.has("Jungle Elevator", player))
# Requires Blue Eco Switch.
temple_int_pre_blue.connect(temple_int_post_blue, rule=lambda state: state.has("Blue Eco Switch", player))
# Requires defeating the plant boss (combat).
temple_int_post_blue.connect(temple_exit, rule=lambda state: can_fight(state, player))
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(lurker_machine)
world.level_to_regions[level_name].append(river)
world.level_to_regions[level_name].append(temple_exit)
world.level_to_regions[level_name].append(temple_exterior)
world.level_to_regions[level_name].append(temple_int_pre_blue)
world.level_to_regions[level_name].append(temple_int_post_blue)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 150 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(3,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area, temple_int_post_blue

View File

@@ -0,0 +1,48 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_reach_orbs_level
from ..locs import scout_locations as scouts
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 48)
main_area.add_cell_locations([92, 93])
main_area.add_fly_locations(scouts.locGR_scoutTable.keys()) # All Flies here are accessible with blue eco.
# The last 2 orbs are barely gettable with the blue eco vent, but it's pushing accessibility. So I moved them here.
cliff = JakAndDaxterRegion("Cliff", player, multiworld, level_name, 2)
cliff.add_cell_locations([94])
main_area.connect(cliff, rule=lambda state:
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)
or state.has_all(("Crouch", "Crouch Uppercut"), player))
cliff.connect(main_area) # Jump down or ride blue eco elevator.
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(cliff)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(0,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,137 @@
from BaseClasses import CollectionState
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity, CompletionCondition
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
# God help me... here we go.
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> tuple[JakAndDaxterRegion | None, ...]:
multiworld = world.multiworld
options = world.options
player = world.player
# This level is full of short-medium gaps that cannot be crossed by single jump alone.
# These helper functions list out the moves that can cross all these gaps (painting with a broad brush but...)
def can_jump_farther(state: CollectionState, p: int) -> bool:
return (state.has_any(("Double Jump", "Jump Kick"), p)
or state.has_all(("Punch", "Punch Uppercut"), p))
def can_triple_jump(state: CollectionState, p: int) -> bool:
return state.has_all(("Double Jump", "Jump Kick"), p)
def can_jump_stairs(state: CollectionState, p: int) -> bool:
return (state.has("Double Jump", p)
or state.has("Jump Dive", p)
or state.has_all(("Crouch", "Crouch Jump"), p)
or state.has_all(("Crouch", "Crouch Uppercut"), p))
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 0)
main_area.add_fly_locations([91], access_rule=lambda state: can_free_scout_flies(state, player))
robot_scaffolding = JakAndDaxterRegion("Scaffolding Around Robot", player, multiworld, level_name, 8)
robot_scaffolding.add_fly_locations([196699], access_rule=lambda state: can_free_scout_flies(state, player))
jump_pad_room = JakAndDaxterRegion("Jump Pad Chamber", player, multiworld, level_name, 88)
jump_pad_room.add_cell_locations([73], access_rule=lambda state: can_fight(state, player))
jump_pad_room.add_special_locations([73], access_rule=lambda state: can_fight(state, player))
jump_pad_room.add_fly_locations([131163]) # Blue eco vent is right next to it.
jump_pad_room.add_fly_locations([65627], access_rule=lambda state:
can_free_scout_flies(state, player) and can_jump_farther(state, player))
jump_pad_room.add_cache_locations([24039, 24040]) # First, blue eco vent, second, blue eco cluster near sage.
blast_furnace = JakAndDaxterRegion("Blast Furnace", player, multiworld, level_name, 39)
blast_furnace.add_cell_locations([71], access_rule=lambda state: can_fight(state, player))
blast_furnace.add_special_locations([71], access_rule=lambda state: can_fight(state, player))
blast_furnace.add_fly_locations([393307]) # Blue eco vent nearby.
blast_furnace.add_cache_locations([24038]) # Blue eco cluster near sage.
bunny_room = JakAndDaxterRegion("Bunny Chamber", player, multiworld, level_name, 45)
bunny_room.add_cell_locations([72], access_rule=lambda state: can_fight(state, player))
bunny_room.add_special_locations([72], access_rule=lambda state: can_fight(state, player))
bunny_room.add_fly_locations([262235], access_rule=lambda state: can_free_scout_flies(state, player))
rotating_tower = JakAndDaxterRegion("Rotating Tower", player, multiworld, level_name, 20)
rotating_tower.add_cell_locations([70], access_rule=lambda state: can_fight(state, player))
rotating_tower.add_special_locations([70], access_rule=lambda state: can_fight(state, player))
rotating_tower.add_fly_locations([327771], access_rule=lambda state: can_free_scout_flies(state, player))
final_boss = JakAndDaxterRegion("Final Boss", player, multiworld, level_name, 0)
# Jump Dive required for a lot of buttons, prepare yourself.
main_area.connect(robot_scaffolding, rule=lambda state:
state.has("Jump Dive", player) or state.has_all(("Roll", "Roll Jump"), player))
main_area.connect(jump_pad_room)
robot_scaffolding.connect(main_area, rule=lambda state: state.has("Jump Dive", player))
robot_scaffolding.connect(blast_furnace, rule=lambda state:
state.has("Jump Dive", player)
and can_jump_farther(state, player)
and (can_triple_jump(state, player) or state.has_all(("Roll", "Roll Jump"), player)))
robot_scaffolding.connect(bunny_room, rule=lambda state:
state.has("Jump Dive", player)
and can_jump_farther(state, player)
and (can_triple_jump(state, player) or state.has_all(("Roll", "Roll Jump"), player)))
jump_pad_room.connect(main_area)
jump_pad_room.connect(robot_scaffolding, rule=lambda state:
state.has("Jump Dive", player)
and (can_triple_jump(state, player) or state.has_all(("Roll", "Roll Jump"), player)))
blast_furnace.connect(robot_scaffolding) # Blue eco elevator takes you right back.
bunny_room.connect(robot_scaffolding, rule=lambda state:
state.has("Jump Dive", player)
and (can_jump_farther(state, player) or state.has_all(("Roll", "Roll Jump"), player)))
# Final climb.
robot_scaffolding.connect(rotating_tower, rule=lambda state:
can_jump_stairs(state, player)
and state.has_all(("Freed The Blue Sage",
"Freed The Red Sage",
"Freed The Yellow Sage"), player))
rotating_tower.connect(main_area) # Take stairs back down.
# Final elevator. Need to break boxes at summit to get blue eco for platform.
rotating_tower.connect(final_boss, rule=lambda state:
can_fight(state, player)
and state.has("Freed The Green Sage", player))
final_boss.connect(rotating_tower) # Take elevator back down.
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(robot_scaffolding)
world.level_to_regions[level_name].append(jump_pad_room)
world.level_to_regions[level_name].append(blast_furnace)
world.level_to_regions[level_name].append(bunny_room)
world.level_to_regions[level_name].append(rotating_tower)
world.level_to_regions[level_name].append(final_boss)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 200 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(15,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
# Final door. Need 100 power cells.
if options.jak_completion_condition == CompletionCondition.option_open_100_cell_door:
final_door = JakAndDaxterRegion("Final Door", player, multiworld, level_name, 0)
final_boss.connect(final_door, rule=lambda state: state.has("Power Cell", player, 100))
world.level_to_regions[level_name].append(final_door)
return main_area, final_boss, final_door
else:
return main_area, final_boss, None

View File

@@ -0,0 +1,38 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_reach_orbs_level
from ..locs import cell_locations as cells, scout_locations as scouts
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 50)
# Everything is accessible by making contact with the zoomer.
main_area.add_cell_locations(cells.locLT_cellTable.keys())
main_area.add_fly_locations(scouts.locLT_scoutTable.keys())
world.level_to_regions[level_name].append(main_area)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(14,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,155 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
# Just the starting area.
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 4)
first_room_upper = JakAndDaxterRegion("First Chamber (Upper)", player, multiworld, level_name, 21)
first_room_lower = JakAndDaxterRegion("First Chamber (Lower)", player, multiworld, level_name, 0)
first_room_lower.add_fly_locations([262193], access_rule=lambda state: can_free_scout_flies(state, player))
first_room_orb_cache = JakAndDaxterRegion("First Chamber Orb Cache", player, multiworld, level_name, 22)
# Need jump dive to activate button, double jump to reach blue eco to unlock cache.
first_room_orb_cache.add_cache_locations([14507], access_rule=lambda state:
state.has_all(("Jump Dive", "Double Jump"), player))
first_hallway = JakAndDaxterRegion("First Hallway", player, multiworld, level_name, 10)
first_hallway.add_fly_locations([131121], access_rule=lambda state: can_free_scout_flies(state, player))
# This entire room is accessible with floating platforms and single jump.
second_room = JakAndDaxterRegion("Second Chamber", player, multiworld, level_name, 28)
# These items can only be gotten with jump dive to activate a button.
second_room.add_cell_locations([45], access_rule=lambda state: state.has("Jump Dive", player))
second_room.add_fly_locations([49, 65585], access_rule=lambda state: state.has("Jump Dive", player))
# This is the scout fly on the way to the pipe cell, requires normal breaking moves.
second_room.add_fly_locations([196657], access_rule=lambda state: can_free_scout_flies(state, player))
# This orb vent and scout fly are right next to each other, can be gotten with blue eco and the floating platforms.
second_room.add_fly_locations([393265])
second_room.add_cache_locations([14838])
# Named after the cell, includes the armored lurker room.
center_complex = JakAndDaxterRegion("Center of the Complex", player, multiworld, level_name, 17)
center_complex.add_cell_locations([51])
color_platforms = JakAndDaxterRegion("Color Platforms", player, multiworld, level_name, 6)
color_platforms.add_cell_locations([44], access_rule=lambda state: can_fight(state, player))
quick_platforms = JakAndDaxterRegion("Quick Platforms", player, multiworld, level_name, 3)
# Jump dive to activate button.
quick_platforms.add_cell_locations([48], access_rule=lambda state: state.has("Jump Dive", player))
first_slide = JakAndDaxterRegion("First Slide", player, multiworld, level_name, 22)
# Raised chamber room, includes vent room with scout fly prior to second slide.
capsule_room = JakAndDaxterRegion("Capsule Chamber", player, multiworld, level_name, 6)
# Use jump dive to activate button inside the capsule. Blue eco vent can ready the chamber and get the scout fly.
capsule_room.add_cell_locations([47], access_rule=lambda state:
state.has("Jump Dive", player)
and (state.has_any(("Double Jump", "Jump Kick"), player)
or state.has_all(("Punch", "Punch Uppercut"), player)))
capsule_room.add_fly_locations([327729])
# You can slide to the bottom of the city, but if you spawn down there, you have no momentum from the slide.
# So you need some kind of jump to reach this cell.
second_slide = JakAndDaxterRegion("Second Slide", player, multiworld, level_name, 31)
second_slide.add_cell_locations([46], access_rule=lambda state:
state.has_any(("Double Jump", "Jump Kick"), player)
or state.has_all(("Punch", "Punch Uppercut"), player))
# If you can enter the helix room, you can jump or fight your way to the top. But you need some kind of movement
# to enter it in the first place.
helix_room = JakAndDaxterRegion("Helix Chamber", player, multiworld, level_name, 30)
helix_room.add_cell_locations([50], access_rule=lambda state:
state.has("Double Jump", player)
or can_fight(state, player))
main_area.connect(first_room_upper) # Run.
first_room_upper.connect(main_area) # Run.
first_room_upper.connect(first_hallway) # Run and jump (floating platforms).
first_room_upper.connect(first_room_lower) # Run and jump down.
first_room_lower.connect(first_room_upper) # Run and jump (floating platforms).
# Needs some movement to reach these orbs and orb cache.
first_room_lower.connect(first_room_orb_cache, rule=lambda state:
state.has_all(("Jump Dive", "Double Jump"), player))
first_room_orb_cache.connect(first_room_lower, rule=lambda state:
state.has_all(("Jump Dive", "Double Jump"), player))
first_hallway.connect(first_room_upper) # Run and jump down.
first_hallway.connect(second_room) # Run and jump (floating platforms).
second_room.connect(first_hallway) # Run and jump.
second_room.connect(center_complex) # Run and jump down.
center_complex.connect(second_room) # Run and jump (swim).
center_complex.connect(color_platforms) # Run and jump (swim).
center_complex.connect(quick_platforms) # Run and jump (swim).
color_platforms.connect(center_complex) # Run and jump (swim).
quick_platforms.connect(center_complex) # Run and jump (swim).
quick_platforms.connect(first_slide) # Slide.
first_slide.connect(capsule_room) # Slide.
capsule_room.connect(second_slide) # Slide.
capsule_room.connect(main_area, rule=lambda state: # Chamber goes back to surface.
state.has("Jump Dive", player)) # (Assume one-way for sanity.)
second_slide.connect(helix_room, rule=lambda state: # As stated above, you need to jump
state.has_any(("Double Jump", "Jump Kick"), player) # across the dark eco pool before
or state.has_all(("Punch", "Punch Uppercut"), player)) # you can climb the helix room.
helix_room.connect(quick_platforms, rule=lambda state: # Escape to get back to here.
state.has("Double Jump", player) # Capsule is a convenient exit to the level.
or can_fight(state, player))
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(first_room_upper)
world.level_to_regions[level_name].append(first_room_lower)
world.level_to_regions[level_name].append(first_room_orb_cache)
world.level_to_regions[level_name].append(first_hallway)
world.level_to_regions[level_name].append(second_room)
world.level_to_regions[level_name].append(center_complex)
world.level_to_regions[level_name].append(color_platforms)
world.level_to_regions[level_name].append(quick_platforms)
world.level_to_regions[level_name].append(first_slide)
world.level_to_regions[level_name].append(capsule_room)
world.level_to_regions[level_name].append(second_slide)
world.level_to_regions[level_name].append(helix_room)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 200 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(7,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,131 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 9)
muse_course = JakAndDaxterRegion("Muse Course", player, multiworld, level_name, 21)
muse_course.add_cell_locations([23])
muse_course.add_fly_locations([327708], access_rule=lambda state: can_free_scout_flies(state, player))
zoomer = JakAndDaxterRegion("Zoomer", player, multiworld, level_name, 32)
zoomer.add_cell_locations([27, 29])
zoomer.add_fly_locations([393244])
ship = JakAndDaxterRegion("Ship", player, multiworld, level_name, 10)
ship.add_cell_locations([24])
ship.add_fly_locations([131100], access_rule=lambda state: can_free_scout_flies(state, player))
far_side = JakAndDaxterRegion("Far Side", player, multiworld, level_name, 16)
# In order to even reach this fly, you must use the seesaw or crouch jump.
far_side_cliff = JakAndDaxterRegion("Far Side Cliff", player, multiworld, level_name, 5)
far_side_cliff.add_fly_locations([28], access_rule=lambda state: can_free_scout_flies(state, player))
# To carry the blue eco fast enough to open this cache, you need to break the bone bridges along the way.
far_side_cache = JakAndDaxterRegion("Far Side Orb Cache", player, multiworld, level_name, 15)
far_side_cache.add_cache_locations([11072], access_rule=lambda state: can_fight(state, player))
barrel_course = JakAndDaxterRegion("Barrel Course", player, multiworld, level_name, 10)
barrel_course.add_fly_locations([196636], access_rule=lambda state: can_free_scout_flies(state, player))
# 14 orbs for the boxes you can only break with the cannon.
cannon = JakAndDaxterRegion("Cannon", player, multiworld, level_name, 14)
cannon.add_cell_locations([26], access_rule=lambda state: can_fight(state, player))
upper_approach = JakAndDaxterRegion("Upper Arena Approach", player, multiworld, level_name, 6)
upper_approach.add_fly_locations([65564, 262172], access_rule=lambda state:
can_free_scout_flies(state, player))
lower_approach = JakAndDaxterRegion("Lower Arena Approach", player, multiworld, level_name, 7)
lower_approach.add_cell_locations([30])
arena = JakAndDaxterRegion("Arena", player, multiworld, level_name, 5)
arena.add_cell_locations([25], access_rule=lambda state: can_fight(state, player))
main_area.connect(muse_course) # TODO - What do you need to chase the muse the whole way around?
main_area.connect(zoomer) # Run and jump down.
main_area.connect(ship) # Run and jump.
main_area.connect(lower_approach) # Run and jump.
# Need to break the bone bridge to access.
main_area.connect(upper_approach, rule=lambda state: can_fight(state, player))
muse_course.connect(main_area) # Run and jump down.
# The zoomer pad is low enough that it requires Crouch Jump specifically.
zoomer.connect(main_area, rule=lambda state: state.has_all(("Crouch", "Crouch Jump"), player))
ship.connect(main_area) # Run and jump down.
ship.connect(far_side) # Run and jump down.
ship.connect(barrel_course) # Run and jump (dodge barrels).
far_side.connect(ship) # Run and jump.
far_side.connect(arena) # Run and jump.
# Only if you can use the seesaw or Crouch Jump from the seesaw's edge.
far_side.connect(far_side_cliff, rule=lambda state:
state.has("Jump Dive", player)
or state.has_all(("Crouch", "Crouch Jump"), player))
# Only if you can break the bone bridges to carry blue eco over the mud pit.
far_side.connect(far_side_cache, rule=lambda state: can_fight(state, player))
far_side_cliff.connect(far_side) # Run and jump down.
barrel_course.connect(cannon) # Run and jump (dodge barrels).
cannon.connect(barrel_course) # Run and jump (dodge barrels).
cannon.connect(arena) # Run and jump down.
cannon.connect(upper_approach) # Run and jump down.
upper_approach.connect(lower_approach) # Jump down.
upper_approach.connect(arena) # Jump down.
# One cliff is accessible, but only via Crouch Jump.
lower_approach.connect(upper_approach, rule=lambda state: state.has_all(("Crouch", "Crouch Jump"), player))
# Requires breaking bone bridges.
lower_approach.connect(arena, rule=lambda state: can_fight(state, player))
arena.connect(lower_approach) # Run.
arena.connect(far_side) # Run.
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(muse_course)
world.level_to_regions[level_name].append(zoomer)
world.level_to_regions[level_name].append(ship)
world.level_to_regions[level_name].append(far_side)
world.level_to_regions[level_name].append(far_side_cliff)
world.level_to_regions[level_name].append(far_side_cache)
world.level_to_regions[level_name].append(barrel_course)
world.level_to_regions[level_name].append(cannon)
world.level_to_regions[level_name].append(upper_approach)
world.level_to_regions[level_name].append(lower_approach)
world.level_to_regions[level_name].append(arena)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 150 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(4,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,67 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_reach_orbs_level
from ..locs import scout_locations as scouts
from worlds.generic.Rules import add_rule
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> tuple[JakAndDaxterRegion, ...]:
multiworld = world.multiworld
options = world.options
player = world.player
# This is basically just Klaww.
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 0)
main_area.add_cell_locations([86])
# Some folks prefer firing Yellow Eco from the hip, so optionally put this rule before Klaww. Klaww is the only
# location in main_area, so he's at index 0.
if world.options.require_punch_for_klaww:
add_rule(main_area.locations[0], lambda state: state.has("Punch", player))
race = JakAndDaxterRegion("Race", player, multiworld, level_name, 50)
race.add_cell_locations([87])
# All scout flies can be broken with the zoomer.
race.add_fly_locations(scouts.locMP_scoutTable.keys())
shortcut = JakAndDaxterRegion("Shortcut", player, multiworld, level_name, 0)
shortcut.add_cell_locations([110])
# Of course, in order to make it to the race region, you must defeat Klaww. He's not optional.
# So we need to set up this inter-region rule as well (or make it free if the setting is off).
if world.options.require_punch_for_klaww:
main_area.connect(race, rule=lambda state: state.has("Punch", player))
else:
main_area.connect(race)
# You actually can go backwards from the race back to Klaww's area.
race.connect(main_area)
race.connect(shortcut, rule=lambda state: state.has("Yellow Eco Switch", player))
shortcut.connect(race)
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(race)
world.level_to_regions[level_name].append(shortcut)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(10,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
# Return race required for inter-level connections.
return main_area, race

View File

@@ -0,0 +1,38 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_reach_orbs_level
from ..locs import cell_locations as cells, scout_locations as scouts
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 200)
# Everything is accessible by making contact with the zoomer.
main_area.add_cell_locations(cells.locPB_cellTable.keys())
main_area.add_fly_locations(scouts.locPB_scoutTable.keys())
world.level_to_regions[level_name].append(main_area)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 200 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(9,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,91 @@
from typing import Iterable
from BaseClasses import MultiWorld, Region
from ..game_id import jak1_name
from ..locations import JakAndDaxterLocation, location_table
from ..locs import (orb_locations as orbs,
cell_locations as cells,
scout_locations as scouts,
special_locations as specials,
orb_cache_locations as caches)
from worlds.generic.Rules import CollectionRule
class JakAndDaxterRegion(Region):
"""
Holds region information such as name, level name, number of orbs available, etc.
We especially need orb counts to be tracked because we need to know when you can
afford the Citizen and Oracle orb payments for more checks.
"""
game: str = jak1_name
level_name: str
orb_count: int
location_count: int = 0
def __init__(self, name: str, player: int, multiworld: MultiWorld, level_name: str = "", orb_count: int = 0):
formatted_name = f"{level_name} {name}".strip()
super().__init__(formatted_name, player, multiworld)
self.level_name = level_name
self.orb_count = orb_count
def add_cell_locations(self, locations: Iterable[int], access_rule: CollectionRule | None = None) -> None:
"""
Adds a Power Cell Location to this region with the given access rule.
Converts Game ID's to AP ID's for you.
"""
for loc in locations:
ap_id = cells.to_ap_id(loc)
self.add_jak_location(ap_id, location_table[ap_id], access_rule)
def add_fly_locations(self, locations: Iterable[int], access_rule: CollectionRule | None = None) -> None:
"""
Adds a Scout Fly Location to this region with the given access rule.
Converts Game ID's to AP ID's for you.
"""
for loc in locations:
ap_id = scouts.to_ap_id(loc)
self.add_jak_location(ap_id, location_table[ap_id], access_rule)
def add_special_locations(self, locations: Iterable[int], access_rule: CollectionRule | None = None) -> None:
"""
Adds a Special Location to this region with the given access rule.
Converts Game ID's to AP ID's for you.
Special Locations should be matched alongside their respective
Power Cell Locations, so you get 2 unlocks for these rather than 1.
"""
for loc in locations:
ap_id = specials.to_ap_id(loc)
self.add_jak_location(ap_id, location_table[ap_id], access_rule)
def add_cache_locations(self, locations: Iterable[int], access_rule: CollectionRule | None = None) -> None:
"""
Adds an Orb Cache Location to this region with the given access rule.
Converts Game ID's to AP ID's for you.
"""
for loc in locations:
ap_id = caches.to_ap_id(loc)
self.add_jak_location(ap_id, location_table[ap_id], access_rule)
def add_orb_locations(self, level_index: int, bundle_index: int, access_rule: CollectionRule | None = None) -> None:
"""
Adds Orb Bundle Locations to this region equal to `bundle_count`. Used only when Per-Level Orbsanity is enabled.
The orb factory class will handle AP ID enumeration.
"""
bundle_address = orbs.create_address(level_index, bundle_index)
location = JakAndDaxterLocation(self.player,
f"{self.level_name} Orb Bundle {bundle_index + 1}".strip(),
orbs.to_ap_id(bundle_address),
self)
if access_rule:
location.access_rule = access_rule
self.locations.append(location)
self.location_count += 1
def add_jak_location(self, ap_id: int, name: str, access_rule: CollectionRule | None = None) -> None:
"""
Helper function to add Locations. Not to be used directly.
"""
location = JakAndDaxterLocation(self.player, name, ap_id, self)
if access_rule:
location.access_rule = access_rule
self.locations.append(location)
self.location_count += 1

View File

@@ -0,0 +1,75 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> tuple[JakAndDaxterRegion, ...]:
multiworld = world.multiworld
options = world.options
player = world.player
# This includes most of the area surrounding LPC as well, for orb_count purposes. You can swim and single jump.
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 23)
main_area.add_cell_locations([31], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([32], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([33], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([34], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([35], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, 34))
# These 2 scout fly boxes can be broken by running with nearby blue eco.
main_area.add_fly_locations([196684, 262220])
main_area.add_fly_locations([76, 131148, 65612, 327756], access_rule=lambda state:
can_free_scout_flies(state, player))
# Warrior Pontoon check. You just talk to him and get his introduction.
main_area.add_special_locations([33])
orb_cache = JakAndDaxterRegion("Orb Cache", player, multiworld, level_name, 20)
# You need roll jump to be able to reach this before the blue eco runs out.
orb_cache.add_cache_locations([10945], access_rule=lambda state: state.has_all(("Roll", "Roll Jump"), player))
# Fly here can be gotten with Yellow Eco from Boggy, goggles, and no extra movement options (see fly ID 43).
pontoon_bridge = JakAndDaxterRegion("Pontoon Bridge", player, multiworld, level_name, 7)
pontoon_bridge.add_fly_locations([393292])
klaww_cliff = JakAndDaxterRegion("Klaww's Cliff", player, multiworld, level_name, 0)
main_area.connect(orb_cache, rule=lambda state: state.has_all(("Roll", "Roll Jump"), player))
main_area.connect(pontoon_bridge, rule=lambda state: state.has("Warrior's Pontoons", player))
orb_cache.connect(main_area)
pontoon_bridge.connect(main_area, rule=lambda state: state.has("Warrior's Pontoons", player))
pontoon_bridge.connect(klaww_cliff, rule=lambda state:
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)
or state.has_all(("Crouch", "Crouch Uppercut", "Jump Kick"), player))
klaww_cliff.connect(pontoon_bridge) # Just jump back down.
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(orb_cache)
world.level_to_regions[level_name].append(pontoon_bridge)
world.level_to_regions[level_name].append(klaww_cliff)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(6,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
# Return klaww_cliff required for inter-level connections.
return main_area, pontoon_bridge, klaww_cliff

View File

@@ -0,0 +1,83 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 26)
# Yakows requires no combat.
main_area.add_cell_locations([10])
main_area.add_cell_locations([11], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([12], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
# These 4 scout fly boxes can be broken by running with all the blue eco from Sentinel Beach.
main_area.add_fly_locations([262219, 327755, 131147, 65611])
# The farmer's scout fly. You can either get the Orb Cache Cliff blue eco, or break it normally.
main_area.add_fly_locations([196683], access_rule=lambda state:
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)
or can_free_scout_flies(state, player))
orb_cache_cliff = JakAndDaxterRegion("Orb Cache Cliff", player, multiworld, level_name, 15)
orb_cache_cliff.add_cache_locations([10344])
yakow_cliff = JakAndDaxterRegion("Yakow Cliff", player, multiworld, level_name, 3)
yakow_cliff.add_fly_locations([75], access_rule=lambda state: can_free_scout_flies(state, player))
oracle_platforms = JakAndDaxterRegion("Oracle Platforms", player, multiworld, level_name, 6)
oracle_platforms.add_cell_locations([13], access_rule=lambda state:
world.can_trade(state, world.total_trade_orbs, None))
oracle_platforms.add_cell_locations([14], access_rule=lambda state:
world.can_trade(state, world.total_trade_orbs, 13))
oracle_platforms.add_fly_locations([393291], access_rule=lambda state:
can_free_scout_flies(state, player))
main_area.connect(orb_cache_cliff, rule=lambda state:
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)
or state.has_all(("Crouch", "Crouch Uppercut", "Jump Kick"), player))
main_area.connect(yakow_cliff, rule=lambda state:
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)
or state.has_all(("Crouch", "Crouch Uppercut", "Jump Kick"), player))
main_area.connect(oracle_platforms, rule=lambda state:
state.has_all(("Roll", "Roll Jump"), player)
or state.has_all(("Double Jump", "Jump Kick"), player))
# All these can go back to main_area immediately.
orb_cache_cliff.connect(main_area)
yakow_cliff.connect(main_area)
oracle_platforms.connect(main_area)
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(orb_cache_cliff)
world.level_to_regions[level_name].append(yakow_cliff)
world.level_to_regions[level_name].append(oracle_platforms)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(1,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,108 @@
from BaseClasses import CollectionState
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 128)
main_area.add_cell_locations([18, 21, 22])
# These scout fly boxes can be broken by running with freely accessible blue eco.
# The 3 clusters by the Flut Flut egg can go surprisingly far.
main_area.add_fly_locations([327700, 20, 65556, 262164])
# This scout fly box can be broken with the locked blue eco vent, or by normal combat tricks.
main_area.add_fly_locations([393236], access_rule=lambda state:
state.has("Blue Eco Switch", player)
or can_free_scout_flies(state, player))
# No need for the blue eco vent for either of the orb caches.
main_area.add_cache_locations([12634, 12635])
pelican = JakAndDaxterRegion("Pelican", player, multiworld, level_name, 0)
pelican.add_cell_locations([16], access_rule=lambda state: can_fight(state, player))
# Only these specific attacks can push the flut flut egg off the cliff.
flut_flut_egg = JakAndDaxterRegion("Flut Flut Egg", player, multiworld, level_name, 0)
flut_flut_egg.add_cell_locations([17], access_rule=lambda state:
state.has_any(("Punch", "Kick", "Jump Kick"), player))
flut_flut_egg.add_special_locations([17], access_rule=lambda state:
state.has_any(("Punch", "Kick", "Jump Kick"), player))
eco_harvesters = JakAndDaxterRegion("Eco Harvesters", player, multiworld, level_name, 0)
eco_harvesters.add_cell_locations([15], access_rule=lambda state: can_fight(state, player))
green_ridge = JakAndDaxterRegion("Ridge Near Green Vents", player, multiworld, level_name, 5)
green_ridge.add_fly_locations([131092], access_rule=lambda state: can_free_scout_flies(state, player))
blue_ridge = JakAndDaxterRegion("Ridge Near Blue Vent", player, multiworld, level_name, 5)
blue_ridge.add_fly_locations([196628], access_rule=lambda state:
state.has("Blue Eco Switch", player)
or can_free_scout_flies(state, player))
cannon_tower = JakAndDaxterRegion("Cannon Tower", player, multiworld, level_name, 12)
cannon_tower.add_cell_locations([19], access_rule=lambda state: can_fight(state, player))
main_area.connect(pelican) # Swim and jump.
main_area.connect(flut_flut_egg) # Run and jump.
main_area.connect(eco_harvesters) # Run.
# We need a helper function for the uppercut logs.
def can_uppercut_and_jump_logs(state: CollectionState, p: int) -> bool:
return (state.has_any(("Double Jump", "Jump Kick"), p)
and (state.has_all(("Crouch", "Crouch Uppercut"), p)
or state.has_all(("Punch", "Punch Uppercut"), p)))
# If you have double jump or crouch jump, you don't need the logs to reach this place.
main_area.connect(green_ridge, rule=lambda state:
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)
or can_uppercut_and_jump_logs(state, player))
# If you have the blue eco jump pad, you don't need the logs to reach this place.
main_area.connect(blue_ridge, rule=lambda state:
state.has("Blue Eco Switch", player)
or can_uppercut_and_jump_logs(state, player))
main_area.connect(cannon_tower, rule=lambda state: state.has("Blue Eco Switch", player))
# All these can go back to main_area immediately.
pelican.connect(main_area)
flut_flut_egg.connect(main_area)
eco_harvesters.connect(main_area)
green_ridge.connect(main_area)
blue_ridge.connect(main_area)
cannon_tower.connect(main_area)
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(pelican)
world.level_to_regions[level_name].append(flut_flut_egg)
world.level_to_regions[level_name].append(eco_harvesters)
world.level_to_regions[level_name].append(green_ridge)
world.level_to_regions[level_name].append(blue_ridge)
world.level_to_regions[level_name].append(cannon_tower)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 150 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(2,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,203 @@
from BaseClasses import CollectionState
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
# God help me... here we go.
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
# We need a few helper functions.
def can_cross_long_gap(state: CollectionState, p: int) -> bool:
return (state.has_all(("Roll", "Roll Jump"), p)
or state.has_all(("Double Jump", "Jump Kick"), p))
def can_jump_blockers(state: CollectionState, p: int) -> bool:
return (state.has_any(("Double Jump", "Jump Kick"), p)
or state.has_all(("Crouch", "Crouch Jump"), p)
or state.has_all(("Punch", "Punch Uppercut"), p))
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 0)
main_area.add_fly_locations([65], access_rule=lambda state: can_free_scout_flies(state, player))
# We need a few virtual regions like we had for Dark Crystals in Spider Cave.
# First, a virtual region for the glacier lurkers.
glacier_lurkers = JakAndDaxterRegion("Glacier Lurkers", player, multiworld, level_name, 0)
# Need to fight all the troops.
# Troop in snowball_canyon: cross main_area.
# Troop in ice_skating_rink: cross main_area and fort_exterior.
# Troop in fort_exterior: cross main_area and fort_exterior.
glacier_lurkers.add_cell_locations([61], access_rule=lambda state:
can_fight(state, player)
and can_cross_long_gap(state, player))
# Second, a virtual region for the precursor blockers. Unlike the others, this contains orbs:
# the total number of orbs that sit on top of the blockers. Yes, there are only 8.
blockers = JakAndDaxterRegion("Precursor Blockers", player, multiworld, level_name, 8)
# 1 in main_area
# 2 in snowball_canyon
# 4 in ice_skating_rink
# 3 in fort_exterior
# 3 in bunny_cave_start
blockers.add_cell_locations([66], access_rule=lambda state:
can_fight(state, player)
and can_cross_long_gap(state, player))
snowball_canyon = JakAndDaxterRegion("Snowball Canyon", player, multiworld, level_name, 28)
# The scout fly box *can* be broken without YES, so leave it in this region.
frozen_box_cave = JakAndDaxterRegion("Frozen Box Cave", player, multiworld, level_name, 12)
frozen_box_cave.add_fly_locations([327745], access_rule=lambda state:
state.has("Yellow Eco Switch", player)
or can_free_scout_flies(state, player))
# This region has crates that can *only* be broken with YES.
frozen_box_cave_crates = JakAndDaxterRegion("Frozen Box Cave Orb Crates", player, multiworld, level_name, 8)
frozen_box_cave_crates.add_cell_locations([67], access_rule=lambda state:
state.has("Yellow Eco Switch", player))
# Include 6 orbs on the twin elevator ice ramp.
ice_skating_rink = JakAndDaxterRegion("Ice Skating Rink", player, multiworld, level_name, 20)
ice_skating_rink.add_fly_locations([131137], access_rule=lambda state: can_free_scout_flies(state, player))
flut_flut_course = JakAndDaxterRegion("Flut Flut Course", player, multiworld, level_name, 15)
flut_flut_course.add_cell_locations([63], access_rule=lambda state: state.has("Flut Flut", player))
flut_flut_course.add_special_locations([63], access_rule=lambda state: state.has("Flut Flut", player))
# Includes the bridge from snowball_canyon, the area beneath that bridge, and the areas around the fort.
fort_exterior = JakAndDaxterRegion("Fort Exterior", player, multiworld, level_name, 20)
fort_exterior.add_fly_locations([65601, 393281], access_rule=lambda state:
can_free_scout_flies(state, player))
# Includes the icy island and bridge outside the cave entrance.
bunny_cave_start = JakAndDaxterRegion("Bunny Cave (Start)", player, multiworld, level_name, 10)
# Includes the cell and 3 orbs at the exit.
bunny_cave_end = JakAndDaxterRegion("Bunny Cave (End)", player, multiworld, level_name, 3)
bunny_cave_end.add_cell_locations([64])
switch_cave = JakAndDaxterRegion("Yellow Eco Switch Cave", player, multiworld, level_name, 4)
switch_cave.add_cell_locations([60])
switch_cave.add_special_locations([60])
# Only what can be covered by single jump.
fort_interior = JakAndDaxterRegion("Fort Interior (Main)", player, multiworld, level_name, 19)
# Reaching the top of the watch tower, getting the fly with the blue eco, and falling down to get the caches.
fort_interior_caches = JakAndDaxterRegion("Fort Interior (Caches)", player, multiworld, level_name, 51)
fort_interior_caches.add_fly_locations([196673])
fort_interior_caches.add_cache_locations([23348, 23349, 23350])
# Need higher jump.
fort_interior_base = JakAndDaxterRegion("Fort Interior (Base)", player, multiworld, level_name, 0)
fort_interior_base.add_fly_locations([262209], access_rule=lambda state:
can_free_scout_flies(state, player))
# Need farther jump.
fort_interior_course_end = JakAndDaxterRegion("Fort Interior (Course End)", player, multiworld, level_name, 2)
fort_interior_course_end.add_cell_locations([62])
# Wire up the virtual regions first.
main_area.connect(blockers, rule=lambda state: can_jump_blockers(state, player))
main_area.connect(glacier_lurkers, rule=lambda state: can_fight(state, player))
# Yes, the only way into the rest of the level requires advanced movement.
main_area.connect(snowball_canyon, rule=lambda state: can_cross_long_gap(state, player))
snowball_canyon.connect(main_area) # But you can just jump down and run up the ramp.
snowball_canyon.connect(bunny_cave_start) # Jump down from the glacier troop cliff.
snowball_canyon.connect(fort_exterior) # Jump down, to the left of frozen box cave.
snowball_canyon.connect(frozen_box_cave, rule=lambda state: # More advanced movement.
can_cross_long_gap(state, player))
frozen_box_cave.connect(snowball_canyon, rule=lambda state: # Same movement to go back.
can_cross_long_gap(state, player))
frozen_box_cave.connect(frozen_box_cave_crates, rule=lambda state: # YES to get these crates.
state.has("Yellow Eco Switch", player))
frozen_box_cave.connect(ice_skating_rink, rule=lambda state: # Same movement to go forward.
can_cross_long_gap(state, player))
frozen_box_cave_crates.connect(frozen_box_cave) # Semi-virtual region, no moves req'd.
ice_skating_rink.connect(frozen_box_cave, rule=lambda state: # Same movement to go back.
can_cross_long_gap(state, player))
ice_skating_rink.connect(flut_flut_course, rule=lambda state: # Duh.
state.has("Flut Flut", player))
ice_skating_rink.connect(fort_exterior) # Just slide down the elevator ramp.
fort_exterior.connect(ice_skating_rink, rule=lambda state: # Twin elevators OR scout fly ledge.
can_cross_long_gap(state, player)) # Both doable with main_gap logic.
fort_exterior.connect(snowball_canyon) # Run across bridge.
fort_exterior.connect(fort_interior, rule=lambda state: # Duh.
state.has("Snowy Fort Gate", player))
fort_exterior.connect(bunny_cave_start) # Run across bridge.
fort_exterior.connect(switch_cave, rule=lambda state: # Yes, blocker jumps work here.
can_jump_blockers(state, player))
fort_interior.connect(fort_interior_caches, rule=lambda state: # Just need a little height.
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player))
fort_interior.connect(fort_interior_base, rule=lambda state: # Just need a little height.
state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player))
fort_interior.connect(fort_interior_course_end, rule=lambda state: # Just need a little distance.
state.has_any(("Double Jump", "Jump Kick"), player)
or state.has_all(("Punch", "Punch Uppercut"), player))
flut_flut_course.connect(fort_exterior) # Ride the elevator.
# Must fight way through cave, but there is also a grab-less ledge we must jump over.
bunny_cave_start.connect(bunny_cave_end, rule=lambda state:
can_fight(state, player)
and (state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)))
# All jump down.
fort_interior_caches.connect(fort_interior)
fort_interior_base.connect(fort_interior)
fort_interior_course_end.connect(fort_interior)
switch_cave.connect(fort_exterior)
bunny_cave_end.connect(fort_exterior)
# I really hope that is everything.
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(glacier_lurkers)
world.level_to_regions[level_name].append(blockers)
world.level_to_regions[level_name].append(snowball_canyon)
world.level_to_regions[level_name].append(frozen_box_cave)
world.level_to_regions[level_name].append(frozen_box_cave_crates)
world.level_to_regions[level_name].append(ice_skating_rink)
world.level_to_regions[level_name].append(flut_flut_course)
world.level_to_regions[level_name].append(fort_exterior)
world.level_to_regions[level_name].append(bunny_cave_start)
world.level_to_regions[level_name].append(bunny_cave_end)
world.level_to_regions[level_name].append(switch_cave)
world.level_to_regions[level_name].append(fort_interior)
world.level_to_regions[level_name].append(fort_interior_caches)
world.level_to_regions[level_name].append(fort_interior_base)
world.level_to_regions[level_name].append(fort_interior_course_end)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 200 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(12,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,127 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_fight, can_reach_orbs_level
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
# A large amount of this area can be covered by single jump, floating platforms, web trampolines, and goggles.
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 63)
main_area.add_cell_locations([78, 84])
main_area.add_fly_locations([327765, 393301, 196693, 131157])
# This is a virtual region describing what you need to DO to get the Dark Crystal power cell,
# rather than describing where each of the crystals ARE, because you can destroy them in any order,
# and you need to destroy ALL of them to get the cell.
dark_crystals = JakAndDaxterRegion("Dark Crystals", player, multiworld, level_name, 0)
# can_fight = The underwater crystal in dark cave.
# Roll Jump = The underwater crystal across a long dark eco pool.
# The rest of the crystals can be destroyed with yellow eco in main_area.
dark_crystals.add_cell_locations([79], access_rule=lambda state:
can_fight(state, player)
and state.has_all(("Roll", "Roll Jump"), player))
dark_cave = JakAndDaxterRegion("Dark Cave", player, multiworld, level_name, 5)
dark_cave.add_cell_locations([80])
dark_cave.add_fly_locations([262229], access_rule=lambda state: can_free_scout_flies(state, player))
robot_cave = JakAndDaxterRegion("Robot Cave", player, multiworld, level_name, 0)
# Need double jump for orbs.
scaffolding_level_zero = JakAndDaxterRegion("Robot Scaffolding Level 0", player, multiworld, level_name, 12)
scaffolding_level_one = JakAndDaxterRegion("Robot Scaffolding Level 1", player, multiworld, level_name, 53)
scaffolding_level_one.add_fly_locations([85]) # Shootable.
scaffolding_level_two = JakAndDaxterRegion("Robot Scaffolding Level 2", player, multiworld, level_name, 4)
# Using the blue eco from the pole course, you can single jump to the scout fly up here.
scaffolding_level_three = JakAndDaxterRegion("Robot Scaffolding Level 3", player, multiworld, level_name, 29)
scaffolding_level_three.add_cell_locations([81])
scaffolding_level_three.add_fly_locations([65621])
pole_course = JakAndDaxterRegion("Pole Course", player, multiworld, level_name, 18)
pole_course.add_cell_locations([82])
# You only need combat to fight through the spiders, but to collect the orb crates,
# you will need the yellow eco vent unlocked.
spider_tunnel = JakAndDaxterRegion("Spider Tunnel", player, multiworld, level_name, 4)
spider_tunnel.add_cell_locations([83])
spider_tunnel_crates = JakAndDaxterRegion("Spider Tunnel Orb Crates", player, multiworld, level_name, 12)
main_area.connect(dark_crystals)
main_area.connect(robot_cave)
main_area.connect(dark_cave, rule=lambda state:
can_fight(state, player)
and (state.has("Double Jump", player)
or state.has_all(("Crouch", "Crouch Jump"), player)))
robot_cave.connect(main_area)
robot_cave.connect(pole_course) # Nothing special required.
robot_cave.connect(scaffolding_level_one) # Ramps lead to level 1.
robot_cave.connect(spider_tunnel) # Web trampolines (bounce twice on each to gain momentum).
pole_course.connect(robot_cave) # Blue eco platform down.
scaffolding_level_one.connect(robot_cave) # All scaffolding (level 1+) connects back by jumping down.
# Elevator, but the orbs need double jump or jump kick.
scaffolding_level_one.connect(scaffolding_level_zero, rule=lambda state:
state.has_any(("Double Jump", "Jump Kick"), player))
# Narrow enough that enemies are unavoidable.
scaffolding_level_one.connect(scaffolding_level_two, rule=lambda state: can_fight(state, player))
scaffolding_level_zero.connect(scaffolding_level_one) # Elevator.
scaffolding_level_two.connect(robot_cave) # Jump down.
scaffolding_level_two.connect(scaffolding_level_one) # Elevator.
# Elevator, but narrow enough that enemies are unavoidable.
scaffolding_level_two.connect(scaffolding_level_three, rule=lambda state: can_fight(state, player))
scaffolding_level_three.connect(robot_cave) # Jump down.
scaffolding_level_three.connect(scaffolding_level_two) # Elevator.
spider_tunnel.connect(robot_cave) # Back to web trampolines.
spider_tunnel.connect(main_area) # Escape with jump pad.
# Requires yellow eco switch.
spider_tunnel.connect(spider_tunnel_crates, rule=lambda state: state.has("Yellow Eco Switch", player))
world.level_to_regions[level_name].append(main_area)
world.level_to_regions[level_name].append(dark_crystals)
world.level_to_regions[level_name].append(dark_cave)
world.level_to_regions[level_name].append(robot_cave)
world.level_to_regions[level_name].append(scaffolding_level_zero)
world.level_to_regions[level_name].append(scaffolding_level_one)
world.level_to_regions[level_name].append(scaffolding_level_two)
world.level_to_regions[level_name].append(scaffolding_level_three)
world.level_to_regions[level_name].append(pole_course)
world.level_to_regions[level_name].append(spider_tunnel)
world.level_to_regions[level_name].append(spider_tunnel_crates)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 200 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(13,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1,52 @@
from .region_base import JakAndDaxterRegion
from ..options import EnableOrbsanity
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import JakAndDaxterWorld
from ..rules import can_free_scout_flies, can_reach_orbs_level
from ..locs import scout_locations as scouts
def build_regions(level_name: str, world: "JakAndDaxterWorld") -> JakAndDaxterRegion:
multiworld = world.multiworld
options = world.options
player = world.player
# No area is inaccessible in VC even with only running and jumping.
main_area = JakAndDaxterRegion("Main Area", player, multiworld, level_name, 50)
main_area.add_cell_locations([96], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([97], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, 96))
main_area.add_cell_locations([98], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, 97))
main_area.add_cell_locations([99], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, 98))
main_area.add_cell_locations([100], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, None))
main_area.add_cell_locations([101], access_rule=lambda state: world.can_trade(state, world.total_trade_orbs, 100))
# Hidden Power Cell: you can carry yellow eco from Spider Cave just by running and jumping
# and using your Goggles to shoot the box (you do not need Punch to shoot from FP mode).
main_area.add_cell_locations([74])
# No blue eco sources in this area, all boxes must be broken by hand (yellow eco can't be carried far enough).
main_area.add_fly_locations(scouts.locVC_scoutTable.keys(), access_rule=lambda state:
can_free_scout_flies(state, player))
# Approach the gondola to get this check.
main_area.add_special_locations([105])
world.level_to_regions[level_name].append(main_area)
# If Per-Level Orbsanity is enabled, build the special Orbsanity Region. This is a virtual region always
# accessible to Main Area. The Locations within are automatically checked when you collect enough orbs.
if options.enable_orbsanity == EnableOrbsanity.option_per_level:
orbs = JakAndDaxterRegion("Orbsanity", player, multiworld, level_name)
bundle_count = 50 // world.orb_bundle_size
for bundle_index in range(bundle_count):
amount = world.orb_bundle_size * (bundle_index + 1)
orbs.add_orb_locations(11,
bundle_index,
access_rule=lambda state, level=level_name, orb_amount=amount:
can_reach_orbs_level(state, player, world, level, orb_amount))
multiworld.regions.append(orbs)
main_area.connect(orbs)
return main_area

View File

@@ -0,0 +1 @@
Pymem>=1.13.0

View File

@@ -0,0 +1,230 @@
import typing
from BaseClasses import CollectionState
from Options import OptionError
from .options import (EnableOrbsanity,
GlobalOrbsanityBundleSize,
PerLevelOrbsanityBundleSize,
FireCanyonCellCount,
MountainPassCellCount,
LavaTubeCellCount,
CitizenOrbTradeAmount,
OracleOrbTradeAmount)
from .locs import cell_locations as cells
from .locations import location_table
from .levels import level_table
if typing.TYPE_CHECKING:
from . import JakAndDaxterWorld
def set_orb_trade_rule(world: "JakAndDaxterWorld"):
options = world.options
player = world.player
if options.enable_orbsanity == EnableOrbsanity.option_off:
world.can_trade = lambda state, required_orbs, required_previous_trade: (
can_trade_vanilla(state, player, world, required_orbs, required_previous_trade))
else:
world.can_trade = lambda state, required_orbs, required_previous_trade: (
can_trade_orbsanity(state, player, world, required_orbs, required_previous_trade))
def recalculate_reachable_orbs(state: CollectionState, player: int, world: "JakAndDaxterWorld") -> None:
# Recalculate every level, every time the cache is stale, because you don't know
# when a specific bundle of orbs in one level may unlock access to another.
accessible_total_orbs = 0
for level in level_table:
accessible_level_orbs = count_reachable_orbs_level(state, world, level)
accessible_total_orbs += accessible_level_orbs
state.prog_items[player][f"{level} Reachable Orbs".lstrip()] = accessible_level_orbs
# Also recalculate the global count, still used even when Orbsanity is Off.
state.prog_items[player]["Reachable Orbs"] = accessible_total_orbs
state.prog_items[player]["Reachable Orbs Fresh"] = True
def count_reachable_orbs_global(state: CollectionState,
world: "JakAndDaxterWorld") -> int:
accessible_orbs = 0
for level_regions in world.level_to_orb_regions.values():
for region in level_regions:
if region.can_reach(state):
accessible_orbs += region.orb_count
return accessible_orbs
def count_reachable_orbs_level(state: CollectionState,
world: "JakAndDaxterWorld",
level_name: str = "") -> int:
accessible_orbs = 0
for region in world.level_to_orb_regions[level_name]:
if region.can_reach(state):
accessible_orbs += region.orb_count
return accessible_orbs
def can_reach_orbs_global(state: CollectionState,
player: int,
world: "JakAndDaxterWorld",
orb_amount: int) -> bool:
if not state.prog_items[player]["Reachable Orbs Fresh"]:
recalculate_reachable_orbs(state, player, world)
return state.has("Reachable Orbs", player, orb_amount)
def can_reach_orbs_level(state: CollectionState,
player: int,
world: "JakAndDaxterWorld",
level_name: str,
orb_amount: int) -> bool:
if not state.prog_items[player]["Reachable Orbs Fresh"]:
recalculate_reachable_orbs(state, player, world)
return state.has(f"{level_name} Reachable Orbs", player, orb_amount)
def can_trade_vanilla(state: CollectionState,
player: int,
world: "JakAndDaxterWorld",
required_orbs: int,
required_previous_trade: typing.Optional[int] = None) -> bool:
# With Orbsanity Off, Reachable Orbs are in fact Tradeable Orbs.
if not state.prog_items[player]["Reachable Orbs Fresh"]:
recalculate_reachable_orbs(state, player, world)
if required_previous_trade:
name_of_previous_trade = location_table[cells.to_ap_id(required_previous_trade)]
return (state.has("Reachable Orbs", player, required_orbs)
and state.can_reach_location(name_of_previous_trade, player=player))
return state.has("Reachable Orbs", player, required_orbs)
def can_trade_orbsanity(state: CollectionState,
player: int,
world: "JakAndDaxterWorld",
required_orbs: int,
required_previous_trade: typing.Optional[int] = None) -> bool:
# Yes, even Orbsanity trades may unlock access to new Reachable Orbs.
if not state.prog_items[player]["Reachable Orbs Fresh"]:
recalculate_reachable_orbs(state, player, world)
if required_previous_trade:
name_of_previous_trade = location_table[cells.to_ap_id(required_previous_trade)]
return (state.has("Tradeable Orbs", player, required_orbs)
and state.can_reach_location(name_of_previous_trade, player=player))
return state.has("Tradeable Orbs", player, required_orbs)
def can_free_scout_flies(state: CollectionState, player: int) -> bool:
return state.has("Jump Dive", player) or state.has_all({"Crouch", "Crouch Uppercut"}, player)
def can_fight(state: CollectionState, player: int) -> bool:
return state.has_any(("Jump Dive", "Jump Kick", "Punch", "Kick"), player)
def enforce_multiplayer_limits(world: "JakAndDaxterWorld"):
options = world.options
friendly_message = ""
if (options.enable_orbsanity == EnableOrbsanity.option_global
and (options.global_orbsanity_bundle_size.value < GlobalOrbsanityBundleSize.friendly_minimum
or options.global_orbsanity_bundle_size.value > GlobalOrbsanityBundleSize.friendly_maximum)):
friendly_message += (f" "
f"{options.global_orbsanity_bundle_size.display_name} must be no less than "
f"{GlobalOrbsanityBundleSize.friendly_minimum} and no greater than "
f"{GlobalOrbsanityBundleSize.friendly_maximum} (currently "
f"{options.global_orbsanity_bundle_size.value}).\n")
if (options.enable_orbsanity == EnableOrbsanity.option_per_level
and options.level_orbsanity_bundle_size.value < PerLevelOrbsanityBundleSize.friendly_minimum):
friendly_message += (f" "
f"{options.level_orbsanity_bundle_size.display_name} must be no less than "
f"{PerLevelOrbsanityBundleSize.friendly_minimum} (currently "
f"{options.level_orbsanity_bundle_size.value}).\n")
if options.fire_canyon_cell_count.value > FireCanyonCellCount.friendly_maximum:
friendly_message += (f" "
f"{options.fire_canyon_cell_count.display_name} must be no greater than "
f"{FireCanyonCellCount.friendly_maximum} (currently "
f"{options.fire_canyon_cell_count.value}).\n")
if options.mountain_pass_cell_count.value > MountainPassCellCount.friendly_maximum:
friendly_message += (f" "
f"{options.mountain_pass_cell_count.display_name} must be no greater than "
f"{MountainPassCellCount.friendly_maximum} (currently "
f"{options.mountain_pass_cell_count.value}).\n")
if options.lava_tube_cell_count.value > LavaTubeCellCount.friendly_maximum:
friendly_message += (f" "
f"{options.lava_tube_cell_count.display_name} must be no greater than "
f"{LavaTubeCellCount.friendly_maximum} (currently "
f"{options.lava_tube_cell_count.value}).\n")
if options.citizen_orb_trade_amount.value > CitizenOrbTradeAmount.friendly_maximum:
friendly_message += (f" "
f"{options.citizen_orb_trade_amount.display_name} must be no greater than "
f"{CitizenOrbTradeAmount.friendly_maximum} (currently "
f"{options.citizen_orb_trade_amount.value}).\n")
if options.oracle_orb_trade_amount.value > OracleOrbTradeAmount.friendly_maximum:
friendly_message += (f" "
f"{options.oracle_orb_trade_amount.display_name} must be no greater than "
f"{OracleOrbTradeAmount.friendly_maximum} (currently "
f"{options.oracle_orb_trade_amount.value}).\n")
if friendly_message != "":
raise OptionError(f"{world.player_name}: The options you have chosen may disrupt the multiworld. \n"
f"Please adjust the following Options for a multiplayer game. \n"
f"{friendly_message}"
f"Or use 'random-range-x-y' instead of 'random' in your player yaml.\n"
f"Or set 'enforce_friendly_options' in the seed generator's host.yaml to false. "
f"(Use at your own risk!)")
def enforce_singleplayer_limits(world: "JakAndDaxterWorld"):
options = world.options
friendly_message = ""
if options.fire_canyon_cell_count.value > FireCanyonCellCount.friendly_maximum:
friendly_message += (f" "
f"{options.fire_canyon_cell_count.display_name} must be no greater than "
f"{FireCanyonCellCount.friendly_maximum} (currently "
f"{options.fire_canyon_cell_count.value}).\n")
if options.mountain_pass_cell_count.value > MountainPassCellCount.friendly_maximum:
friendly_message += (f" "
f"{options.mountain_pass_cell_count.display_name} must be no greater than "
f"{MountainPassCellCount.friendly_maximum} (currently "
f"{options.mountain_pass_cell_count.value}).\n")
if options.lava_tube_cell_count.value > LavaTubeCellCount.friendly_maximum:
friendly_message += (f" "
f"{options.lava_tube_cell_count.display_name} must be no greater than "
f"{LavaTubeCellCount.friendly_maximum} (currently "
f"{options.lava_tube_cell_count.value}).\n")
if friendly_message != "":
raise OptionError(f"The options you have chosen may result in seed generation failures. \n"
f"Please adjust the following Options for a singleplayer game. \n"
f"{friendly_message}"
f"Or use 'random-range-x-y' instead of 'random' in your player yaml.\n"
f"Or set 'enforce_friendly_options' in your host.yaml to false. "
f"(Use at your own risk!)")
def verify_orb_trade_amounts(world: "JakAndDaxterWorld"):
if world.total_trade_orbs > 2000:
raise OptionError(f"{world.player_name}: Required number of orbs for all trades ({world.total_trade_orbs}) "
f"is more than all the orbs in the game (2000). Reduce the value of either "
f"{world.options.citizen_orb_trade_amount.display_name} "
f"or {world.options.oracle_orb_trade_amount.display_name}.")

View File

View File

@@ -0,0 +1,107 @@
from worlds.jakanddaxter import JakAndDaxterWorld
from ..game_id import jak1_name
from test.bases import WorldTestBase
class JakAndDaxterTestBase(WorldTestBase):
game = jak1_name
world: JakAndDaxterWorld
level_info = {
"Geyser Rock": {
"cells": 4,
"flies": 7,
"orbs": 50,
"caches": 0,
},
"Sandover Village": {
"cells": 6,
"flies": 7,
"orbs": 50,
"caches": 1,
},
"Forbidden Jungle": {
"cells": 8,
"flies": 7,
"orbs": 150,
"caches": 1,
},
"Sentinel Beach": {
"cells": 8,
"flies": 7,
"orbs": 150,
"caches": 2,
},
"Misty Island": {
"cells": 8,
"flies": 7,
"orbs": 150,
"caches": 1,
},
"Fire Canyon": {
"cells": 2,
"flies": 7,
"orbs": 50,
"caches": 0,
},
"Rock Village": {
"cells": 6,
"flies": 7,
"orbs": 50,
"caches": 1,
},
"Precursor Basin": {
"cells": 8,
"flies": 7,
"orbs": 200,
"caches": 0,
},
"Lost Precursor City": {
"cells": 8,
"flies": 7,
"orbs": 200,
"caches": 2,
},
"Boggy Swamp": {
"cells": 8,
"flies": 7,
"orbs": 200,
"caches": 0,
},
"Mountain Pass": {
"cells": 4,
"flies": 7,
"orbs": 50,
"caches": 0,
},
"Volcanic Crater": {
"cells": 8,
"flies": 7,
"orbs": 50,
"caches": 0,
},
"Spider Cave": {
"cells": 8,
"flies": 7,
"orbs": 200,
"caches": 0,
},
"Snowy Mountain": {
"cells": 8,
"flies": 7,
"orbs": 200,
"caches": 3,
},
"Lava Tube": {
"cells": 2,
"flies": 7,
"orbs": 50,
"caches": 0,
},
"Gol and Maia's Citadel": {
"cells": 5,
"flies": 7,
"orbs": 200,
"caches": 3,
},
}

View File

@@ -0,0 +1,52 @@
import typing
from .bases import JakAndDaxterTestBase
from ..game_id import jak1_id
from ..regs.region_base import JakAndDaxterRegion
from ..locs import (scout_locations as scouts,
special_locations as specials,
orb_cache_locations as caches,
orb_locations as orbs)
class LocationsTest(JakAndDaxterTestBase):
def get_regions(self):
return [typing.cast(JakAndDaxterRegion, reg) for reg in self.multiworld.get_regions(self.player)]
def test_count_cells(self):
for level in self.level_info:
cell_count = 0
sublevels = [reg for reg in self.get_regions() if reg.level_name == level]
for sl in sublevels:
for loc in sl.locations:
if loc.address in range(jak1_id, jak1_id + scouts.fly_offset):
cell_count += 1
self.assertEqual(self.level_info[level]["cells"] - 1, cell_count, level) # Don't count the Free 7 Cells.
def test_count_flies(self):
for level in self.level_info:
fly_count = 0
sublevels = [reg for reg in self.get_regions() if reg.level_name == level]
for sl in sublevels:
for loc in sl.locations:
if loc.address in range(jak1_id + scouts.fly_offset, jak1_id + specials.special_offset):
fly_count += 1
self.assertEqual(self.level_info[level]["flies"], fly_count, level)
def test_count_orbs(self):
for level in self.level_info:
sublevels = [reg for reg in self.get_regions() if reg.level_name == level]
orb_count = sum([reg.orb_count for reg in sublevels])
self.assertEqual(self.level_info[level]["orbs"], orb_count, level)
def test_count_caches(self):
for level in self.level_info:
cache_count = 0
sublevels = [reg for reg in self.get_regions() if reg.level_name == level]
for sl in sublevels:
for loc in sl.locations:
if loc.address in range(jak1_id + caches.orb_cache_offset, jak1_id + orbs.orb_offset):
cache_count += 1
self.assertEqual(self.level_info[level]["caches"], cache_count, level)

View File

@@ -0,0 +1,32 @@
from .bases import JakAndDaxterTestBase
from ..items import move_item_table
class MoveRandoTest(JakAndDaxterTestBase):
options = {
"enable_move_randomizer": True
}
def test_move_items_in_pool(self):
for move in move_item_table:
self.assertIn(move_item_table[move], {item.name for item in self.multiworld.itempool})
self.assertNotIn(move_item_table[move],
{item.name for item in self.multiworld.precollected_items[self.player]})
def test_cannot_reach_without_move(self):
self.assertAccessDependency(
["GR: Climb Up The Cliff"],
[["Double Jump"], ["Crouch"]],
only_check_listed=True)
class NoMoveRandoTest(JakAndDaxterTestBase):
options = {
"enable_move_randomizer": False
}
def test_move_items_in_inventory(self):
for move in move_item_table:
self.assertNotIn(move_item_table[move], {item.name for item in self.multiworld.itempool})
self.assertIn(move_item_table[move],
{item.name for item in self.multiworld.precollected_items[self.player]})

View File

@@ -0,0 +1,61 @@
from .bases import JakAndDaxterTestBase
from ..items import orb_item_table
class NoOrbsanityTest(JakAndDaxterTestBase):
options = {
"enable_orbsanity": 0, # Off
"level_orbsanity_bundle_size": 25,
"global_orbsanity_bundle_size": 16
}
def test_orb_bundles_not_exist_in_pool(self):
for bundle in orb_item_table:
self.assertNotIn(orb_item_table[bundle], {item.name for item in self.multiworld.itempool})
def test_orb_bundle_count(self):
bundle_name = orb_item_table[self.options["level_orbsanity_bundle_size"]]
count = len([item.name for item in self.multiworld.itempool if item.name == bundle_name])
self.assertEqual(0, count)
bundle_name = orb_item_table[self.options["global_orbsanity_bundle_size"]]
count = len([item.name for item in self.multiworld.itempool if item.name == bundle_name])
self.assertEqual(0, count)
class PerLevelOrbsanityTest(JakAndDaxterTestBase):
options = {
"enable_orbsanity": 1, # Per Level
"level_orbsanity_bundle_size": 25
}
def test_orb_bundles_exist_in_pool(self):
for bundle in orb_item_table:
if bundle == self.options["level_orbsanity_bundle_size"]:
self.assertIn(orb_item_table[bundle], {item.name for item in self.multiworld.itempool})
else:
self.assertNotIn(orb_item_table[bundle], {item.name for item in self.multiworld.itempool})
def test_orb_bundle_count(self):
bundle_name = orb_item_table[self.options["level_orbsanity_bundle_size"]]
count = len([item.name for item in self.multiworld.itempool if item.name == bundle_name])
self.assertEqual(80, count)
class GlobalOrbsanityTest(JakAndDaxterTestBase):
options = {
"enable_orbsanity": 2, # Global
"global_orbsanity_bundle_size": 16
}
def test_orb_bundles_exist_in_pool(self):
for bundle in orb_item_table:
if bundle == self.options["global_orbsanity_bundle_size"]:
self.assertIn(orb_item_table[bundle], {item.name for item in self.multiworld.itempool})
else:
self.assertNotIn(orb_item_table[bundle], {item.name for item in self.multiworld.itempool})
def test_orb_bundle_count(self):
bundle_name = orb_item_table[self.options["global_orbsanity_bundle_size"]]
count = len([item.name for item in self.multiworld.itempool if item.name == bundle_name])
self.assertEqual(125, count)

View File

@@ -0,0 +1,29 @@
from .bases import JakAndDaxterTestBase
class ReorderedCellCountsTest(JakAndDaxterTestBase):
options = {
"enable_ordered_cell_counts": True,
"fire_canyon_cell_count": 20,
"mountain_pass_cell_count": 15,
"lava_tube_cell_count": 10,
}
def test_reordered_cell_counts(self):
self.world.generate_early()
self.assertLessEqual(self.world.options.fire_canyon_cell_count, self.world.options.mountain_pass_cell_count)
self.assertLessEqual(self.world.options.mountain_pass_cell_count, self.world.options.lava_tube_cell_count)
class UnorderedCellCountsTest(JakAndDaxterTestBase):
options = {
"enable_ordered_cell_counts": False,
"fire_canyon_cell_count": 20,
"mountain_pass_cell_count": 15,
"lava_tube_cell_count": 10,
}
def test_unordered_cell_counts(self):
self.world.generate_early()
self.assertGreaterEqual(self.world.options.fire_canyon_cell_count, self.world.options.mountain_pass_cell_count)
self.assertGreaterEqual(self.world.options.mountain_pass_cell_count, self.world.options.lava_tube_cell_count)

View File

@@ -0,0 +1,39 @@
from .bases import JakAndDaxterTestBase
class TradesCostNothingTest(JakAndDaxterTestBase):
options = {
"enable_orbsanity": 2,
"global_orbsanity_bundle_size": 5,
"citizen_orb_trade_amount": 0,
"oracle_orb_trade_amount": 0
}
def test_orb_items_are_filler(self):
self.collect_all_but("")
self.assertNotIn("5 Precursor Orbs", self.multiworld.state.prog_items)
def test_trades_are_accessible(self):
self.assertTrue(self.multiworld
.get_location("SV: Bring 90 Orbs To The Mayor", self.player)
.can_reach(self.multiworld.state))
class TradesCostEverythingTest(JakAndDaxterTestBase):
options = {
"enable_orbsanity": 2,
"global_orbsanity_bundle_size": 5,
"citizen_orb_trade_amount": 120,
"oracle_orb_trade_amount": 150
}
def test_orb_items_are_progression(self):
self.collect_all_but("")
self.assertIn("5 Precursor Orbs", self.multiworld.state.prog_items[self.player])
self.assertEqual(396, self.multiworld.state.prog_items[self.player]["5 Precursor Orbs"])
def test_trades_are_accessible(self):
self.collect_all_but("")
self.assertTrue(self.multiworld
.get_location("SV: Bring 90 Orbs To The Mayor", self.player)
.can_reach(self.multiworld.state))

View File

@@ -0,0 +1,80 @@
from BaseClasses import ItemClassification
from .bases import JakAndDaxterTestBase
class NoTrapsTest(JakAndDaxterTestBase):
options = {
"filler_power_cells_replaced_with_traps": 0,
"filler_orb_bundles_replaced_with_traps": 0,
"trap_weights": {"Trip Trap": 1},
}
def test_trap_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Trip Trap"
and item.classification == ItemClassification.trap])
self.assertEqual(0, count)
def test_prog_power_cells_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Power Cell"
and item.classification == ItemClassification.progression_skip_balancing])
self.assertEqual(72, count)
def test_fill_power_cells_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Power Cell"
and item.classification == ItemClassification.filler])
self.assertEqual(29, count)
class SomeTrapsTest(JakAndDaxterTestBase):
options = {
"filler_power_cells_replaced_with_traps": 10,
"filler_orb_bundles_replaced_with_traps": 10,
"trap_weights": {"Trip Trap": 1},
}
def test_trap_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Trip Trap"
and item.classification == ItemClassification.trap])
self.assertEqual(10, count)
def test_prog_power_cells_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Power Cell"
and item.classification == ItemClassification.progression_skip_balancing])
self.assertEqual(72, count)
def test_fill_power_cells_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Power Cell"
and item.classification == ItemClassification.filler])
self.assertEqual(19, count)
class MaximumTrapsTest(JakAndDaxterTestBase):
options = {
"filler_power_cells_replaced_with_traps": 100,
"filler_orb_bundles_replaced_with_traps": 100,
"trap_weights": {"Trip Trap": 1},
}
def test_trap_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Trip Trap"
and item.classification == ItemClassification.trap])
self.assertEqual(29, count)
def test_prog_power_cells_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Power Cell"
and item.classification == ItemClassification.progression_skip_balancing])
self.assertEqual(72, count)
def test_fill_power_cells_count(self):
count = len([item.name for item in self.multiworld.itempool
if item.name == "Power Cell"
and item.classification == ItemClassification.filler])
self.assertEqual(0, count)