This repository has been archived by the owner on Nov 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCrabChampionSaveManager.py
6075 lines (5446 loc) · 223 KB
/
CrabChampionSaveManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import hashlib
import os
import random
import shutil
import time
import subprocess
import platform
import sys
import json
import threading
import re
from tkinter import filedialog
import tkinter
import traceback
import orjson
import xxhash
global isExe
global isLinux
global Version
isExe = False
isLinux = False
VERSION = "5.0.0"
if platform.system() == "Linux":
isLinux = True
if getattr(sys, "frozen", False):
isExe = True
def unhandledExeceptionHandle(exc_type, exc_value, exc_traceback):
trace = ""
ar = traceback.format_tb(exc_traceback)
for i in ar:
trace += i
f = open("traceback.log", "w")
f.write(
"An Execption/Error happened, contact dev to report or check wiki\n\nType : "
+ str(exc_type)
+ "\nValue : "
+ str(exc_value)
+ "\nTraceback : \n"
+ trace
)
f.close()
infoScreen(
"An Execption/Error happened, contact dev to report or check wiki\n\nType : "
+ str(exc_type)
+ "\nValue : "
+ str(exc_value)
+ "\nTraceback : \n"
+ trace
)
time.sleep(10)
pass
sys.excepthook = unhandledExeceptionHandle
def closeScreen():
global screen
curses.nocbreak()
screen.keypad(False)
curses.echo()
curses.endwin()
StopBackupWatcherEvent = threading.Event()
def exiting(var, force=False):
global infoScreen
StopBackupWatcherEvent.set()
try:
AccountStatsWatcherThread.join()
except BaseException:
None
try:
screen.clear()
closeScreen()
saveSettings()
except BaseException:
None
if force:
os._exit(var)
else:
try:
sys.exit(var)
except SystemExit:
os._exit(var)
try:
import requests
import curses
from SavConverter import (
sav_to_json,
read_sav,
json_to_sav,
load_json,
obj_to_json,
print_json,
get_object_by_path,
insert_object_by_path,
replace_object_by_path,
update_property_by_path,
)
except BaseException:
print("Not all libraries are installed")
perm = input("Permission to download libraries? (requests, SavConverter, windows-curses (windows only)) [y/N]\n")
if "y" in perm.lower():
if not isLinux:
os.system("pip install windows-curses")
os.system("pip install requests")
os.system("pip install SavConverter")
import requests
import curses
from SavConverter import (
sav_to_json,
read_sav,
json_to_sav,
load_json,
obj_to_json,
print_json,
get_object_by_path,
insert_object_by_path,
replace_object_by_path,
update_property_by_path,
)
else:
print("no permission given, script can't start")
exiting(0)
def isValidPathName(name):
"""tests the string to see if it's a valid folder or file name
Args:
name (str): the name of the file or folder to test
Returns:
bool: is it valid or not
"""
invalid_chars = r'[<>:"/\\|?*\x00-\x1F]'
reserved_names = [
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
]
# Check for invalid characters
if re.search(invalid_chars, name):
return False
# Check for reserved names
if name.upper() in reserved_names:
return False
# Check for other conditions (if any) that make the name invalid
# If none of the above conditions match, the name is valid
return True
def parseInt(input_string):
"""Converts the input string to an integer if possible, otherwise returns -1."""
try:
return int(input_string)
except BaseException:
return -1
def isValidFolderName(folder_name):
"""Checks if the folder name is valid based on certain criteria.
The folder name should not contain any of the characters \\/:*?\"<>|,
should not end in a period or consist of only spaces and periods,
and should not be any of the reserved folder names (SaveGames, Logs, Config).
Additionally, it should not be any of the system-reserved names.
Returns True if the folder name is valid, False otherwise.
"""
invalid_characters = r'\\/:*?"<>|'
reserved_names = ["SaveGames", "Logs", "Config"]
# Check for invalid characters
if any(char in folder_name for char in invalid_characters):
return False
# Check if the name ends in a period or consists of only spaces and periods
if folder_name.endswith(".") or folder_name.strip(" .") == "":
return False
# Check if the name is a reserved folder name
if folder_name in reserved_names:
return False
# Check if the name is a system-reserved name
system_reserved_names = [
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
]
if folder_name.upper() in system_reserved_names:
return False
# Check if the name is a reserved name in Windows file system
reserved_words = [
"CON",
"PRN",
"AUX",
"NUL",
"COM",
"LPT",
"CONIN$",
"CONOUT$",
"PRN$",
"AUX$",
"NUL$",
"COM1$",
"COM2$",
"COM3$",
"COM4$",
"COM5$",
"COM6$",
"COM7$",
"COM8$",
"COM9$",
"LPT1$",
"LPT2$",
"LPT3$",
"LPT4$",
"LPT5$",
"LPT6$",
"LPT7$",
"LPT8$",
"LPT9$",
]
if folder_name.upper() in reserved_words:
return False
return True
def backupNameMenu(prompt, escape=None, name="", escapeReturn=None):
global screen
if isinstance(prompt, type("")):
prompt = prompt.split("\n")
curstate = curses.curs_set(1)
folder_name = name
while True:
screen.clear()
for i, prom in enumerate(prompt):
screen.addstr(i, 0, prom)
screen.addstr(len(prompt) - 1, 0, prompt[len(prompt) - 1] + ": " + folder_name)
screen.refresh()
key = screen.getch()
if key == curses.KEY_BACKSPACE or key in [127, 8]:
folder_name = folder_name[:-1]
elif key == curses.KEY_ENTER or key in [10, 13]:
curses.curs_set(curstate)
if folder_name == escape:
return escapeReturn
elif isValidFolderName(folder_name):
return folder_name
else:
infoScreen(
'Invaild backup name\nBackup name can not contain any of these characters \\ / : * ? " < > | .'
)
screen.refresh()
curses.napms(2000) # Display the error message for 2 seconds
folder_name = ""
else:
folder_name += chr(key)
def backupSave():
"""Performs the backup of the save game.
Asks the user for the backup name, validates it, and creates a backup
by copying the SaveGames folder to the specified backup location.
If a backup with the same name already exists, prompts for overwrite confirmation.
"""
current_directory = os.getcwd()
folders = getBackups()
confirm = False
while not confirm:
saveName = backupNameMenu(
"Enter nothing to go back to the main menu\nEnter backup name",
escape="",
escapeReturn="",
)
if saveName not in folders:
confirm = True
else:
ans = yornMenu("There is already a backup by that name. Overwrite?")
if ans:
confirm = True
else:
confirm = False
if saveName == "":
return
saveGame = os.path.join(current_directory, "SaveGames")
backupName = os.path.join(current_directory, saveName)
try:
infoScreen("Making backup\nThis might take a few seconds")
shutil.rmtree(backupName, ignore_errors=True)
shutil.copytree(saveGame, backupName)
loadCache()
except Exception as error:
scrollInfoMenu("Could not make backup. Error below:\n" + str(error))
def restoreBackup():
"""Restores a backup of the save game.
Displays the available backups and prompts the user to choose one.
If a backup is selected, it replaces the current SaveGames folder
with the contents of the chosen backup.
"""
current_directory = os.getcwd()
foldersInfo = getBackups(moreInfo=1)
folders = getBackups()
prompt = "Choose Backup to restore\n"
options = "Go back to main menu"
for i in range(len(foldersInfo)):
options += "\n" + str(foldersInfo[i])
choice = scrollSelectMenu(prompt, options, -1, 1, loop=True)
if parseInt(choice) == 0:
return
start = time.time()
saveGame = os.path.join(current_directory, "SaveGames")
backupName = os.path.join(current_directory, folders[parseInt(choice) - 1])
saveGame += "/SaveSlot.sav"
backupName += "/SaveSlot.sav"
saveGame = saveGame.replace("\\", "/")
backupName = backupName.replace("\\", "/")
saveGameJson = getJSON(saveGame)
backupJson = getJSON(backupName)
# with open("debug1.json","w") as f:
# json.dump(backupJson,f,indent=4)
# with open("debug2.json","w") as f:
# json.dump(saveGameJson,f,indent=4)
if getValue(backupJson, Paths.Autosave) is None:
scrollInfoMenu("Selected backup has no save\nPress Enter to return to main menu")
return
saveGameJson = ensureAutoSave(saveGameJson)
# setValue(saveGameJson, Paths.Autosave, getValue(backupJson,Paths.Autosave))
update_property_by_path(
saveGameJson, Paths.Autosave, getValue(backupJson, Paths.Autosave)
)
saveSavJson(saveGame, saveGameJson)
shutil.copyfile("SaveGames/SaveSlot.sav", "SaveGames/SaveSlotBackupA.sav")
shutil.copyfile("SaveGames/SaveSlot.sav", "SaveGames/SaveSlotBackupB.sav")
infoScreen("Backup Restored - " + str(folders[parseInt(choice) - 1]))
stop = time.time()
# print("it took",round(stop-start,3)," seconds")
return
def ensureAutoSave(JSON):
defaultSaveJson = json.loads(
'{"type": "StructProperty","name": "AutoSave","subtype": "CrabAutoSave","value": []}'
)
save = getValue(JSON, Paths.Autosave)
if save is None:
insert_object_by_path(
JSON, [{"type": "FileEndProperty"}], defaultSaveJson, "before"
)
return JSON
def saveSavJson(path, JSON):
with open(path, "wb") as f:
f.write(json_to_sav(obj_to_json(JSON)))
def deleteBackup():
"""Deletes a backup of the save game.
Displays the available backups and prompts the user to choose one.
If a backup is selected, it permanently deletes the corresponding backup folder.
"""
current_directory = os.getcwd()
foldersInfo = getBackups(moreInfo=1)
folders = getBackups()
prompt = "Choose Backup to delete\n"
options = "Go back to main menu"
for i in range(len(foldersInfo)):
options += "\n" + str(foldersInfo[i])
choice = scrollSelectMenu(prompt, options, -1, 1, loop=True)
if parseInt(choice) == 0:
return
perm = yornMenu(
"Are you sure you want to delete " + folders[parseInt(choice) - 1], False
)
if not perm:
return
backupName = os.path.join(current_directory, folders[parseInt(choice) - 1])
try:
shutil.rmtree(backupName)
except Exception as error:
scrollInfoMenu("Could not delete backup. Error below:\n" + str(error), -1)
def listBackups(lastChoice=0):
global screen
"""Lists all the available backups of the save game.
Retrieves the list of backup folders and displays them to the user.
"""
# current time in seconds -
# ["root"]["properties"]["AutoSave"]["Struct"]["value"]["Struct"]["CurrentTime"]["Int"]["value"]
loadCache()
current_directory = os.getcwd()
foldersInfo = getBackups(moreInfo=1, currentSave=True)
folders = getBackups(currentSave=True)
prompt = (
str(len(folders))
+ " Backups Stored\nSelect Backup for more info about that backup\n"
)
backups = "Go back to main menu\n"
for i, name in enumerate(foldersInfo):
if i == 0:
backups += str(name)
else:
backups += "\n" + str(name)
choice = scrollSelectMenu(
prompt, backups, wrapMode=2, startChoice=lastChoice, loop=True
)
if choice == 0:
return
choice -= 1
backupDetailsScreen(folders[choice])
listBackups(choice + 1)
def getSavesNames():
savesDir = os.getcwd()
savesDir = savesDir.replace("\\", "/")
entries = os.scandir(savesDir)
folders = []
for entry in entries:
if entry.name in ["SaveGames", "Config", "Logs", "CrabChampionSaveManager"]:
None
elif entry.is_dir() and os.path.isfile(
entry.path.replace("\\", "/") + "/SaveSlot.sav"
):
folders.append(entry.name)
return folders
def getBackups(moreInfo=0, currentSave=False, updateCache=True):
global cacheJSON
"""Retrieves the list of backup folders.
Searches the current directory for backup folders and returns a list of their names.
"""
current_directory = os.getcwd()
current_directory = current_directory.replace("\\", "/")
entries = os.scandir(current_directory)
folders = []
for entry in entries:
if entry.name in ["SaveGames", "Config", "Logs", "CrabChampionSaveManager"]:
None
elif entry.is_dir() and os.path.isfile(
entry.path.replace("\\", "/") + "/SaveSlot.sav"
):
folders.append(entry.name)
if currentSave:
folders.insert(0, "Current Save")
if updateCache:
for i in folders:
try:
if cacheJSON["BackupData"][i]["NoSave"]:
folders.pop(folders.index(i))
except BaseException:
folders.pop(folders.index(i))
if moreInfo == 0:
return folders
else:
if updateCache:
loadCache()
# for the config json
# run time seconds - ["BackupData"][BackupName]["RunTime"]
# score - ["BackupData"][BackupName]["Score"]
# difficulty - ["BackupData"][BackupName]["Diff"]
# island num - ["BackupData"][BackupName]["IslandNum"]
# diff mods - ["BackupData"][BackupName]["DiffMods"]
# checksum - ["BackupData"][BackupName]["CheckSum"]
# nosave,if it has a save - ["BackupData"][BackupName]["NoSave"]
ofold = folders
try:
maxLenName = 0
maxLenTime = 0
maxLenDiff = 0
maxLenIsland = 0
maxLenScore = 0
for name in folders:
if not cacheJSON["BackupData"][name]["NoSave"]:
maxLenName = max(maxLenName, len(name))
maxLenTime = max(
maxLenTime,
len(
f"Time: {formatTime(cacheJSON['BackupData'][name]['RunTime'])}"
),
)
maxLenDiff = max(
maxLenDiff,
len("Diff: " + str(cacheJSON["BackupData"][name]["Diff"])),
)
maxLenIsland = max(
maxLenIsland,
len("Island: " + str(cacheJSON["BackupData"][name]["IslandNum"])),
)
maxLenScore = max(
maxLenScore,
len("Score: " + str(cacheJSON["BackupData"][name]["Score"])),
)
distance = 4
maxLenTime += distance
maxLenDiff += distance
maxLenIsland += distance
maxLenScore += distance
for i in range(len(folders)):
name = folders[i]
if not cacheJSON["BackupData"][name]["NoSave"]:
time = "Time: " + str(
formatTime(cacheJSON["BackupData"][name]["RunTime"])
)
time = ensureLength(time, maxLenTime)
diff = "Diff: " + str(cacheJSON["BackupData"][name]["Diff"])
diff = ensureLength(diff, maxLenDiff)
islandnum = "Island: " + str(
cacheJSON["BackupData"][name]["IslandNum"]
)
islandnum = ensureLength(islandnum, maxLenIsland)
score = "Score: " + str(cacheJSON["BackupData"][name]["Score"])
score = ensureLength(score, maxLenScore)
name = ensureLength(name, maxLenName)
folders[i] = name + " - " + time + diff + islandnum + score
return folders
except Exception as e:
# import traceback
# print(e)
# traceback.print_exc()
return ofold
def ensureLength(string, length):
"""
takes in a string and adds spaces to the end up it till it has the same length
"""
while len(string) < length:
string += " "
return str(string)
def isSavesDir(path=os.getcwd()):
"""Checks if the required folders are present in the current directory.
Checks if the folders SaveGames, Logs, and Config exist in the current directory.
Returns True if any of the folders is missing, indicating a directory check failure.
Returns False if all the required folders are present.
"""
folder_names = ["SaveGames", "Logs", "Config"]
for folder_name in folder_names:
folder_path = os.path.join(path, folder_name)
if os.path.exists(folder_path) and os.path.isdir(folder_path):
None
else:
return True
return False
def updateBackup():
current_directory = os.getcwd()
foldersInfo = getBackups(moreInfo=1)
folders = getBackups()
prompt = "Choose Backup to update with current save\n"
options = "Go back to main menu"
for i in range(len(foldersInfo)):
options += "\n" + str(foldersInfo[i])
choice = scrollSelectMenu(prompt, options, -1, 1, loop=True)
if parseInt(choice) == 0:
return
saveGame = os.path.join(current_directory, "SaveGames")
backupName = os.path.join(current_directory, folders[parseInt(choice) - 1])
try:
shutil.rmtree(backupName, ignore_errors=True)
shutil.copytree(saveGame, backupName)
return
except Exception as error:
info = "Could not update backup. Error below:\n"
info += str(error)
scrollInfoMenu(info, -1)
return
def versionToValue(version):
try:
value = 0
points = version.split(".")
value = int(points[0]) * 1000000
value += int(points[1]) * 1000
value += int(points[2])
return int(value)
except BaseException:
return -1
def updateScript():
global isExe
global owd
perm = yornMenu(
"There is a newer version available\nWould you like to update to the latest version?"
)
if perm:
infoScreen("Updating CCSM\nThis may take a few minutes\n1/4")
print("\nUpdating CCSM\nThis may take a few minutes\n2/4")
if isExe:
downloadLatestURL = "https://github.com/O2theC/CrabChampionSaveManager/releases/latest/download/CrabChampionSaveManager.exe"
else:
downloadLatestURL = "https://github.com/O2theC/CrabChampionSaveManager/releases/latest/download/CrabChampionSaveManager.py"
try:
os.chdir(owd)
updaterURL = "https://github.com/O2theC/CrabChampionSaveManager/releases/latest/download/CrabChampionSaveManagerUpdater.exe"
meow = False
response = requests.get(downloadLatestURL)
propath = os.path.join(
owd, downloadLatestURL[downloadLatestURL.rindex("/") + 1 :]
)
propath = propath.replace(
"CrabChampionSaveManager.exe", "CrabChampionSaveManagerUpdated.exe"
)
propath = propath.replace("\\", "/")
with open(propath, "wb") as file:
file.write(response.content)
if isExe:
response = requests.get(updaterURL)
propath = os.path.join(owd, updaterURL[updaterURL.rindex("/") + 1 :])
with open(propath, "wb") as file:
file.write(response.content)
os.system("start CrabChampionSaveManagerUpdater.exe")
meow = True
except BaseException:
infoScreen("Could not download latest version\nThis program may be corrupted")
time.sleep(2)
exiting(1)
if meow:
exiting(0)
infoScreen(
"Latest Version succesfully downloaded\nRestart required for changes to take effect\npress any key to continue"
)
screen.getch()
exiting(0)
else:
return
def makeScreen():
global screen
screen = curses.initscr()
curses.noecho() # Don't display user input
curses.cbreak() # React to keys immediately without Enter
screen.keypad(True) # Enable special keys (e.g., arrow keys)
try:
curses.start_color()
curses.use_default_colors()
except BaseException:
None
def scrollSelectMenu(
prompt,
options,
win_height=-1,
buffer_size=1,
wrapMode=1,
loop=True,
skip=[],
startChoice=0,
returnMore=False,
scrollWindowStart=0,
autoItemRarityColors=False,
colorDisplayType=3,
skipColor=[],
defaultColor=0,
defaultDetails=0,
returnAnything=False,
):
"""
uses curses to create a UI for users to select from entered options with many optinoal arguments for different stuff
prompt - enter as a string or array of strings , sets the prompt at the top of the UI
options - enter as a string, array of strings or array of arrays in this format [ [String/text,color:int,displayType:int] ] , for display type
0 - color text , bold select
1 - color text , color select
2 - color text , bold select details
3 - color text , color select details
"""
global screen
def moreDeatils(opt, details=False):
optio = ""
detail = ""
try:
optio = opt[: opt.index("-")]
detail = opt[opt.index("-") + 1 :]
except BaseException:
optio = opt
detail = ""
details = False
if details:
return str(optio) + " - " + str(detail)
else:
return str(optio)
def itemColor(text, ocolor):
for t in skipColor:
if t in text:
return 0
debug11 = type(ITEMS["Names"]), ITEMS["Names"]
for item in ITEMS["Names"]:
if item in text:
rar = ITEMS[item]
if "Rare" in rar:
return RARECOLOR
elif "Epic" in rar:
return EPICCOLOR
elif "Legendary" in rar:
return LEGENDARYCOLOR
elif "Greed" in rar:
return GREEDCOLOR
return 0
if isinstance(options, type("")):
options = options.split("\n")
if isinstance(prompt, type("")):
prompt = prompt.split("\n")
if win_height == -1:
autoSize = True
win_height = 1000
else:
autoSize = False
win_height = min(win_height, screen.getmaxyx()[0] - (3 + len(prompt)))
win_height = max(1, win_height)
win_wid = screen.getmaxyx()[1]
oBufSize = buffer_size
buffer_size = min(buffer_size, win_height // 2 - 1 + win_height % 2)
buffer_size = max(buffer_size, 0)
selected_option = startChoice
scroll_window = scrollWindowStart
curstate = curses.curs_set(0)
firstPass = False
while True:
screen.clear()
win_wid = screen.getmaxyx()[1]
# Display the main prompt
for i, prom in enumerate(prompt):
if (len(prom) > win_wid) and wrapMode == 2:
prom = prom[:win_wid]
screen.addstr(i, 0, prom)
# Display the options
for i, option in enumerate(options):
if i >= scroll_window and i < scroll_window + win_height:
textArray = [["text", defaultColor, defaultDetails]]
if not isinstance(option, type([])):
textArray[0][0] = str(option)
option = textArray.copy()
elif not isinstance(option[0], type([])) and isinstance(option, type([])):
option = [option]
else:
for ii in range(len(option)):
if not isinstance(option[ii], type([])) or len(option[ii]) == 0:
option[ii] = [str(option[ii]), 0, 0]
else:
ar = option[ii]
l = len(ar)
option[ii] = [str(ar[0]), 0, 0]
if l > 1:
if isinstance(ar[1], type(1)):
option[ii][1] = ar[ii]
else:
option[ii][1] = 0
if l > 2:
if isinstance(ar[2], type(1)):
option[ii][2] = ar[2]
else:
option[ii][2] = 0
for ii in range(len(option)):
if autoItemRarityColors:
option[ii][1] = itemColor(option[ii][0], option[ii][1])
option[ii][2] = colorDisplayType
if option[ii][1] == 0:
if "Rare" in option[ii][0]:
option[ii][1] = RARECOLOR
option[ii][2] = colorDisplayType
elif "Epic" in option[ii][0]:
option[ii][1] = EPICCOLOR
option[ii][2] = colorDisplayType
elif "Legendary" in option[ii][0]:
option[ii][1] = LEGENDARYCOLOR
option[ii][2] = colorDisplayType
elif "Greed" in option[ii][0]:
option[ii][1] = GREEDCOLOR
option[ii][2] = colorDisplayType
xOff = 0
for textOb in option:
prefix = ""
debug1 = type(textOb), str(textOb)
debug2 = type(textOb[0]), str(textOb[0])
debug3 = type(textOb[1]), str(textOb[1])
debug4 = type(textOb[2]), str(textOb[2])
if i == selected_option:
sel = min(xOff, 1)
if xOff == 0:
prefix = " > "
if textOb[2] == 0:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff + sel,
prefix + textOb[0],
curses.A_BOLD,
)
elif textOb[2] == 1:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff + sel,
prefix + textOb[0],
curses.color_pair(textOb[1]),
)
elif textOb[2] == 2:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff + sel,
prefix + moreDeatils(textOb[0], details=True),
curses.A_BOLD,
)
elif textOb[2] == 3:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff + sel,
prefix + moreDeatils(textOb[0], details=True),
curses.color_pair(textOb[1]),
)
else:
if xOff == 0:
prefix = " "
if textOb[2] == 0:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff,
prefix + textOb[0],
curses.color_pair(textOb[1]),
)
elif textOb[2] == 1:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff,
prefix + textOb[0],
curses.color_pair(textOb[1]),
)
elif textOb[2] == 2:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff,
prefix + moreDeatils(textOb[0], details=False),
curses.color_pair(textOb[1]),
)
elif textOb[2] == 3:
screen.addstr(
(i + len(prompt) - scroll_window),
xOff,
prefix + moreDeatils(textOb[0], details=False),
curses.color_pair(textOb[1]),
)
if xOff == 0:
xOff += 2
xOff += len(textOb[0])
screen.addstr(
min(win_height, len(options)) + len(prompt),
0,
" ",
)
screen.addstr(
min(win_height, len(options)) + len(prompt) + 1,
0,
"Use arrow keys to navigate options. Press Enter to select.",
)
screen.refresh()
if firstPass:
key = screen.getch()
else:
key = -1
firstPass = True
if autoSize:
win_height = screen.getmaxyx()[0] - (3 + len(prompt))
buffer_size = oBufSize
buffer_size = min(buffer_size, win_height // 2 - 1 + win_height % 2)
buffer_size = max(buffer_size, 0)
if key == curses.KEY_UP and selected_option > 0:
selected_option -= 1
while options[selected_option] in skip:
if selected_option - 1 > 0:
selected_option -= 1
else:
selected_option += 1
elif key == curses.KEY_DOWN and selected_option < len(options) - 1: