forked from ArchipelagoMW/Archipelago
- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBaseClasses.py
More file actions
Latest commit
1997 lines (1658 loc) · 90.2 KB
/
Copy pathBaseClasses.py
File metadata and controls
1997 lines (1658 loc) · 90.2 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
from __future__ importannotations
importcollections
importfunctools
importlogging
importrandom
importsecrets
importwarnings
fromargparseimportNamespace
fromcollectionsimportCounter, deque, defaultdict
fromcollections.abcimportCallable, Collection, Iterable, Iterator, Mapping, MutableSequence, Set
fromenumimportIntEnum, IntFlag
fromtypingimport (AbstractSet, Any, ClassVar, Dict, List, Literal, NamedTuple,
Optional, Protocol, Tuple, Union, TYPE_CHECKING, overload)
importdataclasses
fromtyping_extensionsimportNotRequired, TypedDict
importNetUtils
importOptions
importUtils
ifTYPE_CHECKING:
fromentrance_randoimportERPlacementState
fromrule_builder.rulesimportRule
fromworldsimportAutoWorld
classGroup(TypedDict):
name: str
game: str
world: "AutoWorld.World"
players: AbstractSet[int]
item_pool: NotRequired[Set[str]]
replacement_items: NotRequired[Dict[int, Optional[str]]]
local_items: NotRequired[Set[str]]
non_local_items: NotRequired[Set[str]]
link_replacement: NotRequired[bool]
classThreadBarrierProxy:
"""Passes through getattr while passthrough is True"""
def__init__(self, obj: object) ->None:
self.passthrough=True
self.obj=obj
def__getattr__(self, name: str) ->Any:
ifself.passthrough:
returngetattr(self.obj, name)
else:
raiseRuntimeError("You are in a threaded context and global random state was removed for your safety. "
"Please use multiworld.per_slot_randoms[player] or randomize ahead of output.")
classHasNameAndPlayer(Protocol):
name: str
player: int
@dataclasses.dataclass
classPlandoItemBlock:
player: int
from_pool: bool
force: bool|Literal["silent"]
worlds: set[int] =dataclasses.field(default_factory=set)
items: list[str] =dataclasses.field(default_factory=list)
locations: list[str] =dataclasses.field(default_factory=list)
resolved_locations: list[Location] =dataclasses.field(default_factory=list)
count: dict[str, int] =dataclasses.field(default_factory=dict)
classMultiWorld():
debug_types=False
player_name: Dict[int, str]
worlds: Dict[int, "AutoWorld.World"]
groups: Dict[int, Group]
regions: RegionManager
itempool: List[Item]
is_race: bool=False
precollected_items: Dict[int, List[Item]]
state: CollectionState
plando_options: PlandoOptions
early_items: Dict[int, Dict[str, int]]
local_early_items: Dict[int, Dict[str, int]]
local_items: Dict[int, Options.LocalItems]
non_local_items: Dict[int, Options.NonLocalItems]
progression_balancing: Dict[int, Options.ProgressionBalancing]
completion_condition: Dict[int, CollectionRule]
indirect_connections: Dict[Region, Set[Entrance]]
exclude_locations: Dict[int, Options.ExcludeLocations]
priority_locations: Dict[int, Options.PriorityLocations]
start_inventory: Dict[int, Options.StartInventory]
start_hints: Dict[int, Options.StartHints]
start_location_hints: Dict[int, Options.StartLocationHints]
item_links: Dict[int, Options.ItemLinks]
plando_item_blocks: Dict[int, List[PlandoItemBlock]]
game: Dict[int, str]
random: random.Random
per_slot_randoms: Utils.DeprecateDict[int, random.Random]
"""Deprecated. Please use `self.random` instead."""
classAttributeProxy():
def__init__(self, rule):
self.rule=rule
def__getitem__(self, player) ->bool:
returnself.rule(player)
classRegionManager:
region_cache: Dict[int, Dict[str, Region]]
entrance_cache: Dict[int, Dict[str, Entrance]]
location_cache: Dict[int, Dict[str, Location]]
def__init__(self, players: int):
self.region_cache= {player: {} forplayerinrange(1, players+1)}
self.entrance_cache= {player: {} forplayerinrange(1, players+1)}
self.location_cache= {player: {} forplayerinrange(1, players+1)}
def__iadd__(self, other: Iterable[Region]):
self.extend(other)
returnself
defappend(self, region: Region):
assertregion.namenotinself.region_cache[region.player], \
f"{region.name} already exists in region cache."
self.region_cache[region.player][region.name] =region
defextend(self, regions: Iterable[Region]):
forregioninregions:
assertregion.namenotinself.region_cache[region.player], \
f"{region.name} already exists in region cache."
self.region_cache[region.player][region.name] =region
defadd_group(self, new_id: int):
self.region_cache[new_id] = {}
self.entrance_cache[new_id] = {}
self.location_cache[new_id] = {}
def__iter__(self) ->Iterator[Region]:
forregionsinself.region_cache.values():
yieldfromregions.values()
def__len__(self):
returnsum(len(regions) forregionsinself.region_cache.values())
def__init__(self, players: int):
# world-local random state is saved for multiple generations running concurrently
self.random=ThreadBarrierProxy(random.Random())
self.players=players
self.player_types= {player: NetUtils.SlotType.playerforplayerinself.player_ids}
self.algorithm='balanced'
self.groups= {}
self.regions=self.RegionManager(players)
self.itempool= []
self.seed=None
self.seed_name: str="Unavailable"
self.precollected_items= {player: [] forplayerinself.player_ids}
self.required_locations= []
self.custom=False
self.customitemarray= []
self.shuffle_ganon=True
self.spoiler=Spoiler(self)
self.early_items= {player: {} forplayerinself.player_ids}
self.local_early_items= {player: {} forplayerinself.player_ids}
self.indirect_connections= {}
self.start_inventory_from_pool: Dict[int, Options.StartInventoryPool] = {}
self.plando_item_blocks= {}
forplayerinrange(1, players+1):
defset_player_attr(attr: str, val) ->None:
self.__dict__.setdefault(attr, {})[player] =val
set_player_attr('plando_item_blocks', [])
set_player_attr('game', "Archipelago")
set_player_attr('completion_condition', lambdastate: True)
self.worlds= {}
self.per_slot_randoms=Utils.DeprecateDict("Using per_slot_randoms is now deprecated. Please use the "
"world's random object instead (usually self.random)", True)
self.plando_options=PlandoOptions.none
defget_all_ids(self) ->Tuple[int, ...]:
returnself.player_ids+tuple(self.groups)
defadd_group(self, name: str, game: str, players: AbstractSet[int] =frozenset()) ->Tuple[int, Group]:
"""Create a group with name and return the assigned player ID and group.
If a group of this name already exists, the set of players is extended instead of creating a new one."""
fromworldsimportAutoWorld
forgroup_id, groupinself.groups.items():
ifgroup["name"] ==name:
group["players"] |=players
returngroup_id, group
new_id: int=self.players+len(self.groups) +1
self.regions.add_group(new_id)
self.game[new_id] =game
self.player_types[new_id] =NetUtils.SlotType.group
world_type=AutoWorld.AutoWorldRegister.world_types[game]
self.worlds[new_id] =world_type.create_group(self, new_id, players)
self.worlds[new_id].collect_item=AutoWorld.World.collect_item.__get__(self.worlds[new_id])
self.worlds[new_id].collect=AutoWorld.World.collect.__get__(self.worlds[new_id])
self.worlds[new_id].remove=AutoWorld.World.remove.__get__(self.worlds[new_id])
self.player_name[new_id] =name
new_group=self.groups[new_id] =Group(name=name, game=game, players=players,
world=self.worlds[new_id])
returnnew_id, new_group
defget_player_groups(self, player: int) ->Set[int]:
return {group_idforgroup_id, groupinself.groups.items() ifplayeringroup["players"]}
defset_seed(self, seed: Optional[int] =None, secure: bool=False, name: Optional[str] =None):
assertnotself.worlds, "seed needs to be initialized before Worlds"
self.seed=get_seed(seed)
ifsecure:
self.secure()
else:
self.random.seed(self.seed)
self.seed_name=nameifnameelsestr(self.seed)
defset_options(self, args: Namespace) ->None:
fromworldsimportAutoWorld
forplayerinself.player_ids:
world_type=AutoWorld.AutoWorldRegister.world_types[self.game[player]]
self.worlds[player] =world_type(self, player)
options_dataclass: type[Options.PerGameCommonOptions] =world_type.options_dataclass
self.worlds[player].options=options_dataclass(**{option_key: getattr(args, option_key)[player]
foroption_keyinoptions_dataclass.type_hints})
defset_item_links(self):
fromworldsimportAutoWorld
item_links= {}
replacement_prio= [False, True, None]
forplayerinself.player_ids:
foritem_linkinself.worlds[player].options.item_links.value:
ifitem_link["name"] initem_links:
ifitem_links[item_link["name"]]["game"] !=self.game[player]:
raiseException(f"Cannot ItemLink across games. Link: {item_link['name']}")
current_link=item_links[item_link["name"]]
current_link["players"][player] =item_link["replacement_item"]
current_link["item_pool"] &=set(item_link["item_pool"])
current_link["exclude"] |=set(item_link.get("exclude", []))
current_link["local_items"] &=set(item_link.get("local_items", []))
current_link["non_local_items"] &=set(item_link.get("non_local_items", []))
current_link["link_replacement"] =min(current_link["link_replacement"],
replacement_prio.index(item_link["link_replacement"]))
else:
ifitem_link["name"] inself.player_name.values():
raiseException(f"Cannot name a ItemLink group the same as a player ({item_link['name']}) "
f"({self.get_player_name(player)}).")
item_links[item_link["name"]] = {
"players": {player: item_link["replacement_item"]},
"item_pool": set(item_link["item_pool"]),
"exclude": set(item_link.get("exclude", [])),
"game": self.game[player],
"local_items": set(item_link.get("local_items", [])),
"non_local_items": set(item_link.get("non_local_items", [])),
"link_replacement": replacement_prio.index(item_link["link_replacement"]),
"skip_if_solo": item_link.get("skip_if_solo", False),
}
for_name, item_linkinitem_links.items():
current_item_name_groups=AutoWorld.AutoWorldRegister.world_types[item_link["game"]].item_name_groups
pool=set()
local_items=set()
non_local_items=set()
foriteminitem_link["item_pool"]:
pool|=current_item_name_groups.get(item, {item})
foriteminitem_link["exclude"]:
pool-=current_item_name_groups.get(item, {item})
foriteminitem_link["local_items"]:
local_items|=current_item_name_groups.get(item, {item})
foriteminitem_link["non_local_items"]:
non_local_items|=current_item_name_groups.get(item, {item})
local_items&=pool
non_local_items&=pool
item_link["item_pool"] =pool
item_link["local_items"] =local_items
item_link["non_local_items"] =non_local_items
forgroup_name, item_linkinitem_links.items():
game=item_link["game"]
ifitem_link["skip_if_solo"] andlen(item_link["players"]) ==1:
continue
group_id, group=self.add_group(group_name, game, set(item_link["players"]))
group["item_pool"] =item_link["item_pool"]
group["replacement_items"] =item_link["players"]
group["local_items"] =item_link["local_items"]
group["non_local_items"] =item_link["non_local_items"]
group["link_replacement"] =replacement_prio[item_link["link_replacement"]]
deflink_items(self) ->None:
"""Called to link together items in the itempool related to the registered item link groups."""
fromworldsimportAutoWorld
forgroup_id, groupinself.groups.items():
deffind_common_pool(players: Set[int], shared_pool: Set[str]) ->Tuple[
Optional[Dict[int, Dict[str, int]]], Optional[Dict[str, int]]
]:
classifications: Dict[str, int] =collections.defaultdict(int)
counters= {player: {name: 0fornameinshared_pool} forplayerinplayers}
foriteminself.itempool:
ifitem.playerincountersanditem.nameinshared_pool:
counters[item.player][item.name] +=1
classifications[item.name] |=item.classification
forplayerinplayers.copy():
ifall([counters[player][item] ==0foriteminshared_pool]):
players.remove(player)
del (counters[player])
ifnotplayers:
returnNone, None
foriteminshared_pool:
count=min(counters[player][item] forplayerinplayers)
ifcount:
forplayerinplayers:
counters[player][item] =count
else:
forplayerinplayers:
del (counters[player][item])
returncounters, classifications
common_item_count, classifications=find_common_pool(group["players"], group["item_pool"])
ifnotcommon_item_count:
continue
new_itempool: List[Item] = []
foritem_name, item_countinnext(iter(common_item_count.values())).items():
for_inrange(item_count):
new_item=group["world"].create_item(item_name)
# mangle together all original classification bits
new_item.classification|=classifications[item_name]
new_itempool.append(new_item)
region=Region(group["world"].origin_region_name, group_id, self, "ItemLink")
self.regions.append(region)
locations=region.locations
# ensure that progression items are linked first, then non-progression
self.itempool.sort(key=lambdaitem: item.advancement)
foriteminself.itempool:
count=common_item_count.get(item.player, {}).get(item.name, 0)
ifcount:
loc=Location(group_id, f"Item Link: {item.name} -> {self.player_name[item.player]}{count}",
None, region)
loc.access_rule=lambdastate, item_name=item.name, group_id_=group_id, count_=count: \
state.has(item_name, group_id_, count_)
locations.append(loc)
loc.place_locked_item(item)
common_item_count[item.player][item.name] -=1
else:
new_itempool.append(item)
itemcount=len(self.itempool)
self.itempool=new_itempool
whileitemcount>len(self.itempool):
items_to_add= []
forplayeringroup["players"]:
ifgroup["link_replacement"]:
item_player=group_id
else:
item_player=player
ifgroup["replacement_items"][player]:
items_to_add.append(AutoWorld.call_single(self, "create_item", item_player,
group["replacement_items"][player]))
else:
items_to_add.append(AutoWorld.call_single(self, "create_filler", item_player))
self.random.shuffle(items_to_add)
self.itempool.extend(items_to_add[:itemcount-len(self.itempool)])
defsecure(self):
self.random=ThreadBarrierProxy(secrets.SystemRandom())
self.is_race=True
@functools.cached_property
defplayer_ids(self) ->Tuple[int, ...]:
returntuple(range(1, self.players+1))
@Utils.cache_self1
defget_game_players(self, game_name: str) ->Tuple[int, ...]:
returntuple(playerforplayerinself.player_idsifself.game[player] ==game_name)
@Utils.cache_self1
defget_game_groups(self, game_name: str) ->Tuple[int, ...]:
returntuple(group_idforgroup_idinself.groupsifself.game[group_id] ==game_name)
@Utils.cache_self1
defget_game_worlds(self, game_name: str):
returntuple(worldforplayer, worldinself.worlds.items() if
playernotinself.groupsandself.game[player] ==game_name)
defget_name_string_for_object(self, obj: HasNameAndPlayer) ->str:
returnobj.nameifself.players==1elsef'{obj.name} ({self.get_player_name(obj.player)})'
defget_player_name(self, player: int) ->str:
returnself.player_name[player]
defget_file_safe_player_name(self, player: int) ->str:
returnUtils.get_file_safe_name(self.get_player_name(player))
defget_out_file_name_base(self, player: int) ->str:
""" the base name (without file extension) for each player's output file for a seed """
returnf"AP_{self.seed_name}_P{player}_{self.get_file_safe_player_name(player).replace(' ', '_')}"
@functools.cached_property
defworld_name_lookup(self):
return {self.player_name[player_id]: player_idforplayer_idinself.player_ids}
defget_regions(self, player: Optional[int] =None) ->Collection[Region]:
returnself.regionsifplayerisNoneelseself.regions.region_cache[player].values()
defget_region(self, region_name: str, player: int) ->Region:
returnself.regions.region_cache[player][region_name]
defget_entrance(self, entrance_name: str, player: int) ->Entrance:
returnself.regions.entrance_cache[player][entrance_name]
defget_location(self, location_name: str, player: int) ->Location:
returnself.regions.location_cache[player][location_name]
defget_all_state(self, use_cache: bool|None=None, allow_partial_entrances: bool=False,
collect_pre_fill_items: bool=True, perform_sweep: bool=True) ->CollectionState:
"""
Creates a new CollectionState, and collects all precollected items, all items in the multiworld itempool, those
specified in each worlds' `get_pre_fill_items()`, and then sweeps the multiworld collecting any other items
it is able to reach, building as complete of a completed game state as possible.
:param use_cache: Deprecated and unused.
:param allow_partial_entrances: Whether the CollectionState should allow for disconnected entrances while
sweeping, such as before entrance randomization is complete.
:param collect_pre_fill_items: Whether the items in each worlds' `get_pre_fill_items()` should be added to this
state.
:param perform_sweep: Whether this state should perform a sweep for reachable locations, collecting any placed
items it can.
:return: The completed CollectionState.
"""
if__debug__anduse_cacheisnotNone:
# TODO swap to Utils.deprecate when we want this to crash on source and warn on frozen
warnings.warn("multiworld.get_all_state no longer caches all_state and this argument will be removed.",
DeprecationWarning)
ret=CollectionState(self, allow_partial_entrances)
foriteminself.itempool:
self.worlds[item.player].collect(ret, item)
ifcollect_pre_fill_items:
forplayerinself.player_ids:
subworld=self.worlds[player]
foriteminsubworld.get_pre_fill_items():
subworld.collect(ret, item)
ifperform_sweep:
ret.sweep_for_advancements()
returnret
defget_items(self) ->List[Item]:
return [loc.itemforlocinself.get_filled_locations()] +self.itempool
deffind_item_locations(self, item: str, player: int, resolve_group_locations: bool=False) ->List[Location]:
ifresolve_group_locations:
player_groups=self.get_player_groups(player)
return [locationforlocationinself.get_locations() if
location.itemandlocation.item.name==itemandlocation.playernotinplayer_groupsand
(location.item.player==playerorlocation.item.playerinplayer_groups)]
return [locationforlocationinself.get_locations() if
location.itemandlocation.item.name==itemandlocation.item.player==player]
deffind_item(self, item: str, player: int) ->Location:
returnnext(locationforlocationinself.get_locations() if
location.itemandlocation.item.name==itemandlocation.item.player==player)
deffind_items_in_locations(self, items: Set[str], player: int, resolve_group_locations: bool=False) ->List[Location]:
ifresolve_group_locations:
player_groups=self.get_player_groups(player)
return [locationforlocationinself.get_locations() if
location.itemandlocation.item.nameinitemsandlocation.playernotinplayer_groupsand
(location.item.player==playerorlocation.item.playerinplayer_groups)]
return [locationforlocationinself.get_locations() if
location.itemandlocation.item.nameinitemsandlocation.item.player==player]
defcreate_item(self, item_name: str, player: int) ->Item:
returnself.worlds[player].create_item(item_name)
defpush_precollected(self, item: Item):
self.precollected_items[item.player].append(item)
self.state.collect(item, True)
defpush_item(self, location: Location, item: Item, collect: bool=True):
location.item=item
item.location=location
ifcollect:
self.state.collect(item, location.advancement, location)
logging.debug('Placed %s at %s', item, location)
defget_entrances(self, player: Optional[int] =None) ->Iterable[Entrance]:
ifplayerisnotNone:
returnself.regions.entrance_cache[player].values()
returnUtils.RepeatableChain(tuple(self.regions.entrance_cache[player].values()
forplayerinself.regions.entrance_cache))
defregister_indirect_condition(self, region: Region, entrance: Entrance):
"""Report that access to this Region can result in unlocking this Entrance,
state.can_reach(Region) in the Entrance's traversal condition, as opposed to pure transition logic."""
self.indirect_connections.setdefault(region, set()).add(entrance)
defget_locations(self, player: Optional[int] =None) ->Iterable[Location]:
ifplayerisnotNone:
returnself.regions.location_cache[player].values()
returnUtils.RepeatableChain(tuple(self.regions.location_cache[player].values()
forplayerinself.regions.location_cache))
defget_unfilled_locations(self, player: Optional[int] =None) ->List[Location]:
return [locationforlocationinself.get_locations(player) iflocation.itemisNone]
defget_filled_locations(self, player: Optional[int] =None) ->List[Location]:
return [locationforlocationinself.get_locations(player) iflocation.itemisnotNone]
defget_reachable_locations(self, state: Optional[CollectionState] =None, player: Optional[int] =None) ->List[Location]:
state: CollectionState=stateifstateelseself.state
return [locationforlocationinself.get_locations(player) iflocation.can_reach(state)]
defget_placeable_locations(self, state=None, player=None) ->List[Location]:
state: CollectionState=stateifstateelseself.state
return [locationforlocationinself.get_locations(player) iflocation.itemisNoneandlocation.can_reach(state)]
defget_unfilled_locations_for_players(self, location_names: List[str], players: Iterable[int]):
forplayerinplayers:
ifnotlocation_names:
valid_locations= [location.nameforlocationinself.get_unfilled_locations(player)]
else:
valid_locations=location_names
relevant_cache=self.regions.location_cache[player]
forlocation_nameinvalid_locations:
location=relevant_cache.get(location_name, None)
iflocationandlocation.itemisNone:
yieldlocation
defunlocks_new_location(self, item: Item) ->bool:
temp_state=self.state.copy()
temp_state.collect(item, True)
forlocationinself.get_unfilled_locations(item.player):
iftemp_state.can_reach(location) andnotself.state.can_reach(location):
returnTrue
returnFalse
defhas_beaten_game(self, state: CollectionState, player: Optional[int] =None) ->bool:
ifplayer:
returnself.completion_condition[player](state)
else:
returnall((self.has_beaten_game(state, p) forpinrange(1, self.players+1)))
defcan_beat_game(self,
starting_state: Optional[CollectionState] =None,
locations: Optional[Iterable[Location]] =None) ->bool:
ifstarting_state:
ifself.has_beaten_game(starting_state):
returnTrue
state=starting_state.copy()
else:
state=CollectionState(self)
ifself.has_beaten_game(state):
returnTrue
for_instate.sweep_for_advancements(locations,
yield_each_sweep=True,
checked_locations=state.locations_checked):
ifself.has_beaten_game(state):
returnTrue
returnFalse
defget_spheres(self) ->Iterator[Set[Location]]:
"""
yields a set of locations for each logical sphere
If there are unreachable locations, the last sphere of reachable
locations is followed by an empty set, and then a set of all of the
unreachable locations.
"""
state=CollectionState(self)
locations=set(self.get_filled_locations())
whilelocations:
sphere: Set[Location] =set()
forlocationinlocations:
iflocation.can_reach(state):
sphere.add(location)
yieldsphere
ifnotsphere:
iflocations:
yieldlocations# unreachable locations
break
forlocationinsphere:
state.collect(location.item, True, location)
locations-=sphere
defget_sendable_spheres(self) ->Iterator[Set[Location]]:
"""
yields a set of multiserver sendable locations (location.item.code: int) for each logical sphere
If there are unreachable locations, the last sphere of reachable locations is followed by an empty set,
and then a set of all of the unreachable locations.
"""
state=CollectionState(self)
locations: Set[Location] =set()
events: Set[Location] =set()
forlocationinself.get_filled_locations():
iftype(location.item.code) isintandtype(location.address) isint:
locations.add(location)
else:
events.add(location)
whilelocations:
sphere: Set[Location] =set()
# cull events out
done_events: Set[Union[Location, None]] = {None}
whiledone_events:
done_events=set()
foreventinevents:
ifevent.can_reach(state):
state.collect(event.item, True, event)
done_events.add(event)
events-=done_events
forlocationinlocations:
iflocation.can_reach(state):
sphere.add(location)
yieldsphere
ifnotsphere:
iflocations:
yieldlocations# unreachable locations
break
forlocationinsphere:
state.collect(location.item, True, location)
locations-=sphere
deffulfills_accessibility(self, state: Optional[CollectionState] =None):
"""Check if accessibility rules are fulfilled with current or supplied state."""
ifnotstate:
state=CollectionState(self)
players: Dict[str, Set[int]] = {
"minimal": set(),
"items": set(),
"full": set()
}
forplayer, worldinself.worlds.items():
players[world.options.accessibility.current_key].add(player)
beatable_fulfilled=False
deflocation_condition(location: Location) ->bool:
"""Determine if this location has to be accessible, location is already filtered by location_relevant"""
returnlocation.playerinplayers["full"] or \
(location.itemandlocation.item.playernotinplayers["minimal"])
deflocation_relevant(location: Location) ->bool:
"""Determine if this location is relevant to sweep."""
returnlocation.playerinplayers["full"] orlocation.advancement
defall_done() ->bool:
"""Check if all access rules are fulfilled"""
ifnotbeatable_fulfilled:
returnFalse
ifany(location_condition(location) forlocationinlocations):
returnFalse# still locations required to be collected
returnTrue
locations= [locationforlocationinself.get_locations() iflocation_relevant(location)]
whilelocations:
sphere: List[Location] = []
forninrange(len(locations) -1, -1, -1):
iflocations[n].can_reach(state):
sphere.append(locations.pop(n))
ifnotsphere:
if__debug__:
fromFillimportFillError
raiseFillError(
f"Could not access required locations for accessibility check. Missing: {locations}",
multiworld=self,
)
# ran out of places and did not finish yet, quit
logging.warning(f"Could not access required locations for accessibility check."
f" Missing: {locations}")
returnFalse
forlocationinsphere:
iflocation.item:
state.collect(location.item, True, location)
ifself.has_beaten_game(state):
beatable_fulfilled=True
ifall_done():
returnTrue
returnFalse
PathValue=Tuple[str, Optional["PathValue"]]
classCollectionState():
prog_items: Dict[int, Counter[str]]
multiworld: MultiWorld
reachable_regions: Dict[int, Set[Region]]
blocked_connections: Dict[int, Set[Entrance]]
advancements: Set[Location]
path: Dict[Union[Region, Entrance], PathValue]
locations_checked: Set[Location]
"""Internal cache for Advancement Locations already checked by this CollectionState. Not for use in logic."""
stale: Dict[int, bool]
allow_partial_entrances: bool
additional_init_functions: List[Callable[[CollectionState, MultiWorld], None]] = []
additional_copy_functions: List[Callable[[CollectionState, CollectionState], CollectionState]] = []
def__init__(self, parent: MultiWorld, allow_partial_entrances: bool=False):
assertparent.worlds, "CollectionState created without worlds initialized in parent"
self.prog_items= {player: Counter() forplayerinparent.get_all_ids()}
self.multiworld=parent
self.reachable_regions= {player: set() forplayerinparent.get_all_ids()}
self.blocked_connections= {player: set() forplayerinparent.get_all_ids()}
self.advancements=set()
self.path= {}
self.locations_checked=set()
self.stale= {player: Trueforplayerinparent.get_all_ids()}
self.allow_partial_entrances=allow_partial_entrances
forfunctioninself.additional_init_functions:
function(self, parent)
foritemsinparent.precollected_items.values():
foriteminitems:
self.collect(item, True)
defupdate_reachable_regions(self, player: int):
self.stale[player] =False
world: AutoWorld.World=self.multiworld.worlds[player]
reachable_regions=self.reachable_regions[player]
queue=deque(self.blocked_connections[player])
start: Region=world.get_region(world.origin_region_name)
# init on first call - this can't be done on construction since the regions don't exist yet
ifstartnotinreachable_regions:
reachable_regions.add(start)
self.blocked_connections[player].update(start.exits)
queue.extend(start.exits)
ifworld.explicit_indirect_conditions:
self._update_reachable_regions_explicit_indirect_conditions(player, queue)
else:
self._update_reachable_regions_auto_indirect_conditions(player, queue)
def_update_reachable_regions_explicit_indirect_conditions(self, player: int, queue: deque[Entrance]):
reachable_regions=self.reachable_regions[player]
blocked_connections=self.blocked_connections[player]
# run BFS on all connections, and keep track of those blocked by missing items
whilequeue:
connection=queue.popleft()
new_region=connection.connected_region
ifnew_regioninreachable_regions:
blocked_connections.remove(connection)
elifconnection.can_reach(self):
ifself.allow_partial_entrancesandnotnew_region:
continue
assertnew_region, f"tried to search through an Entrance \"{connection}\" with no connected Region"
reachable_regions.add(new_region)
blocked_connections.remove(connection)
blocked_connections.update(new_region.exits)
queue.extend(new_region.exits)
self.path[new_region] = (new_region.name, self.path.get(connection, None))
self.multiworld.worlds[player].reached_region(self, new_region)
# Retry connections if the new region can unblock them
entrances=self.multiworld.indirect_connections.get(new_region)
ifentrancesisnotNone:
relevant_entrances=entrances.intersection(blocked_connections)
relevant_entrances.difference_update(queue)
queue.extend(relevant_entrances)
def_update_reachable_regions_auto_indirect_conditions(self, player: int, queue: deque[Entrance]):
reachable_regions=self.reachable_regions[player]
blocked_connections=self.blocked_connections[player]
new_connection: bool=True
# run BFS on all connections, and keep track of those blocked by missing items
whilenew_connection:
new_connection=False
whilequeue:
connection=queue.popleft()
new_region=connection.connected_region
ifnew_regioninreachable_regions:
blocked_connections.remove(connection)
elifconnection.can_reach(self):
ifself.allow_partial_entrancesandnotnew_region:
continue
assertnew_region, f"tried to search through an Entrance \"{connection}\" with no connected Region"
reachable_regions.add(new_region)
blocked_connections.remove(connection)
blocked_connections.update(new_region.exits)
queue.extend(new_region.exits)
self.path[new_region] = (new_region.name, self.path.get(connection, None))
new_connection=True
self.multiworld.worlds[player].reached_region(self, new_region)
# sweep for indirect connections, mostly Entrance.can_reach(unrelated_Region)
queue.extend(blocked_connections)
defcopy(self) ->CollectionState:
ret=CollectionState(self.multiworld)
ret.prog_items= {player: counter.copy() forplayer, counterinself.prog_items.items()}
ret.reachable_regions= {player: region_set.copy() forplayer, region_setin
self.reachable_regions.items()}
ret.blocked_connections= {player: entrance_set.copy() forplayer, entrance_setin
self.blocked_connections.items()}
ret.advancements=self.advancements.copy()
ret.path=self.path.copy()
ret.locations_checked=self.locations_checked.copy()
ret.allow_partial_entrances=self.allow_partial_entrances
forfunctioninself.additional_copy_functions:
ret=function(self, ret)
returnret
defcan_reach(self,
spot: Union[Location, Entrance, Region, str],
resolution_hint: Optional[str] =None,
player: Optional[int] =None) ->bool:
ifisinstance(spot, str):
assertisinstance(player, int), "can_reach: player is required if spot is str"
# try to resolve a name
ifresolution_hint=='Location':
returnself.can_reach_location(spot, player)
elifresolution_hint=='Entrance':
returnself.can_reach_entrance(spot, player)
else:
# default to Region
returnself.can_reach_region(spot, player)
returnspot.can_reach(self)
defcan_reach_location(self, spot: str, player: int) ->bool:
returnself.multiworld.get_location(spot, player).can_reach(self)
defcan_reach_entrance(self, spot: str, player: int) ->bool:
returnself.multiworld.get_entrance(spot, player).can_reach(self)
defcan_reach_region(self, spot: str, player: int) ->bool:
returnself.multiworld.get_region(spot, player).can_reach(self)
defsweep_for_events(self, locations: Optional[Iterable[Location]] =None) ->None:
Utils.deprecate("sweep_for_events has been renamed to sweep_for_advancements. The functionality is the same. "
"Please switch over to sweep_for_advancements.")
returnself.sweep_for_advancements(locations)
def_sweep_for_advancements_impl(self, advancements_per_player: List[Tuple[int, List[Location]]],
yield_each_sweep: bool) ->Iterator[None]:
"""
The implementation for sweep_for_advancements is separated here because it returns a generator due to the use
of a yield statement.
"""
all_players= {playerforplayer, _inadvancements_per_player}
players_to_check=all_players
# As an optimization, it is assumed that each player's world only logically depends on itself. However, worlds
# are allowed to logically depend on other worlds, so once there are no more players that should be checked
# under this assumption, an extra sweep iteration is performed that checks every player, to confirm that the
# sweep is finished.
checking_if_finished=False
whileplayers_to_check:
next_advancements_per_player: List[Tuple[int, List[Location]]] = []
next_players_to_check=set()
forplayer, locationsinadvancements_per_player:
ifplayernotinplayers_to_check:
next_advancements_per_player.append((player, locations))
continue
# Accessibility of each location is checked first because a player's region accessibility cache becomes
# stale whenever one of their own items is collected into the state.
reachable_locations: List[Location] = []
unreachable_locations: List[Location] = []
forlocationinlocations:
iflocation.can_reach(self):
# Locations containing items that do not belong to `player` could be collected immediately
# because they won't stale `player`'s region accessibility cache, but, for simplicity, all the
# items at reachable locations are collected in a single loop.
reachable_locations.append(location)
else:
unreachable_locations.append(location)
ifunreachable_locations:
next_advancements_per_player.append((player, unreachable_locations))
# A previous player's locations processed in the current `while players_to_check` iteration could have
# collected items belonging to `player`, but now that all of `player`'s reachable locations have been
# found, it can be assumed that `player` will not gain any more reachable locations until another one of
# their items is collected.
# It would be clearer to not add players to `next_players_to_check` in the first place if they have yet
# to be processed in the current `while players_to_check` iteration, but checking if a player should be
# added to `next_players_to_check` would need to be run once for every item that is collected, so it is
# more performant to instead discard `player` from `next_players_to_check` once their locations have
# been processed.
next_players_to_check.discard(player)
# Collect the items from the reachable locations.
foradvancementinreachable_locations:
self.advancements.add(advancement)
item=advancement.item
assertisinstance(item, Item), "tried to collect advancement Location with no Item"
ifself.collect(item, True, advancement):
# The player the item belongs to may be able to reach additional locations in the next sweep
# iteration.
next_players_to_check.add(item.player)
ifnotnext_players_to_check:
ifnotchecking_if_finished:
# It is assumed that each player's world only logically depends on itself, which may not be the
# case, so confirm that the sweep is finished by doing an extra iteration that checks every player.
checking_if_finished=True
next_players_to_check=all_players
else:
checking_if_finished=False
players_to_check=next_players_to_check
advancements_per_player=next_advancements_per_player
ifyield_each_sweep:
yield
@overload
defsweep_for_advancements(self, locations: Optional[Iterable[Location]] =None, *,
yield_each_sweep: Literal[True],
checked_locations: Optional[Set[Location]] =None) ->Iterator[None]: ...
@overload
defsweep_for_advancements(self, locations: Optional[Iterable[Location]] =None,
yield_each_sweep: Literal[False] =False,
checked_locations: Optional[Set[Location]] =None) ->None: ...
defsweep_for_advancements(self, locations: Optional[Iterable[Location]] =None, yield_each_sweep: bool=False,
checked_locations: Optional[Set[Location]] =None) ->Optional[Iterator[None]]:
"""
Sweep through the locations that contain uncollected advancement items, collecting the items into the state
until there are no more reachable locations that contain uncollected advancement items.
:param locations: The locations to sweep through, defaulting to all locations in the multiworld.
:param yield_each_sweep: When True, return a generator that yields at the end of each sweep iteration.
:param checked_locations: Optional override of locations to filter out from the locations argument, defaults to
self.advancements when None.
"""
ifchecked_locationsisNone:
checked_locations=self.advancements
# Since the sweep loop usually performs many iterations, the locations are filtered in advance.
# A list of tuples is used, instead of a dictionary, because it is faster to iterate.
advancements_per_player: List[Tuple[int, List[Location]]]
iflocationsisNone:
# `location.advancement` can only be True for filled locations, so unfilled locations are filtered out.
advancements_per_player= []
forplayer, locations_dictinself.multiworld.regions.location_cache.items():
filtered_locations= [locationforlocationinlocations_dict.values()
iflocation.advancementandlocationnotinchecked_locations]
iffiltered_locations:
advancements_per_player.append((player, filtered_locations))
else:
# Filter and separate the locations into a list for each player.
advancements_per_player_dict: Dict[int, List[Location]] =defaultdict(list)
forlocationinlocations:
iflocation.advancementandlocationnotinchecked_locations:
advancements_per_player_dict[location.player].append(location)
# Convert to a list of tuples.
advancements_per_player=list(advancements_per_player_dict.items())
deladvancements_per_player_dict
ifyield_each_sweep:
# Return a generator that will yield at the end of each sweep iteration.
returnself._sweep_for_advancements_impl(advancements_per_player, True)
else:
# Create the generator, but tell it not to yield anything, so it will run to completion in zero iterations
# once started, then start and exhaust the generator by attempting to iterate it.
for_inself._sweep_for_advancements_impl(advancements_per_player, False):
assertFalse, "Generator yielded when it should have run to completion without yielding"
returnNone
# item name related
defhas(self, item: str, player: int, count: int=1) ->bool:
returnself.prog_items[player][item] >=count