forked from KevinCathcart/ALttPEntranceRandomizer
-
Notifications
You must be signed in to change notification settings - Fork 28
/
DoorShuffle.py
3181 lines (2901 loc) · 157 KB
/
DoorShuffle.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
import RaceRandom as random
from collections import defaultdict, deque
import logging
import time
from enum import unique, Flag
from typing import DefaultDict, Dict, List
from BaseClasses import RegionType, Region, Door, DoorType, Direction, Sector, CrystalBarrier, DungeonInfo, dungeon_keys
from BaseClasses import PotFlags, LocationType
from Doors import reset_portals
from Dungeons import dungeon_regions, region_starts, standard_starts, split_region_starts
from Dungeons import dungeon_bigs, dungeon_hints
from Items import ItemFactory
from RoomData import DoorKind, PairedDoor, reset_rooms
from DungeonGenerator import ExplorationState, convert_regions, generate_dungeon, pre_validate, determine_required_paths, drop_entrances
from DungeonGenerator import create_dungeon_builders, split_dungeon_builder, simple_dungeon_builder, default_dungeon_entrances
from DungeonGenerator import dungeon_portals, dungeon_drops, GenerationException
from DungeonGenerator import valid_region_to_explore as valid_region_to_explore_lim
from KeyDoorShuffle import analyze_dungeon, build_key_layout, validate_key_layout, determine_prize_lock
from Utils import ncr, kth_combination
def link_doors(world, player):
orig_swamp_patch = world.swamp_patch_required[player]
attempt, valid = 1, False
while not valid:
try:
link_doors_main(world, player)
valid = True
except GenerationException as e:
logging.getLogger('').debug(f'Irreconcilable generation. {str(e)} Starting a new attempt.')
attempt += 1
if attempt > 10:
raise Exception('Could not create world in 10 attempts. Generation algorithms need more work', e)
for door in world.doors:
if door.player == player:
door.dest = None
door.entranceFlag = False
ent = door.entrance
if (door.type != DoorType.Logical or door.controller) and ent.connected_region is not None:
ent.connected_region.entrances = [x for x in ent.connected_region.entrances if x != ent]
ent.connected_region = None
for portal in world.dungeon_portals[player]:
disconnect_portal(portal, world, player)
reset_portals(world, player)
reset_rooms(world, player)
world.get_door("Skull Pinball WS", player).no_exit()
world.swamp_patch_required[player] = orig_swamp_patch
link_doors_prep(world, player)
def link_doors_prep(world, player):
# Drop-down connections & push blocks
for exitName, regionName in logical_connections:
connect_simple_door(world, exitName, regionName, player)
# These should all be connected for now as normal connections
for edge_a, edge_b in interior_doors:
connect_interior_doors(edge_a, edge_b, world, player)
# These connections are here because they are currently unable to be shuffled
for exitName, regionName in falldown_pits:
connect_simple_door(world, exitName, regionName, player)
for exitName, regionName in dungeon_warps:
connect_simple_door(world, exitName, regionName, player)
if world.intensity[player] < 2:
for entrance, ext in open_edges:
connect_two_way(world, entrance, ext, player)
for entrance, ext in straight_staircases:
connect_two_way(world, entrance, ext, player)
for entrance, ext in ladders:
connect_two_way(world, entrance, ext, player)
if world.intensity[player] < 3 or world.doorShuffle[player] == 'vanilla':
mirror_route = world.get_entrance('Sanctuary Mirror Route', player)
mr_door = mirror_route.door
sanctuary = mirror_route.parent_region
if mirror_route in sanctuary.exits:
sanctuary.exits.remove(mirror_route)
world.remove_entrance(mirror_route, player)
world.remove_door(mr_door, player)
connect_custom(world, player)
find_inaccessible_regions(world, player)
if world.intensity[player] >= 3 and world.doorShuffle[player] in ['basic', 'crossed']:
choose_portals(world, player)
else:
if world.shuffle[player] == 'vanilla':
if world.mode[player] == 'standard':
world.get_portal('Sanctuary', player).destination = True
world.get_portal('Desert East', player).destination = True
if world.mode[player] == 'inverted':
world.get_portal('Desert West', player).destination = True
else:
world.get_portal('Skull 2 West', player).destination = True
world.get_portal('Turtle Rock Lazy Eyes', player).destination = True
world.get_portal('Turtle Rock Eye Bridge', player).destination = True
else:
analyze_portals(world, player)
for portal in world.dungeon_portals[player]:
connect_portal(portal, world, player)
if not world.doorShuffle[player] == 'vanilla':
fix_big_key_doors_with_ugly_smalls(world, player)
else:
unmark_ugly_smalls(world, player)
if world.doorShuffle[player] == 'vanilla':
for entrance, ext in open_edges:
connect_two_way(world, entrance, ext, player)
for entrance, ext in straight_staircases:
connect_two_way(world, entrance, ext, player)
for exitName, regionName in vanilla_logical_connections:
connect_simple_door(world, exitName, regionName, player)
for entrance, ext in spiral_staircases:
connect_two_way(world, entrance, ext, player)
for entrance, ext in ladders:
connect_two_way(world, entrance, ext, player)
for entrance, ext in default_door_connections:
connect_two_way(world, entrance, ext, player)
for ent, ext in default_one_way_connections:
connect_one_way(world, ent, ext, player)
vanilla_key_logic(world, player)
def link_doors_main(world, player):
if world.doorShuffle[player] == 'basic':
within_dungeon(world, player)
elif world.doorShuffle[player] == 'crossed':
cross_dungeon(world, player)
elif world.doorShuffle[player] != 'vanilla':
logging.getLogger('').error('Invalid door shuffle setting: %s' % world.doorShuffle[player])
raise Exception('Invalid door shuffle setting: %s' % world.doorShuffle[player])
if world.doorShuffle[player] != 'vanilla':
create_door_spoiler(world, player)
# todo: I think this function is not necessary
def mark_regions(world, player):
# traverse dungeons and make sure dungeon property is assigned
player_dungeons = [dungeon for dungeon in world.dungeons if dungeon.player == player]
for dungeon in player_dungeons:
queue = deque(dungeon.regions)
while len(queue) > 0:
region = world.get_region(queue.popleft(), player)
if region.name not in dungeon.regions:
dungeon.regions.append(region.name)
region.dungeon = dungeon
for ext in region.exits:
d = world.check_for_door(ext.name, player)
connected = ext.connected_region
if d is not None and connected is not None:
if d.dest is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue:
queue.append(connected) # needs to be added
elif connected is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue:
queue.append(connected) # needs to be added
def create_door_spoiler(world, player):
logger = logging.getLogger('')
queue = deque(world.dungeon_layouts[player].values())
while len(queue) > 0:
builder = queue.popleft()
done = set()
start_regions = set(convert_regions(builder.layout_starts, world, player)) # todo: set all_entrances for basic
reg_queue = deque(start_regions)
visited = set(start_regions)
while len(reg_queue) > 0:
next = reg_queue.pop()
for ext in next.exits:
door_a = ext.door
connect = ext.connected_region
if door_a and door_a.type in [DoorType.Normal, DoorType.SpiralStairs, DoorType.Open,
DoorType.StraightStairs, DoorType.Ladder] and door_a not in done:
done.add(door_a)
door_b = door_a.dest
if door_b and not isinstance(door_b, Region):
done.add(door_b)
if not door_a.blocked and not door_b.blocked:
world.spoiler.set_door(door_a.name, door_b.name, 'both', player, builder.name)
elif door_a.blocked:
world.spoiler.set_door(door_b.name, door_a.name, 'entrance', player, builder.name)
elif door_b.blocked:
world.spoiler.set_door(door_a.name, door_b.name, 'entrance', player, builder.name)
else:
logger.warning('This is a bug during door spoiler')
elif not isinstance(door_b, Region):
logger.warning('Door not connected: %s', door_a.name)
if connect and connect.type == RegionType.Dungeon and connect not in visited:
visited.add(connect)
reg_queue.append(connect)
def vanilla_key_logic(world, player):
builders = []
world.dungeon_layouts[player] = {}
for dungeon in [dungeon for dungeon in world.dungeons if dungeon.player == player]:
sector = Sector()
sector.name = dungeon.name
sector.regions.extend(convert_regions(dungeon.regions, world, player))
builder = simple_dungeon_builder(sector.name, [sector])
builder.master_sector = sector
builders.append(builder)
world.dungeon_layouts[player][builder.name] = builder
add_inaccessible_doors(world, player)
for builder in builders:
origin_list = find_accessible_entrances(world, player, builder)
start_regions = convert_regions(origin_list, world, player)
doors = convert_key_doors(default_small_key_doors[builder.name], world, player)
key_layout = build_key_layout(builder, start_regions, doors, world, player)
valid = validate_key_layout(key_layout, world, player)
if not valid:
logging.getLogger('').info('Vanilla key layout not valid %s', builder.name)
builder.key_door_proposal = doors
if player not in world.key_logic.keys():
world.key_logic[player] = {}
analyze_dungeon(key_layout, world, player)
world.key_logic[player][builder.name] = key_layout.key_logic
world.key_layout[player][builder.name] = key_layout
log_key_logic(builder.name, key_layout.key_logic)
# if world.shuffle[player] == 'vanilla' and world.accessibility[player] == 'items' and not world.retro[player] and not world.keydropshuffle[player]:
# validate_vanilla_key_logic(world, player)
def validate_vanilla_reservation(dungeon, world, player):
return validate_key_layout(world.key_layout[player][dungeon.name], world, player)
# some useful functions
oppositemap = {
Direction.South: Direction.North,
Direction.North: Direction.South,
Direction.West: Direction.East,
Direction.East: Direction.West,
Direction.Up: Direction.Down,
Direction.Down: Direction.Up,
}
def switch_dir(direction):
return oppositemap[direction]
def convert_key_doors(k_doors, world, player):
result = []
for d in k_doors:
if type(d) is tuple:
result.append((world.get_door(d[0], player), world.get_door(d[1], player)))
else:
result.append(world.get_door(d, player))
return result
def connect_custom(world, player):
if hasattr(world, 'custom_doors') and world.custom_doors[player]:
for entrance, ext in world.custom_doors[player]:
connect_two_way(world, entrance, ext, player)
def connect_simple_door(world, exit_name, region_name, player):
region = world.get_region(region_name, player)
world.get_entrance(exit_name, player).connect(region)
d = world.check_for_door(exit_name, player)
if d is not None:
d.dest = region
def connect_door_only(world, exit_name, region, player):
d = world.check_for_door(exit_name, player)
if d is not None:
d.dest = region
def connect_interior_doors(a, b, world, player):
door_a = world.get_door(a, player)
door_b = world.get_door(b, player)
if door_a.blocked:
connect_one_way(world, b, a, player)
elif door_b.blocked:
connect_one_way(world, a, b, player)
else:
connect_two_way(world, a, b, player)
def connect_two_way(world, entrancename, exitname, player):
entrance = world.get_entrance(entrancename, player)
ext = world.get_entrance(exitname, player)
# if these were already connected somewhere, remove the backreference
if entrance.connected_region is not None:
entrance.connected_region.entrances.remove(entrance)
if ext.connected_region is not None:
ext.connected_region.entrances.remove(ext)
entrance.connect(ext.parent_region)
ext.connect(entrance.parent_region)
if entrance.parent_region.dungeon:
ext.parent_region.dungeon = entrance.parent_region.dungeon
x = world.check_for_door(entrancename, player)
y = world.check_for_door(exitname, player)
if x is not None:
x.dest = y
if y is not None:
y.dest = x
def connect_one_way(world, entrancename, exitname, player):
entrance = world.get_entrance(entrancename, player)
ext = world.get_entrance(exitname, player)
# if these were already connected somewhere, remove the backreference
if entrance.connected_region is not None:
entrance.connected_region.entrances.remove(entrance)
if ext.connected_region is not None:
ext.connected_region.entrances.remove(ext)
entrance.connect(ext.parent_region)
if entrance.parent_region.dungeon:
ext.parent_region.dungeon = entrance.parent_region.dungeon
x = world.check_for_door(entrancename, player)
y = world.check_for_door(exitname, player)
if x is not None:
x.dest = y
if y is not None:
y.dest = x
def unmark_ugly_smalls(world, player):
for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S',
'TR Lava Escape SE', 'GT Hidden Spikes SE']:
door = world.get_door(d, player)
door.smallKey = False
def fix_big_key_doors_with_ugly_smalls(world, player):
remove_ugly_small_key_doors(world, player)
unpair_big_key_doors(world, player)
def remove_ugly_small_key_doors(world, player):
for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S',
'TR Lava Escape SE', 'GT Hidden Spikes SE']:
door = world.get_door(d, player)
room = world.get_room(door.roomIndex, player)
if not door.entranceFlag:
room.change(door.doorListPos, DoorKind.Normal)
door.smallKey = False
door.ugly = False
def unpair_big_key_doors(world, player):
problematic_bk_doors = ['Eastern Courtyard N', 'Eastern Big Key NE', 'Thieves BK Corner NE', 'Mire BK Door Room N',
'TR Dodgers NE', 'GT Dash Hall NE']
for paired_door in world.paired_doors[player]:
if paired_door.door_a in problematic_bk_doors or paired_door.door_b in problematic_bk_doors:
paired_door.pair = False
def pair_existing_key_doors(world, player, door_a, door_b):
already_paired = False
door_names = [door_a.name, door_b.name]
for pd in world.paired_doors[player]:
if pd.door_a in door_names and pd.door_b in door_names:
already_paired = True
break
if already_paired:
return
for paired_door in world.paired_doors[player]:
if paired_door.door_a in door_names or paired_door.door_b in door_names:
paired_door.pair = False
world.paired_doors[player].append(PairedDoor(door_a, door_b))
def choose_portals(world, player):
if world.doorShuffle[player] in ['basic', 'crossed']:
cross_flag = world.doorShuffle[player] == 'crossed'
# key drops allow the big key in the right place in Desert Tiles 2
bk_shuffle = world.bigkeyshuffle[player] or world.pottery[player] not in ['none', 'cave']
std_flag = world.mode[player] == 'standard'
# roast incognito doors
world.get_room(0x60, player).delete(5)
world.get_room(0x60, player).change(2, DoorKind.DungeonEntrance)
world.get_room(0x62, player).delete(5)
world.get_room(0x62, player).change(1, DoorKind.DungeonEntrance)
info_map = {}
for dungeon, portal_list in dungeon_portals.items():
info = DungeonInfo(dungeon)
region_map = defaultdict(list)
reachable_portals = []
inaccessible_portals = []
hc_flag = std_flag and dungeon == 'Hyrule Castle'
for portal in portal_list:
placeholder = world.get_region(portal + ' Portal', player)
portal_region = placeholder.exits[0].connected_region
name = portal_region.name
if portal_region.type == RegionType.LightWorld:
world.get_portal(portal, player).light_world = True
if name in world.inaccessible_regions[player] or (hc_flag and portal != 'Hyrule Castle South'):
name_key = 'Desert Ledge' if name == 'Desert Palace Entrance (North) Spot' else name
region_map[name_key].append(portal)
inaccessible_portals.append(portal)
else:
reachable_portals.append(portal)
info.total = len(portal_list)
info.required_passage = region_map
if len(reachable_portals) == 0:
if len(inaccessible_portals) == 1:
info.sole_entrance = inaccessible_portals[0]
info.required_passage.clear()
else:
raise Exception(f'No reachable entrances for {dungeon}')
if len(reachable_portals) == 1:
info.sole_entrance = reachable_portals[0]
info_map[dungeon] = info
master_door_list = [x for x in world.doors if x.player == player and x.portalAble]
portal_assignment = defaultdict(list)
shuffled_info = list(info_map.items())
if cross_flag:
random.shuffle(shuffled_info)
for dungeon, info in shuffled_info:
outstanding_portals = list(dungeon_portals[dungeon])
hc_flag = std_flag and dungeon == 'Hyrule Castle'
rupee_bow_flag = hc_flag and world.retro[player] # rupee bow
if hc_flag:
sanc = world.get_portal('Sanctuary', player)
sanc.destination = True
clean_up_portal_assignment(portal_assignment, dungeon, sanc, master_door_list, outstanding_portals)
for target_region, possible_portals in info.required_passage.items():
info.required_passage[target_region] = [x for x in possible_portals if x != sanc.name]
info.required_passage = {x: y for x, y in info.required_passage.items() if len(y) > 0}
for target_region, possible_portals in info.required_passage.items():
candidates = find_portal_candidates(master_door_list, dungeon, need_passage=True, crossed=cross_flag,
bk_shuffle=bk_shuffle, rupee_bow=rupee_bow_flag)
choice, portal = assign_portal(candidates, possible_portals, world, player)
portal.destination = True
clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals)
dead_end_choices = info.total - 1 - len(portal_assignment[dungeon])
for i in range(0, dead_end_choices):
candidates = find_portal_candidates(master_door_list, dungeon, dead_end_allowed=True,
crossed=cross_flag, bk_shuffle=bk_shuffle, rupee_bow=rupee_bow_flag)
possible_portals = outstanding_portals if not info.sole_entrance else [x for x in outstanding_portals if x != info.sole_entrance]
choice, portal = assign_portal(candidates, possible_portals, world, player)
if choice.deadEnd:
if choice.passage:
portal.destination = True
else:
portal.deadEnd = True
clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals)
the_rest = info.total - len(portal_assignment[dungeon])
for i in range(0, the_rest):
candidates = find_portal_candidates(master_door_list, dungeon, crossed=cross_flag,
bk_shuffle=bk_shuffle, standard=hc_flag, rupee_bow=rupee_bow_flag)
choice, portal = assign_portal(candidates, outstanding_portals, world, player)
clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals)
for portal in world.dungeon_portals[player]:
connect_portal(portal, world, player)
hc_south = world.get_door('Hyrule Castle Lobby S', player)
if not hc_south.entranceFlag:
world.get_room(0x61, player).delete(6)
world.get_room(0x61, player).change(4, DoorKind.NormalLow)
else:
world.get_room(0x61, player).change(4, DoorKind.DungeonEntrance)
world.get_room(0x61, player).change(6, DoorKind.CaveEntranceLow)
sanctuary_door = world.get_door('Sanctuary S', player)
if not sanctuary_door.entranceFlag:
world.get_room(0x12, player).delete(3)
world.get_room(0x12, player).change(2, DoorKind.NormalLow)
else:
world.get_room(0x12, player).change(2, DoorKind.DungeonEntrance)
world.get_room(0x12, player).change(3, DoorKind.CaveEntranceLow)
hera_door = world.get_door('Hera Lobby S', player)
if not hera_door.entranceFlag:
world.get_room(0x77, player).change(0, DoorKind.NormalLow2)
# tr rock bomb entrances
for portal in world.dungeon_portals[player]:
if not portal.destination and not portal.deadEnd:
if portal.door.name == 'TR Lazy Eyes SE':
world.get_room(0x23, player).change(0, DoorKind.DungeonEntrance)
if portal.door.name == 'TR Eye Bridge SW':
world.get_room(0xd5, player).change(0, DoorKind.DungeonEntrance)
if not world.swamp_patch_required[player]:
swamp_portal = world.get_portal('Swamp', player)
if swamp_portal.door.name != 'Swamp Lobby S':
world.swamp_patch_required[player] = True
def analyze_portals(world, player):
info_map = {}
for dungeon, portal_list in dungeon_portals.items():
info = DungeonInfo(dungeon)
region_map = defaultdict(list)
reachable_portals = []
inaccessible_portals = []
for portal in portal_list:
placeholder = world.get_region(portal + ' Portal', player)
portal_region = placeholder.exits[0].connected_region
name = portal_region.name
if portal_region.type == RegionType.LightWorld:
world.get_portal(portal, player).light_world = True
if name in world.inaccessible_regions[player]:
name_key = 'Desert Ledge' if name == 'Desert Palace Entrance (North) Spot' else name
region_map[name_key].append(portal)
inaccessible_portals.append(portal)
else:
reachable_portals.append(portal)
info.total = len(portal_list)
info.required_passage = region_map
if len(reachable_portals) == 0:
if len(inaccessible_portals) == 1:
info.sole_entrance = inaccessible_portals[0]
info.required_passage.clear()
else:
raise Exception(f'No reachable entrances for {dungeon}')
if len(reachable_portals) == 1:
info.sole_entrance = reachable_portals[0]
if world.intensity[player] < 2 and world.doorShuffle[player] == 'basic' and dungeon == 'Desert Palace':
if len(inaccessible_portals) == 1 and inaccessible_portals[0] == 'Desert Back':
info.required_passage.clear() # can't make a passage at this intensity level, something else must exit
info_map[dungeon] = info
for dungeon, info in info_map.items():
if dungeon == 'Hyrule Castle' and world.mode[player] == 'standard':
sanc = world.get_portal('Sanctuary', player)
sanc.destination = True
for target_region, possible_portals in info.required_passage.items():
if len(possible_portals) == 1:
world.get_portal(possible_portals[0], player).destination = True
elif len(possible_portals) > 1:
dest_portal = random.choice(possible_portals)
access_portal = world.get_portal(dest_portal, player)
access_portal.destination = True
for other_portal in possible_portals:
if other_portal != dest_portal:
world.get_portal(dest_portal, player).dependent = access_portal
def connect_portal(portal, world, player):
ent, ext, entrance_name = portal_map[portal.name]
if world.mode[player] == 'inverted' and portal.name in ['Ganons Tower', 'Agahnims Tower']:
ext = 'Inverted ' + ext
portal_entrance = world.get_entrance(portal.door.entrance.name, player) # ensures I get the right one for copying
target_exit = world.get_entrance(ext, player)
portal_entrance.connected_region = target_exit.parent_region
portal_region = world.get_region(portal.name + ' Portal', player)
portal_region.entrances.append(portal_entrance)
edit_entrance = world.get_entrance(entrance_name, player)
edit_entrance.connected_region = portal_entrance.parent_region
chosen_door = world.get_door(portal_entrance.name, player)
chosen_door.blocked = False
connect_door_only(world, chosen_door, portal_region, player)
portal_entrance.parent_region.entrances.append(edit_entrance)
def disconnect_portal(portal, world, player):
ent, ext, entrance_name = portal_map[portal.name]
portal_entrance = world.get_entrance(portal.door.entrance.name, player)
# portal_region = world.get_region(portal.name + ' Portal', player)
edit_entrance = world.get_entrance(entrance_name, player)
chosen_door = world.get_door(portal_entrance.name, player)
# reverse work
if edit_entrance in portal_entrance.parent_region.entrances:
portal_entrance.parent_region.entrances.remove(edit_entrance)
chosen_door.blocked = chosen_door.blocked_orig
chosen_door.entranceFlag = False
def find_portal_candidates(door_list, dungeon, need_passage=False, dead_end_allowed=False, crossed=False,
bk_shuffle=False, standard=False, rupee_bow=False):
ret = [x for x in door_list if bk_shuffle or not x.bk_shuffle_req]
if crossed:
ret = [x for x in ret if not x.dungeonLink or x.dungeonLink == dungeon or x.dungeonLink.startswith('link')]
else:
ret = [x for x in ret if x.entrance.parent_region.dungeon.name == dungeon]
if need_passage:
ret = [x for x in ret if x.passage]
if not dead_end_allowed:
ret = [x for x in ret if not x.deadEnd]
if standard:
ret = [x for x in ret if not x.standard_restricted]
if rupee_bow:
ret = [x for x in ret if not x.rupee_bow_restricted]
return ret
def assign_portal(candidates, possible_portals, world, player):
candidate = random.choice(candidates)
portal_choice = random.choice(possible_portals)
portal = world.get_portal(portal_choice, player)
while candidate.lw_restricted and not portal.light_world:
candidates.remove(candidate)
candidate = random.choice(candidates)
if candidate != portal.door:
if candidate.entranceFlag:
for other_portal in world.dungeon_portals[player]:
if other_portal.door == candidate:
other_portal.door = None
break
old_door = portal.door
if old_door:
old_door.entranceFlag = False
if old_door.name not in ['Hyrule Castle Lobby S', 'Sanctuary S', 'Hera Lobby S']:
old_door_kind = DoorKind.NormalLow if old_door.layer or old_door.pseudo_bg else DoorKind.Normal
world.get_room(old_door.roomIndex, player).change(old_door.doorListPos, old_door_kind)
portal.change_door(candidate)
if candidate.name not in ['Hyrule Castle Lobby S', 'Sanctuary S']:
if candidate.name == 'Swamp Hub S':
new_door_kind = DoorKind.CaveEntranceLow
elif candidate.layer or candidate.pseudo_bg:
new_door_kind = DoorKind.DungeonEntranceLow
else:
new_door_kind = DoorKind.DungeonEntrance
world.get_room(candidate.roomIndex, player).change(candidate.doorListPos, new_door_kind)
candidate.entranceFlag = True
return candidate, portal
def clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals):
portal_assignment[dungeon].append(portal)
master_door_list[:] = [x for x in master_door_list if x.roomIndex != portal.door.roomIndex]
if portal.door.dungeonLink and portal.door.dungeonLink.startswith('link'):
match_link = portal.door.dungeonLink
for door in master_door_list:
if door.dungeonLink == match_link:
door.dungeonLink = dungeon
outstanding_portals.remove(portal.name)
def create_dungeon_entrances(world, player):
entrance_map = defaultdict(list)
split_map: DefaultDict[str, DefaultDict[str, List]] = defaultdict(lambda: defaultdict(list))
originating: DefaultDict[str, DefaultDict[str, Dict]] = defaultdict(lambda: defaultdict(dict))
for key, portal_list in dungeon_portals.items():
if key in dungeon_drops.keys():
entrance_map[key].extend(dungeon_drops[key])
if key in split_portals.keys():
dead_ends = []
destinations = []
the_rest = []
for portal_name in portal_list:
portal = world.get_portal(portal_name, player)
entrance_map[key].append(portal.door.entrance.parent_region.name)
if portal.deadEnd:
dead_ends.append(portal)
elif portal.destination:
destinations.append(portal)
else:
the_rest.append(portal)
choices = list(split_portals[key])
for portal in dead_ends:
choice = random.choice(choices)
choices.remove(choice)
r_name = portal.door.entrance.parent_region.name
split_map[key][choice].append(r_name)
for portal in the_rest:
if len(choices) == 0:
choices.append('Extra')
choice = random.choice(choices)
p_entrance = portal.door.entrance
r_name = p_entrance.parent_region.name
split_map[key][choice].append(r_name)
entrance_region = find_entrance_region(portal)
originating[key][choice][entrance_region.name] = None
dest_choices = [x for x in choices if len(split_map[key][x]) > 0]
for portal in destinations:
entrance_region = find_entrance_region(portal)
restricted = entrance_region.name in world.inaccessible_regions[player]
if restricted:
filtered_choices = [x for x in choices if any(y not in world.inaccessible_regions[player] for y in originating[key][x].keys())]
else:
filtered_choices = dest_choices
if len(filtered_choices) == 0:
raise Exception('No valid destinations')
choice = random.choice(filtered_choices)
r_name = portal.door.entrance.parent_region.name
split_map[key][choice].append(r_name)
else:
for portal_name in portal_list:
portal = world.get_portal(portal_name, player)
r_name = portal.door.entrance.parent_region.name
entrance_map[key].append(r_name)
return entrance_map, split_map
def find_entrance_region(portal):
for entrance in portal.door.entrance.connected_region.entrances:
if entrance.parent_region.type != RegionType.Dungeon:
return entrance.parent_region
return None
# def unpair_all_doors(world, player):
# for paired_door in world.paired_doors[player]:
# paired_door.pair = False
def within_dungeon(world, player):
add_inaccessible_doors(world, player)
entrances_map, potentials, connections = determine_entrance_list(world, player)
connections_tuple = (entrances_map, potentials, connections)
dungeon_builders = {}
for key in dungeon_regions.keys():
sector_list = convert_to_sectors(dungeon_regions[key], world, player)
dungeon_builders[key] = simple_dungeon_builder(key, sector_list)
dungeon_builders[key].entrance_list = list(entrances_map[key])
recombinant_builders = {}
entrances, splits = create_dungeon_entrances(world, player)
builder_info = entrances, splits, connections_tuple, world, player
handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info)
main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player)
paths = determine_required_paths(world, player)
check_required_paths(paths, world, player)
# shuffle_key_doors for dungeons
logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors"))
start = time.process_time()
for builder in world.dungeon_layouts[player].values():
shuffle_key_doors(builder, world, player)
logging.getLogger('').info('%s: %s', world.fish.translate("cli", "cli", "keydoor.shuffle.time"), time.process_time()-start)
smooth_door_pairs(world, player)
if world.intensity[player] >= 3:
portal = world.get_portal('Sanctuary', player)
target = portal.door.entrance.parent_region
connect_simple_door(world, 'Sanctuary Mirror Route', target, player)
refine_boss_exits(world, player)
def handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info):
dungeon_entrances, split_dungeon_entrances, c_tuple, world, player = builder_info
if dungeon_entrances is None:
dungeon_entrances = default_dungeon_entrances
if split_dungeon_entrances is None:
split_dungeon_entrances = split_region_starts
builder_info = dungeon_entrances, split_dungeon_entrances, c_tuple, world, player
for name, split_list in split_dungeon_entrances.items():
builder = dungeon_builders.pop(name)
recombinant_builders[name] = builder
split_builders = split_dungeon_builder(builder, split_list, builder_info)
dungeon_builders.update(split_builders)
for sub_name, split_entrances in split_list.items():
key = name+' '+sub_name
if key not in dungeon_builders:
continue
sub_builder = dungeon_builders[key]
sub_builder.split_flag = True
entrance_list = list(split_entrances)
for ent in entrances_map[name]:
add_shuffled_entrances(sub_builder.sectors, ent, entrance_list)
filtered_entrance_list = [x for x in entrance_list if x in entrances_map[name]]
sub_builder.entrance_list = filtered_entrance_list
def main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player):
entrances_map, potentials, connections = connections_tuple
enabled_entrances = world.enabled_entrances[player] = {}
sector_queue = deque(dungeon_builders.values())
last_key, loops = None, 0
logging.getLogger('').info(world.fish.translate("cli", "cli", "generating.dungeon"))
while len(sector_queue) > 0:
builder = sector_queue.popleft()
split_dungeon = builder.name.startswith('Desert Palace') or builder.name.startswith('Skull Woods')
name = builder.name
if split_dungeon:
name = ' '.join(builder.name.split(' ')[:-1])
if len(builder.sectors) == 0:
del dungeon_builders[builder.name]
continue
origin_list = list(builder.entrance_list)
find_enabled_origins(builder.sectors, enabled_entrances, origin_list, entrances_map, name)
split_dungeon = treat_split_as_whole_dungeon(split_dungeon, name, origin_list, world, player)
if len(origin_list) <= 0 or not pre_validate(builder, origin_list, split_dungeon, world, player):
if last_key == builder.name or loops > 1000:
origin_name = world.get_region(origin_list[0], player).entrances[0].parent_region.name if len(origin_list) > 0 else 'no origin'
raise GenerationException(f'Infinite loop detected for "{builder.name}" located at {origin_name}')
sector_queue.append(builder)
last_key = builder.name
loops += 1
else:
ds = generate_dungeon(builder, origin_list, split_dungeon, world, player)
find_new_entrances(ds, entrances_map, connections, potentials, enabled_entrances, world, player)
ds.name = name
builder.master_sector = ds
builder.layout_starts = origin_list if len(builder.entrance_list) <= 0 else builder.entrance_list
last_key = None
combine_layouts(recombinant_builders, dungeon_builders, entrances_map)
world.dungeon_layouts[player] = {}
for builder in dungeon_builders.values():
builder.entrance_list = builder.layout_starts = builder.path_entrances = find_accessible_entrances(world, player, builder)
world.dungeon_layouts[player] = dungeon_builders
def determine_entrance_list_vanilla(world, player):
entrance_map = {}
potential_entrances = {}
connections = {}
for key, r_names in region_starts.items():
entrance_map[key] = []
if world.mode[player] == 'standard' and key in standard_starts.keys():
r_names = ['Hyrule Castle Lobby']
for region_name in r_names:
region = world.get_region(region_name, player)
for ent in region.entrances:
parent = ent.parent_region
if (parent.type != RegionType.Dungeon and parent.name != 'Menu') or parent.name == 'Sewer Drop':
if parent.name not in world.inaccessible_regions[player]:
entrance_map[key].append(region_name)
else:
if ent.parent_region not in potential_entrances.keys():
potential_entrances[parent] = []
potential_entrances[parent].append(region_name)
connections[region_name] = parent
return entrance_map, potential_entrances, connections
def determine_entrance_list(world, player):
entrance_map = {}
potential_entrances = {}
connections = {}
for key, portal_list in dungeon_portals.items():
entrance_map[key] = []
r_names = {}
if key in dungeon_drops.keys():
for drop in dungeon_drops[key]:
r_names[drop] = None
for portal_name in portal_list:
portal = world.get_portal(portal_name, player)
r_names[portal.door.entrance.parent_region.name] = portal
for region_name, portal in r_names.items():
if portal:
region = world.get_region(portal.name + ' Portal', player)
else:
region = world.get_region(region_name, player)
for ent in region.entrances:
parent = ent.parent_region
if (parent.type != RegionType.Dungeon and parent.name != 'Menu') or parent.name == 'Sewer Drop':
std_inaccessible = is_standard_inaccessible(key, portal, world, player)
if parent.name not in world.inaccessible_regions[player] and not std_inaccessible:
entrance_map[key].append(region_name)
else:
if parent not in potential_entrances.keys():
potential_entrances[parent] = []
if region_name not in potential_entrances[parent]:
potential_entrances[parent].append(region_name)
connections[region_name] = parent
return entrance_map, potential_entrances, connections
def is_standard_inaccessible(key, portal, world, player):
return world.mode[player] == 'standard' and key in standard_starts and (not portal or portal.name not in standard_starts[key])
def add_shuffled_entrances(sectors, region_list, entrance_list):
for sector in sectors:
for region in sector.regions:
if region.name in region_list and region.name not in entrance_list:
entrance_list.append(region.name)
def find_enabled_origins(sectors, enabled, entrance_list, entrance_map, key):
for sector in sectors:
for region in sector.regions:
if region.name in enabled.keys() and region.name not in entrance_list:
entrance_list.append(region.name)
origin_reg, origin_dungeon = enabled[region.name]
if origin_reg != region.name and origin_dungeon != region.dungeon:
if key not in entrance_map.keys():
key = ' '.join(key.split(' ')[:-1])
entrance_map[key].append(region.name)
def find_new_entrances(sector, entrances_map, connections, potentials, enabled, world, player):
for region in sector.regions:
if region.name in connections.keys() and (connections[region.name] in potentials.keys() or connections[region.name].name in world.inaccessible_regions[player]):
enable_new_entrances(region, connections, potentials, enabled, world, player, region)
inverted_aga_check(entrances_map, connections, potentials, enabled, world, player)
def enable_new_entrances(region, connections, potentials, enabled, world, player, region_enabler):
new_region = connections[region.name]
if new_region in potentials.keys():
for potential in potentials.pop(new_region):
enabled[potential] = (region_enabler.name, region_enabler.dungeon)
# see if this unexplored region connects elsewhere
queue = deque(new_region.exits)
visited = set()
while len(queue) > 0:
ext = queue.popleft()
visited.add(ext)
region_name = ext.connected_region.name
if region_name in connections.keys() and connections[region_name] in potentials.keys():
for potential in potentials.pop(connections[region_name]):
enabled[potential] = (region.name, region.dungeon)
if ext.connected_region.name in world.inaccessible_regions[player] or ext.connected_region.name.endswith(' Portal'):
for new_exit in ext.connected_region.exits:
if new_exit not in visited:
queue.append(new_exit)
def inverted_aga_check(entrances_map, connections, potentials, enabled, world, player):
if world.mode[player] == 'inverted':
if 'Agahnims Tower' in entrances_map.keys() or aga_tower_enabled(enabled):
for region in list(potentials.keys()):
if region.name == 'Hyrule Castle Ledge':
enabler = world.get_region('Tower Agahnim 1', player)
for r_name in potentials[region]:
new_region = world.get_region(r_name, player)
enable_new_entrances(new_region, connections, potentials, enabled, world, player, enabler)
def aga_tower_enabled(enabled):
for region_name, enabled_tuple in enabled.items():
entrance, dungeon = enabled_tuple
if dungeon.name == 'Agahnims Tower':
return True
return False
def treat_split_as_whole_dungeon(split_dungeon, name, origin_list, world, player):
# what about ER dungeons? - find an example? (bad key doors 0 keys not valid)
if split_dungeon and name in multiple_portal_map:
possible_entrances = []
for portal_name in multiple_portal_map[name]:
portal = world.get_portal(portal_name, player)
portal_entrance = world.get_entrance(portal_map[portal_name][0], player)
if not portal.destination and portal_entrance.parent_region.name not in world.inaccessible_regions[player]:
possible_entrances.append(portal)
if len(possible_entrances) == 1:
single_portal = possible_entrances[0]
if single_portal.door.entrance.parent_region.name in origin_list and len(origin_list) == 1:
return False
return split_dungeon
# goals:
# 1. have enough chests to be interesting (2 more than dungeon items)
# 2. have a balanced amount of regions added (check)
# 3. prevent soft locks due to key usage (algorithm written)
# 4. rules in place to affect item placement (lamp, keys, etc. -- in rules)
# 5. to be complete -- all doors linked (check, somewhat)
# 6. avoid deadlocks/dead end dungeon (check)
# 7. certain paths through dungeon must be possible - be able to reach goals (check)
def cross_dungeon(world, player):
add_inaccessible_doors(world, player)
entrances_map, potentials, connections = determine_entrance_list(world, player)
connections_tuple = (entrances_map, potentials, connections)
all_sectors, all_regions = [], []
for key in dungeon_regions.keys():
all_regions += dungeon_regions[key]
all_sectors.extend(convert_to_sectors(all_regions, world, player))
merge_sectors(all_sectors, world, player)
entrances, splits = create_dungeon_entrances(world, player)
dungeon_builders = create_dungeon_builders(all_sectors, connections_tuple, world, player, entrances, splits)
for builder in dungeon_builders.values():
builder.entrance_list = list(entrances_map[builder.name])
dungeon_obj = world.get_dungeon(builder.name, player)
for sector in builder.sectors:
for region in sector.regions:
region.dungeon = dungeon_obj
for loc in region.locations:
if loc.forced_item:
key_name = dungeon_keys[builder.name] if loc.name != 'Hyrule Castle - Big Key Drop' else dungeon_bigs[builder.name]
loc.forced_item = loc.item = ItemFactory(key_name, player)
recombinant_builders = {}
builder_info = entrances, splits, connections_tuple, world, player
handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info)
main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player)
paths = determine_required_paths(world, player)
check_required_paths(paths, world, player)
hc_compass = ItemFactory('Compass (Escape)', player)
at_compass = ItemFactory('Compass (Agahnims Tower)', player)
at_map = ItemFactory('Map (Agahnims Tower)', player)
if world.restrict_boss_items[player] != 'none':
hc_compass.advancement = at_compass.advancement = at_map.advancement = True
hc = world.get_dungeon('Hyrule Castle', player)
hc.dungeon_items.append(hc_compass)
at = world.get_dungeon('Agahnims Tower', player)
at.dungeon_items.append(at_compass)
at.dungeon_items.append(at_map)