-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathRandomizeItemsBadgesAssumedFill.py
1469 lines (1189 loc) · 50.3 KB
/
RandomizeItemsBadgesAssumedFill.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 string
import LoadLocationData
from collections import defaultdict
import random
import copy
import time
import RandomizeFunctions
def DebugLegality(toAllocate, location, input1):
DEBUG_LEGALITY = False
if DEBUG_LEGALITY:
print("Legality reason change:", toAllocate, location, input1)
def findAllSilverUnlocks(req, locList, handled=None):
#req = "Mt. Silver Outside"
if handled is None:
handled = []
newFind = []
findSilverItems = list(filter(lambda x: req in x.LocationReqs, locList))
for findSilver in findSilverItems:
if findSilver in handled:
continue
handled.append(findSilver)
if findSilver.Type == "Item":
newFind.append(findSilver)
# TODO: Investigate adding Transition as well as fixing warp issues
elif findSilver.Type == "Map":
newFinds = findAllSilverUnlocks(findSilver.Name, locList, handled)
for find in newFinds:
newFind.append(find)
return newFind
def LoopWarpSet(startingGroups, warpLocations, inputFlags):
newSet = []
newSet.extend(startingGroups.copy())
state = defaultdict(lambda: False)
for flag in inputFlags:
state[flag] = True
dupes = []
for group in newSet:
state[group] = True
possibilities = list(filter(lambda x: group in x.LocationReqs, warpLocations))
for poss in possibilities:
requirements = poss.requirementsNeeded(state)
if len(requirements) == 0:
if poss.Name not in newSet:
newSet.append(poss.Name)
warpLocations.remove(poss)
# Also remove other locations with the same name, for closed loop scenarios!
othersWithSameName = list(filter(lambda x: x.Name == poss.Name, warpLocations))
for other in othersWithSameName:
dupes.append(other)
for dupe in dupes:
if dupe in warpLocations:
warpLocations.remove(dupe)
return newSet
def GetWarpGroupsSets(locList, inputFlags):
# Check all the locations in the list
# Where you can get to with no requirements
# Then, we can assume no requirements from then on
# Must be done at processing level due to potential changes with modifiers, etc.
# May also be able to turn this into 'warp sets', so that all the warps you can reach
# With a given additional requirement
# To condense these down massively!
# This does not yet factor in 'free' transitions
# Or transitations at all which can now be deemed a transition between sets!
warpSets = []
warpSpace = list(filter(lambda x: x.Type == "Map" and x.Name.endswith(LoadLocationData.WARP_OPTION),locList)).copy()
startWarpGroups = list(filter(lambda x: x.Type == "Starting Warp",locList))
groupList = [ x.Name for x in startWarpGroups ]
startingGroup = LoopWarpSet(groupList, warpSpace, inputFlags)
warpSets.append(startingGroup)
skips = []
previouslySkipped = []
while len(warpSpace) > 0:
nextCheckItem = warpSpace.pop(0)
if nextCheckItem in previouslySkipped:
break
if nextCheckItem in skips:
break
nextCheck = [nextCheckItem.Name]
nextGroup = LoopWarpSet(nextCheck, warpSpace, inputFlags)
for item in nextGroup:
if item in skips:
skips.remove(item)
if len(nextGroup) > 1:
# These may be issues solely to do with purging!
warpSets.append(nextGroup)
else:
previouslySkipped.append(nextCheckItem)
skips.append(nextCheckItem)
warpSpace.append(nextCheckItem)
# Anything left over is a seperate singleton group
# Many of these may be exclusive to transitions
for item in skips:
isContainedWithin = [ x for x in warpSets if item.Name in x ]
if not isContainedWithin:
warpSets.append([item.Name])
riskDuplicates = []
reverseWarpSet = {}
for set in warpSets:
for setItem in set:
if setItem in reverseWarpSet:
print("Work out way to handle these duplicates on the reverse...:", setItem)
if setItem not in riskDuplicates:
riskDuplicates.append(setItem)
else:
reverseWarpSet[setItem] = set
# Remove the duplicate cases to avoid potential issues with extensions after
for dup in riskDuplicates:
if dup in reverseWarpSet:
del reverseWarpSet[dup]
transitionSpace = list(
filter(lambda x: x.Type == "Transition" and x.Name.endswith(LoadLocationData.WARP_OPTION), locList)).copy()
extensions = []
state = defaultdict(lambda: False)
for flag in inputFlags:
state[flag] = True
for transition in transitionSpace:
transitionReqs = [ x for x in transition.requirementsNeeded(state) if not x.endswith(LoadLocationData.WARP_OPTION) ]
# May be recommended to handle whether a transition is reversible or not here
# This shouldn't be done here, but at warp-loaded
# However, if not loaded, it may mark groups together which AREN'T possible
# Such as jumping a ledge and there is nothing to say which way you came from here
# This may be caused by purge level
extStart = transition.LocationReqs[0]
extEnd = transition.Name
reverseTransitions = list(filter(lambda x: len(x.LocationReqs) > 0 and x.LocationReqs[0] == extEnd
and x.Name == extStart, transitionSpace))
reverseTransitionReqs = ["Impossible"]
if len(reverseTransitions) > 0:
reverseTransition = reverseTransitions[0]
reverseTransitionReqs = [x for x in reverseTransition.requirementsNeeded(state) if
not x.endswith(LoadLocationData.WARP_OPTION)]
if len(transitionReqs) == 0 and len(reverseTransitionReqs) == 0:
extensions.append(transition)
for ext in extensions:
extStart = ext.LocationReqs[0]
extEnd = ext.Name
# Cannot find implies group could not be reached by any other means
# e.g. Rocket Block North is otherwise unreachable via base walk on vanilla
if extStart not in reverseWarpSet and extEnd not in reverseWarpSet:
print("Cannot find either", extStart, "or", extEnd)
elif extStart not in reverseWarpSet:
print("Cannot find", extStart, "with", extEnd)
elif extEnd not in reverseWarpSet:
print("Cannot find", extEnd, "with", extStart)
else:
groupA = reverseWarpSet[extStart]
groupB = reverseWarpSet[extEnd]
# Transition may lead to itself
if groupA != groupB:
mergeInto = groupA if groupB != startingGroup else groupB
removeGroup = groupB if mergeInto == groupA else groupA
for rm in removeGroup:
mergeInto.append(rm)
reverseWarpSet[rm] = mergeInto
warpSets.remove(removeGroup)
return warpSets
def RandomizeItems(goalID,locationTree, progressItems, trashItems, badgeData, seed, inputFlags=None, inputVariables=None, reqBadges = { 'Zephyr Badge', 'Fog Badge', 'Hive Badge', 'Plain Badge', 'Storm Badge', 'Glacier Badge', 'Rising Badge'},
coreProgress= ['Surf','Fog Badge', 'Pass', 'S S Ticket', 'Squirtbottle','Cut','Hive Badge'],
allPossibleFlags = ['Johto Mode','Kanto Mode'],
plandoPlacements = {},
dontReplace = None, badgeShuffle=True):
if dontReplace is None:
dontReplace = []
if inputFlags is None:
inputFlags = []
if inputVariables is None:
inputVariables = {}
monReqItems = ['ENGINE_POKEDEX','COIN_CASE', 'OLD_ROD', 'GOOD_ROD', 'SUPER_ROD']
if not badgeShuffle and "Allocate Badges First" not in inputFlags:
inputFlags.append("Allocate Badges First")
random.seed(seed)
#add the "Ok" flag to the input flags, which is used to handle locations that lose all their restrictions
inputFlags.append('Ok')
#build progress set
progressList = copy.copy(sorted(progressItems))
progressList.extend(sorted(reqBadges))
progressSet = copy.copy(sorted(progressList))
coreProgress = list(sorted(frozenset(coreProgress).intersection(frozenset(progressSet))))
locList = sorted(LoadLocationData.FlattenLocationTree(locationTree), key= lambda i: ''.join(i.Name).join(i.requirementsNeeded(defaultdict(lambda: False))))
#locs = [ x.Name for x in locList if x.isItem() or x.isGym() ]
#print(locs)
# Required as oherwise non-trash is stored in previous results!
#locList = copy.deepcopy(locList_base)
allocatedList = []
#print("Trash count:", len(trashItems))
#trashItems.sort()
#print(trashItems)
#define set of badges
badgeSet = list(sorted(badgeData.keys()))
#define set of trash badges
trashBadges = list(sorted(frozenset(badgeData.keys()).difference(frozenset(reqBadges))))
trashItems.extend(sorted(trashBadges))
trashItems.sort()
#stores current requirements for each location
requirementsDict = defaultdict(lambda: [])
bannedPaths = {}
MtSilverSubItems = findAllSilverUnlocks("Mt. Silver Outside",locList)
Route28SubItems = findAllSilverUnlocks("Route 28", locList)
MtSilverSubItems.extend(Route28SubItems)
#shuffle the lists (no seriously, this is a perfectly valid randomization strategy)
#random.shuffle(locList)
#random.shuffle(progressList)
#random.shuffle(coreProgress)
#random.shuffle(trashItems)
locList = random.sample(locList, k=len(locList))
progressList = random.sample(progressList, k=len(progressList))
coreProgress = random.sample(coreProgress, k=len(coreProgress))
trashItems = random.sample(trashItems, k=len(trashItems))
#build spoiler
spoiler = {}
#print('Building mappings')
#note: these are the randomizer only flags, they do not map to actual logic defined in the config files
#flagList = ['Rocket Invasion', '8 Badges', 'All Badges']
flagList = ['Assumed Fill', 'All Badges', 'Ok','External Checking']
if(len(plandoPlacements) > 0):
flagList.append('External Checking')
#build the initial requirements mappings
allReqsList = copy.copy(progressSet)
itemCount = 0
single_flags_set = []
flags_with_path = []
# This a list of required items that are actually base items and therefore can be deleted, etc so in shopsanity
# These must be purchaseable
requiredItems = []
for i in locList:
#baseline requirements
#allReqs = i.LocationReqs+i.FlagReqs+i.itemReqs
allReqs = sorted(i.requirementsNeeded(defaultdict(lambda: False)))
allReqsList.extend(allReqs)
allReqsList.append(i.Name)
requirementsDict[i.Name].append(allReqs)
for j in sorted(i.FlagsSet):
requirementsDict[j].append(allReqs)
flagList.append(j)
if j in flags_with_path:
pass
elif j in single_flags_set:
single_flags_set.remove(j)
flags_with_path.append(j)
else:
single_flags_set.append(j)
if i.isItem() and not i.Dummy:
itemCount = itemCount+1
for iReq in i.ItemReqs:
iReq = iReq.replace("_", " ")
iReq = string.capwords(iReq," ")
if iReq not in requiredItems:
requiredItems.append(iReq)
for iReq in i.RecommendedItemReqs:
iReq = iReq.replace("_", " ")
iReq = string.capwords(iReq, " ")
if iReq not in requiredItems:
requiredItems.append(iReq)
# Store flags set in a single location and forcibly update
# All instances of that flag with its requirements
# To resolve a placement issue
# e.g. Dragons Den Entrance requiring Strength due to flag changes
# However, working out the way to do this is complex
# Especially as those location requirements would also need updating
# Is there a better way to do this?
#for flag in single_flags_set:
#affected = list(filter(lambda x: flag in x,requirementsDict.iteritems()))
# do updating
# pass
#print('Total number of items: '+str(itemCount))
E4Badges = random.sample(badgeSet,8)
#print('E4Badges')
#print(E4Badges)
#choose 8 random badges and make them the "required" badges to access the elite 4
#this is needed to break the randomizer's addiction to E4 required seeds on extreme
if 'Sane Extreme E4 Access' in inputFlags:
for i in requirementsDict['8 Badges']:
i.extend(E4Badges)
#if we are in plando mode (explicit placements, only use explicit checks for locations which have the option)
if(len(plandoPlacements)>0 or "Warps" in inputFlags):
for i in requirementsDict:
explicitable = False
explicitOption = None
for j in requirementsDict[i]:
if('Explicit Checking' in j):
explicitable = True
explicitOption = j
if explicitable:
#print(requirementsDict[i])
requirementsDict[i] = [explicitOption]
#print(requirementsDict[i])
#extract all core items out and put them in shuffled order at the start (which is the BACK) of the item list
#this is done because these items unlock way too many item locations, so we want to maximize their legal locations
for i in coreProgress:
progressList.remove(i)
progressList = progressList+coreProgress
if 'Allocate Badges First' in inputFlags:
addEnd = []
for i in progressList:
if 'Badge' in i:
addEnd.append(i)
for i in addEnd:
progressList.remove(i)
progressList.append(i)
#put surf at the front of the list because with badges being shuffled, there is otherwise an abnormal bias towards early surf
progressList.remove('Surf')
progressList.append('Surf')
#print(progressList)
if "Fly Warps" in inputFlags:
progressList.remove('Fly')
progressList.remove('Storm Badge')
progressList.append('Storm Badge')
progressList.append('Fly')
if 'Warps' in inputFlags:
warp_sets = GetWarpGroupsSets(locList, inputFlags)
hubs = RandomizeFunctions.GetWarpHubs(locList, inputFlags)
hubSize = 5
warpHubsForHints = [x[0] for x in hubs.items() if x[1] > hubSize]
hubsInBaseGroup = [ group for group in warp_sets[0] if group in warpHubsForHints ]
for hub in hubsInBaseGroup:
requirementsDict[hub] = []
# This is the starting group so you can get to all of these warp groups with no other requirements
# Just finding the right path!
# Change this behaviour to be just as optimal (ish)
# But also work with hints
# Detect any area as a 'Hub' and remove THESE from having requirements!
# Should still be massively preferred
# Otherwise, each other warp group set means no requirements once reaching ANY of those
# This doesn't 'save as much time' however
# Skip for now, need to ensure the above method works correctly
#for nonStartSet in warp_sets[1:]:
# Standard warps use a 2-for-2 system so no optimisation with these
# if len(nonStartSet) > 2:
#go through all the plandomizer allocations and try to put them in locations specified (generated seed will ATTEMPT to obey these)
#this works by putting the plando placements to be tried first
for i in plandoPlacements:
if (plandoPlacements[i] in progressList):
for j in range(0, len(locList)):
if(locList[j].Name == i):
locInd = j
#print(j)
#print(locList[0].Name)
locList.insert(0, locList.pop(locInd))
#print(locList[0].Name)
progressList.remove(plandoPlacements[i])
progressList.insert(len(progressList),plandoPlacements[i])
#print(plandoPlacements)
#print(progressList)
#keep copy of initial requirements dictionary to check tautologies
initReqDict = copy.copy(requirementsDict)
fullDependenciesList = {}
usedFlagsList = list(sorted(frozenset(allReqsList).intersection(allPossibleFlags)))
#begin assumed fill loop
valid = True
# while(len(progressList)>0 and valid):
#pick an item to place
# toAllocate = progressList.pop()
# #print('Allocating '+toAllocate)
# if toAllocate in progressItems:
# allocationType = 'Item'
# else:
# allocationType = 'Gym'
#iterate through randomly ordered locations until a feasible location to place item is found
maxIter = len(progressList)
#progressList.reverse()
#print(progressList)
previousCount = 0
while len(progressList) > 0 and maxIter > 0:
#print("iter=",maxIter, "pl:", len(progressList), progressList)
if previousCount == len(progressList):
remainingLocations = list(filter(lambda x: (x.Type == "Item" or x.Type == "Gym") and not x.Dummy, locList))
for r in remainingLocations:
pass
#print("r=",r.Name)
#print("--")
print(progressList)
previousCount = len(progressList)
maxIter = maxIter - 1
valid = False
iter = 0
retryPasses = 4
#determine type of location to allocate based of progress list
allocationType = 'Item'
#if progressList[-1] in progressItems:
# allocationType = 'Item'
#else:
# allocationType = 'Gym'
# toAllocate = progressList[-1] #If its a badge, we always force the allocation of THAT badge
#LocationList = list(filter(lambda x: x.Type != "Map" and x.Type != "Transition"), locList)
while not valid and iter < len(locList) and retryPasses > 0 and len(progressList) > 0:
#sub item allocation loop, so that locations are at least randomly given items they can actually have
allocated = False
nLeft = len(progressList)
while nLeft > 0 and not allocated:
#if its a plando placement, just place it, we'll complain if infeasible later on
# TODO Investigate this functionality, as seems to want 'Name' appended
if locList[iter].Name in plandoPlacements:
toAllocate = plandoPlacements[locList[iter].Name]
nLeft = 0
placeable = True
else:
#skip over entries until we get to the type we're trying to allocate
placeable = False
while not placeable and nLeft > 0 and allocationType != 'Gym':
nLeft = nLeft - 1
toAllocate = progressList[nLeft]
if allocationType == 'Item' and toAllocate in progressList:
placeable = True
# if allocationType == 'Gym' and not (toAllocate in progressItems):
# placeable = True
#print('Allocating '+toAllocate)
if allocationType == 'Gym':
placeable = True
nLeft = 0
legal = True
illegalReason = None
#don't attempt to put badges in mt. silver
#if('Mt. Silver' in locList[iter].LocationReqs and toAllocate in badgeSet and not 'Open Mt. Silver' in inputFlags):
# placeable = False
badgesRemaining = len(reqBadges) - len(spoiler.keys()) > 0
if badgesRemaining and 'Allocate Badges First' in inputFlags and toAllocate not in badgeSet:
continue
if (locList[iter] in MtSilverSubItems and toAllocate in badgeSet and not 'Open Mt. Silver' in inputFlags):
placeable = False
if (locList[iter] in MtSilverSubItems and toAllocate in coreProgress):
placeable = False
#if locList[iter].isShop() and \
# (toAllocate in badgeSet or toAllocate in RandomizeFunctions.ShopFlagItems):
# # Shopsanity does not yet support flags in shops
# placeable = False
# Enforce Shopsanity items to be buyable;;
if not locList[iter].isShop():
if toAllocate in RandomizeFunctions.REQUIRED_BUY_ITEMS:
placeable = False
# only in ordinary shops
if toAllocate in RandomizeFunctions.REQUIRED_BUY_ITEMS:
if locList[iter].isBargainShop() or locList[iter].isPrize() or \
locList[iter].isVendingMachine() or locList[iter].isBuenaItem():
placeable = False
if toAllocate not in RandomizeFunctions.REQUIRED_BUY_ITEMS:
if locList[iter].isShopLike() and "RerollShopPercent" in inputVariables:
random_value = random.random() * 100
if random_value % 100 <= float(inputVariables["RerollShopPercent"]):
break
if locList[iter].Type == "Map" or locList[iter].Type == "Transition" or locList[iter].Dummy:
break
if not badgeShuffle and toAllocate in badgeSet and not locList[iter].IsActuallyGym:
placeable = False
elif not badgeShuffle and toAllocate not in badgeSet and locList[iter].IsActuallyGym:
placeable = False
#if placeable and not badgeShuffle and toAllocate in badgeSet:
# print("Attempt:", locList[iter].Name, toAllocate)
warpImpossibleCheck = requirementsDict[locList[iter].Name]
impossible_paths = 0
for path in warpImpossibleCheck:
path_is_impossible = ("Impossible" in path) or ("Unreachable" in path) or ("Banned" in path)
if path_is_impossible:
impossible_paths +=1
if impossible_paths > 0 and impossible_paths >= len(warpImpossibleCheck):
#print("Impossible:", locList[iter].Name + ' cannot contain ' + toAllocate)
break
#is it the right type of location?
##print(locList[iter].Name)
##print(locList[iter].Type)
#all locations are now the same!
if((locList[iter].Type == 'Item' or locList[iter].Type == 'Gym' \
or locList[iter].isShopLike() ) and placeable):
#print('Trying '+locList[iter].Name +' as ' +toAllocate)
#do any of its dependencies depend on this item/badge?
randOpt = random.choice(range(0,len(requirementsDict[locList[iter].Name])))
allDepsList = sorted(copy.copy(requirementsDict[locList[iter].Name][randOpt]))
oldDepsList = []
newDeps = allDepsList
addedList = [locList[iter].Name]
revReqDict = defaultdict(lambda: [])
lastWarpStep = None
while oldDepsList != allDepsList and legal:
oldDepsList = allDepsList
for j in newDeps:
# Break out before continuing if item is locked to Red due to modifiers
if "Red" in newDeps or "Defeated Red" in newDeps:
DebugLegality(toAllocate, locList[iter].Name, "Red")
#illegalReason = "Red"
legal = False
if j == "Mt. Silver Unlock":
if toAllocate in badgeSet and not 'Open Mt. Silver' in inputFlags:
DebugLegality(toAllocate, locList[iter].Name,"Mt Silver")
legal = False
if toAllocate in badgeSet and j == "All Badges":
DebugLegality(toAllocate, locList[iter].Name, "All Badges")
legal = False
if not legal:
break
jReqs = []
if(len(requirementsDict[j])>0):
#print('Choosing non-tautological path for '+j)
#choose a random path through dependencies that IS NOT A TAUTOLOGY!
# If a path has no requirements, choose this one as means always available
# Similarly, if a path only contains 'Warps'
# Otherwise X% chance of failure on each run through
paths = copy.copy(requirementsDict[j])
random.shuffle(paths)
defaultPath = None
removedPaths = []
for check in paths:
if len(check) == 0:
defaultPath = check
# If Warps option enabled, always pick this one!
elif len(check) == 1 and check[0] in inputFlags:
defaultPath = check
elif j in bannedPaths:
jBanned = bannedPaths[j]
if check in jBanned:
removedPaths.append(check)
if lastWarpStep is not None:
warpCheck = True
for c in check:
if c == lastWarpStep:
warpCheck = False
if not warpCheck:
removedPaths.append(check)
#print("Prevent path back:", j, check)
for path in removedPaths:
paths.remove(path)
if len(paths) == 0:
DebugLegality(toAllocate, locList[iter].Name, "Banned Paths")
#print("Banned paths only, cannot take a route")
legal = False
break
#pick an option from paths which isn't a tautology!
tautologyCheck = True
tautIter = 0
#only need to pick if there are two options!
if(len(requirementsDict[j])>1):
# better strategy, if you choose option A from the multiple options, then the locations required by A CANNOT require j!
# so when choosing a path to the locations required by A, we CANNOT choose an option with j as a dependency!
# also, we don't pick paths that require the item we're trying to allocate, for obvious reasons
trueOption = defaultPath
if trueOption is None:
for k in paths:
#print('trying potential path:')
#print(k)
# Tiny optimisation, break out of path if contains the item to be allocated in the path
# Previously, continued through each step in the path requirements
if toAllocate in k:
continue
kTrue = True
for l in k:
if not kTrue:
break
# Warps add edge case where warps can lead to themselves!
# But exclude input flags from this check
isFlag = l in inputFlags
if not isFlag:
# Only have this check for flag names
kTrue = kTrue and (l != j)
#print("Check element l in k", l)
#kTrue = not (len(requirementsDict[l]) == 1 and j in requirementsDict[l][0])
#if not kTrue:
# print("Debug: A")
kTrue = kTrue and (l not in revReqDict[j])
#if not kTrue:
# print("Debug: B")
lTrueOr = len(requirementsDict[l]) == 0
lPathOr = len(requirementsDict[l]) == 0
# Add warp edge case, only route back is to itself
for m in requirementsDict[l]:
lTrueOr = lTrueOr or toAllocate not in m
allInputFlags = len(m) > 0
for pFlag in m:
allInputFlags = allInputFlags and pFlag in inputFlags
if allInputFlags:
lPathOr = True
else:
lPathOr = lPathOr or (j not in m)
kTrue = kTrue and lTrueOr
kTrue = kTrue and lPathOr
#if not kTrue:
# print("Debug: C")
#also make sure the location doesn't literally require it
kTrue = kTrue and l != toAllocate
#if not kTrue:
# print("Debug: D")
#also make sure its not impossible
kTrue = kTrue and l != 'Impossible' and l != "Banned" and l != "Unreachable"
#if not kTrue:
# print("Debug: E")
#also make sure the requirements aren't impossible (accounts for multi-entrances, which can never be impossible)
#TODO investigate this as sub-optimal!
if len(requirementsDict[l]) != 0:
lPossible = False
for m in requirementsDict[l]:
lPossible = lPossible or \
not ('Banned' in m or
'Impossible' in m or
'Unreachable' in m)
kTrue = kTrue and lPossible
if(len(requirementsDict[l]) != 0):
kTrue = kTrue and not ('Impossible' in requirementsDict[l][0] or\
'Banned' in requirementsDict[l][0] or\
'Unreachable' in requirementsDict[l][0])
# if not kTrue:
# print("Debug: F")
#if not lTrueOr:
# 1+1
#print('False because '+l+' requires:')
#print(requirementsDict[l])
#if a flag we don't have is needed, we can't use that path
kTrue = kTrue and not (l in usedFlagsList and l not in inputFlags)
# Warps are bi-directional, so add clause here to prevent automatic tautology
#if l.endswith(LoadLocationData.WARP_OPTION):
# kTrue = kTrue and (l not in allDepsList)
#if not kTrue:
# print("Debug: G")
if (l in usedFlagsList and l not in inputFlags):
1+1
#print('False because the needed flag '+ l +' is not set')
#print(usedFlagsList)
#print(inputFlags)
# If all requirements have already been found, then the potential path is forbidden
# As it may require cyclic access, especially with warp logic
# e.g. Ledges only being accessible by warps, but using vanilla within dungeons
#if len(l) > 0 and len(k) == reqInCurrent:
# kTrue = False
if(kTrue):
trueOption = k
#print('found non-tautological path')
#print(k)
break
else:
1+1
#print('Path is false')
#if new choice is none, ignore it because this is a true tautology
#e.g. trying to place the squirtbottle at the sudowoodo junction
if(not trueOption is None):
#add all reverse dependencies onto new choice
for k in trueOption:
revReqDict[k].extend(sorted(revReqDict[j]))
revReqDict[k].append(j)
jReqs = trueOption
if j not in addedList:
addedList.append(j)
if len(paths)>1:
1+1
#print(revReqDict)
else:
DebugLegality(toAllocate, locList[iter].Name, "Tautology")
legal = False
illegalReason = allDepsList.copy()
#this is not a legal item location! because it involves a tautology!
#print('Illegal tautology:')
#print(paths)
#print('The following could create the tautology when allocating '+ toAllocate +' to '+locList[iter].Name+':')
#print(revReqDict[j])
else:
jReqs = sorted(requirementsDict[j][0])
# Due to some behaviour with Warps, need this requirements check
# Even with a single path as could be randomised
# Into a tautology (potentially at a previous path)
if len(paths) > 0:
singleTrue = True
for l in paths[0]:
if not singleTrue:
break
isFlag = l in inputFlags
if not isFlag:
# Only have this check for flag names
singleTrue = singleTrue and (l != j)
singleTrue = singleTrue and (l not in revReqDict[j])
lTrueOr = len(requirementsDict[l]) == 0
lPathOr = len(requirementsDict[l]) == 0
for m in requirementsDict[l]:
lTrueOr = lTrueOr or toAllocate not in m
allInputFlags = len(m) > 0
for pFlag in m:
allInputFlags = allInputFlags and pFlag in inputFlags
if allInputFlags:
lPathOr = True
else:
lPathOr = lPathOr or (j not in m)
singleTrue = singleTrue and lPathOr
singleTrue = singleTrue and lTrueOr
singleTrue = singleTrue and l != toAllocate
# TODO investigate this as sub-optimal!
# e.g. impossible route to Radio Tower 3F Sunny Day
# The thing preventing it from being removed!
singleTrue = singleTrue and l != 'Impossible' and l != "Banned" and l != "Unreachable"
if len(requirementsDict[l]) != 0:
lPossible = False
for m in requirementsDict[l]:
lPossible = lPossible or \
not ('Banned' in m or
'Impossible' in m or
'Unreachable' in m)
singleTrue = singleTrue and lPossible
#if (len(requirementsDict[l]) != 0):
# singleTrue = singleTrue and not ('Impossible' in requirementsDict[l][0] or \
# 'Banned' in requirementsDict[l][0] or \
# 'Unreachable' in requirementsDict[l][0])
if not lTrueOr:
1 + 1
singleTrue = singleTrue and not (l in usedFlagsList and l not in inputFlags)
if not singleTrue:
DebugLegality(toAllocate, locList[iter].Name, "SingleTrue:"+str(paths[0]))
legal = False
else:
for l in paths[0]:
revReqDict[l].extend(sorted(revReqDict[j]))
revReqDict[l].append(j)
else:
if 'Impossible' in jReqs or "Banned" in jReqs or "Unreachable" in jReqs:
DebugLegality(toAllocate, locList[iter].Name, "Impossible Path")
legal = False
if j not in addedList:
addedList.append(j)
for k in jReqs:
if k not in allDepsList:
if LoadLocationData.WARP_OPTION in k:
lastWarpStep = k
else:
lastWarpStep = None
newDeps.append(k)
#print(newDeps)
allDepsList.extend(newDeps)
#print("New dependencies:", allDepsList)
#print('Expanded dependencies of '+locList[iter].Name+' to:')
#print(allDepsList)
newDeps = []
#if a dependency requires an input flag (not set by a location, a location, or a progress item), that flag MUST be set
#print(allDepsList)
#print(legal)
#print(frozenset(allDepsList).intersection(frozenset(usedFlagsList)).issubset(inputFlags))
#print(usedFlagsList)
#print(frozenset(allDepsList).intersection(set(usedFlagsList)))
legal = legal and frozenset(allDepsList).intersection(frozenset(usedFlagsList)).issubset(inputFlags)
if(not frozenset(allDepsList).intersection(frozenset(usedFlagsList)).issubset(inputFlags)):
1+1
#print(locList[iter].Name + ' is not legal because it needs flags that are not set')
#print(set(allDepsList).intersection(set(usedFlagsList)))
#Impossible locations are illegal
if("Impossible" in allDepsList or "Banned" in allDepsList or "Unreachable" in allDepsList):
DebugLegality(toAllocate, locList[iter].Name, "Impossible-2")
legal = False
if(toAllocate not in allDepsList and legal or (toAllocate in plandoPlacements.values() and 'unsafePlando' in inputFlags)):
loc = locList.pop(iter)
valid = True
#print('Gave '+ toAllocate +' to '+ loc.Name)
progressList.remove(toAllocate)
allocated = True
#if(loc.isItem()):
loc.item = toAllocate
loc.IsGym = False
loc.IsItem = True
#print("Spoilers:", loc.Name, loc.item)
spoiler[loc.item] = loc.Name
#if(loc.isGym()):
# loc.badge = badgeData[toAllocate]
# badgeSet.remove(toAllocate)
# spoiler[loc.badge.Name] = loc.Name
allocatedList.append(loc)
#requirementsDict[toAllocate] = requirementsDict[loc.Name]
if not 'unsafePlando' in inputFlags:
requirementsDict[toAllocate] = [list(frozenset(allDepsList))]
fullDependenciesList[toAllocate] = allDepsList
#print(spoiler)
else:
#print(locList[iter].Name+' cannot contain '+toAllocate)
if(toAllocate in allDepsList):
1+1
#print('...because it requires '+toAllocate+' to be reached in the first place!')
#print(spoiler)
else:
1+1
#print('...because its currently an illegal location')
#print(spoiler)
#iter = iter+1
# else:
# iter = iter+1
# if iter == len(locList) and not valid:
# iter = 0
# retryPasses = retryPasses-1
# #print('retrying with different paths')
iter = iter + 1
#print('----')
#print("spoiler is: ", spoiler)
# This should be moved to prevent it running on each attempt through!
if "RandomiseItems" in inputFlags:
handles = list(filter(lambda x: len(x.Handles) > 0, locList))
for handle in handles:
extraFlags = []
if "ImpossibleRandomise" in handle.Handles and "Banned" in handle.FlagReqs:
specialFlagName = handle.Name
toHandle = list(filter(lambda x: specialFlagName in x.FlagReqs, locList))
for h in toHandle:
h.FlagReqs.append("ImpossibleRandomise")
for flag in h.FlagsSet:
if flag not in extraFlags:
extraFlags.append(flag)
for flag in handle.FlagsSet:
if flag not in extraFlags:
extraFlags.append(flag)
for extraFlag in extraFlags:
toHandleFlag = list(filter(lambda x: extraFlag in x.FlagReqs, locList))
for h in toHandleFlag:
h.FlagReqs.append("ImpossibleRandomise")
if "RandomiseItems" in inputFlags:
item_processor = RandomizeFunctions.RandomItemProcessor(dontReplace)
else:
item_processor = None
reachable, stateDist, randomizerFailed, trashSpoiler, randomizedExtra, upgradedItems, beatabilityWarnings = \
checkBeatability(spoiler, locationTree, inputFlags, trashItems, plandoPlacements, monReqItems, locList,