forked from AmazingAmpharos/OoT-Randomizer
-
Notifications
You must be signed in to change notification settings - Fork 233
/
Hints.py
1913 lines (1632 loc) · 95.6 KB
/
Hints.py
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
from __future__ import annotations
import itertools
import json
import logging
import os
import random
import sys
import urllib.request
from collections import OrderedDict, defaultdict
from collections.abc import Callable, Iterable
from enum import Enum
from typing import TYPE_CHECKING, Optional
from urllib.error import URLError, HTTPError
from HintList import Hint, get_hint, get_multi, get_hint_group, get_upgrade_hint_list, hint_exclusions, \
misc_item_hint_table, misc_location_hint_table
from Item import Item, make_event_item
from ItemList import REWARD_COLORS
from Messages import Message, COLOR_MAP, update_message_by_id
from Region import Region
from Search import Search
from TextBox import line_wrap
from Utils import data_path
if sys.version_info >= (3, 10):
from typing import TypeAlias
else:
TypeAlias = str
if TYPE_CHECKING:
from Dungeon import Dungeon
from Entrance import Entrance
from Goals import GoalCategory
from Location import Location
from Spoiler import Spoiler
from World import World
Spot: TypeAlias = "Entrance | Location | Region"
HintReturn: TypeAlias = "Optional[tuple[GossipText, Optional[list[Location]]]]"
HintFunc: TypeAlias = "Callable[[Spoiler, World, set[str]], HintReturn]"
BarrenFunc: TypeAlias = "Callable[[Spoiler, World, set[str], set[str]], HintReturn]"
bingoBottlesForHints: set[str] = {
"Bottle", "Bottle with Red Potion", "Bottle with Green Potion", "Bottle with Blue Potion",
"Bottle with Fairy", "Bottle with Fish", "Bottle with Blue Fire", "Bottle with Bugs",
"Bottle with Big Poe", "Bottle with Poe",
}
defaultHintDists: list[str] = [
'balanced.json',
'bingo.json',
'chaos.json',
'chaos_no_goal.json',
'coop.json',
'ddr.json',
'important_checks.json',
'league.json',
'mw_path.json',
'mw_woth.json',
'scrubs.json',
'strong.json',
'tournament.json',
'useless.json',
'very_strong.json',
'very_strong_magic.json',
'weekly.json',
]
unHintableWothItems: set[str] = {*REWARD_COLORS, 'Triforce Piece', 'Gold Skulltula Token', 'Piece of Heart', 'Piece of Heart (Treasure Chest Game)', 'Heart Container'}
class RegionRestriction(Enum):
NONE = 0,
DUNGEON = 1,
OVERWORLD = 2,
class GossipStone:
def __init__(self, name: str, location: str) -> None:
self.name: str = name
self.location: str = location
self.reachable: bool = True
class GossipText:
def __init__(self, text: str, colors: Optional[list[str]] = None, hinted_locations: Optional[list[str]] = None,
hinted_items: Optional[list[str]] = None, prefix: str = "They say that ", capitalize: bool = True) -> None:
text = prefix + text
if capitalize:
text = text[:1].upper() + text[1:]
self.text: str = text
self.colors: Optional[list[str]] = colors
self.hinted_locations: Optional[list[str]] = hinted_locations
self.hinted_items: Optional[list[str]] = hinted_items
def to_json(self) -> dict:
return {'text': self.text, 'colors': self.colors, 'hinted_locations': self.hinted_locations, 'hinted_items': self.hinted_items}
def __str__(self) -> str:
return get_raw_text(line_wrap(color_text(self)))
# Abbreviations
# DMC Death Mountain Crater
# DMT Death Mountain Trail
# GC Goron City
# GV Gerudo Valley
# HC Hyrule Castle
# HF Hyrule Field
# KF Kokiri Forest
# LH Lake Hylia
# LW Lost Woods
# SFM Sacred Forest Meadow
# ToT Temple of Time
# ZD Zora's Domain
# ZF Zora's Fountain
# ZR Zora's River
gossipLocations: dict[int, GossipStone] = {
0x0405: GossipStone('DMC (Bombable Wall)', 'DMC Gossip Stone'),
0x0404: GossipStone('DMT (Biggoron)', 'DMT Gossip Stone'),
0x041A: GossipStone('Colossus (Spirit Temple)', 'Colossus Gossip Stone'),
0x0414: GossipStone('Dodongos Cavern (Bombable Wall)', 'Dodongos Cavern Gossip Stone'),
0x0411: GossipStone('GV (Waterfall)', 'GV Gossip Stone'),
0x0415: GossipStone('GC (Maze)', 'GC Maze Gossip Stone'),
0x0419: GossipStone('GC (Medigoron)', 'GC Medigoron Gossip Stone'),
0x040A: GossipStone('Graveyard (Shadow Temple)', 'Graveyard Gossip Stone'),
0x0412: GossipStone('HC (Malon)', 'HC Malon Gossip Stone'),
0x040B: GossipStone('HC (Rock Wall)', 'HC Rock Wall Gossip Stone'),
0x0413: GossipStone('HC (Storms Grotto)', 'HC Storms Grotto Gossip Stone'),
0x041F: GossipStone('KF (Deku Tree Left)', 'KF Deku Tree Gossip Stone (Left)'),
0x0420: GossipStone('KF (Deku Tree Right)', 'KF Deku Tree Gossip Stone (Right)'),
0x041E: GossipStone('KF (Outside Storms)', 'KF Gossip Stone'),
0x0403: GossipStone('LH (Lab)', 'LH Lab Gossip Stone'),
0x040F: GossipStone('LH (Southeast Corner)', 'LH Gossip Stone (Southeast)'),
0x0408: GossipStone('LH (Southwest Corner)', 'LH Gossip Stone (Southwest)'),
0x041D: GossipStone('LW (Bridge)', 'LW Gossip Stone'),
0x0416: GossipStone('SFM (Maze Lower)', 'SFM Maze Gossip Stone (Lower)'),
0x0417: GossipStone('SFM (Maze Upper)', 'SFM Maze Gossip Stone (Upper)'),
0x041C: GossipStone('SFM (Saria)', 'SFM Saria Gossip Stone'),
0x0406: GossipStone('ToT (Left)', 'ToT Gossip Stone (Left)'),
0x0407: GossipStone('ToT (Left-Center)', 'ToT Gossip Stone (Left-Center)'),
0x0410: GossipStone('ToT (Right)', 'ToT Gossip Stone (Right)'),
0x040E: GossipStone('ToT (Right-Center)', 'ToT Gossip Stone (Right-Center)'),
0x0409: GossipStone('ZD (Mweep)', 'ZD Gossip Stone'),
0x0401: GossipStone('ZF (Fairy)', 'ZF Fairy Gossip Stone'),
0x0402: GossipStone('ZF (Jabu)', 'ZF Jabu Gossip Stone'),
0x040D: GossipStone('ZR (Near Grottos)', 'ZR Near Grottos Gossip Stone'),
0x040C: GossipStone('ZR (Near Domain)', 'ZR Near Domain Gossip Stone'),
0x041B: GossipStone('HF (Cow Grotto)', 'HF Cow Grotto Gossip Stone'),
0x0430: GossipStone('HF (Near Market Grotto)', 'HF Near Market Grotto Gossip Stone'),
0x0432: GossipStone('HF (Southeast Grotto)', 'HF Southeast Grotto Gossip Stone'),
0x0433: GossipStone('HF (Open Grotto)', 'HF Open Grotto Gossip Stone'),
0x0438: GossipStone('Kak (Open Grotto)', 'Kak Open Grotto Gossip Stone'),
0x0439: GossipStone('ZR (Open Grotto)', 'ZR Open Grotto Gossip Stone'),
0x043C: GossipStone('KF (Storms Grotto)', 'KF Storms Grotto Gossip Stone'),
0x0444: GossipStone('LW (Near Shortcuts Grotto)', 'LW Near Shortcuts Grotto Gossip Stone'),
0x0447: GossipStone('DMT (Storms Grotto)', 'DMT Storms Grotto Gossip Stone'),
0x044A: GossipStone('DMC (Upper Grotto)', 'DMC Upper Grotto Gossip Stone'),
}
gossipLocations_reversemap: dict[str, int] = {
stone.name: stone_id for stone_id, stone in gossipLocations.items()
}
def get_item_generic_name(item: Item) -> str:
if item.unshuffled_dungeon_item and item.type != 'DungeonReward':
return item.type
else:
return item.name
def is_restricted_dungeon_item(item: Item) -> bool:
if item.world is None:
return False
return (
((item.map or item.compass) and item.world.settings.shuffle_mapcompass == 'dungeon') or
(item.type in ('SmallKey', 'SmallKeyRing') and item.world.settings.shuffle_smallkeys == 'dungeon') or
(item.type == 'BossKey' and item.world.settings.shuffle_bosskeys == 'dungeon') or
(item.type == 'GanonBossKey' and item.world.settings.shuffle_ganon_bosskey == 'dungeon') or
(item.type == 'SilverRupee' and item.world.settings.shuffle_silver_rupees == 'dungeon') or
(item.type == 'DungeonReward' and item.world.settings.shuffle_dungeon_rewards in ('vanilla', 'reward', 'dungeon'))
)
def add_hint(spoiler: Spoiler, world: World, groups: list[list[int]], gossip_text: GossipText, count: int,
locations: Optional[list[Location]] = None, force_reachable: bool = False, hint_type: str = None) -> bool:
random.shuffle(groups)
skipped_groups = []
duplicates = []
first = True
success = True
# Prevent randomizer from placing hint in removed locations for this hint type
if 'remove_stones' in world.hint_dist_user['distribution'][hint_type]:
removed_stones = world.hint_dist_user['distribution'][hint_type]['remove_stones']
for group in groups:
gossip_names = [gossipLocations[id].name for id in group]
if any(map(lambda name: name in removed_stones, gossip_names)):
skipped_groups.append(group)
for group in skipped_groups:
groups.remove(group)
# early failure if not enough
if len(groups) < int(count):
return False
# move all priority stones to the front of the list so they get picked first
if 'priority_stones' in world.hint_dist_user['distribution'][hint_type]:
priority_stones = world.hint_dist_user['distribution'][hint_type]['priority_stones']
# iterate in reverse so that the top priority stone gets inserted at index 0 last
for priority_stone in reversed(priority_stones):
matching_groups = list(filter(lambda group: list(set([priority_stone]) & set([gossipLocations[id].name for id in group])), groups))
if len(matching_groups) > 0:
index = groups.index(matching_groups[0])
priority_group = groups.pop(index)
groups.insert(0, priority_group)
# Randomly round up, if we have enough groups left
total = int(random.random() + count) if len(groups) > count else int(count)
while total:
if groups:
group = groups.pop(0)
if any(map(lambda id: gossipLocations[id].reachable, group)):
stone_names = [gossipLocations[id].location for id in group]
stone_locations = [world.get_location(stone_name) for stone_name in stone_names]
reachable = True
if locations:
for location in locations:
if not any(map(lambda stone_location: can_reach_hint(spoiler.worlds, stone_location, location), stone_locations)):
reachable = False
if not first or reachable:
if first and locations:
# just name the event item after the gossip stone directly
event_item = None
for i, stone_name in enumerate(stone_names):
# place the same event item in each location in the group
if event_item is None:
event_item = make_event_item(stone_name, stone_locations[i], event_item)
else:
make_event_item(stone_name, stone_locations[i], event_item)
assert event_item is not None
# This mostly guarantees that we don't lock the player out of an item hint
# by establishing a (hint -> item) -> hint -> item -> (first hint) loop
for location in locations:
location.add_rule(world.parser.parse_rule(repr(event_item.name)))
total -= 1
first = False
for id in group:
spoiler.hints[world.id][id] = gossip_text
# Immediately start choosing duplicates from stones we passed up earlier
while duplicates and total:
group = duplicates.pop(0)
total -= 1
for id in group:
spoiler.hints[world.id][id] = gossip_text
else:
# Temporarily skip this stone but consider it for duplicates
duplicates.append(group)
else:
if not force_reachable:
# The stones are not readable at all in logic, so we ignore any kind of logic here
if not first:
total -= 1
for id in group:
spoiler.hints[world.id][id] = gossip_text
else:
# Temporarily skip this stone but consider it for duplicates
duplicates.append(group)
else:
# If flagged to guarantee reachable, then skip
# If no stones are reachable, then this will place nothing
skipped_groups.append(group)
else:
# Out of groups
if not force_reachable and len(duplicates) >= total:
# Didn't find any appropriate stones for this hint, but maybe enough completely unreachable ones.
# We'd rather not use reachable stones for this.
unr = [group for group in duplicates if all(map(lambda id: not gossipLocations[id].reachable, group))]
if len(unr) >= total:
duplicates = [group for group in duplicates if group not in unr[:total]]
for group in unr[:total]:
for id in group:
spoiler.hints[world.id][id] = gossip_text
# Success
break
# Failure
success = False
break
groups.extend(duplicates)
groups.extend(skipped_groups)
return success
def can_reach_hint(worlds: list[World], hint_location: Location, location: Location) -> bool:
if location is None:
return True
old_item = location.item
location.item = None
search = Search.max_explore([world.state for world in worlds])
location.item = old_item
return (search.spot_access(hint_location)
and (hint_location.type != 'HintStone' or search.state_list[location.world.id].guarantee_hint()))
def write_gossip_stone_hints(spoiler: Spoiler, world: World, messages: list[Message]) -> None:
for id, gossip_text in spoiler.hints[world.id].items():
update_message_by_id(messages, id, str(gossip_text), 0x23)
def filter_trailing_space(text: str) -> str:
if text.endswith('& '):
return text[:-1]
else:
return text
hintPrefixes: list[str] = [
'a few ',
'some ',
'plenty of ',
'a ',
'an ',
'the ',
'',
]
def get_simple_hint_no_prefix(item: Item) -> Hint:
hint = get_hint(item.name, True).text
for prefix in hintPrefixes:
if hint.startswith(prefix):
# return without the prefix
return hint[len(prefix):]
# no prefex
return hint
def color_text(gossip_text: GossipText) -> str:
text = gossip_text.text
colors = list(gossip_text.colors) if gossip_text.colors is not None else []
color = 'White'
while '#' in text:
split_text = text.split('#', 2)
if len(colors) > 0:
color = colors.pop(0)
for prefix in hintPrefixes:
if split_text[1].startswith(prefix):
split_text[0] += split_text[1][:len(prefix)]
split_text[1] = split_text[1][len(prefix):]
break
split_text[1] = '\x05' + COLOR_MAP[color] + split_text[1] + '\x05\x40'
text = ''.join(split_text)
return text
class HintAreaNotFound(RuntimeError):
pass
class HintArea(Enum):
# internal name prepositions display name short name color internal dungeon name
# vague clear
ROOT = 'in', 'in', "Link's pocket", 'Free', 'White', None
HYRULE_FIELD = 'in', 'in', 'Hyrule Field', 'Hyrule Field', 'Light Blue', None
LON_LON_RANCH = 'at', 'at', 'Lon Lon Ranch', 'Lon Lon Ranch', 'Light Blue', None
MARKET = 'in', 'in', 'the Market', 'Market', 'Light Blue', None
TEMPLE_OF_TIME = 'inside', 'inside', 'the Temple of Time', 'Temple of Time', 'Light Blue', None
CASTLE_GROUNDS = 'on', 'on', 'the Castle Grounds', None, 'Light Blue', None # required for warp songs
HYRULE_CASTLE = 'at', 'at', 'Hyrule Castle', 'Hyrule Castle', 'Light Blue', None
OUTSIDE_GANONS_CASTLE = None, None, "outside Ganon's Castle", "Outside Ganon's Castle", 'Light Blue', None
INSIDE_GANONS_CASTLE = 'inside', None, "inside Ganon's Castle", "Inside Ganon's Castle", 'Light Blue', 'Ganons Castle'
GANONDORFS_CHAMBER = 'in', 'in', "Ganondorf's Chamber", "Ganondorf's Chamber", 'Light Blue', None
KOKIRI_FOREST = 'in', 'in', 'Kokiri Forest', "Kokiri Forest", 'Green', None
DEKU_TREE = 'inside', 'inside', 'the Deku Tree', "Deku Tree", 'Green', 'Deku Tree'
LOST_WOODS = 'in', 'in', 'the Lost Woods', "Lost Woods", 'Green', None
SACRED_FOREST_MEADOW = 'at', 'at', 'the Sacred Forest Meadow', "Sacred Forest Meadow", 'Green', None
FOREST_TEMPLE = 'in', 'in', 'the Forest Temple', "Forest Temple", 'Green', 'Forest Temple'
DEATH_MOUNTAIN_TRAIL = 'on', 'on', 'the Death Mountain Trail', "Death Mountain Trail", 'Red', None
DODONGOS_CAVERN = 'within', 'in', "Dodongo's Cavern", "Dodongo's Cavern", 'Red', 'Dodongos Cavern'
GORON_CITY = 'in', 'in', 'Goron City', "Goron City", 'Red', None
DEATH_MOUNTAIN_CRATER = 'in', 'in', 'the Death Mountain Crater', "Death Mountain Crater", 'Red', None
FIRE_TEMPLE = 'on', 'in', 'the Fire Temple', "Fire Temple", 'Red', 'Fire Temple'
ZORA_RIVER = 'at', 'at', "Zora's River", "Zora's River", 'Blue', None
ZORAS_DOMAIN = 'at', 'at', "Zora's Domain", "Zora's Domain", 'Blue', None
ZORAS_FOUNTAIN = 'at', 'at', "Zora's Fountain", "Zora's Fountain", 'Blue', None
JABU_JABUS_BELLY = 'in', 'inside', "Jabu Jabu's Belly", "Jabu Jabu's Belly", 'Blue', 'Jabu Jabus Belly'
ICE_CAVERN = 'inside', 'in' , 'the Ice Cavern', "Ice Cavern", 'Blue', 'Ice Cavern'
LAKE_HYLIA = 'at', 'at', 'Lake Hylia', "Lake Hylia", 'Blue', None
WATER_TEMPLE = 'under', 'in', 'the Water Temple', "Water Temple", 'Blue', 'Water Temple'
KAKARIKO_VILLAGE = 'in', 'in', 'Kakariko Village', "Kakariko Village", 'Pink', None
BOTTOM_OF_THE_WELL = 'within', 'at', 'the Bottom of the Well', "Bottom of the Well", 'Pink', 'Bottom of the Well'
GRAVEYARD = 'in', 'in', 'the Graveyard', "Graveyard", 'Pink', None
SHADOW_TEMPLE = 'within', 'in', 'the Shadow Temple', "Shadow Temple", 'Pink', 'Shadow Temple'
GERUDO_VALLEY = 'at', 'at', 'Gerudo Valley', "Gerudo Valley", 'Yellow', None
GERUDO_FORTRESS = 'at', 'at', "Gerudo's Fortress", "Gerudo's Fortress", 'Yellow', None
THIEVES_HIDEOUT = 'in', 'in', "the Thieves' Hideout", "Thieves' Hideout", 'Yellow', None
GERUDO_TRAINING_GROUND = 'within', 'on', 'the Gerudo Training Ground', "Gerudo Training Ground", 'Yellow', 'Gerudo Training Ground'
HAUNTED_WASTELAND = 'in', 'in', 'the Haunted Wasteland', "Haunted Wasteland", 'Yellow', None
DESERT_COLOSSUS = 'at', 'at', 'the Desert Colossus', "Desert Colossus", 'Yellow', None
SPIRIT_TEMPLE = 'inside', 'in', 'the Spirit Temple', "Spirit Temple", 'Yellow', 'Spirit Temple'
# Performs a breadth first search to find the closest hint area from a given spot (region, location, or entrance).
# May fail to find a hint if the given spot is only accessible from the root and not from any other region with a hint area
@staticmethod
def at(spot: Spot, use_alt_hint: bool = False) -> HintArea:
if isinstance(spot, Region):
original_parent = spot
else:
original_parent = spot.parent_region
already_checked = []
spot_queue = [spot]
fallback_spot_queue = []
while spot_queue or fallback_spot_queue:
if not spot_queue:
spot_queue = fallback_spot_queue
fallback_spot_queue = []
current_spot = spot_queue.pop(0)
already_checked.append(current_spot)
if isinstance(current_spot, Region):
parent_region = current_spot
else:
parent_region = current_spot.parent_region
if parent_region.hint and (original_parent.name == 'Root' or parent_region.name != 'Root'):
if use_alt_hint and parent_region.alt_hint:
return parent_region.alt_hint
return parent_region.hint
for entrance in parent_region.entrances:
if entrance not in already_checked:
# prioritize two-way entrances
if entrance.type in ('OverworldOneWay', 'OwlDrop', 'Spawn', 'WarpSong'):
fallback_spot_queue.append(entrance)
else:
spot_queue.append(entrance)
raise HintAreaNotFound('No hint area could be found for %s [World %d]' % (spot, spot.world.id))
@classmethod
def for_dungeon(cls, dungeon_name: str) -> Optional[HintArea]:
if '(' in dungeon_name and ')' in dungeon_name:
# A dungeon item name was passed in - get the name of the dungeon from it.
dungeon_name = dungeon_name[dungeon_name.index('(') + 1:dungeon_name.index(')')]
if dungeon_name == "Thieves Hideout":
# Special case for Thieves' Hideout since it's not considered a dungeon
return cls.THIEVES_HIDEOUT
if dungeon_name == "Treasure Chest Game":
# Special case for Treasure Chest Game keys: treat them as part of the market hint area regardless of where the treasure box shop actually is.
return cls.MARKET
for hint_area in cls:
if hint_area.dungeon_name is not None and hint_area.dungeon_name in dungeon_name:
return hint_area
return None
def preposition(self, clearer_hints: bool) -> str:
return self.value[1 if clearer_hints else 0]
def __str__(self) -> str:
return self.value[2]
# used for dungeon reward locations in the pause menu
@property
def short_name(self) -> str:
return self.value[3]
# Hint areas are further grouped into colored sections of the map by association with the medallions.
# These colors are used to generate the text boxes for shuffled warp songs.
@property
def color(self) -> str:
return self.value[4]
@property
def dungeon_name(self) -> Optional[str]:
return self.value[5]
@property
def is_dungeon(self) -> bool:
return self.dungeon_name is not None
def dungeon(self, world: World) -> Optional[Dungeon]:
dungeons = [dungeon for dungeon in world.dungeons if dungeon.name == self.dungeon_name]
if dungeons:
return dungeons[0]
def is_dungeon_item(self, item: Item) -> bool:
for dungeon in item.world.dungeons:
if dungeon.name == self.dungeon_name:
return dungeon.is_dungeon_item(item)
return False
# Formats the hint text for this area with proper grammar.
# Dungeons are hinted differently depending on the clearer_hints setting.
def text(self, clearer_hints: bool, preposition: bool = False, use_2nd_person: bool = False, world: Optional[int] = None) -> str:
if self.is_dungeon and self.dungeon_name:
text = get_hint(self.dungeon_name, clearer_hints).text
else:
text = str(self)
prefix, suffix = text.replace('#', '').split(' ', 1)
if world is None:
if prefix == "Link's":
if use_2nd_person:
text = f'your {suffix}'
else:
text = f"@'s {suffix}"
else:
replace_prefixes = ('a', 'an', 'the')
move_prefixes = ('outside', 'inside')
if prefix in replace_prefixes:
text = f"world {world}'s {suffix}"
elif prefix in move_prefixes:
text = f"{prefix} world {world}'s {suffix}"
elif prefix == "Link's":
text = f"player {world}'s {suffix}"
else:
text = f"world {world}'s {text}"
if '#' not in text:
text = f'#{text}#'
if preposition and self.preposition(clearer_hints) is not None:
text = f'{self.preposition(clearer_hints)} {text}'
return text
def get_woth_hint(spoiler: Spoiler, world: World, checked: set[str]) -> HintReturn:
locations = spoiler.required_locations[world.id]
locations = list(filter(lambda location:
location.name not in checked
and not (world.woth_dungeon >= world.hint_dist_user['dungeons_woth_limit'] and HintArea.at(location).is_dungeon)
and location.name not in world.hint_exclusions
and location.name not in world.hint_type_overrides['woth']
and location.item.name not in world.item_hint_type_overrides['woth']
and location.item.name not in unHintableWothItems,
locations))
if not locations:
return None
location = random.choice(locations)
checked.add(location.name)
hint_area = HintArea.at(location)
if hint_area.is_dungeon:
world.woth_dungeon += 1
location_text = hint_area.text(world.settings.clearer_hints)
return GossipText('%s is on the way of the hero.' % location_text, ['Light Blue'], [location.name], [location.item.name]), [location]
def get_checked_areas(world: World, checked: set[str]) -> set[HintArea | str]:
def get_area_from_name(check: str) -> HintArea | str:
try:
location = world.get_location(check)
except Exception:
return check
# Don't consider dungeons as already hinted from the reward hint on the Temple of Time altar
if location.type == 'Boss' and world.settings.shuffle_dungeon_rewards in ('vanilla', 'reward'):
return None
return HintArea.at(location)
return set(get_area_from_name(check) for check in checked)
def get_goal_category(spoiler: Spoiler, world: World, goal_categories: dict[str, GoalCategory]) -> GoalCategory:
cat_sizes = []
cat_names = []
zero_weights = True
goal_category = None
for cat_name, category in goal_categories.items():
# Only add weights if the category has goals with hintable items
if world.id in spoiler.goal_locations and cat_name in spoiler.goal_locations[world.id]:
# Build lists for weighted choice
if category.weight > 0:
zero_weights = False
# If one hint per goal is on, only add a category for random selection if:
# 1. Unhinted goals exist in the category, or
# 2. All goals in all categories have been hinted at least once
if (not world.one_hint_per_goal or
len([goal for goal in category.goals if goal.weight > 0]) > 0 or
len([goal for cat in world.goal_categories.values() for goal in cat.goals if goal.weight == 0]) == len([goal for cat in world.goal_categories.values() for goal in cat.goals])):
cat_sizes.append(category.weight)
cat_names.append(category.name)
# Depends on category order to choose next in the priority list
# Each category is guaranteed a hint first round, then weighted based on goal count
if not goal_category and category.name not in world.hinted_categories:
goal_category = category
world.hinted_categories.append(category.name)
# random choice if each category has at least one hint
if not goal_category and len(cat_names) > 0:
if zero_weights:
goal_category = goal_categories[random.choice(cat_names)]
else:
goal_category = goal_categories[random.choices(cat_names, weights=cat_sizes)[0]]
return goal_category
def get_goal_hint(spoiler: Spoiler, world: World, checked: set[str]) -> HintReturn:
goal_category = get_goal_category(spoiler, world, world.goal_categories)
# check if no goals were generated (and thus no categories available)
if not goal_category:
return None
goals = goal_category.goals
category_locations = []
zero_weights = True
required_location_reverse_map = defaultdict(list)
# Filters Goal.required_locations to those still eligible to be hinted.
hintable_required_locations_filter = (lambda required_location:
required_location[0].name not in checked
and required_location[0].name not in world.hint_exclusions
and required_location[0].name not in world.hint_type_overrides['goal']
and required_location[0].item.name not in world.item_hint_type_overrides['goal']
and required_location[0].item.name not in unHintableWothItems)
# Collect unhinted locations for the category across all category goals.
# If all locations for all goals in the category are hinted, try remaining goal categories
# If all locations for all goal categories are hinted, return no hint.
while not required_location_reverse_map:
# Filter hinted goals until every goal in the category has been hinted.
weights = []
zero_weights = True
for goal in goals:
if goal.weight > 0:
zero_weights = False
weights.append(goal.weight)
# Collect set of unhinted locations for the category. Reduces the bias
# from locations in multiple goals for the category.
required_location_reverse_map = defaultdict(list)
for goal in goals:
if zero_weights or goal.weight > 0:
hintable_required_locations = list(filter(hintable_required_locations_filter, goal.required_locations))
for required_location in hintable_required_locations:
for world_id in required_location[3]:
required_location_reverse_map[required_location[0]].append((goal, world_id))
if not required_location_reverse_map:
del world.goal_categories[goal_category.name]
goal_category = get_goal_category(spoiler, world, world.goal_categories)
if not goal_category:
return None
else:
goals = goal_category.goals
location, goal_list = random.choice(list(required_location_reverse_map.items()))
goal, world_id = random.choice(goal_list)
checked.add(location.name)
# Make sure this wasn't the last hintable location for other goals.
# If so, set weights to zero. This is important for one-hint-per-goal.
# Locations are unique per-category, so we don't have to check the others.
last_chance_overrides = []
for other_goal in goals:
if not zero_weights and other_goal.weight <= 0:
continue
hintable_required_locations = list(filter(hintable_required_locations_filter, other_goal.required_locations))
if not hintable_required_locations:
other_goal.weight = 0
if world.one_hint_per_goal:
for required_location in other_goal.required_locations:
if required_location[0] == location:
for other_world_id in required_location[3]:
last_chance_overrides.append((other_goal, other_world_id))
if (last_chance_overrides):
# Replace randomly chosen goal with a goal that has all its locations
# hinted without being directly hinted itself.
goal, world_id = random.choice(last_chance_overrides)
# Goal weight to zero mitigates double hinting this goal
# Once all goals in a category are 0, selection is true random
goal.weight = 0
location_text = HintArea.at(location).text(world.settings.clearer_hints)
if world_id == world.id:
player_text = "the"
goal_text = goal.hint_text
else:
player_text = "Player %s's" % (world_id + 1)
goal_text = spoiler.goal_categories[world_id][goal_category.name].get_goal(goal.name).hint_text
return GossipText('%s is on %s %s.' % (location_text, player_text, goal_text), ['Light Blue', goal.color], [location.name], [location.item.name]), [location]
def get_barren_hint(spoiler: Spoiler, world: World, checked: set[str], all_checked: set[str]) -> HintReturn:
if not hasattr(world, 'get_barren_hint_prev'):
world.get_barren_hint_prev = RegionRestriction.NONE
checked_areas = get_checked_areas(world, checked)
areas = list(filter(lambda area:
area not in checked_areas
and str(area) not in world.hint_type_overrides['barren']
and not (world.barren_dungeon >= world.hint_dist_user['dungeons_barren_limit'] and world.empty_areas[area]['dungeon'])
and any(
location.name not in all_checked
and location.name not in world.hint_exclusions
and location.name not in hint_exclusions(world)
and HintArea.at(location) == area
for location in world.get_filled_locations()
),
world.empty_areas))
if not areas:
return None
# Randomly choose between overworld or dungeon
dungeon_areas = list(filter(lambda area: world.empty_areas[area]['dungeon'], areas))
overworld_areas = list(filter(lambda area: not world.empty_areas[area]['dungeon'], areas))
if not dungeon_areas:
# no dungeons left, default to overworld
world.get_barren_hint_prev = RegionRestriction.OVERWORLD
elif not overworld_areas:
# no overworld left, default to dungeons
world.get_barren_hint_prev = RegionRestriction.DUNGEON
else:
if world.get_barren_hint_prev == RegionRestriction.NONE:
# 50/50 draw on the first hint
world.get_barren_hint_prev = random.choices([RegionRestriction.DUNGEON, RegionRestriction.OVERWORLD], [0.5, 0.5])[0]
elif world.get_barren_hint_prev == RegionRestriction.DUNGEON:
# weights 75% against drawing dungeon again
world.get_barren_hint_prev = random.choices([RegionRestriction.DUNGEON, RegionRestriction.OVERWORLD], [0.25, 0.75])[0]
elif world.get_barren_hint_prev == RegionRestriction.OVERWORLD:
# weights 75% against drawing overworld again
world.get_barren_hint_prev = random.choices([RegionRestriction.DUNGEON, RegionRestriction.OVERWORLD], [0.75, 0.25])[0]
if world.get_barren_hint_prev == RegionRestriction.DUNGEON:
areas = dungeon_areas
else:
areas = overworld_areas
if not areas:
return None
area_weights = [world.empty_areas[area]['weight'] for area in areas]
area = random.choices(areas, weights=area_weights)[0]
if world.empty_areas[area]['dungeon']:
world.barren_dungeon += 1
checked.add(area)
return GossipText("plundering %s is a foolish choice." % area.text(world.settings.clearer_hints), ['Pink']), None
def is_not_checked(locations: Iterable[Location], checked: set[HintArea | str]) -> bool:
return not any(location.name in checked or HintArea.at(location) in checked for location in locations)
def get_good_item_hint(spoiler: Spoiler, world: World, checked: set[str]) -> HintReturn:
locations = list(filter(lambda location:
is_not_checked([location], checked)
and ((location.item.majoritem
and location.item.name not in unHintableWothItems)
or location.name in world.added_hint_types['item']
or location.item.name in world.item_added_hint_types['item'])
and not location.locked
and location.name not in world.hint_exclusions
and location.name not in world.hint_type_overrides['item']
and location.item.name not in world.item_hint_type_overrides['item'],
world.get_filled_locations()))
if not locations:
return None
location = random.choice(locations)
checked.add(location.name)
item_text = get_hint(get_item_generic_name(location.item), world.settings.clearer_hints).text
hint_area = HintArea.at(location)
if hint_area.is_dungeon:
location_text = hint_area.text(world.settings.clearer_hints)
return GossipText('%s hoards #%s#.' % (location_text, item_text), ['Red', 'Green'], [location.name], [location.item.name]), [location]
else:
location_text = hint_area.text(world.settings.clearer_hints, preposition=True)
return GossipText('#%s# can be found %s.' % (item_text, location_text), ['Green', 'Red'], [location.name], [location.item.name]), [location]
def get_specific_item_hint(spoiler: Spoiler, world: World, checked: set[str]) -> HintReturn:
if len(world.named_item_pool) == 0:
logger = logging.getLogger('')
logger.info("Named item hint requested, but pool is empty.")
return None
if world.settings.world_count == 1:
while True:
itemname = world.named_item_pool.pop(0)
if itemname == "Bottle" and world.settings.hint_dist == "bingo":
locations = [
location for location in world.get_filled_locations()
if (is_not_checked([location], checked)
and location.name not in world.hint_exclusions
and location.item.name in bingoBottlesForHints
and not location.locked
and location.name not in world.hint_type_overrides['named-item']
)
]
else:
locations = [
location for location in world.get_filled_locations()
if (is_not_checked([location], checked)
and location.name not in world.hint_exclusions
and location.item.name == itemname
and not location.locked
and location.name not in world.hint_type_overrides['named-item']
)
]
if len(locations) > 0:
break
elif world.hint_dist_user['named_items_required']:
raise Exception("Unable to hint item {}".format(itemname))
else:
logger = logging.getLogger('')
logger.info("Unable to hint item {}".format(itemname))
if len(world.named_item_pool) == 0:
return None
location = random.choice(locations)
checked.add(location.name)
item_text = get_hint(get_item_generic_name(location.item), world.settings.clearer_hints).text
hint_area = HintArea.at(location)
if world.hint_dist_user.get('vague_named_items', False):
location_text = hint_area.text(world.settings.clearer_hints)
return GossipText('%s may be on the hero\'s path.' % location_text, ['Green'], [location.name], [location.item.name]), [location]
elif hint_area.is_dungeon:
location_text = hint_area.text(world.settings.clearer_hints)
return GossipText('%s hoards #%s#.' % (location_text, item_text), ['Red', 'Green'], [location.name], [location.item.name]), [location]
else:
location_text = hint_area.text(world.settings.clearer_hints, preposition=True)
return GossipText('#%s# can be found %s.' % (item_text, location_text), ['Green', 'Red'], [location.name], [location.item.name]), [location]
else:
while True:
# This operation is likely to be costly (especially for large multiworlds), so cache the result for later
# named_item_locations: Filtered locations from all worlds that may contain named-items
try:
named_item_locations = spoiler._cached_named_item_locations
always_locations = spoiler._cached_always_locations
except AttributeError:
worlds = spoiler.worlds
all_named_items = set(itertools.chain.from_iterable([w.named_item_pool for w in worlds]))
if "Bottle" in all_named_items and world.settings.hint_dist == "bingo":
all_named_items.update(bingoBottlesForHints)
named_item_locations = [location for w in worlds for location in w.get_filled_locations() if (location.item.name in all_named_items)]
spoiler._cached_named_item_locations = named_item_locations
always_hints = [(hint, w.id) for w in worlds for hint in get_hint_group('always', w)]
always_locations = []
for hint, id in always_hints:
location = worlds[id].get_location(hint.name)
if location.item.name in bingoBottlesForHints and world.settings.hint_dist == 'bingo':
always_item = 'Bottle'
else:
always_item = location.item.name
always_locations.append((always_item, location.item.world.id))
spoiler._cached_always_locations = always_locations
itemname = world.named_item_pool.pop(0)
if itemname == "Bottle" and world.settings.hint_dist == "bingo":
locations = [
location for location in named_item_locations
if (is_not_checked([location], checked)
and location.item.world.id == world.id
and location.name not in world.hint_exclusions
and location.item.name in bingoBottlesForHints
and not location.locked
and (itemname, world.id) not in always_locations
and location.name not in world.hint_type_overrides['named-item'])
]
else:
locations = [
location for location in named_item_locations
if (is_not_checked([location], checked)
and location.item.world.id == world.id
and location.name not in world.hint_exclusions
and location.item.name == itemname
and not location.locked
and (itemname, world.id) not in always_locations
and location.name not in world.hint_type_overrides['named-item'])
]
if len(locations) > 0:
break
elif world.hint_dist_user['named_items_required'] and (itemname, world.id) not in always_locations:
raise Exception("Unable to hint item {} in world {}".format(itemname, world.id))
else:
logger = logging.getLogger('')
if (itemname, world.id) not in spoiler._cached_always_locations:
logger.info("Hint for item {} in world {} skipped due to Always hint".format(itemname, world.id))
else:
logger.info("Unable to hint item {} in world {}".format(itemname, world.id))
if len(world.named_item_pool) == 0:
return None
location = random.choice(locations)
checked.add(location.name)
item_text = get_hint(get_item_generic_name(location.item), world.settings.clearer_hints).text
hint_area = HintArea.at(location)
if world.hint_dist_user.get('vague_named_items', False):
location_text = hint_area.text(world.settings.clearer_hints, world=location.world.id + 1)
return GossipText('%s may be on the hero\'s path.' % location_text, ['Green'], [location.name], [location.item.name]), [location]
elif hint_area.is_dungeon:
location_text = hint_area.text(world.settings.clearer_hints, world=location.world.id + 1)
return GossipText('%s hoards #%s#.' % (location_text, item_text), ['Red', 'Green'], [location.name], [location.item.name]), [location]
else:
location_text = hint_area.text(world.settings.clearer_hints, preposition=True, world=location.world.id + 1)
return GossipText('#%s# can be found %s.' % (item_text, location_text), ['Green', 'Red'], [location.name], [location.item.name]), [location]
def get_random_location_hint(spoiler: Spoiler, world: World, checked: set[str]) -> HintReturn:
locations = list(filter(lambda location:
is_not_checked([location], checked)
and location.item.type not in ('Drop', 'Event', 'Shop')
and not is_restricted_dungeon_item(location.item)
and not location.locked
and location.name not in world.hint_exclusions
and location.name not in world.hint_type_overrides['item']
and location.item.name not in world.item_hint_type_overrides['item']
and (location.world.settings.empty_dungeons_mode == 'none' or not location.world.empty_dungeons[HintArea.at(location).dungeon_name].empty),
world.get_filled_locations()))
if not locations:
return None
location = random.choice(locations)
checked.add(location.name)
item_text = get_hint(get_item_generic_name(location.item), world.settings.clearer_hints).text
hint_area = HintArea.at(location)
if hint_area.is_dungeon:
location_text = hint_area.text(world.settings.clearer_hints)
return GossipText('%s hoards #%s#.' % (location_text, item_text), ['Red', 'Green'], [location.name], [location.item.name]), [location]
else:
location_text = hint_area.text(world.settings.clearer_hints, preposition=True)
return GossipText('#%s# can be found %s.' % (item_text, location_text), ['Green', 'Red'], [location.name], [location.item.name]), [location]
def get_specific_hint(spoiler: Spoiler, world: World, checked: set[str], hint_type: str) -> HintReturn:
def is_valid_hint(hint: Hint) -> bool:
location = world.get_location(hint.name)
if not is_not_checked([world.get_location(hint.name)], checked):
return False
if location.world.settings.empty_dungeons_mode != 'none' and location.world.empty_dungeons[HintArea.at(location).dungeon_name].empty:
return False
return True
hint_group = get_hint_group(hint_type, world)
hint_group = list(filter(is_valid_hint, hint_group))
if not hint_group:
return None
hint = random.choice(hint_group)
if world.hint_dist_user['upgrade_hints'] in ['on', 'limited']:
upgrade_list = get_upgrade_hint_list(world, [hint.name])
upgrade_list = list(filter(lambda upgrade: is_not_checked([world.get_location(location) for location in get_multi(
upgrade.name).locations], checked), upgrade_list))
if upgrade_list is not None:
multi = None
for upgrade in upgrade_list:
upgrade_multi = get_multi(upgrade.name)
if not multi or len(multi.locations) < len(upgrade_multi.locations):
hint = upgrade
multi = get_multi(hint.name)
if multi:
return get_specific_multi_hint(spoiler, world, checked, hint)