forked from theonlydude/RandomMetroidSolver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.py
executable file
·1548 lines (1310 loc) · 66.3 KB
/
solver.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
#!/usr/bin/python
import sys, math, argparse, re, json, os, subprocess, logging
from time import gmtime, strftime
# the difficulties for each technics
from parameters import Knows, Settings, isKnows, isSettings
from parameters import easy, medium, hard, harder, hardcore, mania, god, samus, impossibru, infinity, diff2text
# the helper functions
from smbool import SMBool
from smboolmanager import SMBoolManager
from helpers import Pickup, Bosses
from rom import RomLoader, RomPatcher, RomReader
from itemrandomizerweb.Items import ItemManager
from graph_locations import locations as graphLocations
from graph import AccessGraph
from graph_access import vanillaTransitions, accessPoints, getDoorConnections, getTransitions, vanillaBossesTransitions, getAps2DoorsPtrs
from utils import PresetLoader
from vcr import VCR
import log
class Conf:
# keep getting majors of at most this difficulty before going for minors or changing area
difficultyTarget = medium
# display the generated path (spoilers!)
displayGeneratedPath = False
# choose how many items are required (possible value: minimal/all/any)
itemsPickup = 'minimal'
# the list of items to not pick up
itemsForbidden = []
class SolverState(object):
def __init__(self, debug=False):
self.debug = debug
def fromSolver(self, solver):
self.state = {}
# string
self.state["majorsSplit"] = solver.majorsSplit
# bool
self.state["areaRando"] = solver.areaRando
# bool
self.state["bossRando"] = solver.bossRando
# dict of raw patches
self.state["patches"] = solver.patches
# dict {locName: {itemName: "xxx", "accessPoint": "xxx"}, ...}
self.state["locsData"] = self.getLocsData(solver.locations)
# list [(ap1, ap2), (ap3, ap4), ...]
self.state["areaTransitions"] = solver.areaTransitions
# list [(ap1, ap2), (ap3, ap4), ...]
self.state["bossTransitions"] = solver.bossTransitions
# list [(ap1, ap2), ...]
self.state["curGraphTransitions"] = solver.curGraphTransitions
# preset file name
self.state["presetFileName"] = solver.presetFileName
## items collected / locs visited / bosses killed
# list [item1, item2, ...]
self.state["collectedItems"] = solver.collectedItems
# dict {locName: {index: 0, difficulty: (bool, diff, ...), ...} with index being the position of the loc in visitedLocations
self.state["visitedLocations"] = self.getVisitedLocations(solver.visitedLocations)
# dict {locName: (bool, diff, [know1, ...], [item1, ...]), ...}
self.state["availableLocations"] = self.getAvailableLocations(solver.majorLocations)
# string of last access point
self.state["lastLoc"] = solver.lastLoc
# list of killed bosses: ["boss1", "boss2"]
self.state["bosses"] = [boss for boss in Bosses.golden4Dead if Bosses.golden4Dead[boss] == True]
# dict {locNameWeb: {infos}, ...}
self.state["availableLocationsWeb"] = self.getAvailableLocationsWeb(solver.majorLocations)
# dict {locNameWeb: {infos}, ...}
self.state["visitedLocationsWeb"] = self.getAvailableLocationsWeb(solver.visitedLocations)
# dict {locNameWeb: {infos}, ...}
self.state["remainLocationsWeb"] = self.getRemainLocationsWeb(solver.majorLocations)
# string: standard/seedless/plando
self.state["mode"] = solver.mode
# string:
self.state["seed"] = solver.seed
# dict {point: point, ...} / array of startPoints
(self.state["linesWeb"], self.state["linesSeqWeb"]) = self.getLinesWeb(solver.curGraphTransitions)
# bool
self.state["allTransitions"] = len(solver.curGraphTransitions) == len(solver.areaTransitions) + len(solver.bossTransitions)
def toSolver(self, solver):
if 'majorsSplit' in self.state:
solver.majorsSplit = self.state["majorsSplit"]
else:
# compatibility with existing sessions
if self.state['fullRando'] == True:
solver.majorsSplit = 'Full'
else:
solver.majorsSplit = 'Major'
solver.areaRando = self.state["areaRando"]
solver.bossRando = self.state["bossRando"]
solver.patches = self.setPatches(self.state["patches"])
self.setLocsData(solver.locations)
solver.areaTransitions = self.state["areaTransitions"]
solver.bossTransitions = self.state["bossTransitions"]
solver.curGraphTransitions = self.state["curGraphTransitions"]
# preset
solver.presetFileName = self.state["presetFileName"]
# items collected / locs visited / bosses killed
solver.collectedItems = self.state["collectedItems"]
(solver.visitedLocations, solver.majorLocations) = self.setLocations(self.state["visitedLocations"],
self.state["availableLocations"],
solver.locations)
solver.lastLoc = self.state["lastLoc"]
Bosses.reset()
for boss in self.state["bosses"]:
Bosses.beatBoss(boss)
solver.mode = self.state["mode"]
solver.seed = self.state["seed"]
def getLocsData(self, locations):
ret = {}
for loc in locations:
ret[loc["Name"]] = {"itemName": loc["itemName"]}
if "accessPoint" in loc:
ret[loc["Name"]]["accessPoint"] = loc["accessPoint"]
return ret
def setLocsData(self, locations):
for loc in locations:
loc["itemName"] = self.state["locsData"][loc["Name"]]["itemName"]
if "accessPoint" in self.state["locsData"][loc["Name"]]:
loc["accessPoint"] = self.state["locsData"][loc["Name"]]["accessPoint"]
def getVisitedLocations(self, visitedLocations):
# need to keep the order (for cancelation)
ret = {}
i = 0
for loc in visitedLocations:
diff = loc["difficulty"]
ret[loc["Name"]] = {"index": i, "difficulty": (diff.bool, diff.difficulty, diff.knows, diff.items)}
i += 1
return ret
def setLocations(self, visitedLocations, availableLocations, locations):
retVis = []
retMaj = []
for loc in locations:
if loc["Name"] in visitedLocations:
# visitedLocations contains an index
diff = visitedLocations[loc["Name"]]["difficulty"]
loc["difficulty"] = SMBool(diff[0], diff[1], diff[2], diff[3])
retVis.append((visitedLocations[loc["Name"]]["index"], loc))
else:
if loc["Name"] in availableLocations:
diff = availableLocations[loc["Name"]]
loc["difficulty"] = SMBool(diff[0], diff[1], diff[2], diff[3])
retMaj.append(loc)
retVis.sort(key=lambda x: x[0])
return ([loc for (i, loc) in retVis], retMaj)
def diff4isolver(self, difficulty):
if difficulty == -1:
return "break"
elif difficulty < medium:
return "easy"
elif difficulty < hard:
return "medium"
elif difficulty < harder:
return "hard"
elif difficulty < hardcore:
return "harder"
elif difficulty < mania:
return "hardcore"
else:
return "mania"
def name4isolver(self, locName):
# remove space and special characters
# sed -e 's+ ++g' -e 's+,++g' -e 's+(++g' -e 's+)++g' -e 's+-++g'
return locName.translate(None, " ,()-")
def knows2isolver(self, knows):
result = []
for know in knows:
if know in Knows.desc:
result.append(Knows.desc[know]['display'])
else:
result.append(know)
return list(set(result))
def transition2isolver(self, transition):
transition = str(transition)
return transition[0].lower()+transition[1:].translate(None, " ,()-")
def getAvailableLocationsWeb(self, locations):
ret = {}
for loc in locations:
if "difficulty" in loc and loc["difficulty"].bool == True:
diff = loc["difficulty"]
locName = self.name4isolver(loc["Name"])
ret[locName] = {"difficulty": self.diff4isolver(diff.difficulty),
"knows": self.knows2isolver(diff.knows),
"items": list(set(diff.items)),
"item": loc["itemName"],
"name": loc["Name"]}
if "comeBack" in loc:
ret[locName]["comeBack"] = loc["comeBack"]
# for debug purpose
if self.debug == True:
if "path" in loc:
ret[locName]["path"] = [a.Name for a in loc["path"]]
return ret
def getRemainLocationsWeb(self, locations):
ret = {}
for loc in locations:
if "difficulty" not in loc or ("difficulty" in loc and loc["difficulty"].bool == False):
locName = self.name4isolver(loc["Name"])
ret[locName] = {"item": loc["itemName"],
"name": loc["Name"],
"knows": ["Sequence Break"],
"items": []}
return ret
def getLinesWeb(self, transitions):
lines = {}
linesSeq = []
for (start, end) in transitions:
startWeb = self.transition2isolver(start)
endWeb = self.transition2isolver(end)
lines[startWeb] = endWeb
lines[endWeb] = startWeb
linesSeq.append((startWeb, endWeb))
return (lines, linesSeq)
def getAvailableLocations(self, locations):
ret = {}
for loc in locations:
if "difficulty" in loc and loc["difficulty"].bool == True:
diff = loc["difficulty"]
ret[loc["Name"]] = (diff.bool, diff.difficulty, diff.knows, diff.items)
return ret
def setPatches(self, patchesData):
# json's dicts keys are strings
ret = {}
for address in patchesData:
ret[int(address)] = patchesData[address]
return ret
def fromJson(self, stateJsonFileName):
with open(stateJsonFileName, 'r') as jsonFile:
self.state = json.load(jsonFile)
# print("Loaded Json State:")
# for key in self.state:
# if key in ["availableLocationsWeb", "visitedLocationsWeb", "collectedItems", "availableLocations", "visitedLocations"]:
# print("{}: {}".format(key, self.state[key]))
# print("")
def toJson(self, outputFileName):
with open(outputFileName, 'w') as jsonFile:
json.dump(self.state, jsonFile)
# print("Dumped Json State:")
# for key in self.state:
# if key in ["availableLocationsWeb", "visitedLocationsWeb", "collectedItems", "visitedLocations"]:
# print("{}: {}".format(key, self.state[key]))
# print("")
class CommonSolver(object):
def loadRom(self, rom, interactive=False, magic=None):
if rom == None:
self.romFileName = 'seedless'
self.majorsSplit = 'Full'
self.areaRando = True
self.bossRando = True
self.patches = RomReader.getDefaultPatches()
RomLoader.factory(self.patches).loadPatches()
self.curGraphTransitions = []
self.areaTransitions = []
self.bossTransitions = []
for loc in self.locations:
loc['itemName'] = 'Nothing'
else:
self.romFileName = rom
self.romLoader = RomLoader.factory(rom, magic)
self.majorsSplit = self.romLoader.assignItems(self.locations)
(self.areaRando, self.bossRando) = self.romLoader.loadPatches()
if interactive == False:
self.patches = self.romLoader.getPatches()
else:
self.patches = self.romLoader.getRawPatches()
print("ROM {} majors: {} area: {} boss: {} patches: {}".format(rom, self.majorsSplit, self.areaRando, self.bossRando, self.patches))
(self.areaTransitions, self.bossTransitions) = self.romLoader.getTransitions()
if interactive == True and self.debug == False:
# in interactive area mode we build the graph as we play along
if self.areaRando == True and self.bossRando == True:
self.curGraphTransitions = []
elif self.areaRando == True:
self.curGraphTransitions = self.bossTransitions[:]
elif self.bossRando == True:
self.curGraphTransitions = self.areaTransitions[:]
else:
self.curGraphTransitions = self.bossTransitions + self.areaTransitions
else:
self.curGraphTransitions = self.bossTransitions + self.areaTransitions
self.areaGraph = AccessGraph(accessPoints, self.curGraphTransitions)
if self.log.getEffectiveLevel() == logging.DEBUG:
self.log.debug("Display items at locations:")
for location in self.locations:
self.log.debug('{:>50}: {:>16}'.format(location["Name"], location['itemName']))
def loadPreset(self, presetFileName):
presetLoader = PresetLoader.factory(presetFileName)
presetLoader.load()
self.smbm.createKnowsFunctions()
if self.log.getEffectiveLevel() == logging.DEBUG:
presetLoader.printToScreen()
def computeLocationsDifficulty(self, locations):
self.areaGraph.getAvailableLocations(locations, self.smbm, infinity, self.lastLoc)
# check post available functions too
for loc in locations:
if loc['difficulty'].bool == True:
if 'PostAvailable' in loc:
# in plando mode we can have the same major multiple times
already = self.smbm.haveItem(loc['itemName'])
isCount = self.smbm.isCountItem(loc['itemName'])
self.smbm.addItem(loc['itemName'])
postAvailable = loc['PostAvailable'](self.smbm)
if not already or isCount == True:
self.smbm.removeItem(loc['itemName'])
loc['difficulty'] = self.smbm.wand(loc['difficulty'], postAvailable)
# also check if we can come back to landing site from the location
loc['comeBack'] = self.areaGraph.canAccess(self.smbm, loc['accessPoint'], self.lastLoc, infinity, loc['itemName'])
if self.log.getEffectiveLevel() == logging.DEBUG:
self.log.debug("available locs:")
for loc in locations:
if loc['difficulty'].bool == True:
self.log.debug("{}: {}".format(loc['Name'], loc['difficulty']))
def collectMajor(self, loc, itemName=None):
self.majorLocations.remove(loc)
self.visitedLocations.append(loc)
area = self.collectItem(loc, itemName)
return area
def collectMinor(self, loc):
self.minorLocations.remove(loc)
self.visitedLocations.append(loc)
area = self.collectItem(loc)
return area
def collectItem(self, loc, item=None):
if item == None:
item = loc["itemName"]
if self.vcr != None:
self.vcr.addLocation(loc['Name'], item)
if self.firstLogFile is not None:
if item not in self.collectedItems:
self.firstLogFile.write("{};{};{};{}\n".format(item, loc['Name'], loc['Area'], loc['GraphArea']))
if item not in Conf.itemsForbidden:
self.collectedItems.append(item)
if self.checkDuplicateMajor == True:
if item not in ['Nothing', 'NoEnergy', 'Missile', 'Super', 'PowerBomb', 'ETank', 'Reserve']:
if self.smbm.haveItem(item):
print("WARNING: {} has already been picked up".format(item))
self.smbm.addItem(item)
else:
# update the name of the item
item = "-{}-".format(item)
loc["itemName"] = item
self.collectedItems.append(item)
# we still need the boss difficulty
if 'Pickup' not in loc:
loc["difficulty"] = SMBool(False)
if 'Pickup' in loc:
loc['Pickup']()
self.log.debug("collectItem: {} at {}".format(item, loc['Name']))
# last loc is used as root node for the graph
self.lastLoc = loc['accessPoint']
return loc['SolveArea']
class InteractiveSolver(CommonSolver):
def __init__(self, output):
self.checkDuplicateMajor = False
self.vcr = None
self.log = log.get('Solver')
self.outputFileName = output
self.firstLogFile = None
self.locations = graphLocations
(self.locsAddressName, self.locsWeb2Internal) = self.initLocsAddressName()
self.transWeb2Internal = self.initTransitionsName()
def initLocsAddressName(self):
addressName = {}
web2Internal = {}
for loc in graphLocations:
webName = self.locNameInternal2Web(loc["Name"])
addressName[loc["Address"] % 0x10000] = webName
web2Internal[webName] = loc["Name"]
return (addressName, web2Internal)
def initTransitionsName(self):
web2Internal = {}
for (startPoint, endPoint) in vanillaTransitions + vanillaBossesTransitions:
for point in [startPoint, endPoint]:
web2Internal[self.apNameInternal2Web(point)] = point
return web2Internal
def dumpState(self):
state = SolverState(self.debug)
state.fromSolver(self)
state.toJson(self.outputFileName)
def initialize(self, mode, rom, presetFileName, magic, debug):
# load rom and preset, return first state
self.debug = debug
self.mode = mode
if self.mode != "seedless":
self.seed = os.path.basename(os.path.splitext(rom)[0])+'.sfc'
else:
self.seed = "seedless"
self.smbm = SMBoolManager()
self.presetFileName = presetFileName
self.loadPreset(self.presetFileName)
self.loadRom(rom, interactive=True, magic=magic)
self.clearItems()
# in debug mode don't load plando locs/transitions
if self.mode == 'plando' and self.debug == False:
if self.areaRando == True:
plandoTrans = self.loadPlandoTransitions()
if len(plandoTrans) > 0:
self.curGraphTransitions = plandoTrans
self.areaGraph = AccessGraph(accessPoints, self.curGraphTransitions)
self.loadPlandoLocs()
# compute new available locations
self.computeLocationsDifficulty(self.majorLocations)
self.dumpState()
def iterate(self, stateJson, scope, action, params):
self.debug = params["debug"]
self.smbm = SMBoolManager()
state = SolverState()
state.fromJson(stateJson)
state.toSolver(self)
RomLoader.factory(self.patches).loadPatches()
self.loadPreset(self.presetFileName)
# add already collected items to smbm
self.smbm.addItems(self.collectedItems)
if scope == 'item':
if action == 'clear':
self.clearItems(True)
else:
if action == 'add':
if self.mode == 'plando' or self.mode == 'seedless':
self.setItemAt(params['loc'], params['item'])
else:
# pickup item at locName
self.pickItemAt(params['loc'])
elif action == 'remove':
# remove last collected item
self.cancelLastItems(params['count'])
elif action == 'replace':
self.replaceItemAt(params['loc'], params['item'])
elif scope == 'area':
if action == 'clear':
self.clearTransitions()
else:
if action == 'add':
startPoint = params['startPoint']
endPoint = params['endPoint']
self.addTransition(self.transWeb2Internal[startPoint], self.transWeb2Internal[endPoint])
elif action == 'remove':
# remove last transition
self.cancelLastTransition()
self.areaGraph = AccessGraph(accessPoints, self.curGraphTransitions)
if scope == 'common' and action == 'save':
return self.savePlando()
# compute new available locations
self.clearLocs(self.majorLocations)
self.computeLocationsDifficulty(self.majorLocations)
# return them
self.dumpState()
def getLocNameFromAddress(self, address):
return self.locsAddressName[address]
def loadPlandoTransitions(self):
transitionsAddr = self.romLoader.getPlandoTransitions(len(vanillaBossesTransitions) + len(vanillaTransitions))
return getTransitions(transitionsAddr)
def loadPlandoLocs(self):
# get the addresses of the already filled locs, with the correct order
addresses = self.romLoader.getPlandoAddresses()
# create a copy of the locations to avoid removing locs from self.locations
self.majorLocations = self.locations[:]
for address in addresses:
# TODO::compute only the difficulty of the current loc
self.computeLocationsDifficulty(self.majorLocations)
locName = self.getLocNameFromAddress(address)
self.pickItemAt(locName)
def savePlando(self):
# store filled locations addresses in the ROM for next creating session
locsItems = {}
itemLocs = []
for loc in self.visitedLocations:
locsItems[loc["Name"]] = loc["itemName"]
for loc in self.locations:
if loc["Name"] in locsItems:
itemLocs.append({'Location': loc, 'Item': ItemManager.getItem(locsItems[loc["Name"]])})
else:
itemLocs.append({'Location': loc, 'Item': ItemManager.getItem(loc["itemName"])})
# patch the ROM
romPatcher = RomPatcher()
romPatcher.writeItemsLocs(itemLocs)
romPatcher.writeItemsNumber()
romPatcher.writeSpoiler(itemLocs)
romPatcher.writePlandoAddresses(self.visitedLocations)
if self.areaRando == True:
doors = getDoorConnections(self.areaGraph)
romPatcher.writeDoorConnections(doors)
doorsPtrs = getAps2DoorsPtrs()
romPatcher.writePlandoTransitions(self.curGraphTransitions, doorsPtrs,
len(vanillaBossesTransitions) + len(vanillaTransitions))
romPatcher.end()
data = romPatcher.romFile.data
preset = os.path.splitext(os.path.basename(self.presetFileName))[0]
seedCode = 'FX'
if self.bossRando == True:
seedCode = 'B'+seedCode
if self.areaRando == True:
seedCode = 'A'+seedCode
fileName = 'VARIA_Plandomizer_{}{}_{}.sfc'.format(seedCode, strftime("%Y%m%d%H%M%S", gmtime()), preset)
data["fileName"] = fileName
# error msg in json to be displayed by the web site
data["errorMsg"] = ""
with open(self.outputFileName, 'w') as jsonFile:
json.dump(data, jsonFile)
def locNameInternal2Web(self, locName):
return locName.translate(None, " ,()-")
def locNameWeb2Internal(self, locNameWeb):
return self.locsWeb2Internal[locNameWeb]
def apNameInternal2Web(self, apName):
return apName[0].lower()+apName[1:].translate(None, " ")
def getLoc(self, locNameWeb):
locName = self.locNameWeb2Internal(locNameWeb)
for loc in self.locations:
if loc["Name"] == locName:
return loc
raise Exception("Location '{}' not found".format(locName))
def pickItemAt(self, locName):
# collect new item at newLoc
loc = self.getLoc(locName)
if "difficulty" not in loc or loc["difficulty"] == False:
# sequence break
loc["difficulty"] = SMBool(True, -1)
if "accessPoint" not in loc:
# take first ap of the loc
loc["accessPoint"] = loc["AccessFrom"].keys()[0]
self.collectMajor(loc)
def setItemAt(self, locName, itemName):
# set itemName at locName
loc = self.getLoc(locName)
# plando mode
loc["itemName"] = itemName
if "difficulty" not in loc:
# sequence break
loc["difficulty"] = SMBool(True, -1)
if "accessPoint" not in loc:
# take first ap of the loc
loc["accessPoint"] = loc["AccessFrom"].keys()[0]
self.collectMajor(loc, itemName)
def replaceItemAt(self, locName, itemName):
# replace itemName at locName
loc = self.getLoc(locName)
oldItemName = loc["itemName"]
loc["itemName"] = itemName
# major item can be set multiple times in plando mode
count = self.collectedItems.count(oldItemName)
isCount = self.smbm.isCountItem(oldItemName)
# replace item at the old item spot in collectedItems
index = next(i for i, vloc in enumerate(self.visitedLocations) if vloc['Name'] == loc['Name'])
self.collectedItems[index] = itemName
# update smbm if count item or major was only there once
if isCount == True or count == 1:
self.smbm.removeItem(oldItemName)
self.smbm.addItem(itemName)
def cancelLastItems(self, count):
for _ in range(count):
if len(self.visitedLocations) == 0:
return
loc = self.visitedLocations.pop()
self.majorLocations.append(loc)
# pickup func
if 'Unpickup' in loc:
loc['Unpickup']()
# access point
if len(self.visitedLocations) == 0:
self.lastLoc = "Landing Site"
else:
self.lastLoc = self.visitedLocations[-1]["accessPoint"]
# item
item = loc["itemName"]
if item != self.collectedItems[-1]:
raise Exception("Item of last collected loc {}: {} is different from last collected item: {}".format(loc["Name"], item, self.collectedItems[-1]))
self.smbm.removeItem(item)
self.collectedItems.pop()
def clearItems(self, reload=False):
self.collectedItems = []
self.visitedLocations = []
self.lastLoc = 'Landing Site'
self.majorLocations = self.locations
if reload == True:
for loc in self.majorLocations:
if "difficulty" in loc:
del loc["difficulty"]
Bosses.reset()
self.smbm.resetItems()
def addTransition(self, startPoint, endPoint):
# already check in controller if transition is valid for seed
self.curGraphTransitions.append((startPoint, endPoint))
def cancelLastTransition(self):
if self.areaRando == True and self.bossRando == True:
if len(self.curGraphTransitions) > 0:
self.curGraphTransitions.pop()
elif self.areaRando == True:
if len(self.curGraphTransitions) > len(self.bossTransitions):
self.curGraphTransitions.pop()
elif self.bossRando == True:
if len(self.curGraphTransitions) > len(self.areaTransitions):
self.curGraphTransitions.pop()
def clearTransitions(self):
if self.areaRando == True and self.bossRando == True:
self.curGraphTransitions = []
elif self.areaRando == True:
self.curGraphTransitions = self.bossTransitions[:]
elif self.bossRando == True:
self.curGraphTransitions = self.areaTransitions[:]
else:
self.curGraphTransitions = self.bossTransitions + self.areaTransitions
def clearLocs(self, locs):
for loc in locs:
if 'difficulty' in loc:
del loc['difficulty']
class StandardSolver(CommonSolver):
# given a rom and parameters returns the estimated difficulty
def __init__(self, rom, presetFileName, difficultyTarget, pickupStrategy, itemsForbidden=[], type='console', firstItemsLog=None, displayGeneratedPath=False, outputFileName=None, magic=None, checkDuplicateMajor=False, vcr=False):
self.checkDuplicateMajor = checkDuplicateMajor
self.vcr = VCR(rom, 'solver') if vcr == True else None
self.log = log.get('Solver')
self.setConf(difficultyTarget, pickupStrategy, itemsForbidden, displayGeneratedPath)
self.firstLogFile = None
if firstItemsLog is not None:
self.firstLogFile = open(firstItemsLog, 'w')
self.firstLogFile.write('Item;Location;Area\n')
# can be called from command line (console) or from web site (web)
self.type = type
self.output = Out.factory(self.type, self)
self.outputFileName = outputFileName
self.locations = graphLocations
self.smbm = SMBoolManager()
self.presetFileName = presetFileName
self.loadPreset(self.presetFileName)
self.loadRom(rom, magic=magic)
self.pickup = Pickup(Conf.itemsPickup)
def setConf(self, difficultyTarget, pickupStrategy, itemsForbidden, displayGeneratedPath):
Conf.difficultyTarget = difficultyTarget
Conf.itemsPickup = pickupStrategy
Conf.displayGeneratedPath = displayGeneratedPath
Conf.itemsForbidden = itemsForbidden
def solveRom(self):
self.lastLoc = 'Landing Site'
(self.difficulty, self.itemsOk) = self.computeDifficulty()
if self.firstLogFile is not None:
self.firstLogFile.close()
(self.knowsUsed, self.knowsKnown) = self.getKnowsUsed()
if self.vcr != None:
self.vcr.dump()
self.output.out()
def getRemainMajors(self):
return [loc for loc in self.majorLocations if loc['difficulty'].bool == False and loc['itemName'] not in ['Nothing', 'NoEnergy']]
def getRemainMinors(self):
if self.majorsSplit == 'Full':
return None
else:
return [loc for loc in self.minorLocations if loc['difficulty'].bool == False and loc['itemName'] not in ['Nothing', 'NoEnergy']]
def getSkippedMajors(self):
return [loc for loc in self.majorLocations if loc['difficulty'].bool == True and loc['itemName'] not in ['Nothing', 'NoEnergy']]
def getUnavailMajors(self):
return [loc for loc in self.majorLocations if loc['difficulty'].bool == False and loc['itemName'] not in ['Nothing', 'NoEnergy']]
def getLoc(self, locName):
for loc in self.locations:
if loc['Name'] == locName:
return loc
def getDiffThreshold(self):
target = Conf.difficultyTarget
threshold = target
epsilon = 0.001
if target <= easy:
threshold = medium - epsilon
elif target <= medium:
threshold = hard - epsilon
elif target <= hard:
threshold = harder - epsilon
elif target <= harder:
threshold = hardcore - epsilon
elif target <= hardcore:
threshold = mania - epsilon
return threshold
def computeDifficulty(self):
# loop on the available locations depending on the collected items.
# before getting a new item, loop on all of them and get their difficulty,
# the next collected item is the one with the smallest difficulty,
# if equality between major and minor, take major first.
if self.majorsSplit == 'Major':
self.majorLocations = [loc for loc in self.locations if "Major" in loc["Class"] or "Boss" in loc["Class"]]
self.minorLocations = [loc for loc in self.locations if "Minor" in loc["Class"]]
elif self.majorsSplit == 'Chozo':
self.majorLocations = [loc for loc in self.locations if "Chozo" in loc["Class"] or "Boss" in loc["Class"]]
self.minorLocations = [loc for loc in self.locations if "Chozo" not in loc["Class"]]
else:
# Full
self.majorLocations = self.locations[:] # copy
self.minorLocations = self.majorLocations
self.visitedLocations = []
self.collectedItems = []
# with the knowsXXX conditions some roms can be unbeatable, so we have to detect it
previous = -1
current = 0
self.log.debug("{}: available major: {}, available minor: {}, visited: {}".format(Conf.itemsPickup, len(self.majorLocations), len(self.minorLocations), len(self.visitedLocations)))
isEndPossible = False
endDifficulty = mania
area = 'Crateria Landing Site'
diffThreshold = self.getDiffThreshold()
while True:
# actual while condition
hasEnoughMinors = self.pickup.enoughMinors(self.smbm, self.minorLocations)
hasEnoughMajors = self.pickup.enoughMajors(self.smbm, self.majorLocations)
hasEnoughItems = hasEnoughMajors and hasEnoughMinors
canEndGame = self.canEndGame()
(isEndPossible, endDifficulty) = (canEndGame.bool, canEndGame.difficulty)
if isEndPossible and hasEnoughItems and endDifficulty <= diffThreshold:
# check if last visited location is mother brain
if self.visitedLocations[-1]['Name'] != 'Mother Brain':
self.computeLocationsDifficulty(self.majorLocations)
mbLoc = self.getLoc('Mother Brain')
self.collectMajor(mbLoc)
self.log.debug("END")
break
#self.log.debug(str(self.collectedItems))
self.log.debug("Current Area : " + area)
# check if we have collected an item in the last loop
current = len(self.collectedItems)
if current == previous:
if not isEndPossible:
self.log.debug("STUCK ALL")
else:
self.log.debug("HARD END")
break
previous = current
# compute the difficulty of all the locations
self.computeLocationsDifficulty(self.majorLocations)
if self.majorsSplit != 'Full':
self.computeLocationsDifficulty(self.minorLocations)
# keep only the available locations
majorsAvailable = [loc for loc in self.majorLocations if 'difficulty' in loc and loc["difficulty"].bool == True]
minorsAvailable = [loc for loc in self.minorLocations if 'difficulty' in loc and loc["difficulty"].bool == True]
# check if we're stuck
if len(majorsAvailable) == 0 and len(minorsAvailable) == 0:
if not isEndPossible:
self.log.debug("STUCK MAJORS and MINORS")
else:
self.log.debug("HARD END")
break
# sort them on difficulty and proximity
majorsAvailable = self.getAvailableItemsList(majorsAvailable, area, diffThreshold)
if self.majorsSplit == 'Full':
minorsAvailable = majorsAvailable
else:
minorsAvailable = self.getAvailableItemsList(minorsAvailable, area, diffThreshold)
# choose one to pick up
area = self.nextDecision(majorsAvailable, minorsAvailable, hasEnoughMinors, diffThreshold, area)
# compute difficulty value
(difficulty, itemsOk) = self.computeDifficultyValue()
self.log.debug("difficulty={}".format(difficulty))
self.log.debug("itemsOk={}".format(itemsOk))
self.log.debug("{}: remaining major: {}, remaining minor: {}, visited: {}".format(Conf.itemsPickup, len(self.majorLocations), len(self.minorLocations), len(self.visitedLocations)))
self.log.debug("remaining majors:")
for loc in self.majorLocations:
self.log.debug("{} ({})".format(loc['Name'], loc['itemName']))
self.log.debug("bosses: {}".format(Bosses.golden4Dead))
return (difficulty, itemsOk)
def handleNoComeBack(self, locations):
# check if all the available locations have the no come back flag
# if so add a new parameter with the number of locations in each graph area
graphLocs = {}
for loc in locations:
if "comeBack" not in loc:
return False
if loc["comeBack"] == True:
return False
if loc["GraphArea"] in graphLocs:
graphLocs[loc["GraphArea"]] += 1
else:
graphLocs[loc["GraphArea"]] = 1
if len(graphLocs) == 1:
return False
for graphLoc in graphLocs:
graphLocs[graphLoc] = 1.0/graphLocs[graphLoc]
for loc in locations:
loc["areaWeight"] = graphLocs[loc["GraphArea"]]
print("WARNING: use no come back heuristic for {} locs in {} graph locs".format(len(locations), len(graphLocs)))
return True
def getAvailableItemsList(self, locations, area, threshold):
# locations without distance are not available
locations = [loc for loc in locations if 'distance' in loc]
if len(locations) == 0:
return []
cleanAreaWeight = self.handleNoComeBack(locations)
around = [loc for loc in locations if ((loc['SolveArea'] == area or loc['distance'] < 3)
and loc['difficulty'].difficulty <= threshold
and not Bosses.areaBossDead(area)
and 'comeBack' in loc and loc['comeBack'] == True)]
outside = [loc for loc in locations if not loc in around]
self.log.debug("around1 = {}".format([(loc['Name'], loc['difficulty'], loc['distance'], loc['comeBack'], loc['SolveArea']) for loc in around]))
self.log.debug("outside1 = {}".format([(loc['Name'], loc['difficulty'], loc['distance'], loc['comeBack'], loc['SolveArea']) for loc in outside]))
around.sort(key=lambda loc: (
# locs in the same area
0 if loc['SolveArea'] == area
else 1,
# nearest locs
loc['distance'],
# beating a boss
0 if 'Pickup' in loc
else 1,
# easiest first
loc['difficulty'].difficulty
)
)
# we want to sort the outside locations by putting the ones is the same area first
# then we sort the remaining areas starting whith boss dead status
outside.sort(key=lambda loc: (
# no come back heuristic
loc["areaWeight"] if "areaWeight" in loc
else 0,
# first loc where we can come back
0 if 'comeBack' in loc and loc['comeBack'] == True
else 1,
# first locs in the same area
0 if loc['SolveArea'] == area and loc['difficulty'].difficulty <= threshold
else 1,
# first nearest locs
loc['distance'] if loc['difficulty'].difficulty <= threshold
else 100000,
# beating a boss
loc['difficulty'].difficulty if (not Bosses.areaBossDead(loc['Area'])
and loc['difficulty'].difficulty <= threshold
and 'Pickup' in loc)
else 100000,
# areas with boss still alive
loc['difficulty'].difficulty if (not Bosses.areaBossDead(loc['Area'])
and loc['difficulty'].difficulty <= threshold)
else 100000,
loc['difficulty'].difficulty))
self.log.debug("around2 = " + str([(loc['Name'], loc['difficulty'], loc['distance'], loc['comeBack'], loc['SolveArea']) for loc in around]))
self.log.debug("outside2 = " + str([(loc['Name'], loc['difficulty'], loc['distance'], loc['comeBack'], loc['SolveArea']) for loc in outside]))
if cleanAreaWeight == True:
for loc in locations:
del loc["areaWeight"]
return around + outside
def nextDecision(self, majorsAvailable, minorsAvailable, hasEnoughMinors, diffThreshold, area):
# first take major items of acceptable difficulty in the current area
if (len(majorsAvailable) > 0
and majorsAvailable[0]['SolveArea'] == area
and majorsAvailable[0]['difficulty'].difficulty <= diffThreshold
and majorsAvailable[0]['comeBack'] == True):
return self.collectMajor(majorsAvailable.pop(0))
# next item decision
if len(minorsAvailable) == 0 and len(majorsAvailable) > 0:
self.log.debug('MAJOR')