-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path__init__.py
More file actions
2089 lines (1858 loc) · 114 KB
/
__init__.py
File metadata and controls
2089 lines (1858 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""File specifically used for the cases of archipelago generation."""
import os
import typing
import math
import threading
import time
import json
import zipfile
import codecs
from io import BytesIO
import pkgutil
import shutil
import sys
import tempfile
from typing import Any, TypedDict
baseclasses_loaded = False
try:
# DO NOT DO IMPORTS FOR AP BEFORE THIS OR IN THIS BLOCK
# THIS BLOCK JUST DETERMINES IF AP IS INSTALLED
import BaseClasses
baseclasses_loaded = True
except ImportError:
pass
if baseclasses_loaded:
def display_error_box(title: str, text: str) -> bool | None:
"""Display an error message box."""
from tkinter import Tk, messagebox
root = Tk()
root.withdraw()
ret = messagebox.showerror(title, text)
root.update()
def copy_dependencies(zip_path, file):
"""Copy a ZIP file from the package to a temporary directory, extracts its contents.
Ensures the temporary directory exists.
Args:
zip_path (str): The relative path to the ZIP file within the package.
Behavior:
- Creates a temporary directory if it does not exist.
- Reads the ZIP file from the package using `pkgutil.get_data`.
- Writes the ZIP file to the temporary directory if it does not already exist.
- Extracts the contents of the ZIP file into the temporary directory.
Prints:
- A message if the ZIP file could not be read.
- A message when the ZIP file is successfully copied.
- A message when the ZIP file is successfully extracted.
"""
# Create a temporary directory
temp_dir = tempfile.mkdtemp()
zip_dest = os.path.join(temp_dir, file)
try:
# Load the ZIP file from the package
zip_data = pkgutil.get_data(__name__, zip_path)
# Check if the zip already exists in the destination
if not os.path.exists(zip_dest):
if zip_data is None:
print(f"Failed to read {zip_path}")
else:
# Write the ZIP file to the destination
with open(zip_dest, "wb") as f:
f.write(zip_data)
print(f"Copied {zip_path} to {zip_dest}")
# Extract the ZIP file
with zipfile.ZipFile(zip_dest, "r") as zip_ref:
zip_ref.extractall(temp_dir)
print(f"Extracted {zip_dest} into {temp_dir}")
except PermissionError:
display_error_box("Permission Error", "Unable to install Dependencies to AP, please try to install AP as an admin.")
raise PermissionError("Permission Error: Unable to install Dependencies to AP, please try to install AP as an admin.")
# Add the temporary directory to sys.path
if temp_dir not in sys.path:
sys.path.insert(0, temp_dir)
platform_type = sys.platform
python_version = f"{sys.version_info.major}{sys.version_info.minor}"
baseclasses_path = os.path.dirname(os.path.dirname(BaseClasses.__file__))
if not baseclasses_path.endswith("lib"):
baseclasses_path = os.path.join(baseclasses_path, "lib")
# Remove ANY PIL folders from the baseclasses_path
# Or Pyxdelta or pillow folders
try:
for folder in os.listdir(baseclasses_path):
if folder.startswith("PIL") or folder.startswith("pyxdelta") or folder.startswith("pillow"):
folder_path = os.path.join(baseclasses_path, folder)
if os.path.isdir(folder_path):
shutil.rmtree(folder_path)
elif os.path.isfile(folder_path):
os.remove(folder_path)
# Also if its windows.zip or linux.zip, remove it
if folder.startswith("windows.zip") or folder.startswith("linux.zip"):
os.remove(os.path.join(baseclasses_path, folder))
except Exception as e:
pass
if platform_type == "win32":
zip_path = "vendor/windows.zip" # Path inside the package
copy_dependencies(zip_path, "windows.zip")
elif platform_type == "linux":
# Try version-specific zip first, fall back to generic
version_zip = f"vendor/linux_{python_version}.zip"
generic_zip = "vendor/linux.zip"
try:
copy_dependencies(version_zip, f"linux_{python_version}.zip")
except (FileNotFoundError, KeyError):
try:
copy_dependencies(generic_zip, "linux.zip")
except (FileNotFoundError, KeyError):
raise Exception(f"Could not find vendor dependencies for Linux Python {python_version}")
else:
raise Exception(f"Unsupported platform: {platform_type}")
# Add paths for APWorld context - use __file__ to get the correct base path
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
sys.path.append("worlds/dk64/")
sys.path.append("worlds/dk64/archipelago/")
sys.path.append("custom_worlds/dk64.apworld/dk64/")
sys.path.append("custom_worlds/dk64.apworld/dk64/archipelago/")
from BaseClasses import Item, MultiWorld, Tutorial, ItemClassification, CollectionState
from BaseClasses import Location, LocationProgressType
from entrance_rando import randomize_entrances, EntranceRandomizationError, disconnect_entrance_for_randomization
import settings
import logging
import randomizer.ItemPool as DK64RItemPool
from randomizer.Enums.Items import Items as DK64RItems
from archipelago.Goals import GOAL_MAPPING, QUANTITY_GOALS, calculate_quantity, pp_wincon
from archipelago.Items import DK64Item, full_item_table, setup_items
from archipelago.Options import DK64Options, Goal, SwitchSanity, SelectStartingKong, dk64_option_groups, LoadingZoneRando
from archipelago.Regions import all_locations, create_regions, connect_regions, connect_exit_level_and_deathwarp, connect_glitch_transitions
from archipelago.Rules import set_rules
from archipelago.client.common import check_version
from worlds.AutoWorld import WebWorld, World, AutoLogicRegister
from worlds.Files import APPlayerContainer
from archipelago.Logic import LogicVarHolder, logic_item_name_to_id
from randomizer.Spoiler import Spoiler
from randomizer.Settings import Settings
from randomizer.ShuffleWarps import LinkWarps
from randomizer.Patching.ApplyRandomizer import patching_response
from version import version
from randomizer.Patching.EnemyRando import randomize_enemies_0
from randomizer.Fill import ShuffleItems, Generate_Spoiler, IdentifyMajorItems
from randomizer.CompileHints import compileMicrohints
from archipelago.Hints import CompileArchipelagoHints
from randomizer.Enums.Types import Types, BarrierItems
from randomizer.Enums.Enemies import Enemies
from randomizer.Enums.Kongs import Kongs
from randomizer.Enums.Levels import Levels
from randomizer.Enums.Maps import Maps
from randomizer.Enums.Minigames import Minigames
from randomizer.Enums.Locations import Locations as DK64RLocations
from randomizer.Enums.Settings import (
Enemies,
GlitchesSelected,
Items,
LevelRandomization,
Kongs,
MicrohintsEnabled,
ShuffleLoadingZones,
TricksSelected,
SlamRequirement,
)
from randomizer.Enums.Switches import Switches
from randomizer.Enums.SwitchTypes import SwitchType
from randomizer.Enums.EnemySubtypes import EnemySubtype
from randomizer.Lists import Item as DK64RItem
from randomizer.Lists.Location import ShopLocationReference
from randomizer.Lists.ShufflableExit import ShufflableExits
from randomizer.Lists.Switches import SwitchInfo
from randomizer.Lists.EnemyTypes import EnemyLoc, EnemyMetaData
from worlds.LauncherComponents import Component, SuffixIdentifier, components, Type, icon_paths
import randomizer.ShuffleExits as ShuffleExits
from archipelago.FillSettings import fillsettings
from archipelago.Prices import generate_prices
from Utils import open_filename
import shutil
import zlib
boss_map_names = {
Maps.JapesBoss: "Army Dillo 1",
Maps.AztecBoss: "Dogadon 1",
Maps.FactoryBoss: "Mad Jack",
Maps.GalleonBoss: "Pufftoss",
Maps.FungiBoss: "Dogadon 2",
Maps.CavesBoss: "Army Dillo 2",
Maps.CastleBoss: "King Kut Out",
Maps.KroolDonkeyPhase: "DK Phase",
Maps.KroolDiddyPhase: "Diddy Phase",
Maps.KroolLankyPhase: "Lanky Phase",
Maps.KroolTinyPhase: "Tiny Phase",
Maps.KroolChunkyPhase: "Chunky Phase",
}
def crc32_of_file(file_path):
"""Compute CRC32 checksum of a file."""
crc_value = 0
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
crc_value = zlib.crc32(chunk, crc_value)
return f"{crc_value & 0xFFFFFFFF:08X}" # Convert to 8-character hex
def launch_client():
"""Launch the DK64 client."""
from archipelago.DK64Client import launch
from worlds.LauncherComponents import launch as launch_component
launch_component(launch, name="DK64 Client")
components.append(Component("DK64 Client", func=launch_client, component_type=Type.CLIENT, file_identifier=SuffixIdentifier(".chunky"), icon="dk64"))
icon_paths["dk64"] = f"ap:{__name__}/base-hack/assets/DKTV/logo3.png"
class DK64Container(APPlayerContainer):
"""This class defines the container file for DK64."""
game: str = "Donkey Kong 64"
patch_file_ending: str = ".chunky"
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize the DK64 container."""
if "data" in kwargs:
self.data = kwargs["data"]
del kwargs["data"]
super().__init__(*args, **kwargs)
def write_contents(self, opened_zipfile: zipfile.ZipFile) -> None:
"""Write the contents of the container file."""
super().write_contents(opened_zipfile)
# Write the patch data for the game
if "patch_data" in self.data:
opened_zipfile.writestr("patch_data", self.data["patch_data"])
class DK64CollectionState(metaclass=AutoLogicRegister):
"""Logic Mixin to handle some awkward situations when the CollectionState is copied."""
def init_mixin(self, parent: MultiWorld):
"""Reset the logic holder in all DK64 worlds. This is called on every CollectionState init."""
dk64_ids = parent.get_game_players(DK64World.game) + parent.get_game_groups(DK64World.game)
self.dk64_logic_holder = {}
for player in dk64_ids:
if hasattr(parent.worlds[player], "spoiler"):
self.dk64_logic_holder[player] = LogicVarHolder(parent.worlds[player].spoiler, player) # If we don't reset here, we double-collect the starting inventory
def copy_mixin(self, ret) -> CollectionState:
"""Update the current logic holder in all DK64 worlds with the current CollectionState. This is called after the CollectionState init inside the copy() method, so this essentially undoes the above method."""
dk64_ids = ret.multiworld.get_game_players(DK64World.game) + ret.multiworld.get_game_groups(DK64World.game)
for player in dk64_ids:
if player in ret.dk64_logic_holder.keys():
ret.dk64_logic_holder[player].UpdateFromArchipelagoItems(ret) # If we don't update here, every copy wipes the logic holder's knowledge
else:
if hasattr(ret.multiworld.worlds[player], "spoiler"):
print("Hey")
return ret
class DK64Settings(settings.Group):
"""Settings for the DK64 randomizer."""
class ReleaseVersion(str):
"""Choose the release version of the DK64 randomizer to use.
By setting it to master (Default) you will always pull the latest stable version.
By setting it to dev you will pull the latest development version.
If you want a specific version, you can set it to a AP version number eg: v1.0.45
"""
class EnableMinimalLogic(settings.Bool):
"""Enable minimal logic for DK64.
If disabled, any player YAML with minimal logic enabled will be forced to use glitchless logic instead.
This allows hosts to disable the minimal logic option if they don't want it on their server.
"""
release_branch: ReleaseVersion = ReleaseVersion("master")
enable_minimal_logic_dk64: EnableMinimalLogic | bool = False
class DK64Web(WebWorld):
"""WebWorld for DK64."""
theme = "jungle"
setup_en = Tutorial("Multiworld Setup Guide", "A guide to setting up the Donkey Kong 64 randomizer connected to an Archipelago Multiworld.", "English", "setup_en.md", "setup/en", ["PoryGone"])
tutorials = [setup_en]
option_groups = dk64_option_groups
class LZRSeedGroup(TypedDict):
"""Type definition for Loading Zone Randomizer seed groups."""
shuffle_helm_level_order: bool # whether helm level order is shuffled
enable_chaos_blockers: bool # whether chaos blockers are enabled (disabled if any player has it off)
randomize_blocker_required_amounts: bool # whether to randomize B. Lockers
blocker_max: int # maximum B. Locker value
maximize_helm_blocker: bool # whether to maximize Helm B. Locker (enabled if any player has it on)
level_blockers: typing.Dict[str, int] # manual B. Locker values (if not randomized)
generated_blockers: typing.Optional[typing.List[int]] # actual blocker values after generation (shared across group)
logic_type: int # logic type: 1=glitchless, 0=advanced_glitchless, 2=glitched
tricks_selected: typing.Set[str] # intersection of tricks enabled by all players
glitches_selected: typing.Set[str] # intersection of glitches enabled by all players
class DK64World(World):
"""Donkey Kong 64 is a 3D collectathon platforming game.
Play as the whole DK Crew and rescue the Golden Banana hoard from King K. Rool.
"""
game: str = "Donkey Kong 64"
options_dataclass = DK64Options
options: DK64Options
topology_present = False
settings: typing.ClassVar[DK64Settings]
seed_groups: typing.ClassVar[dict[str, LZRSeedGroup]] = {}
item_name_to_id = {name: data.code for name, data in full_item_table.items()}
location_name_to_id = all_locations
def blueprint_item_group() -> str:
"""Item group for blueprints."""
res = set()
for name, _ in full_item_table.items():
if "Blueprint" in name:
res.add(name)
return res
def gun_item_group() -> str:
"""Item group for guns."""
res = set()
gun_items = ["Coconut", "Peanut", "Grape", "Feather", "Pineapple"]
for item in gun_items:
if item in full_item_table:
res.add(item)
return res
def inst_item_group() -> str:
"""Item group for instruments."""
res = set()
inst_items = ["Bongos", "Guitar", "Trombone", "Saxophone", "Triangle"]
for item in inst_items:
if item in full_item_table:
res.add(item)
return res
def shared_item_group() -> str:
"""Item group for Training Moves."""
res = set()
training_items = ["Vines", "Diving", "Oranges", "Barrels", "Climbing", "progression Slam", "Fairy Camera", "Shockwave"]
for item in training_items:
if item in full_item_table:
res.add(item)
return res
def barrels_item_group() -> str:
"""Item group for Barrels."""
res = set()
barrels_items = ["Strong Kong", "Rocketbarrel Boost", "Orangstand Sprint", "Mini Monkey", "Hunky Chunky"]
for item in barrels_items:
if item in full_item_table:
res.add(item)
return res
def active_item_group() -> str:
"""Item group for Active Moves."""
res = set()
active_items = ["Gorilla Grab", "Chimpy Charge", "Pony Tail Twirl", "Orangstand", "Primate Punch"]
for item in active_items:
if item in full_item_table:
res.add(item)
return res
def pad_item_group() -> str:
"""Item group for Pads."""
res = set()
pad_items = ["Baboon Blast", "Simian Spring", "Baboon Balloon", "Monkeyport", "Gorilla Gone"]
for item in pad_items:
if item in full_item_table:
res.add(item)
return res
def dk_item_group() -> str:
"""Item group for DK Moves."""
res = set()
dk_items = ["Coconut", "Bongos", "Gorilla Grab", "Strong Kong", "Baboon Blast"]
for item in dk_items:
if item in full_item_table:
res.add(item)
return res
def diddy_item_group() -> str:
"""Item group for Diddy Moves."""
res = set()
diddy_items = ["Peanut", "Guitar", "Chimpy Charge", "Rocketbarrel Boost", "Simian Spring"]
for item in diddy_items:
if item in full_item_table:
res.add(item)
return res
def lanky_item_group() -> str:
"""Item group for Lanky Moves."""
res = set()
lanky_items = ["Grape", "Trombone", "Orangstand", "Orangstand Spring", "Baboon Balloon"]
for item in lanky_items:
if item in full_item_table:
res.add(item)
return res
def tiny_item_group() -> str:
"""Item group for Tiny Moves."""
res = set()
tiny_items = ["Feather", "Saxophone", "Pony Tail Twirl", "Mini Monkey", "Monkeyport"]
for item in tiny_items:
if item in full_item_table:
res.add(item)
return res
def chunky_item_group() -> str:
"""Item group for Chunky Moves."""
res = set()
chunky_items = ["Pineapple", "Triangle", "Primate Punch", "Hunky Chunky", "Triangle"]
for item in chunky_items:
if item in full_item_table:
res.add(item)
return res
def key_item_group() -> str:
"""Item group for Keys."""
res = set()
key_items = ["Key 1", "Key 2", "Key 3", "Key 4", "Key 5", "Key 6", "Key 7", "Key 8"]
for item in key_items:
if item in full_item_table:
res.add(item)
return res
def kong_item_group() -> str:
"""Item group for Kongs."""
res = set()
kong_items = ["Donkey", "Diddy", "Lanky", "Tiny", "Chunky"]
for item in kong_items:
if item in full_item_table:
res.add(item)
return res
def company_coin_item_group() -> str:
"""Item group for Company Coins."""
res = set()
coin_items = ["Nintendo Coin", "Rareware Coin"]
for item in coin_items:
if item in full_item_table:
res.add(item)
return res
def dk_name() -> str:
"""Add Kong to end of Kongs."""
res = set()
if "Donkey" in full_item_table:
res.add("Donkey")
return res
def diddy_name() -> str:
"""Add Kong to end of Kongs."""
res = set()
if "Diddy" in full_item_table:
res.add("Diddy")
return res
def lanky_name() -> str:
"""Add Kong to end of Kongs."""
res = set()
if "Lanky" in full_item_table:
res.add("Lanky")
return res
def tiny_name() -> str:
"""Add Kong to end of Kongs."""
res = set()
if "Tiny" in full_item_table:
res.add("Tiny")
return res
def chunky_name() -> str:
"""Add Kong to end of Kongs."""
res = set()
if "Chunky" in full_item_table:
res.add("Chunky")
return res
def isles_locations() -> str:
"""Location group for Isles locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Isles"):
res.add(location_name)
# Add specific Banana Fairy related locations
if "The Banana Fairy's Gift" in all_locations:
res.add("The Banana Fairy's Gift")
if "Returning the Banana Fairies" in all_locations:
res.add("Returning the Banana Fairies")
return res
def japes_locations() -> str:
"""Location group for Japes locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Japes"):
res.add(location_name)
return res
def aztec_locations() -> str:
"""Location group for Aztec locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Aztec"):
res.add(location_name)
return res
def factory_locations() -> str:
"""Location group for Factory locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Factory") or location_name.startswith("DK Arcade"):
res.add(location_name)
return res
def galleon_locations() -> str:
"""Location group for Galleon locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Galleon") or location_name.startswith("Treasure Chest"):
res.add(location_name)
return res
def forest_locations() -> str:
"""Location group for Forest locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Forest"):
res.add(location_name)
return res
def caves_locations() -> str:
"""Location group for Caves locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Caves"):
res.add(location_name)
return res
def castle_locations() -> str:
"""Location group for Castle locations."""
res = set()
for location_name in all_locations.keys():
if location_name.startswith("Castle"):
res.add(location_name)
return res
def helm_locations() -> str:
"""Location group for Helm locations."""
res = set()
# Locations to exclude from Helm group
excluded_locations = {
"Helm Donkey Barrel 1",
"Helm Donkey Barrel 2",
"Helm Diddy Barrel 1",
"Helm Diddy Barrel 2",
"Helm Lanky Barrel 1",
"Helm Lanky Barrel 2",
"Helm Tiny Barrel 1",
"Helm Tiny Barrel 2",
"Helm Chunky Barrel 1",
"Helm Chunky Barrel 2",
}
for location_name in all_locations.keys():
if location_name.startswith("Helm") and location_name not in excluded_locations:
res.add(location_name)
if location_name == "The End of Helm":
res.add(location_name)
return res
def medal_locations() -> str:
"""Location group for Medal locations."""
res = set()
for location_name in all_locations.keys():
if "Medal" in location_name:
res.add(location_name)
return res
def boss_locations() -> str:
"""Location group for Boss locations."""
res = set()
for location_name in all_locations.keys():
if "Boss Defeated" in location_name:
res.add(location_name)
return res
item_name_groups = {
"Blueprints": blueprint_item_group(),
"Guns": gun_item_group(),
"Instruments": inst_item_group(),
"Shared Moves": shared_item_group(),
"Transformation Barrels": barrels_item_group(),
"Active Moves": active_item_group(),
"Pad Moves": pad_item_group(),
"DK Moves": dk_item_group(),
"Diddy Moves": diddy_item_group(),
"Lanky Moves": lanky_item_group(),
"Tiny Moves": tiny_item_group(),
"Chunky Moves": chunky_item_group(),
"Donkey Kong": dk_name(),
"Diddy Kong": diddy_name(),
"Lanky Kong": lanky_name(),
"Tiny Kong": tiny_name(),
"Chunky Kong": chunky_name(),
"Keys": key_item_group(),
"Kongs": kong_item_group(),
"Company Coins": company_coin_item_group(),
}
location_name_groups = {
"DK Isles": isles_locations(),
"Jungle Japes": japes_locations(),
"Angry Aztec": aztec_locations(),
"Frantic Factory": factory_locations(),
"Gloomy Galleon": galleon_locations(),
"Fungi Forest": forest_locations(),
"Crystal Caves": caves_locations(),
"Creepy Castle": castle_locations(),
"Hideout Helm": helm_locations(),
"Banana Medals": medal_locations(),
"Bosses": boss_locations(),
}
# with open("donklocations.txt", "w") as f:
# print(location_name_to_id, file=f)
# with open("donkitems.txt", "w") as f:
# print(item_name_to_id, file=f)
web = DK64Web()
def __init__(self, multiworld: MultiWorld, player: int):
"""Initialize the DK64 world."""
self.rom_name_available_event = threading.Event()
self.hint_data_available = threading.Event()
self.hint_compilation_complete = threading.Event()
super().__init__(multiworld, player)
self.ap_version = json.loads(pkgutil.get_data(__name__, "archipelago.json").decode("utf-8"))["world_version"]
self.entrance_connections: dict[str, str] = {}
@classmethod
def stage_assert_generate(cls, multiworld: MultiWorld):
"""Assert the stage and generate the world."""
# Check if dk64.z64 exists, if it doesn't prompt the user to provide it
# ANd then we will copy it to the root directory
crc_values = ["D44B4FC6"]
rom_file = "dk64.z64"
if not os.path.exists(rom_file):
print("Please provide a DK64 ROM file.")
file = open_filename("Select DK64 ROM", (("N64 ROM", (".z64", ".n64")),))
if not file:
raise FileNotFoundError("No ROM file selected.")
crc = crc32_of_file(file)
print(f"CRC32: {crc}")
if crc not in crc_values:
print("Invalid DK64 ROM file, please make sure your ROM is big endian.")
raise FileNotFoundError("Invalid DK64 ROM file, please make sure your ROM is a vanilla DK64 file in big endian.")
# Copy the file to the root directory
try:
shutil.copy(file, rom_file)
except Exception as e:
raise FileNotFoundError(f"Failed to copy ROM file, this may be a permissions issue: {e}")
else:
crc = crc32_of_file(rom_file)
print(f"CRC32: {crc}")
if crc not in crc_values:
print("Invalid DK64 ROM file, please make sure your ROM is big endian.")
raise FileNotFoundError("Invalid DK64 ROM file, please make sure your ROM is a vanilla DK64 file in big endian.")
check_version()
def generate_early(self):
"""Generate the world."""
# Check host setting for minimal logic and force glitchless if disabled
if not self.settings.enable_minimal_logic_dk64:
dk64_worlds_for_minimal_check: tuple[DK64World] = self.multiworld.get_game_worlds("Donkey Kong 64")
affected_players = []
for world in dk64_worlds_for_minimal_check:
if world.options.logic_type.value == 4: # 4 = minimal logic
affected_players.append(world.player_name)
world.options.logic_type.value = 1 # Force to glitchless
if affected_players:
import logging
logging.warning(
f"DK64: Minimal logic is DISABLED in host.yaml. "
f"The following player(s) have tried to sneak Minimal Logic in: {', '.join(affected_players)}. As such, they have been forced to use glitchless logic."
)
# Handle seed group synchronization for custom LZR seed groups
# We need to process ALL DK64 worlds to build/update seed groups before any player applies settings
dk64_worlds: tuple[DK64World] = self.multiworld.get_game_worlds("Donkey Kong 64")
for world in dk64_worlds:
if world.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
# Only process custom seed group strings, not standard numeric option values
if isinstance(world.options.loading_zone_rando.value, str):
group = world.options.loading_zone_rando.value
# if this is the first world in the group, set the rules equal to its rules
if group not in self.seed_groups:
helm_value = bool(world.options.shuffle_helm_level_order.value)
self.seed_groups[group] = LZRSeedGroup(
shuffle_helm_level_order=helm_value,
enable_chaos_blockers=bool(world.options.enable_chaos_blockers.value),
randomize_blocker_required_amounts=bool(world.options.randomize_blocker_required_amounts.value),
blocker_max=int(world.options.blocker_max.value),
maximize_helm_blocker=bool(world.options.maximize_level8_blocker.value),
level_blockers={
"level_1": int(world.options.level_blockers.value.get("level_1", 0)),
"level_2": int(world.options.level_blockers.value.get("level_2", 0)),
"level_3": int(world.options.level_blockers.value.get("level_3", 0)),
"level_4": int(world.options.level_blockers.value.get("level_4", 0)),
"level_5": int(world.options.level_blockers.value.get("level_5", 0)),
"level_6": int(world.options.level_blockers.value.get("level_6", 0)),
"level_7": int(world.options.level_blockers.value.get("level_7", 0)),
"level_8": int(world.options.level_blockers.value.get("level_8", 64)),
},
generated_blockers=None, # will be filled after first player generates
logic_type=int(world.options.logic_type.value),
tricks_selected=set(world.options.tricks_selected.value),
glitches_selected=set(world.options.glitches_selected.value),
)
else:
# Group already exists - update with more permissive/restrictive rules
# shuffle_helm_level_order: if any player has it enabled, enable it for the group
if world.options.shuffle_helm_level_order.value:
self.seed_groups[group]["shuffle_helm_level_order"] = True
# chaos_blockers: if any player has it disabled, disable it for the group
if not world.options.enable_chaos_blockers.value:
self.seed_groups[group]["enable_chaos_blockers"] = False
# randomize_blockers: if any player has it disabled, disable it for the group
if not world.options.randomize_blocker_required_amounts.value:
self.seed_groups[group]["randomize_blocker_required_amounts"] = False
# blocker_max: use the lowest value in the group
self.seed_groups[group]["blocker_max"] = min(self.seed_groups[group]["blocker_max"], int(world.options.blocker_max.value))
# maximize_helm_blocker: if any player has it enabled, enable it for the group
if world.options.maximize_level8_blocker.value:
self.seed_groups[group]["maximize_helm_blocker"] = True
# level blockers: use the lowest value in the group for each
for level_num in range(1, 9):
blocker_key = f"level_{level_num}"
option_key = "level_blockers"
self.seed_groups[group][option_key][blocker_key] = min(self.seed_groups[group][option_key][blocker_key], int(getattr(world.options, option_key)[blocker_key]))
# logic_type: use most restrictive (glitchless=1 > advanced_glitchless=0 > glitched=2)
# Priority order: glitchless (1) is most restrictive, then advanced_glitchless (0), then glitched (2)
current_logic = self.seed_groups[group]["logic_type"]
new_logic = int(world.options.logic_type.value)
# If current is glitched (2) and new is anything else, use new (more restrictive)
if current_logic == 2 and new_logic != 2:
self.seed_groups[group]["logic_type"] = new_logic
# If current is advanced_glitchless (0) and new is glitchless (1), use glitchless
elif current_logic == 0 and new_logic == 1:
self.seed_groups[group]["logic_type"] = 1
# If current is glitchless (1), keep it (most restrictive)
# If new is glitched (2), keep current (more restrictive)
# tricks_selected: intersection of all players' tricks (only tricks ALL players have)
self.seed_groups[group]["tricks_selected"] = self.seed_groups[group]["tricks_selected"].intersection(set(world.options.tricks_selected.value))
# glitches_selected: intersection of all players' glitches (only glitches ALL players have)
self.seed_groups[group]["glitches_selected"] = self.seed_groups[group]["glitches_selected"].intersection(set(world.options.glitches_selected.value))
# Apply seed group settings and create group random if using a custom seed group BEFORE fillsettings
self.group_random = None
self.original_random = None
if self.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
# Only apply seed group settings for custom string values, not standard numeric options
if isinstance(self.options.loading_zone_rando.value, str):
group = self.options.loading_zone_rando.value
if group in self.seed_groups:
# Override player's options with seed group settings
self.options.shuffle_helm_level_order.value = int(self.seed_groups[group]["shuffle_helm_level_order"])
self.options.enable_chaos_blockers.value = int(self.seed_groups[group]["enable_chaos_blockers"])
self.options.randomize_blocker_required_amounts.value = int(self.seed_groups[group]["randomize_blocker_required_amounts"])
self.options.blocker_max.value = self.seed_groups[group]["blocker_max"]
self.options.maximize_level8_blocker.value = int(self.seed_groups[group]["maximize_helm_blocker"])
self.options.level_blockers.value = self.seed_groups[group]["level_blockers"]
# Create group random for LZR seed synchronization and replace self.random
combined_seed = f"{self.multiworld.seed}_{group}"
from hashlib import sha256
seed_hash = int(sha256(combined_seed.encode()).hexdigest()[:16], 16)
from random import Random
self.group_random = Random(seed_hash)
self.original_random = self.random
self.random = self.group_random
# Use the fillsettings function to configure all settings
settings = fillsettings(self.options, self.multiworld, self.random)
# Enable entrance randomization if the option is set (any value other than no/off/false/0)
if self.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
settings.level_randomization = LevelRandomization.loadingzone
settings.shuffle_loading_zones = ShuffleLoadingZones.all
else:
settings.level_randomization = LevelRandomization.level_order_complex
settings.shuffle_loading_zones = ShuffleLoadingZones.levels
self.spoiler = Spoiler(settings)
# Undo any changes to this location's name, until we find a better way to prevent this from confusing the tracker and the AP code that is responsible for sending out items
self.spoiler.LocationList[DK64RLocations.FactoryDonkeyDKArcade].name = "Factory Donkey DK Arcade Round 1"
self.spoiler.settings.shuffled_location_types.append(Types.ArchipelagoItem)
Generate_Spoiler(self.spoiler)
# Store/retrieve blocker values for seed group synchronization
if self.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
if self.options.loading_zone_rando.value not in LoadingZoneRando.options.values():
group = self.options.loading_zone_rando.value
if group in self.seed_groups:
# If this is the first player to generate, store the blocker values
if self.seed_groups[group]["generated_blockers"] is None:
blocker_values = [
self.spoiler.settings.blocker_0,
self.spoiler.settings.blocker_1,
self.spoiler.settings.blocker_2,
self.spoiler.settings.blocker_3,
self.spoiler.settings.blocker_4,
self.spoiler.settings.blocker_5,
self.spoiler.settings.blocker_6,
self.spoiler.settings.blocker_7,
]
self.seed_groups[group]["generated_blockers"] = blocker_values
else:
# Use the stored blocker values from the first player
blocker_values = self.seed_groups[group]["generated_blockers"]
self.spoiler.settings.blocker_0 = blocker_values[0]
self.spoiler.settings.blocker_1 = blocker_values[1]
self.spoiler.settings.blocker_2 = blocker_values[2]
self.spoiler.settings.blocker_3 = blocker_values[3]
self.spoiler.settings.blocker_4 = blocker_values[4]
self.spoiler.settings.blocker_5 = blocker_values[5]
self.spoiler.settings.blocker_6 = blocker_values[6]
self.spoiler.settings.blocker_7 = blocker_values[7]
# randomize_blockers: if any player has it disabled, disable it for the group
if not world.options.randomize_blocker_required_amounts.value:
self.seed_groups[group]["randomize_blocker_required_amounts"] = False
# blocker_max: use the lowest value in the group
self.seed_groups[group]["blocker_max"] = min(self.seed_groups[group]["blocker_max"], int(world.options.blocker_max.value))
# maximize_helm_blocker: if any player has it enabled, enable it for the group
if world.options.maximize_level8_blocker.value:
self.seed_groups[group]["maximize_helm_blocker"] = True
# level blockers: use the lowest value in the group for each
for level_num in range(1, 9):
blocker_key = f"level_{level_num}"
option_key = "level_blockers"
self.seed_groups[group][option_key][blocker_key] = min(self.seed_groups[group][option_key][blocker_key], int(getattr(world.options, option_key)[blocker_key]))
# Apply seed group settings and create group random if using a custom seed group BEFORE fillsettings
self.group_random = None
self.original_random = None
if self.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
if self.options.loading_zone_rando.value not in LoadingZoneRando.options.values():
group = self.options.loading_zone_rando.value
if group in self.seed_groups:
# Override player's options with seed group settings
self.options.shuffle_helm_level_order.value = int(self.seed_groups[group]["shuffle_helm_level_order"])
self.options.enable_chaos_blockers.value = int(self.seed_groups[group]["enable_chaos_blockers"])
self.options.randomize_blocker_required_amounts.value = int(self.seed_groups[group]["randomize_blocker_required_amounts"])
self.options.blocker_max.value = self.seed_groups[group]["blocker_max"]
self.options.maximize_level8_blocker.value = int(self.seed_groups[group]["maximize_helm_blocker"])
self.options.level_blockers.value = self.seed_groups[group]["level_blockers"]
# Apply synchronized logic and glitch settings
self.options.logic_type.value = self.seed_groups[group]["logic_type"]
self.options.tricks_selected.value = list(self.seed_groups[group]["tricks_selected"])
self.options.glitches_selected.value = list(self.seed_groups[group]["glitches_selected"])
# Create group random for LZR seed synchronization and replace self.random
from random import Random
self.group_random = Random(group)
self.original_random = self.random
self.random = self.group_random
# Use the fillsettings function to configure all settings
settings = fillsettings(self.options, self.multiworld, self.random)
# Enable entrance randomization if the option is set (any value other than no/off/false/0)
if self.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
settings.level_randomization = LevelRandomization.loadingzone
settings.shuffle_loading_zones = ShuffleLoadingZones.all
else:
settings.level_randomization = LevelRandomization.level_order_complex
settings.shuffle_loading_zones = ShuffleLoadingZones.levels
self.spoiler = Spoiler(settings)
# Undo any changes to this location's name, until we find a better way to prevent this from confusing the tracker and the AP code that is responsible for sending out items
self.spoiler.LocationList[DK64RLocations.FactoryDonkeyDKArcade].name = "Factory Donkey DK Arcade Round 1"
self.spoiler.settings.shuffled_location_types.append(Types.ArchipelagoItem)
Generate_Spoiler(self.spoiler)
# Store/retrieve blocker values for seed group synchronization
if self.options.loading_zone_rando.value not in [0, LoadingZoneRando.option_no]:
if self.options.loading_zone_rando.value not in LoadingZoneRando.options.values():
group = self.options.loading_zone_rando.value
if group in self.seed_groups:
# If this is the first player to generate, store the blocker values
if self.seed_groups[group]["generated_blockers"] is None:
blocker_values = [
self.spoiler.settings.blocker_0,
self.spoiler.settings.blocker_1,
self.spoiler.settings.blocker_2,
self.spoiler.settings.blocker_3,
self.spoiler.settings.blocker_4,
self.spoiler.settings.blocker_5,
self.spoiler.settings.blocker_6,
self.spoiler.settings.blocker_7,
]
self.seed_groups[group]["generated_blockers"] = blocker_values
else:
# Use the stored blocker values from the first player
blocker_values = self.seed_groups[group]["generated_blockers"]
self.spoiler.settings.blocker_0 = blocker_values[0]
self.spoiler.settings.blocker_1 = blocker_values[1]
self.spoiler.settings.blocker_2 = blocker_values[2]
self.spoiler.settings.blocker_3 = blocker_values[3]
self.spoiler.settings.blocker_4 = blocker_values[4]
self.spoiler.settings.blocker_5 = blocker_values[5]
self.spoiler.settings.blocker_6 = blocker_values[6]
self.spoiler.settings.blocker_7 = blocker_values[7]
if self.options.enable_shared_shops.value:
from randomizer.Lists.Location import SharedShopLocations
all_shared_shops = list(SharedShopLocations)
self.random.shuffle(all_shared_shops)
self.spoiler.settings.selected_shared_shops = set(all_shared_shops[:10])
else:
self.spoiler.settings.selected_shared_shops = set()
# Generate custom shop prices for Archipelago
generate_prices(self.spoiler, self.options, self.random)
# Handle Loading Zones - this will handle LO and (someday?) LZR appropriately
if self.spoiler.settings.shuffle_loading_zones != ShuffleLoadingZones.none:
if self.spoiler.settings.level_randomization != LevelRandomization.loadingzone:
# UT should not reshuffle the level order, but should update the exits
if not hasattr(self.multiworld, "generation_is_fake"):
ShuffleExits.ExitShuffle(self.spoiler, skip_verification=True)
self.spoiler.UpdateExits()
# else: LZR shuffling happens in connect_entrances()
# Repopulate any spoiler-related stuff at this point from slot data
if hasattr(self.multiworld, "generation_is_fake"):
if hasattr(self.multiworld, "re_gen_passthrough"):
if "Donkey Kong 64" in self.multiworld.re_gen_passthrough:
passthrough = self.multiworld.re_gen_passthrough["Donkey Kong 64"]
if passthrough["EnemyData"]:
for location, data in passthrough["EnemyData"].items():
self.spoiler.enemy_location_list[DK64RLocations[location]] = EnemyLoc(Maps[data["map"]], Enemies[data["enemy"]], 0, [], False)
if passthrough["MinigameData"]:
for loc, minigame in passthrough["MinigameData"].items():
self.spoiler.shuffled_barrel_data[DK64RLocations[loc]].minigame = Minigames[minigame]
if passthrough["JunkedLocations"]:
for loc in passthrough["JunkedLocations"]:
del self.location_name_to_id[loc]
if passthrough.get("ShopPrices"):
# Restore shop prices from slot data (shop locations only)
restored_prices = {}
for location_name, price in passthrough["ShopPrices"].items():
# Convert location name string back to enum
try:
location_id = DK64RLocations[location_name]
restored_prices[location_id] = price
except (KeyError, AttributeError):
print(f"Warning: Could not restore price for location {location_name}")
self.spoiler.settings.prices = restored_prices
# Handle hint preparation by initiating some variables
self.hint_data = {