-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathplando_validation.py
1684 lines (1504 loc) · 77.1 KB
/
plando_validation.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
"""Code to collect and validate the selected plando options."""
from enum import IntEnum, auto
import json
import re
import js
from randomizer.Enums.Items import Items
from randomizer.Enums.Kongs import Kongs
from randomizer.Enums.Levels import Levels
from randomizer.Enums.Locations import Locations
from randomizer.Enums.Minigames import Minigames
from randomizer.Enums.Plandomizer import ItemToPlandoItemMap, PlandoItems
from randomizer.Enums.Settings import KasplatRandoSetting
from randomizer.Enums.Switches import Switches
from randomizer.Enums.SwitchTypes import SwitchType
from randomizer.Lists.Location import LocationListOriginal as LocationList
from randomizer.Lists.Plandomizer import (
CrownLocationEnumList,
CrownPlandoLocationList,
CrownVanillaLocationMap,
DirtPatchPlandoLocationList,
DirtPatchVanillaLocationMap,
FairyPlandoLocationList,
FairyVanillaLocationMap,
GetLevelString,
HintLocationList,
ItemLocationList,
KasplatLocationEnumList,
KasplatLocationToRewardMap,
KasplatPlandoLocationList,
MelonCratePlandoLocationList,
MelonCrateVanillaLocationMap,
MinigameLocationList,
PlannableItemLimits,
ShopLocationKongMap,
ShopLocationList,
SwitchVanillaMap,
TnsPortalLocationList,
TnsVanillaMap,
WrinklyDoorEnumList,
WrinklyVanillaMap,
)
from randomizer.Lists.Switches import SwitchData
from randomizer.Patching.Library.Generic import plando_colors
from randomizer.LogicFiles.Shops import LogicRegions
from randomizer.PlandoUtils import GetNameFromPlandoItem, PlandoEnumMap
from ui.bindings import bind, bindList
class ValidationError(IntEnum):
"""Specific validation failures associated with an element."""
exceeds_item_limits = auto()
shop_has_shared_and_solo_rewards = auto()
smaller_shops_conflict = auto()
invalid_hint_text = auto()
too_many_hints_with_fixed_hints = auto()
invalid_shop_cost = auto()
invalid_starting_kong_count = auto()
level_order_duplicates = auto()
krool_order_duplicates = auto()
helm_order_duplicates = auto()
assigned_shop_when_shuffled = auto()
assigned_dirt_patch_when_shuffled = auto()
assigned_fairy_when_shuffled = auto()
assigned_crown_when_shuffled = auto()
assigned_crate_when_shuffled = auto()
assigned_kasplat_when_shuffled = auto()
key_8_locked_in_helm = auto()
only_available_as_custom_location = auto()
random_custom_location = auto()
duplicate_custom_location = auto()
duplicate_custom_door = auto()
switchsanity_not_enabled = auto()
# This dictionary stores all elements that have either been disabled or marked
# invalid. It stores the current errors that apply to each element. This will
# prevent us from marking an element as enabled or valid if there is still an
# error with it.
element_error_dict = dict()
def get_errors(elementId: str) -> dict:
"""Get, or create, the dict of current errors for this element."""
if elementId not in element_error_dict:
element_error_dict[elementId] = {
# Each of these two dictionaries maps ValidationError enums to
# error strings.
"invalid": dict(),
"disabled": dict(),
}
return element_error_dict[elementId]
def write_current_tooltip(elementId) -> None:
"""Add a Bootstrap tooltip to the given element for its current errors."""
tooltips = []
elemErrors = get_errors(elementId)
for _, invalidError in elemErrors["invalid"].items():
if invalidError != "":
tooltips.append(invalidError)
for _, disabledError in elemErrors["disabled"].items():
if disabledError != "":
tooltips.append(disabledError)
wrapper = js.document.getElementById(f"{elementId}_wrapper")
wrapper.setAttribute("data-bs-original-title", "\n".join(tooltips))
def mark_option_invalid(element, errType: ValidationError, errMessage: str) -> None:
"""Mark the given option as invalid, and add an associated error."""
if errMessage == "":
raise ValueError("The error string passed to mark_option_invalid must be non-empty.")
elemErrors = get_errors(element.id)
elemErrors["invalid"][errType] = errMessage
element.classList.add("invalid")
write_current_tooltip(element.id)
def mark_option_valid(element, errType: ValidationError) -> None:
"""Remove an error from a given option, and maybe mark it as valid."""
elemErrors = get_errors(element.id)
elemErrors["invalid"][errType] = ""
# If there are no more invalid-style errors, mark this as valid.
valid = True
for _, errString in elemErrors["invalid"].items():
if errString != "":
valid = False
if valid:
element.classList.remove("invalid")
write_current_tooltip(element.id)
def mark_option_disabled(element, errType: ValidationError, errMessage: str, optionValue: str = "") -> None:
"""Disable the given option, and add an associated error."""
if errMessage == "":
raise ValueError("The error string passed to mark_option_disabled must be non-empty.")
elemErrors = get_errors(element.id)
elemErrors["disabled"][errType] = errMessage
element.value = optionValue
element.setAttribute("disabled", "disabled")
write_current_tooltip(element.id)
def mark_option_enabled(element, errType: ValidationError) -> None:
"""Remove an error from a given option, and maybe enable it."""
elemErrors = get_errors(element.id)
elemErrors["disabled"][errType] = ""
# If there are no more disabled-style errors, enable this.
enabled = True
for _, errString in elemErrors["disabled"].items():
if errString != "":
enabled = False
if enabled:
element.removeAttribute("disabled")
write_current_tooltip(element.id)
def remove_all_errors_from_option(element) -> None:
"""Remove all errors from a given option, and mark it as valid/enabled."""
elemErrors = get_errors(element.id)
elemErrors["invalid"] = dict()
elemErrors["disabled"] = dict()
element.removeAttribute("disabled")
element.classList.remove("invalid")
write_current_tooltip(element.id)
def count_items() -> dict:
"""Count all currently placed items to ensure limits aren't exceeded.
The result will be a dictionary, where each item is linked to all of the
HTML selects that have this item selected.
"""
count_dict = {}
def add_all_items(locList: list[str], suffix: str = ""):
"""Add all items from the location list into the dict."""
for itemLocation in locList:
elemName = f"plando_{itemLocation}{suffix}"
elemValue = js.document.getElementById(elemName).value
# The default value, for when no selection is made.
plandoItemEnum = PlandoItems.Randomize
if elemValue != "":
plandoItemEnum = PlandoItems[elemValue]
if plandoItemEnum in count_dict:
count_dict[plandoItemEnum].append(elemName)
else:
count_dict[plandoItemEnum] = [elemName]
add_all_items(ItemLocationList, "_item")
add_all_items(ShopLocationList, "_item")
if arena_locations_assigned():
add_all_items([f"{loc}_location_reward" for loc in CrownLocationEnumList])
if patch_locations_assigned():
add_all_items([f"patch_{i}_location_reward" for i in range(0, 16)])
if fairy_locations_assigned():
add_all_items([f"fairy_{i}_location_reward" for i in range(0, 20)])
if kasplat_locations_assigned():
add_all_items([f"{loc}_location_reward" for loc in KasplatLocationEnumList])
if crate_locations_assigned():
add_all_items([f"crate_{i}_location_reward" for i in range(0, 13)])
return count_dict
def get_shop_location_element(locName: str):
"""Get the element corresponding to the dropdown for this location."""
return js.document.getElementById(f"plando_{locName}_item")
def shop_has_assigned_item(shopElement) -> bool:
"""Return true if the given shop has an item assigned to it."""
return shopElement.value and shopElement.value != "NoItem"
def arena_locations_assigned() -> bool:
"""Return true if arenas are having their locations assigned."""
return js.document.getElementById("plando_place_arenas").checked
def patch_locations_assigned() -> bool:
"""Return true if patches are having their locations assigned."""
return js.document.getElementById("plando_place_patches").checked
def fairy_locations_assigned() -> bool:
"""Return true if fairies are having their locations assigned."""
return js.document.getElementById("plando_place_fairies").checked
def kasplat_locations_assigned() -> bool:
"""Return true if Kasplats are having their locations assigned."""
return js.document.getElementById("plando_place_kasplats").checked
def crate_locations_assigned() -> bool:
"""Return true if crates are having their locations assigned."""
return js.document.getElementById("plando_place_crates").checked
def wrinkly_locations_assigned() -> bool:
"""Return true if Wrinkly doors are having their locations assigned."""
return js.document.getElementById("plando_place_wrinkly").checked
def tns_locations_assigned() -> bool:
"""Return true if TnS portals are having their locations assigned."""
return js.document.getElementById("plando_place_tns").checked
########################
# VALIDATION FUNCTIONS #
########################
def hint_text_validation_fn(hintString: str) -> str:
"""Return an error if the element's hint contains invalid characters."""
colors = []
for key in plando_colors:
colors.extend(plando_colors[key])
# Test the hint string without color tags.
trimmedHintString = hintString
for color in colors:
trimmedHintString = trimmedHintString.replace(f"[{color}]", "")
trimmedHintString = trimmedHintString.replace(f"[/{color}]", "")
if re.search("[^A-Za-z0-9 '\,\:\.\-\?!]", trimmedHintString) is not None:
errString = "Only letters, numbers, spaces, the characters ',.:-?! and color tags are allowed in hints."
return errString
if len(trimmedHintString) > 123:
errString = "Hints can be a maximum of 123 characters (excluding color tags)."
return errString
# Ensure that the color tags are correctly utilized.
tagRegex = rf"\[\/?(?:{'|'.join(colors)})\]"
tags = re.finditer(tagRegex, hintString)
currentTag = None
for tag in tags:
if currentTag is None:
# Is there a closing tag before an opening one?
if "/" in tag[0]:
errString = f"Closing color tag {tag[0]} has no opening tag."
return errString
currentTag = tag
else:
# Is the next tag a closing tag?
if "/" not in tag[0]:
errString = f"Color tag {tag[0]} overlaps color tag {currentTag[0]}."
return errString
# Do the two tags match in color?
currentTagColor = re.search("^\[\/?(.+)\]$", currentTag[0])[1]
newTagColor = re.search("^\[\/?(.+)\]$", tag[0])[1]
if currentTagColor != newTagColor:
errString = f"Color tag {currentTag[0]} has non-matching closing tag {tag[0]}."
return errString
# Is there any text at all between the tags?
if currentTag.end(0) == tag.start(0):
errString = f"There is no text within color tag {currentTag[0]}."
return errString
# Erase the current tag, as it's been matched.
currentTag = None
# If we still have a tag, they are unmatched.
if currentTag:
errString = f"Color tag {currentTag[0]} is unmatched."
return errString
# If we've made it to this point, the element is valid.
return None
############
# BINDINGS #
############
@bindList("click", [str(i) for i in range(1, 6)], prefix="starting_moves_list_mover_")
@bindList("change", [str(i) for i in range(1, 6)], prefix="starting_moves_list_count_")
@bindList("change", ItemLocationList, prefix="plando_", suffix="_item")
@bindList("change", ShopLocationList, prefix="plando_", suffix="_item")
@bindList("change", CrownLocationEnumList, prefix="plando_", suffix="_location_reward")
@bindList("change", KasplatLocationEnumList, prefix="plando_", suffix="_location_reward")
@bindList("change", [str(i) for i in range(0, 16)], prefix="plando_patch_", suffix="_location_reward")
@bindList("change", [str(i) for i in range(0, 20)], prefix="plando_fairy_", suffix="_location_reward")
@bindList("change", [str(i) for i in range(0, 13)], prefix="plando_crate_", suffix="_location_reward")
@bind("change", "plando_place_arenas")
@bind("change", "plando_place_patches")
@bind("change", "plando_place_fairies")
@bind("change", "plando_place_kasplats")
@bind("change", "plando_place_crates")
@bind("click", "starting_moves_reset")
@bind("click", "starting_moves_start_all")
@bind("click", "starting_moves_start_vanilla")
def validate_item_limits(evt):
"""Raise an error if any item has been placed too many times."""
count_dict = count_items()
# Add in starting moves, which also count toward the totals.
startingMoveSet = set()
# Look at every list, and if any list will have all of its items given,
# add those moves to the set.
for i in range(1, 6):
moveListElem = js.document.getElementById(f"starting_moves_list_{i}")
moveCountElem = js.document.getElementById(f"starting_moves_list_count_{i}")
givenMoveCount = 0 if moveCountElem.value == "" else int(moveCountElem.value)
listedMoveCount = 0
for opt in moveListElem.options:
if not opt.hidden:
listedMoveCount += 1
if givenMoveCount == listedMoveCount:
for opt in moveListElem.options:
moveId = re.search("^starting_move_(.+)$", opt.id)[1]
plandoMove = ItemToPlandoItemMap[Items(int(moveId))]
startingMoveSet.add(plandoMove)
if plandoMove in count_dict:
# Add in None, so we don't attempt to mark a nonexistent
# element.
count_dict[plandoMove].append(None)
else:
count_dict[plandoMove] = [None]
for item, locations in count_dict.items():
if item not in PlannableItemLimits:
for loc in locations:
if loc is not None:
mark_option_valid(js.document.getElementById(loc), ValidationError.exceeds_item_limits)
continue
itemCount = len(locations)
if item == PlandoItems.GoldenBanana:
# Add 40 items to account for blueprint rewards.
itemCount += 40
itemMax = PlannableItemLimits[item]
if itemCount > itemMax:
maybePluralTimes = "time" if itemMax == 1 else "times"
maybeStartingMoves = " (This includes guaranteed starting moves.)" if None in locations else ""
errString = f'Item "{GetNameFromPlandoItem(item)}" can be placed at most {itemMax} {maybePluralTimes}, but has been placed {itemCount} times.{maybeStartingMoves}'
if item == PlandoItems.GoldenBanana:
errString += " (40 Golden Bananas are always allocated to blueprint rewards.)"
for loc in locations:
if loc is not None:
mark_option_invalid(js.document.getElementById(loc), ValidationError.exceeds_item_limits, errString)
else:
for loc in locations:
if loc is not None:
mark_option_valid(js.document.getElementById(loc), ValidationError.exceeds_item_limits)
@bindList("change", ShopLocationList, prefix="plando_", suffix="_item")
def validate_shop_kongs(evt):
"""Raise an error if a shop has both individual and shared rewards."""
errString = "Shop vendors cannot have both shared rewards and Kong rewards assigned in the same level."
for _, vendors in ShopLocationKongMap.items():
for _, vendor_locations in vendors.items():
# Check the shared location for this vendor.
if not vendor_locations["shared"]:
# This vendor is not in this level.
continue
vendor_shared_element = get_shop_location_element(vendor_locations["shared"]["name"])
if not shop_has_assigned_item(vendor_shared_element):
# This vendor has nothing assigned for its shared location.
continue
# Check each of the individual locations.
shared_location_valid = True
for location in vendor_locations["individual"]:
vendor_element = get_shop_location_element(location["name"])
if shop_has_assigned_item(vendor_element):
# An individual shop has an assigned item.
# This is always a conflict at this point.
shared_location_valid = False
mark_option_invalid(vendor_element, ValidationError.shop_has_shared_and_solo_rewards, errString)
else:
mark_option_valid(vendor_element, ValidationError.shop_has_shared_and_solo_rewards)
if shared_location_valid:
mark_option_valid(vendor_shared_element, ValidationError.shop_has_shared_and_solo_rewards)
else:
mark_option_invalid(vendor_shared_element, ValidationError.shop_has_shared_and_solo_rewards, errString)
@bindList("change", ShopLocationList, prefix="plando_", suffix="_item")
@bind("change", "smaller_shops")
def validate_smaller_shops_no_conflict(evt):
"""Disable shops if we have a conflict with Smaller Shops.
If the user is using the Smaller Shops setting, they cannot place anything
in the shops. This causes fill issues.
"""
useSmallerShops = js.document.getElementById("smaller_shops").checked
for locationName in ShopLocationList:
# This check does not apply to Jetpac.
if locationName == Locations.RarewareCoin.name:
continue
shopElem = js.document.getElementById(f"plando_{locationName}_item")
if useSmallerShops:
errString = 'Shop locations cannot be assigned if "Smaller Shops" is selected.'
mark_option_disabled(shopElem, ValidationError.smaller_shops_conflict, errString)
else:
mark_option_enabled(shopElem, ValidationError.smaller_shops_conflict)
@bindList("change", ShopLocationList, prefix="plando_", suffix="_item")
@bind("change", "shuffle_shops")
def validate_shuffle_shops_no_conflict(evt):
"""Disable shops if the user has shuffled shops."""
shuffleShops = js.document.getElementById("shuffle_shops").checked
for locationName in ShopLocationList:
# This check does not apply to Jetpac.
if locationName == Locations.RarewareCoin.name:
continue
shopElem = js.document.getElementById(f"plando_{locationName}_item")
if shuffleShops:
errString = "Items cannot be assigned to shops when shop locations are shuffled."
mark_option_disabled(shopElem, ValidationError.assigned_shop_when_shuffled, errString)
else:
mark_option_enabled(shopElem, ValidationError.assigned_shop_when_shuffled)
@bindList("change", HintLocationList, prefix="plando_", suffix="_hint")
@bindList("keyup", HintLocationList, prefix="plando_", suffix="_hint")
def validate_hint_text_binding(evt):
"""Raise an error if this target's hint contains invalid characters."""
validate_hint_text(evt.target)
def validate_hint_text(element) -> None:
"""Raise an error if the element's hint contains invalid characters."""
errString = hint_text_validation_fn(element.value)
if errString is not None:
mark_option_invalid(element, ValidationError.invalid_hint_text, errString)
else:
mark_option_valid(element, ValidationError.invalid_hint_text)
@bindList("change", HintLocationList, prefix="plando_", suffix="_hint")
@bindList("keyup", HintLocationList, prefix="plando_", suffix="_hint")
@bind("change", "wrinkly_hints")
def validate_hint_count(evt):
"""Raise an error if there are too many hints for the current settings."""
# Mark all hints as valid, since we don't know which ones were recently
# removed, and take note of all the plando'd hints.
plandoHintList = []
for hint in HintLocationList:
hintElem = js.document.getElementById(f"plando_{hint}_hint")
mark_option_valid(hintElem, ValidationError.too_many_hints_with_fixed_hints)
if hintElem.value != "":
plandoHintList.append(hintElem)
# If we're not using fixed hints, return here after we've marked all the
# hints as valid.
if js.document.getElementById("wrinkly_hints").value != "fixed_racing":
return
# If there are more than five hints, and we are using fixed hints, this is
# an error.
if len(plandoHintList) > 5:
for hintElem in plandoHintList:
errString = "Fixed hints are incompatible with more than 5 plandomized hints."
mark_option_invalid(hintElem, ValidationError.too_many_hints_with_fixed_hints, errString)
@bindList("change", ShopLocationList, prefix="plando_", suffix="_shop_cost")
@bindList("keyup", ShopLocationList, prefix="plando_", suffix="_shop_cost")
def validate_shop_costs_binding(evt):
"""Raise an error if this target's shop has an invalid cost."""
validate_shop_costs(evt.target)
def validate_shop_costs(element) -> None:
"""Raise an error if this element's shop has an invalid cost."""
shopCost = element.value
if shopCost == "":
mark_option_valid(element, ValidationError.invalid_shop_cost)
elif shopCost.isdigit() and int(shopCost) >= 0 and int(shopCost) <= 255:
mark_option_valid(element, ValidationError.invalid_shop_cost)
else:
errString = "Shop costs must be a whole number between 0 and 255."
mark_option_invalid(element, ValidationError.invalid_shop_cost, errString)
@bind("change", "starting_kongs_count")
@bind("change", "plando_starting_kongs_selected")
def validate_starting_kong_count(evt):
"""Raise an error if the starting Kongs don't match the selected count."""
startingKongs = js.document.getElementById("plando_starting_kongs_selected")
selectedKongs = {x.value for x in startingKongs.selectedOptions}
numStartingKongs = int(js.document.getElementById("starting_kongs_count").value)
isRandomStartingKongCount = js.document.getElementById("starting_random").checked
if isRandomStartingKongCount:
# With a random starting Kong count, everything is fair game in this box and it'll try to meet expectations as best as it can
mark_option_valid(startingKongs, ValidationError.invalid_starting_kong_count)
elif len(selectedKongs) > numStartingKongs or (len(selectedKongs) < numStartingKongs and "" not in selectedKongs):
maybePluralKongText = "Kong was selected as a starting Kong" if len(selectedKongs) == 1 else "Kongs were selected as starting Kongs"
errSuffix = "." if len(selectedKongs) > numStartingKongs else ', and "Random Kong(s)" was not chosen.'
errString = f"The number of starting Kongs was set to {numStartingKongs}, but {len(selectedKongs)} {maybePluralKongText}{errSuffix}"
mark_option_invalid(startingKongs, ValidationError.invalid_starting_kong_count, errString)
else:
mark_option_valid(startingKongs, ValidationError.invalid_starting_kong_count)
@bind("change", "plando_level_order_", 8)
def validate_level_order_no_duplicates(evt):
"""Raise an error if the same level is chosen twice in the level order."""
levelDict = {}
# Count the instances of each level.
for i in range(0, 8):
levelElemName = f"plando_level_order_{i}"
levelOrderElem = js.document.getElementById(levelElemName)
level = levelOrderElem.value
if level in levelDict:
levelDict[level].append(levelElemName)
else:
levelDict[level] = [levelElemName]
# Invalidate any selects that re-use the same level.
for level, selects in levelDict.items():
if level == "" or len(selects) == 1:
for select in selects:
selectElem = js.document.getElementById(select)
mark_option_valid(selectElem, ValidationError.level_order_duplicates)
else:
for select in selects:
selectElem = js.document.getElementById(select)
errString = "The same level cannot be used twice in the level order."
mark_option_invalid(selectElem, ValidationError.level_order_duplicates, errString)
@bind("change", "plando_krool_order_", 5)
@bind("change", "plando_boss_order_", 7)
def validate_krool_order_no_duplicates(evt):
"""Raise an error if the same boss is chosen twice in the K. Rool or Boss order."""
battleDict = {}
# Count the instances of each boss battle.
for i in range(0, 5):
kroolElemName = f"plando_krool_order_{i}"
kroolOrderElem = js.document.getElementById(kroolElemName)
battle = kroolOrderElem.value
if battle in battleDict:
battleDict[battle].append(kroolElemName)
else:
battleDict[battle] = [kroolElemName]
for i in range(0, 7):
tnsElemName = f"plando_boss_order_{i}"
tnsOrderElem = js.document.getElementById(tnsElemName)
battle = tnsOrderElem.value
if battle in battleDict:
battleDict[battle].append(tnsElemName)
else:
battleDict[battle] = [tnsElemName]
# Invalidate any selects that re-use the same battle.
for battle, selects in battleDict.items():
if battle == "" or len(selects) == 1:
for select in selects:
selectElem = js.document.getElementById(select)
mark_option_valid(selectElem, ValidationError.krool_order_duplicates)
else:
for select in selects:
selectElem = js.document.getElementById(select)
errString = "The same boss battle cannot be used twice in the K. Rool order."
mark_option_invalid(selectElem, ValidationError.krool_order_duplicates, errString)
@bind("change", "plando_helm_order_", 5)
def validate_helm_order_no_duplicates(evt):
"""Raise an error if the same Kong is chosen twice in the Helm order."""
kongDict = {}
# Count the instances of each Kong.
for i in range(0, 5):
helmElemName = f"plando_helm_order_{i}"
helmOrderElem = js.document.getElementById(helmElemName)
kong = helmOrderElem.value
if kong in kongDict:
kongDict[kong].append(helmElemName)
else:
kongDict[kong] = [helmElemName]
# Invalidate any selects that re-use the same Kong.
for kong, selects in kongDict.items():
if kong == "" or len(selects) == 1:
for select in selects:
selectElem = js.document.getElementById(select)
mark_option_valid(selectElem, ValidationError.helm_order_duplicates)
else:
for select in selects:
selectElem = js.document.getElementById(select)
errString = "The same Kong cannot be used twice in the Helm order."
mark_option_invalid(selectElem, ValidationError.helm_order_duplicates, errString)
@bind("change", "plando_place_arenas")
@bind("change", "plando_place_patches")
@bind("change", "plando_place_fairies")
@bind("change", "plando_place_kasplats")
@bind("change", "plando_place_crates")
@bindList("change", CrownLocationEnumList, prefix="plando_", suffix="_location")
@bindList("change", KasplatLocationEnumList, prefix="plando_", suffix="_location")
@bindList("change", [f"patch_{i}" for i in range(0, 16)], prefix="plando_", suffix="_location")
@bindList("change", [f"fairy_{i}" for i in range(0, 20)], prefix="plando_", suffix="_location")
@bindList("change", [f"crate_{i}" for i in range(0, 13)], prefix="plando_", suffix="_location")
def validate_custom_locations_no_duplicates(evt):
"""Prevent any custom location from being used twice."""
def count_location(location: str, elem_name: str, loc_dict: dict):
"""Add the given element to our location-counting dictionary."""
if location in loc_dict:
loc_dict[location].append(elem_name)
else:
loc_dict[location] = [elem_name]
# We group patches, crowns and crates together to check locations, because
# they all use the same custom locations.
locDict = {}
if patch_locations_assigned():
for locElem in [f"plando_patch_{i}_location" for i in range(0, 16)]:
custLocation = js.document.getElementById(locElem).value
count_location(custLocation, locElem, locDict)
if crate_locations_assigned():
for locElem in [f"plando_crate_{i}_location" for i in range(0, 13)]:
custLocation = js.document.getElementById(locElem).value
count_location(custLocation, locElem, locDict)
if arena_locations_assigned():
for crownLocation in CrownLocationEnumList:
level = LocationList[Locations[crownLocation]].level.name
locElem = f"plando_{crownLocation}_location"
custLocation = js.document.getElementById(locElem).value
fullLocation = "" if custLocation == "" else f"{level};{custLocation}"
count_location(fullLocation, locElem, locDict)
if fairy_locations_assigned():
for locElem in [f"plando_fairy_{i}_location" for i in range(0, 20)]:
custLocation = js.document.getElementById(locElem).value
# We'll append "fairy" to the start to avoid conflict with
# non-fairy locations.
fullLocation = "" if custLocation == "" else f"fairy{custLocation}"
count_location(fullLocation, locElem, locDict)
if kasplat_locations_assigned():
for kasplatLocation in KasplatLocationEnumList:
# Kasplat locations already start with "Levelname Kasplat" so we
# don't need to do anything to avoid conflicts with non-Kasplat
# locations.
locElem = f"plando_{kasplatLocation}_location"
custLocation = js.document.getElementById(locElem).value
count_location(custLocation, locElem, locDict)
# Invalidate any selects that re-use the same location.
for location, selects in locDict.items():
if location == "" or len(selects) == 1:
for select in selects:
selectElem = js.document.getElementById(select)
mark_option_valid(selectElem, ValidationError.duplicate_custom_location)
else:
for select in selects:
selectElem = js.document.getElementById(select)
errString = "Custom locations cannot be used more than once."
mark_option_invalid(selectElem, ValidationError.duplicate_custom_location, errString)
@bind("change", "plando_place_wrinkly")
@bind("change", "plando_place_tns")
@bindList("change", [x.name for x in WrinklyDoorEnumList], prefix="plando_", suffix="_wrinkly_door")
@bindList("change", TnsPortalLocationList, prefix="plando_", suffix="_tns_portal")
def validate_custom_doors_no_duplicate_locations(evt):
"""Prevent any door location from being used twice."""
locDict = {}
def count_location(location: str, elem_name: str):
"""Add the given element to our location-counting dictionary."""
if location in locDict:
locDict[location].append(elem_name)
else:
locDict[location] = [elem_name]
if wrinkly_locations_assigned():
for wrinklyDoor in WrinklyDoorEnumList:
locElem = f"plando_{wrinklyDoor.name}_wrinkly_door"
custDoor = js.document.getElementById(locElem).value
count_location(custDoor, locElem)
if tns_locations_assigned():
for tnsPortal in TnsPortalLocationList:
locElem = f"plando_{tnsPortal}_tns_portal"
custDoor = js.document.getElementById(locElem).value
count_location(custDoor, locElem)
# Invalidate any selects that re-use the same door.
for location, selects in locDict.items():
if location == "" or location == "none" or len(selects) == 1:
for select in selects:
selectElem = js.document.getElementById(select)
mark_option_valid(selectElem, ValidationError.duplicate_custom_door)
else:
for select in selects:
selectElem = js.document.getElementById(select)
errString = "Custom door locations cannot be used more than once."
mark_option_invalid(selectElem, ValidationError.duplicate_custom_door, errString)
@bindList("change", CrownLocationEnumList, prefix="plando_", suffix="_location")
@bindList("change", KasplatLocationEnumList, prefix="plando_", suffix="_location")
@bindList("change", [f"patch_{i}" for i in range(0, 16)], prefix="plando_", suffix="_location")
@bindList("change", [f"fairy_{i}" for i in range(0, 20)], prefix="plando_", suffix="_location")
@bindList("change", [f"crate_{i}" for i in range(0, 13)], prefix="plando_", suffix="_location")
def validate_no_reward_with_random_location_binding(evt):
"""Disable assigning rewards for checks with random locations."""
validate_no_reward_with_random_location(evt.target)
def validate_no_reward_with_random_location(elem):
"""Disable assigning rewards for checks with random locations."""
elemId = elem.id
rewardElem = js.document.getElementById(f"{elemId}_reward")
if elem.value == "":
errString = "Rewards cannot be assigned to randomized locations."
mark_option_disabled(rewardElem, ValidationError.random_custom_location, errString)
else:
mark_option_enabled(rewardElem, ValidationError.random_custom_location)
def full_validate_no_reward_with_random_location():
"""Perform random location reward validation on all elements."""
locations = [
[f"plando_patch_{i}_location" for i in range(0, 16)],
[f"plando_fairy_{i}_location" for i in range(0, 20)],
[f"plando_crate_{i}_location" for i in range(0, 13)],
[f"plando_{loc}_location" for loc in CrownLocationEnumList],
[f"plando_{loc}_location" for loc in KasplatLocationEnumList],
]
for locationList in locations:
for location in locationList:
locElem = js.document.getElementById(location)
validate_no_reward_with_random_location(locElem)
@bind("change", "random_crates")
def validate_no_crate_items_with_shuffled_crates(evt):
"""Prevent crate items from being assigned with shuffled crates."""
randomCrates = js.document.getElementById("random_crates")
for location in MelonCratePlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if randomCrates.checked:
errString = "Items cannot be assigned to melon crates when melon crate locations are shuffled."
mark_option_disabled(locElem, ValidationError.assigned_crate_when_shuffled, errString)
else:
mark_option_enabled(locElem, ValidationError.assigned_crate_when_shuffled)
@bind("change", "crown_placement_rando")
def validate_no_crown_items_with_shuffled_crowns(evt):
"""Prevent crown items from being assigned with shuffled crowns."""
randomCrowns = js.document.getElementById("crown_placement_rando")
for location in CrownPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if randomCrowns.checked:
errString = "Items cannot be assigned to battle arenas when battle arena locations are shuffled."
mark_option_disabled(locElem, ValidationError.assigned_crown_when_shuffled, errString)
else:
mark_option_enabled(locElem, ValidationError.assigned_crown_when_shuffled)
@bind("change", "random_patches")
def validate_no_dirt_items_with_shuffled_patches(evt):
"""Prevent dirt patch items from being assigned with shuffled patches."""
randomPatches = js.document.getElementById("random_patches")
for location in DirtPatchPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if randomPatches.checked:
errString = "Items cannot be assigned to dirt patches when dirt patch locations are shuffled."
mark_option_disabled(locElem, ValidationError.assigned_dirt_patch_when_shuffled, errString)
else:
mark_option_enabled(locElem, ValidationError.assigned_dirt_patch_when_shuffled)
@bind("change", "random_fairies")
def validate_no_fairy_items_with_shuffled_fairies(evt):
"""Prevent fairy items from being assigned with shuffled fairies."""
randomFairies = js.document.getElementById("random_fairies")
for location in FairyPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if randomFairies.checked:
errString = "Items cannot be assigned to fairies when fairies are shuffled."
mark_option_disabled(locElem, ValidationError.assigned_fairy_when_shuffled, errString)
else:
mark_option_enabled(locElem, ValidationError.assigned_fairy_when_shuffled)
@bind("change", "kasplat_rando_setting")
def validate_no_kasplat_items_with_location_shuffle(evt):
"""Prevent Kasplat items from being assigned with location shuffle."""
kasplatRandoElem = js.document.getElementById("kasplat_rando_setting")
shuffled = kasplatRandoElem.value == KasplatRandoSetting.location_shuffle.name
for location in KasplatPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if shuffled:
errString = "Items cannot be assigned to Kasplats when Kasplat locations are shuffled."
mark_option_disabled(locElem, ValidationError.assigned_kasplat_when_shuffled, errString)
else:
mark_option_enabled(locElem, ValidationError.assigned_kasplat_when_shuffled)
@bind("change", "plando_place_arenas")
def validate_custom_arena_locations(evt):
"""Require arena items be placed through Custom Locations."""
for location in CrownPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if arena_locations_assigned():
errString = "This item must be assigned through the Custom Locations tab."
mark_option_disabled(locElem, ValidationError.only_available_as_custom_location, errString)
else:
mark_option_enabled(locElem, ValidationError.only_available_as_custom_location)
@bind("change", "plando_place_patches")
def validate_custom_patch_locations(evt):
"""Require patch items be placed through Custom Locations."""
for location in DirtPatchPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if patch_locations_assigned():
errString = "This item must be assigned through the Custom Locations tab."
mark_option_disabled(locElem, ValidationError.only_available_as_custom_location, errString)
else:
mark_option_enabled(locElem, ValidationError.only_available_as_custom_location)
@bind("change", "plando_place_fairies")
def validate_custom_fairy_locations(evt):
"""Require fairy items be placed through Custom Locations."""
for location in FairyPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if fairy_locations_assigned():
errString = "This item must be assigned through the Custom Locations tab."
mark_option_disabled(locElem, ValidationError.only_available_as_custom_location, errString)
else:
mark_option_enabled(locElem, ValidationError.only_available_as_custom_location)
@bind("change", "plando_place_kasplats")
def validate_custom_kasplat_locations(evt):
"""Require Kasplat items be placed through Custom Locations."""
for location in KasplatPlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if kasplat_locations_assigned():
errString = "This item must be assigned through the Custom Locations tab."
mark_option_disabled(locElem, ValidationError.only_available_as_custom_location, errString)
else:
mark_option_enabled(locElem, ValidationError.only_available_as_custom_location)
@bind("change", "plando_place_crates")
def validate_custom_crate_locations(evt):
"""Require crate items be placed through Custom Locations."""
for location in MelonCratePlandoLocationList:
locElem = js.document.getElementById(f"plando_{location}_item")
if crate_locations_assigned():
errString = "This item must be assigned through the Custom Locations tab."
mark_option_disabled(locElem, ValidationError.only_available_as_custom_location, errString)
else:
mark_option_enabled(locElem, ValidationError.only_available_as_custom_location)
def enable_switch_plando():
"""Enable or disable placing switches based on the Switchsanity setting."""
switchsanity = js.document.getElementById("switchsanity").value
for switchEnum in SwitchData.keys():
switchElem = js.document.getElementById(f"plando_{switchEnum.name}_switch")
if switchsanity == "all":
mark_option_enabled(switchElem, ValidationError.switchsanity_not_enabled)
elif switchEnum in [Switches.IslesHelmLobbyGone, Switches.IslesMonkeyport]:
if switchsanity == "helm_access":
mark_option_enabled(switchElem, ValidationError.switchsanity_not_enabled)
else:
errString = 'To set this switch, Switchsanity must be set to "All" or "Helm Access Only".'
mark_option_disabled(switchElem, ValidationError.switchsanity_not_enabled, errString, SwitchVanillaMap[switchEnum.name])
else:
errString = 'To set this Switch, Switchsanity must be set to "All".'
mark_option_disabled(switchElem, ValidationError.switchsanity_not_enabled, errString, SwitchVanillaMap[switchEnum.name])
@bind("change", "switchsanity")
def set_plando_switches(evt):
"""Set values and enable switches based on the Switchsanity setting."""
enable_switch_plando()
switchsanity = js.document.getElementById("switchsanity").value
for switchEnum in SwitchData.keys():
switchElem = js.document.getElementById(f"plando_{switchEnum.name}_switch")
if switchsanity == "all":
# If this switch is currently set to its vanilla value, change it
# to "Randomize".
if switchElem.value == SwitchVanillaMap[switchEnum.name]:
switchElem.value = ""
elif switchEnum in [Switches.IslesHelmLobbyGone, Switches.IslesMonkeyport]:
if switchsanity == "helm_access":
# If this switch is currently set to its vanilla value, change
# it to "Randomize".
if switchElem.value == SwitchVanillaMap[switchEnum.name]:
switchElem.value = ""
@bind("click", "key_8_helm")
def lock_key_8_in_helm(evt):
"""If key 8 is locked in Helm, force that location to hold key 8."""
helm_is_shuffled = js.document.getElementById("shuffle_helm_location").checked
is_level_order = js.document.getElementById("level_randomization").value in ["level_order", "level_order_complex"]
helm_key_lock = js.document.getElementById("key_8_helm").checked
end_of_helm = js.document.getElementById("plando_HelmKey_item")
# If the settings require Key 8 to be at the End of Helm...
if helm_key_lock and not (is_level_order and helm_is_shuffled):
# Forcibly select Key 8 for the End of Helm dropdown and disable it.
errString = 'The "Lock Key 8 in Helm" setting has been chosen.'
mark_option_disabled(end_of_helm, ValidationError.key_8_locked_in_helm, errString, Items.HideoutHelmKey.name)
else:
# Enable the End of Helm dropdown. If Key 8 is currently placed there,
# remove it as the dropdown option.
if end_of_helm.value == Items.HideoutHelmKey.name:
end_of_helm.value = ""
mark_option_enabled(end_of_helm, ValidationError.key_8_locked_in_helm)
@bind("click", "nav-plando-tab")
def validate_on_nav(evt):
"""Apply certain changes when navigating to the plandomizer tab."""
perform_setting_conflict_validation(evt)
def perform_setting_conflict_validation(evt):
"""Perform checks that compare plando settings to other settings."""
lock_key_8_in_helm(evt)
validate_smaller_shops_no_conflict(evt)
validate_shuffle_shops_no_conflict(evt)
validate_no_crate_items_with_shuffled_crates(evt)
validate_no_crown_items_with_shuffled_crowns(evt)
validate_no_dirt_items_with_shuffled_patches(evt)
validate_no_fairy_items_with_shuffled_fairies(evt)
validate_no_kasplat_items_with_location_shuffle(evt)
validate_custom_arena_locations(evt)
validate_custom_crate_locations(evt)
validate_custom_fairy_locations(evt)
validate_custom_kasplat_locations(evt)
validate_custom_patch_locations(evt)
validate_custom_locations_no_duplicates(evt)
validate_custom_doors_no_duplicate_locations(evt)
full_validate_no_reward_with_random_location()
js.plando_toggle_custom_arena_locations(evt)
js.plando_toggle_custom_crate_locations(evt)
js.plando_toggle_custom_fairy_locations(evt)
js.plando_toggle_custom_kasplat_locations(evt)
js.plando_toggle_custom_patch_locations(evt)
js.plando_toggle_custom_tns_locations(evt)
js.plando_toggle_custom_wrinkly_locations(evt)
js.plando_toggle_custom_locations_tab(evt)
enable_switch_plando()
# This is a fallback for errors with Bootstrap sliders.
validate_starting_kong_count(evt)
@bind("click", "reset_plando_settings")
def reset_plando_options(evt):
"""Return all plandomizer options to their default settings.
Issues a prompt first, warning the user.
"""
if js.window.confirm("Are you sure you want to reset all plandomizer settings?"):
reset_plando_options_no_prompt()
# Plando options where the value is of type Levels.
level_options = [
"plando_level_order_0",
"plando_level_order_1",
"plando_level_order_2",
"plando_level_order_3",
"plando_level_order_4",
"plando_level_order_5",