forked from vg-json-data/sm-json-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeywords.py
More file actions
1473 lines (1369 loc) · 74.8 KB
/
keywords.py
File metadata and controls
1473 lines (1369 loc) · 74.8 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
# pylint: disable=global-at-module-level, invalid-name, too-many-locals
'''
Check for validity of keywords in files
'''
import json
import os
import re
import subprocess
import sys
from flatten_json import flatten
bail = False # throw an exit code
last_enemy = "" # helper for enemy validation
uniques = { # track used IDs and make sure that they're successively unique
"groupName": [],
"roomID": [],
"roomName": [],
"roomAddress": [],
"nodeAddress": []
}
messages = { # track messages and message counts
"greens": [],
"yellows": [],
"reds": [],
"counts": {
"greens": 0,
"yellows": 0,
"reds": 0
}
}
strat_name_entrance_conditions = [
("Come In Normally", "comeInNormally"),
("Come In Running", "comeInRunning"),
("Come In Jumping", "comeInJumping"),
("Come In Space Jumping", "comeInSpaceJumping"),
("Come In Blue Space Jumping", "comeInBlueSpaceJumping"),
("Come In Shinecharging", "comeInShinecharging"),
("Come In Shinecharged Jumping", "comeInShinechargedJumping"),
("Come In Shinecharged", "comeInShinecharged"),
("Carry Shinecharge", "comeInShinecharged"),
("Come In With Spark", "comeInWithSpark"),
("Come In With Bomb Boost", "comeInWithBombBoost"),
("Come In Speedballing", "comeInSpeedballing"),
("Come In With Temporary Blue", "comeInWithTemporaryBlue"),
("Come In With Mockball", "comeInWithMockball"),
("Come In With Spring Ball Bounce", "comeInWithSpringBallBounce"),
("Come In With Blue Spring Ball Bounce", "comeInWithBlueSpringBallBounce"),
("Come In Spinning", "comeInSpinning"),
("Come In Blue Spinning", "comeInBlueSpinning"),
("Stored Moonfall Clip", "comeInWithStoredFallSpeed"),
("Transition with Stored Fall Speed", "comeInWithStoredFallSpeed"),
("Carry Grapple Teleport", "comeInWithGrappleTeleport"),
("Carry G-Mode", "comeInWithGMode"),
("Grapple Teleport", "comeInWithGrappleTeleport"),
# TODO: add checks for cases not covered:
# G-Mode
# Cross Room Jump
# comeInStutterShinecharging
# comeInWithRMode
]
strat_name_exit_conditions = [
("Leave Normally", "leaveNormally"),
("Leave With Runway", "leaveWithRunway"),
("Leave Shinecharged", "leaveShinecharged"),
("Carry Shinecharge", "leaveShinecharged"),
("Leave With Spark", "leaveWithSpark"),
("Leave With Temporary Blue", "leaveWithTemporaryBlue"),
("Leave Spinning", "leaveSpinning"),
("Leave With Mockball", "leaveWithMockball"),
("Leave With Spring Ball Bounce", "leaveWithSpringBallBounce"),
("Leave Space Jumping", "leaveSpaceJumping"),
("Leave With Stored Fall Speed", "leaveWithStoredFallSpeed"),
("Leave With Moondance", "leaveWithStoredFallSpeed"),
("Leave With Extended Moondance", "leaveWithStoredFallSpeed"),
("G-Mode Setup", "leaveWithGModeSetup"),
("Carry G-Mode", "leaveWithGMode"),
("Leave With Door Frame Below", "leaveWithDoorFrameBelow"),
("Leave With Platform Below", "leaveWithPlatformBelow"),
("Leave With Grapple Teleport", "leaveWithGrappleTeleport"),
]
def process_keyvalue(k, v, metadata):
'''
Take a keyvalue pair and see if the value exists in our list of keywords
'''
global last_enemy
goodValue = True
processValue = True
# keys to ignore because they can't have bad data or they've been manually verified
goodKeys = [
"subarea",
"twinDoorAddresses"
]
# keys to ignore for documented reasons
manualKeys = [
"clearsObstacles",
"resetsObstacles",
"initiateRemotely",
"obstaclesCleared",
"obstaclesNotCleared"
]
# keys to ignore for documented reasons
badKeys = [
"$schema", # immaterial
"description", # immaterial
"devNote", # immaterial
"detailNote", # immaterial
"note", # immaterial
"name", # !!could check for unique
"id", # !!could check for unique
# "groupName", # !!could check for unique
# "nodeAddress", # !!could check for unique
# "roomAddress", # !!could check for unique
"notable", # checked explicitly below
"jumpwayType", # validated by schema
"lockType", # validated by schema
"nodeType", # validated by schema
"nodeSubType", # validated by schema
"obstacleType", # validated by schema
"physics", # validated by schema
"utility", # validated by schema
"resourceCapacity", # validated by schema
"resourceAvailable",# validated by schema
"refill", # validated by schema
"partialRefill", # validated by schema
"autoReserveTrigger", # validated by schema
"comeInWithSpark", # validated by schema
"comeInWithDoorStuckSetup", # validated by schema
"comeInRunning", # validated by schema
"comeInJumping", # validated by schema,
"comeInWithGMode", # validated by schema,
"leaveWithGModeSetup", # validated by schema
"gModeRegainMobility", # validated by schema
"leaveWithSpark", # validated by schema
"speedBooster", # validated by schema
"framesRemaining", # validated by schema
"comesThroughToilet", # validated by schema
"direction", # validated by schema
"blue", # validated by schema
"movementType", # validated by schema
"doorOrientation", # validated by schema
"minExtraRunSpeed", # validated by schema
"maxExtraRunSpeed", # validated by schema
"types", # validated by schema in 'unlocksDoors', manually in 'enemyDamage'
"type", # validated by schema in 'resourceAvailable', 'resourceCapacity'
"position", # validated by schema
"environment", # validated by schema
"bypassesDoorShell", # validated by schema
]
# check if it's a key we want to check
if k in badKeys or k in goodKeys:
processValue = False
else:
for checkKey in badKeys:
if checkKey in k:
processValue = False
for checkKey in manualKeys:
if checkKey in k:
processValue = False
for checkKey in goodKeys:
if checkKey in k:
processValue = False
isSkip = False
kCheck = k.split(".")[-1]
# check uniques
if kCheck in uniques and "twinDoorAddresses" not in k:
if v not in uniques[kCheck]:
uniques[kCheck].append(v)
isSkip = True
elif kCheck == "nodeAddress" and int(v, 16) in [0x189ca, 0x189d6]:
# nodeAddress is normally unique but there are two exceptions in West Ocean for the bridge doors.
isSkip = True
else:
msg = f"🔴ERROR: {k}:{v} not unique!"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
# let's do this thing
if processValue:
# helpers for data type
isFloat = isinstance(v, float)
isInt = isinstance(v, int)
isList = isinstance(v, list)
isEmptyList = isList and len(v) == 0
isEmptyDict = v == {}
isNumeric = not isFloat and not isInt and not isList and not isEmptyDict and v.isnumeric()
if not isFloat and \
not isInt and \
not isEmptyList and \
not isEmptyDict and \
not isNumeric and \
not isSkip:
# helpers for value type
isArea = v \
.replace("Ceres Station", "Ceres") \
.replace(" ", "") \
.lower() in keywords["areas"]
isEnemy = v in keywords["enemies"]["enemyByName"]
isHelper = v in keywords["helpers"]
isItem = v in keywords["items"]
isFlag = v in keywords["flags"]
isTech = v in keywords["techs"]
isWeapon = v in keywords["weapons"]
isValue = v in keywords["values"]
# process enemy
if (isEnemy or last_enemy != "") and ".enemy" in k and ".enemyKill" not in k:
if ".type" not in k:
last_enemy = v
elif ".type" in k:
# validate enemy name
if last_enemy in keywords["enemies"]["enemyByName"]:
enemyID = keywords["enemies"]["enemyByName"][last_enemy]
if enemyID in enemies:
if "attacks" in enemies[enemyID]:
attackExists = False
for attack in enemies[enemyID]["attacks"]:
if "name" in attack:
# validate attack name
if attack["name"] == v:
attackExists = True
goodValue = attackExists
if not goodValue:
msg = f"🔴ERROR: {k}:{last_enemy} doesn't have attack '{v}'"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
last_enemy = ""
else:
msg = f"🔴ERROR: {last_enemy} not found!"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
else:
# if it doesn't match a known value type
if not isArea and \
not isEnemy and \
not isHelper and \
not isItem and \
not isFlag and \
not isTech and \
not isWeapon and \
not isValue:
goodValue = False
msg = f"🔴ERROR: {k} {v}"
msg = {"msg": msg, "region": metadata["region"]}
if v == "":
msg["note"] = "Empty string!"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
return goodValue
# try to navigate a path between nodes if no direct path
def search_for_path(fromNodes, sourceNode, targetNode, stratRef):
foundPath = False
msg = ""
for tNode in fromNodes[str(sourceNode)]["to"]:
if not foundPath:
# print(f"Testing {sourceNode}:{tNode}:{targetNode}")
if (str(tNode) in roomData["links"]["from"]) and \
(str(targetNode) in roomData["links"]["from"][str(tNode)]["to"]):
foundPath = True
# msg = f"🟢Found Path:{stratRef}::{sourceNode}:{tNode}:{targetNode}"
# print(msg)
# messages["greens"].append(msg)
# messages["counts"]["greens"] += 1
if not foundPath:
msg = f"🟡WARNING: Path not found:{stratRef}::{sourceNode}:{tNode}:{targetNode}::Is it longer than a 3-node chain? Gave up looking"
return [foundPath, msg]
def find_door_unlocked_nodes_rec(req):
if isinstance(req, dict):
if "doorUnlockedAtNode" in req:
return set([req["doorUnlockedAtNode"]])
if "and" in req:
return find_door_unlocked_nodes_rec(req["and"])
if "or" in req:
return find_door_unlocked_nodes_rec(req["or"])
if isinstance(req, list):
return set(y for x in req for y in find_door_unlocked_nodes_rec(x))
return set()
def find_door_unlocked_nodes(strat, node_subtype, nodes_without_implicit_unlocks):
nodes = find_door_unlocked_nodes_rec(strat["requires"])
from_node = strat["link"][0]
to_node = strat["link"][1]
if "exitCondition" in strat and strat.get("bypassesDoorShell") not in [True, "free"] and node_subtype not in ["elevator", "doorway", "sandpit", "passage"]:
nodes.add(to_node)
if "entranceCondition" not in strat and from_node in nodes:
nodes.remove(from_node)
if to_node in nodes_without_implicit_unlocks and strat.get("bypassesDoorShell") not in [True, "free"] and "gModeRegainMobility" not in strat:
nodes.add(to_node)
return nodes
def check_node_covered_in_unlocks_doors(strat, node_id):
unlocks_doors = strat.get("unlocksDoors", [])
to_node = strat["link"][1]
types = [t for x in unlocks_doors if x.get("nodeId", to_node) == node_id for t in x["types"]]
if "ammo" in types:
return []
missing_types = {"missiles", "super", "powerbomb"}.difference(types)
return missing_types
def check_shinespark_req(req):
if isinstance(req, dict):
if "shinespark" in req:
return True
if "and" in req:
return any(check_shinespark_req(v) for v in req["and"])
if "or" in req:
return all(check_shinespark_req(v) for v in req["or"])
def check_shinecharge_req(req):
if isinstance(req, str):
if req in ["h_shinechargeMaxRunway", "canStutterWaterShineCharge", "canPreciseStutterWaterShineCharge"]:
return True
if isinstance(req, dict):
if "canShineCharge" in req:
return True
if "and" in req:
return any(check_shinecharge_req(v) for v in req["and"])
if "or" in req:
return all(check_shinecharge_req(v) for v in req["or"])
def check_heat_req(req):
if isinstance(req, str):
if req in ["h_heatProof", "h_heatedCrystalFlash", "h_heatedLavaCrystalFlash", "h_heatedAcidCrystalFlash",
"h_LowerNorfairElevatorDownwardFrames",
"h_LowerNorfairElevatorUpwardFrames", "h_MainHallElevatorFrames", "h_heatedGreenGateGlitch",
"h_heatedDirectGModeLeaveSameDoor", "h_heatedIndirectGModeOpenSameDoor",
"h_heatedGModeOpenDifferentDoor", "h_heatedGModeOffCameraDoor", "h_heatedGModePauseAbuse"]:
return True
if isinstance(req, dict):
if "heatFrames" in req or "heatFramesWithEnergyDrops" in req:
return True
if "and" in req:
return any(check_heat_req(v) for v in req["and"])
if "or" in req:
return all(check_heat_req(v) for v in req["or"])
def check_cycle_frames_req(req):
if isinstance(req, dict):
if "cycleFrames" in req:
return True
if "and" in req:
return any(check_cycle_frames_req(v) for v in req["and"])
if "or" in req:
return all(check_cycle_frames_req(v) for v in req["or"])
# give list of keys to check
# give label for output message
# give list of valid values
# give data object
def search_for_valid_keyvalue(keys, label, valids, data):
keyvalueErrors = []
data = {
label: data
}
flattened_dict = [
flatten(d, '.') for d in [data]
][0]
for [k, v] in flattened_dict.items():
if (isinstance(v, int)) or \
(isinstance(v, list) and len(v)) or \
(isinstance(v, str) and len(v)):
if isinstance(v, list):
print(v)
for checkKey in keys:
goodValue = False
if k.endswith(checkKey):
goodValue = True
if checkKey.endswith("."):
if checkKey in k:
if k[k.rfind('.')+1:].isnumeric():
goodValue = True
if goodValue:
if isinstance(v, list):
for ele in v:
if ele not in valids:
keyvalueErrors.append((checkKey,k,v,ele))
else:
if v not in valids:
keyvalueErrors.append((checkKey,k,v))
return keyvalueErrors
# process a list of strats
def process_strats(src, paramData):
'''
Process strats
'''
key = paramData["key"]
fromNode = paramData["fromNode"]
fromNodeRef = paramData["fromNodeRef"]
roomData = paramData["roomData"]
toNode = paramData["toNode"]
bail = paramData["bail"]
stratNames = []
showNodes = True
toNodeRef = f"{fromNodeRef}:destinationNode[{toNode}]"
# cycle through strats
for strat in src:
stratRef = f"{toNodeRef}:stratName[{strat['name']}]"
if(strat["name"] in stratNames):
msg = f"🔴ERROR: Duplicate strat:{stratRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
stratNames.append(strat["name"])
paramData = {
"fromNode": fromNode,
"fromNodeRef": fromNodeRef,
"roomData": roomData,
"showNodes": showNodes,
"toNode": toNode,
"bail": bail
}
return paramData
def check_and_or(req, err_fn):
if isinstance(req, dict):
if "or" in req:
if len(req["or"]) < 2:
err_fn("'or' should have at least 2 elements")
for r in req["or"]:
if isinstance(r, dict) and "or" in r:
err_fn("'or' should not have a directly nested 'or' inside.")
check_and_or(r, err_fn)
elif "and" in req:
if len(req["and"]) < 2:
err_fn("'and' should have at least 2 elements")
for r in req["and"]:
if isinstance(r, dict) and "and" in r:
err_fn("'and' should not have a directly nested 'and' inside.")
check_and_or(r, err_fn)
def has_reset_room(req):
if isinstance(req, dict):
if "resetRoom" in req:
return True
elif "or" in req:
return any(has_reset_room(x) for x in req["or"])
elif "and" in req:
return any(has_reset_room(x) for x in req["and"])
else:
return False
def covers_shinecharge_frames(req):
if isinstance(req, dict):
if "shineChargeFrames" in req:
return True
elif "or" in req:
return all(covers_shinecharge_frames(x) for x in req["or"])
elif "and" in req:
return any(covers_shinecharge_frames(x) for x in req["and"])
else:
return False
def process_req_speed_state(req, states, err_fn):
if isinstance(req, str):
if req in ["h_shinechargeMaxRunway", "canWaterShineCharge", "canStutterWaterShineCharge", "canPreciseStutterWaterShineCharge", "h_shinechargeSlideTemporaryBlue"]:
states = {"shinecharging"}
elif req in ["h_getBlueSpeedMaxRunway", "canSpeedKeep", "h_waterGetBlueSpeed", "h_stutterWaterGetBlueSpeed"]:
# Note: "canSpeedKeep" can be used for other purposes than obtaining blue, but its presence should be
# enough to satisfy the test as a way that blue may be obtained.
states = {"blue"}
elif req in ["h_flashSuitIceClip"]:
states = {"preshinespark"}
elif req in ["canTemporaryBlue", "canChainTemporaryBlue", "canLongChainTemporaryBlue", "canSpeedball", "canXRayCancelShinecharge"]:
if not states.issubset(["shinecharging", "blue"]):
err_fn(f"{req} while not in blue state")
states = {"blue"}
elif isinstance(req, dict):
if "canShineCharge" in req:
states = {"shinecharging"}
elif "shineChargeFrames" in req:
if not states.issubset(["shinecharging", "shinecharged"]):
err_fn(f"shineChargeFrames requirement while not in shinecharged state: {req}")
elif "useFlashSuit" in req:
states = {"preshinespark"}
elif "shinespark" in req:
if not states.issubset(["shinecharging", "shinecharged", "shinespark", "preshinespark"]):
err_fn(f"shinespark requirement while not in shinecharging/shinecharged/shinespark state: {req}")
states = {"shinespark"}
elif "getBlueSpeed" in req or "speedball" in req:
states = {"blue"}
elif "and" in req:
for r in req["and"]:
states = process_req_speed_state(r, states, err_fn)
elif "or" in req:
# Apply the check independently to each branch of the "or", taking the union of the ending sets of states
new_states = set()
for r in req["or"]:
branch_states = process_req_speed_state(r, states, err_fn)
new_states.update(branch_states)
states = new_states
else:
raise RuntimeError(f"Unexpected requirement type {type(req)}: {req}")
return states
def check_speed_states(strat, err_fn):
# Check that transitions between Speedbooster-related states are valid, to help prevent
# requirements (or entrance/exit conditions) from being accidentally omitted or included by mistake.
#
# states:
# "normal": normal movement state
# "shinecharging": just gained a shinecharge, still valid to convert to "blue" (via canTemporaryBlue)
# "shinecharged": gained a shinecharge earlier, no longer valid to convert to "blue"
# "shinespark": performed a shinespark, valid to continue with additional "shinespark" requirements
# "preshinespark": expecting a subsequent shinespark requirement (e.g. after comeInWithSpark or useFlashSuit)
# "blue": gained blue in some way, e.g. getBlueSpeed, speedball, comeInBlueSpinning, etc.
#
# States are represented as a set of strings, representing possible states, since different branches of
# "or" can lead to different states.
states = {"normal"}
if "entranceCondition" in strat:
keys = set(strat["entranceCondition"].keys())
if keys.intersection(["comeInShinecharging", "comeInStutterShinecharging"]):
states = {"shinecharging"}
elif keys.intersection(["comeInShinecharged", "comeInShinechargedJumping"]):
states = {"shinecharged"}
elif "comeInWithSpark" in keys:
states = {"preshinespark"}
elif keys.intersection(["comeInWithTemporaryBlue", "comeInGettingBlueSpeed", "comeInSpeedballing", "comeInWithBlueSpringBallBounce",
"comeInBlueSpinning", "comeInBlueSpaceJumping"]):
states = {"blue"}
if strat.get("startsWithShineCharge") is True:
err_fn("startsWithShineCharge should not be combined with an entranceCondition")
elif strat.get("startsWithShineCharge") is True:
states = {"shinecharged"}
for req in strat["requires"]:
states = process_req_speed_state(req, states, err_fn)
# TODO: handle door unlock requires
if "exitCondition" in strat:
keys = set(strat["exitCondition"].keys())
if "leaveShinecharged" in keys:
if not states.issubset({"shinecharging", "shinecharged"}):
err_fn("leaveShinecharged missing requirements to gain shinecharge")
if "leaveWithTemporaryBlue" in keys:
if not states.issubset({"shinecharging", "blue"}):
err_fn("leaveWithTemporaryBlue missing requirements to gain blue")
if "leaveWithSpark" in keys:
if states != {"shinespark"}:
err_fn("leaveWithSpark missing shinespark requirement")
if strat.get("endsWithShineCharge") is True:
err_fn("endsWithShineCharge should not be combined with an exitCondition")
elif strat.get("endsWithShineCharge") is True:
if not states.issubset({"shinecharging", "shinecharged"}):
err_fn("endsWithShineCharge missing requirements to gain shinecharge")
else:
if "preshinespark" in states:
err_fn("strat ends while expecting a shinespark requirement")
if "shinecharged" in states or "shinecharging" in states:
err_fn("strat ends without using shinecharge")
keywords = []
# load keywords
print("Load Keywords")
keywordsPath = os.path.join(
".",
"resources",
"app",
"manifests",
"keywords.json"
)
with open(keywordsPath, encoding="utf-8") as keywordsFile:
keywords = json.load(keywordsFile)
keywords["values"] = [
"never",
"free",
"spinjump"
]
# load enemies
print("Load Enemies & Bosses")
enemies = {}
enemiesPaths = [
os.path.join(".","enemies","main.json"),
os.path.join(".","enemies","bosses","main.json")
]
for enemiesPath in enemiesPaths:
with open(enemiesPath, encoding="utf-8") as enemiesFile:
enemiesJSON = json.load(enemiesFile)
if "enemies" in enemiesJSON:
for enemy in enemiesJSON["enemies"]:
if "id" in enemy:
enemies[enemy["id"]] = enemy
# validate enemies, helpers, tech, weapons
for jsonPath in [
os.path.join(".","enemies","main.json"),
os.path.join(".","enemies","bosses","main.json"),
os.path.join(".","helpers.json"),
os.path.join(".","tech.json"),
os.path.join(".","weapons","main.json")
]:
pattern = r"(?:[\.][\\])([\w]+)"
matches = re.match(pattern, jsonPath)
if matches:
dataType = matches.group(1)
dataType = dataType[0].upper() + dataType[1:]
print(f"Check {dataType}")
with open(jsonPath, encoding="utf-8") as dataFile:
dataJSON = json.load(dataFile)
flattened_dict = [
flatten(d, '.') for d in [dataJSON]
][0]
# print(flattened_dict)
for [k, v] in flattened_dict.items():
process_keyvalue(k, v, {})
# process connections to identify door positions:
vertical_door_nodes = set()
door_position_dict = {}
connections = {
"inter": {},
"intra": {},
"subarea": {}
}
connectionPath = os.path.join(".","connection")
for root, dirs, files in os.walk(os.path.join(".", "connection")):
for filename in files:
if not filename.endswith(".json"):
continue
with open(os.path.join(root, filename), "r", encoding="utf-8") as connectionFile:
connections_json = json.load(connectionFile)
for connection in connections_json["connections"]:
for i, node in enumerate(connection["nodes"]):
door_position_dict[(node["roomid"], node["nodeid"])] = node["position"]
if connection["connectionType"] in ["VerticalDoor", "VerticalSandpit"]:
for i, node in enumerate(connection["nodes"]):
vertical_door_nodes.add((node["roomid"], node["nodeid"]))
print("")
print("Check Regions")
for r,d,f in os.walk(os.path.join(".","region")):
for filename in f:
if ".json" in filename and "roomDiagrams" not in filename:
roomPath = os.path.join(r, filename)
with open(roomPath, encoding="utf-8") as regionFile:
roomJSON = json.load(regionFile)
flattened_dict = [
flatten(d, '.') for d in [roomJSON]
][0]
# print(flattened_dict)
# check rooms
room = roomJSON
roomName = room["name"]
area = room["area"]
subarea = room["subarea"]
subsubarea = room["subsubarea"] if "subsubarea" in room else ""
showArea = False
fullarea = f"{area}/{subarea}" + ((subsubarea != "") and f"/{subsubarea}" or "")
# do a naive pass on all data in this region
for [k, v] in flattened_dict.items():
ret = process_keyvalue(k, v, {"region": fullarea})
if not ret and not showArea:
showArea = True
# cycle through rooms
for room in [roomJSON]:
roomRef = f"{fullarea}:{room['id']}:{roomName}"
# check for uniqueness
if room["id"] not in uniques["roomID"]:
uniques["roomID"].append(room["id"])
else:
msg = f"🔴ERROR: Room ID not unique! {roomRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if room["name"] not in uniques["roomName"]:
uniques["roomName"].append(room["name"])
else:
msg = f"🔴ERROR: Room Name not unique! {roomRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
# build an outline for this room
roomData = {
"id": room["id"],
"area": area,
"subarea": subarea,
"subsubarea": subsubarea,
"fullarea": fullarea,
"links": {
"from": {}
},
"nodes": {
"froms": [],
"tos": [],
"ids": [],
"names": [],
"leaveCharged": {
"from": {}
}
},
"obstacles": {
"ids": []
},
"enemies": {
"ids": []
}
}
# Volcano Room will not be tested for heat requirements since it is sometimes not heated.
heated = all(e["heated"] for e in room["roomEnvironments"])
# Check that room `mapTileMask` is a rectangle:
mapHeight = len(room["mapTileMask"])
mapWidth = len(room["mapTileMask"][0])
if not all(len(row) == mapWidth for row in room["mapTileMask"]):
msg = f"🔴ERROR: Not all rows of room mapTileMask have the same length: {roomRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
# Document Obstacles
if "obstacles" in room:
for obstacle in room["obstacles"]:
obstacleRef = f"{roomRef}:{obstacle['id']}:{obstacle['name']}"
if obstacle["id"] in roomData["obstacles"]["ids"]:
msg = f"🔴ERROR: Obstacle ID not unique! {obstacleRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
else:
roomData["obstacles"]["ids"].append(obstacle["id"])
# Document Nodes
# Validate Nodes
node_lookup = {}
nodes_without_implicit_unlocks = set()
node_tile_set = set()
for node in room["nodes"]:
node_lookup[node['id']] = node
nodeRef = f"{roomRef}:{node['id']}"
if node["id"] in roomData["nodes"]["froms"]:
msg = f"🔴ERROR: Node ID not unique! {nodeRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
else:
roomData["nodes"]["froms"].append(node["id"])
if node["name"] in roomData["nodes"]["names"]:
msg = f"🔴ERROR: Node Name not unique! {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
else:
roomData["nodes"]["names"].append(node["name"])
roomData["nodes"]["ids"].append(node["id"])
if len(node["mapTileMask"]) != mapHeight or not all(len(row) == mapWidth for row in node["mapTileMask"]):
msg = f"🔴ERROR: Node mapTileMask has wrong shape: {nodeRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
else:
for y in range(mapHeight):
for x in range(mapWidth):
node_tile = node["mapTileMask"][y][x]
room_tile = room["mapTileMask"][y][x]
if node_tile == 2:
node_tile_set.add((x, y))
if room_tile == 0:
msg = f"🔴ERROR: Node mapTileMask has 2 at invalid position ({x}, {y}): {nodeRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
else:
if room_tile != node_tile:
msg = f"🔴ERROR: Node mapTileMask is inconsistent with room mapTileMask at position ({x}, {y}): {nodeRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if node.get("useImplicitDoorUnlocks") is False:
nodes_without_implicit_unlocks.add(node['id'])
node_orientation = node.get("doorOrientation")
door_position = door_position_dict.get((room["id"], node["id"]))
if (node_orientation, door_position) not in [
("left", "right"),
("right", "left"),
("up", "bottom"),
("down", "top"),
(None, None),
]:
msg = f"🔴ERROR: Door orientation '{node_orientation}' inconsistent with connection position '{door_position}': {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if node.get("useImplicitLeaveNormally") is False and not any(
s["link"][1] == node["id"]
and s.get("exitCondition", {}).get("leaveNormally") is not None
for s in room["strats"]
):
msg = f"🔴ERROR: Node disables useImplicitLeaveNormally but has no leaveNormally strat: {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if node.get("useImplicitComeInNormally") is False and not any(
s["link"][0] == node["id"]
and s.get("entranceCondition", {}).get("comeInNormally") is not None
for s in room["strats"]
):
msg = f"🔴ERROR: Node disables useImplicitComeInNormally but has no comeInNormally strat: {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if node.get("useImplicitComeInWithMockball") is False and not any(
s["link"][0] == node["id"]
and s.get("entranceCondition", {}).get("comeInWithMockball") is not None
for s in room["strats"]
):
msg = f"🔴ERROR: Node disables useImplicitComeInWithMockball but has no comeInWithMockball strat: {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if node.get("useImplicitCarryGModeBackThrough") is False and not any(
s["link"][0] == node["id"]
and s.get("entranceCondition", {}).get("comeInWithGMode") is not None
and s.get("exitCondition", {}).get("leaveWithGMode") is not None
for s in room["strats"]
):
if room["id"] == 321 or (room["id"] == 44 and node["id"] == 1):
# Toilet Bowl (321) is an exception where there legitimately is no comeInWithGMode+leaveWithGMode strat
# Green Brinstar Main Shaft (44) is also an exception because the elevator takes Samus to a G-mode junction which can lead back up
pass
else:
msg = f"🔴ERROR: Node disables useImplicitCarryGModeBackThrough but has no comeInWithGMode+leaveWithGMode strat: {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if node.get("useImplicitCarryGModeMorphBackThrough") is False and not any(
s["link"][0] == node["id"]
and s.get("entranceCondition", {}).get("comeInWithGMode") is not None
and s.get("exitCondition", {}).get("leaveWithGMode") is not None
and s["exitCondition"]["leaveWithGMode"]["morphed"]
for s in room["strats"]
):
if room["id"] == 321 or node["nodeSubType"] == "elevator":
# Toilet Bowl and elevators are an exception where there legitimately is no comeInWithGMode+leaveWithGMode morphed strat
pass
else:
msg = f"🔴ERROR: Node disables useImplicitCarryGModeMorphBackThrough but has no comeInWithGMode+leaveWithGMode morphed strat: {nodeRef}:{node['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
# Check that every map tile is covered by some node:
for y in range(mapHeight):
for x in range(mapWidth):
if room["mapTileMask"][y][x] == 1 and (x, y) not in node_tile_set:
msg = f"🔴ERROR: Map tile ({x}, {y}) is not covered by any node:{roomRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
# Document Links
link_set = set()
for link_from in room["links"]:
from_node_id = link_from["from"]
if from_node_id not in roomData["nodes"]["ids"]:
msg = f"🔴ERROR: In links, from node {from_node_id} doesn't exist."
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
for link in link_from["to"]:
to_node_id = link["id"]
if to_node_id not in roomData["nodes"]["ids"]:
msg = f"🔴ERROR: In links, to node {to_node_id} doesn't exist."
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
link_set.add((from_node_id, to_node_id))
# Document Link Strats
for strat in room["strats"]:
if "link" not in strat:
msg = f"🔴ERROR: Strat is missing `link` property: {roomRef}:{strat['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
continue
link = strat["link"]
linkRef = str(link)
if tuple(strat["link"]) not in link_set:
msg = f"🔴ERROR: Link {linkRef} doesn't exist: {roomRef}:{strat['name']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
toNode = link[1]
roomData["nodes"]["tos"].append(toNode)
# Validate "enemies"
if "enemies" in room:
for enemy in room["enemies"]:
enemyGroupRef = ""
# Unique IDs
if enemy["id"] not in roomData["enemies"]["ids"]:
roomData["enemies"]["ids"].append(enemy["id"])
enemyGroupRef = f"{enemy['id']}:{enemy['groupName']}"
else:
msg = f"🔴ERROR: Enemy ID not unique! {roomRef}:{enemy['id']}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if "homeNodes" in enemy:
for homeNode in enemy["homeNodes"]:
homeNodeRef = f"Node[{roomRef}:{homeNode}]"
if homeNode not in roomData["nodes"]["froms"]:
msg = f"🔴ERROR: Invalid Home Node:{enemyGroupRef}:{homeNodeRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if "betweenNodes" in enemy:
for betweenNode in enemy["betweenNodes"]:
betweenNodeRef = f"Node[{roomRef}:{betweenNode}]"
if betweenNode not in roomData["nodes"]["froms"]:
msg = f"🔴ERROR: Invalid Between Node:{enemyGroupRef}:{betweenNodeRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
# Validate Obstacles
# check these keys
# check against obstacle IDs
# pass the whole room object
obstacleErrors = search_for_valid_keyvalue(
[
"clearsObstacles.",
"resetsObstacles.",
"obstaclesCleared.",
"obstaclesNotCleared.",
],
f"{roomData['fullarea']}:room",
roomData["obstacles"]["ids"],
room
)
if obstacleErrors:
for obstacleError in obstacleErrors:
msg = f"🔴ERROR: Invalid Obstacles ID:{roomRef}:{obstacleError}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
notable_id_set = set()
notable_name_set = set()
for notable in room.get("notables", []):
notable_id = notable["id"]
if notable_id in notable_id_set:
msg = f"🔴ERROR: Non-unique notable ID {notable_id} in notable:{roomRef}:{notable_name}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
if notable_id >= room["nextNotableId"]:
next_notable_id = room["nextNotableId"]
msg = f"🔴ERROR: Notable ID {notable_id} is not less than nextNotableId ({next_notable_id}):{roomRef}:{notable_name}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
notable_id_set.add(notable["id"])
notable_name = notable["name"]
if notable_name in notable_name_set:
msg = f"🔴ERROR: Non-unique notable name {notable_name} in notable:{roomRef}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1
notable_name_set.add(notable_name)
# Validate Requires Nodes
# check these keys
# check against node IDs that have links leading from
# pass the whole room object
requiresErrors = search_for_valid_keyvalue(
[
# "fromNode",
"fromNodes.",
"inRoomPath.",
"resetRoom.nodes.",
"itemNotCollectedAtNode",
"itemCollectedAtNode"
],
"room",
roomData["nodes"]["froms"],
room
)
if requiresErrors:
for requiresError in requiresErrors:
msg = f"🔴ERROR: Invalid Node ID:{roomRef}:{requiresError}"
messages["reds"].append(msg)
messages["counts"]["reds"] += 1