-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
3696 lines (3462 loc) · 190 KB
/
main.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
# main.py
# Copyright (c) 2024 by @Cromha
#
# Bane Of Wargs is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later version.
#
# Bane Of Wargs is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <https://www.gnu.org/licenses/>.
# source imports
import battle
import check_yaml
import terminal_handling
import mission_handling
import event_handling
import dialog_handling
import enemy_handling
import data_handling
import npc_handling
import text_handling
import zone_handling
import weapon_upgrade_handling
import script_handling
import consumable_handling
import item_handling
import time_handling
import logger_sys
import yaml_handling
from colors import *
from time_handling import *
from consumable_handling import *
from zone_handling import *
from terminal_handling import cout, cinput
# external imports
import random
import os
import time
import subprocess
import tempfile
import appdirs
import io
import pydoc
from sys import exit
from rich.console import Console
from rich.markdown import Markdown
from rich.table import Table
text_handling.clear_prompt()
# defines console for the rich module
# to work properly
console = Console()
# says you are not playing.
global play, game_elapsed_time, menu
play = 0
menu = True
game_elapsed_time = 0
separator = COLOR_STYLE_BRIGHT + "###############################" + COLOR_RESET_ALL
COLUMNS, LINES = terminal_handling.get_size()
# Check if player has the config folder if
# not, create it with all its required content
program_dir = str(appdirs.user_config_dir(appname='Bane-Of-Wargs'))
first_start = False
if not os.path.exists(program_dir):
GAME_DATA_VERSION = 0.24
os.mkdir(program_dir)
# Open default config file and store the text into
# a variable to write it into the user config file
default_config_data = {
"latest preset": {
"save": " ",
"type": 'vanilla'
},
"speed up": False,
"theme": 'greenblue',
"title style": 1,
"auto update": False,
"logging level": 2,
"game data analyzing": True,
"game data download": {
"branch": "master",
"repository": "Bane-Of-Wargs",
"org": "Dungeons-Of-Kathallion"
}
}
default_config_data = yaml_handling.dump(default_config_data)
with open(program_dir + '/preferences.yaml', 'w') as f:
f.write(default_config_data)
logger_sys.log_message(f"INFO: PROGRAM RUN START")
logger_sys.log_message(f"INFO: Created player preferences at '{program_dir}/preferences.yaml'")
# Create the plugins, saves, game data folder in the config file
logger_sys.log_message(f"INFO: Creating directory '{program_dir}/plugins'")
os.mkdir(program_dir + "/plugins")
logger_sys.log_message(f"INFO: Creating directory '{program_dir}/saves'")
os.mkdir(program_dir + "/saves")
logger_sys.log_message(f"INFO: Creating directory '{program_dir}/game'")
os.mkdir(program_dir + "/game")
logger_sys.log_message(f"INFO: Creating directory '{program_dir}/logs'")
os.mkdir(program_dir + "/logs")
logger_sys.log_message(f"INFO: Creating directory '{program_dir}/docs'")
os.mkdir(program_dir + "/docs")
logger_sys.log_message(f"INFO: Writing game data version to '{program_dir}/game/VERSION.bow'")
with open(f"{program_dir}/game/VERSION.bow", 'w') as f:
f.write(str(GAME_DATA_VERSION))
first_start = True
# Download game data from github master branch
# and install them (auto-update)
logger_sys.log_message("INFO: Loading user preferences")
with open(program_dir + '/preferences.yaml', 'r') as f:
preferences = yaml_handling.safe_load(f)
# Compare the latest source code version with
# the current code version
logger_sys.log_message("INFO: Checking if game source code is up to date")
global latest_version
latest_version = None # placeholder
SOURCE_CODE_VERSION = 0.24
latest_main_class = io.StringIO(data_handling.temporary_git_file_download(
'source/main.py', 'https://github.com/Dungeons-of-Kathallion/Bane-Of-Wargs.git'
)).readlines()
count = 0
continuing = True
while count < len(latest_main_class) and continuing:
if latest_main_class[count].startswith('SOURCE_CODE_VERSION = '):
latest_version = latest_main_class[count].split("= ", 1)[1]
continuing = False
count += 1
if latest_main_class == [] or latest_version is None: # if the file didn't download
cout("Skipping game updating process...")
time.sleep(1)
else:
continuing = True
if float(latest_version) > float(SOURCE_CODE_VERSION):
latest_version = float(str(latest_version).replace('\n', ''))
logger_sys.log_message("WARNING: The game source code is outdated")
logger_sys.log_message(
f"DEBUG: You're using version {SOURCE_CODE_VERSION} while the latest version is {latest_version}"
)
cout(
COLOR_YELLOW + "WARNING: The game source code is outdated:\nYou're using " +
f"version {SOURCE_CODE_VERSION} while the latest version is {latest_version}" +
COLOR_RESET_ALL
)
time.sleep(3)
text_handling.clear_prompt()
# Get latest game data version
logger_sys.log_message(f"INFO: Checking if game data at '{program_dir}/game/' is up to date")
global latest_game_data_version
latest_game_data_version = None
try:
with open(f'{program_dir}/game/VERSION.bow') as f:
GAME_DATA_VERSION = f.read().replace('\n', '')
except Exception as error:
cout(f"ERROR: Couldn't find required file '{program_dir}/game/VERSION.bow'")
cout(f"DEBUG: Please try to restart the game with the preferences option 'auto update' turned on")
logger_sys.log_message(f"ERROR: Couldn't find required file '{program_dir}/game/VERSION.bow'")
logger_sys.log_message(f"DEBUG: Please try to restart the game with the preferences option 'auto update' turned on")
time.sleep(3)
text_handling.exit_game()
continuing = True
count = 0
while count < len(latest_main_class) and continuing:
if latest_main_class[count].startswith(' GAME_DATA_VERSION = '):
latest_game_data_version = latest_main_class[count].split("= ", 1)[1]
continuing = False
count += 1
if preferences["auto update"] or first_start:
data_handling.update_game_data(preferences, latest_game_data_version)
# we exmine it after the update, or errors happen because of required files to there yet
check_yaml.examine(program_dir + '/preferences.yaml')
# Compare the latest game data version with
# the current game data version
if float(GAME_DATA_VERSION) < float(latest_game_data_version):
latest_game_data_version = float(str(latest_game_data_version).replace('\n', ''))
logger_sys.log_message(f"WARNING: The game data at '{program_dir}' is outdated")
logger_sys.log_message(
f"DEBUG: You're using version {GAME_DATA_VERSION} while the latest version is {latest_game_data_version}"
)
cout(
COLOR_YELLOW + f"WARNING: The game data at '{program_dir}' is outdated:\nYou're using " +
f"version {GAME_DATA_VERSION} while the latest version is {latest_game_data_version}" +
COLOR_RESET_ALL
)
time.sleep(3)
cout("\nDo you want to update your game data right now?")
cout("Note that you may want to update the game source code version for compatibility reasons")
want_to_update = terminal_handling.show_menu(["Yes", "No"])
if want_to_update == "Yes":
text_handling.clear_prompt()
data_handling.update_game_data(preferences, latest_game_data_version)
text_handling.clear_prompt()
# main menu start
while menu:
global player, previous_player
# Get player preferences
logger_sys.log_message(f"INFO: Opening player '{program_dir}/preferences.yaml'")
with open(program_dir + '/preferences.yaml', 'r') as f:
preferences = yaml_handling.safe_load(f)
check_yaml.examine(program_dir + '/preferences.yaml')
text_handling.clear_prompt()
text_handling.print_title(preferences)
options = ['Play Game', 'Manage Saves', 'Preferences', 'Gameplay Guide', 'Check Logs', 'Credits', 'Quit']
choice = terminal_handling.show_menu(options)
text_handling.clear_prompt()
text_handling.print_title(preferences)
if choice == 'Play Game':
options = ['Use Latest Preset', 'Play Vanilla', 'Play Plugin']
choice = terminal_handling.show_menu(options)
using_latest_preset = False
latest_preset = preferences["latest preset"]
# Make these variables global
global map, item, drinks, enemy, npcs, start_player
global lists, zone, dialog, mission, mounts
# load data files
if choice == 'Use Latest Preset':
logger_sys.log_message(f"INFO: Starting game with latest preset: {latest_preset}")
using_latest_preset = True
if preferences["latest preset"]["type"] == 'vanilla':
(
map, item, drinks, enemy, npcs, start_player,
lists, zone, dialog, mission, mounts, event
) = data_handling.load_game_data('vanilla', preferences)
else:
(
map, item, drinks, enemy, npcs, start_player,
lists, zone, dialog, mission, mounts, event
) = data_handling.load_game_data('plugin', preferences)
open_save = preferences["latest preset"]["save"]
save_file = program_dir + "/saves/save_" + open_save + ".yaml"
check_file = os.path.isfile(save_file)
if not check_file:
cout(COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: Couldn't find save file '" + save_file + "'" + COLOR_RESET_ALL)
logger_sys.log_message(f"ERROR: Couldn't find save file '{save_file}'")
play = 0
text_handling.exit_game()
logger_sys.log_message("INFO: Opening Save File")
with open(save_file) as f:
error_loading = False
try:
player = yaml_handling.safe_load(f)
except Exception as error:
error_loading = True
previous_player = player
check_yaml.examine(save_file)
if type(player) is not type({}) and not error_loading:
error_loading = True
error = 'not a yaml file'
if error_loading:
cout(
COLOR_RED + "FATAL ERROR: " + COLOR_STYLE_BRIGHT +
"Save corrupted! Check logs files for further information" + COLOR_RESET_ALL
)
logger_sys.log_message(f"FATAL ERROR: Save '{save_file}' corrupted!")
logger_sys.log_message(
f"DEBUG: This could have been the result of closing the game at bad moments or " +
"a game bug. Please report the bug on the github repo: " +
"https://github.com/Dungeons-of-Kathallion/Bane-Of-Wargs/issues/new/choose"
)
logger_sys.log_message(f"DEBUG: error '{error}'")
time.sleep(5)
text_handling.exit_game()
play = 1
menu = False
logger_sys.log_message("INFO: Starting game and exiting menu")
elif choice == 'Play Plugin':
logger_sys.log_message("INFO: Updating latest preset")
preferences["latest preset"]["type"] = "plugin"
(
map, item, drinks, enemy, npcs, start_player,
lists, zone, dialog, mission, mounts, event
) = data_handling.load_game_data('plugin', preferences)
else:
logger_sys.log_message("INFO: Updating latest preset")
preferences["latest preset"]["type"] = "vanilla"
(
map, item, drinks, enemy, npcs, start_player,
lists, zone, dialog, mission, mounts, event
) = data_handling.load_game_data('vanilla', preferences)
if not using_latest_preset:
text = "\nPlease select an action:"
text_handling.print_speech_text_effect(text, preferences)
options = ['Open Save', 'New Save']
choice = terminal_handling.show_menu(options)
if choice == 'Open Save':
res = []
logger_sys.log_message(f"INFO: Searching for saves in the '{program_dir}/saves/' directory")
for search_for_saves in os.listdir(program_dir + '/saves/'):
if search_for_saves.startswith("save_"):
res.append(search_for_saves.replace("save_", "").replace(".yaml", ""))
text = "Please select a save to open."
text_handling.print_speech_text_effect(text, preferences)
open_save = text_handling.select_save(res)
logger_sys.log_message("INFO: Updating latest preset")
preferences["latest preset"]["save"] = open_save
save_file = program_dir + "/saves/save_" + open_save + ".yaml"
check_file = os.path.isfile(save_file)
if not check_file:
cout(COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: Couldn't find save file '" + save_file + "'" + COLOR_RESET_ALL)
logger_sys.log_message(f"ERROR: Couldn't find save file '{save_file}'")
play = 0
text_handling.exit_game()
logger_sys.log_message("INFO: Opening save file")
with open(save_file) as f:
error_loading = False
try:
player = yaml_handling.safe_load(f)
except Exception as error:
error_loading = True
previous_player = player
check_yaml.examine(save_file)
if type(player) is not type({}) and not error_loading:
error_loading = True
error = 'not a yaml file'
if error_loading:
cout(
COLOR_RED + "FATAL ERROR: " + COLOR_STYLE_BRIGHT +
"Save corrupted! Check logs files for further information" + COLOR_RESET_ALL
)
logger_sys.log_message(f"FATAL ERROR: Save '{save_file}' corrupted!")
logger_sys.log_message(
f"DEBUG: This could have been the result of closing the game at bad moments or " +
"a game bug. Please report the bug on the github repo: " +
"https://github.com/Dungeons-of-Kathallion/Bane-Of-Wargs/issues/new/choose"
)
logger_sys.log_message(f"DEBUG: error '{error}'")
time.sleep(5)
text_handling.exit_game()
play = 1
menu = False
else:
text = "Please name your adventurer: "
text_handling.print_speech_text_effect(text, preferences)
enter_save_name = cinput('> ')
player = start_player
save_name = program_dir + "/saves/save_" + enter_save_name + ".yaml"
save_name_backup = program_dir + "/saves/~0 save_" + enter_save_name + ".yaml"
check_file = os.path.isfile(save_name)
logger_sys.log_message("INFO: Updating latest preset")
preferences["latest preset"]["save"] = enter_save_name
if check_file:
cout(
COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: Save file '" +
save_name + "'" + " already exists" + COLOR_RESET_ALL
)
logger_sys.log_message(f"ERROR: Save file '{save_name}' already exists")
play = 0
text_handling.exit_game()
difficulty_modes = ['Easy', 'Normal', 'Hard']
cout("\nPlease select a difficulty:")
difficulty = difficulty_modes.index(terminal_handling.show_menu(difficulty_modes))
player["difficulty mode"] = difficulty
logger_sys.log_message(
"INFO: Player has chosen difficulty " +
f"'{difficulty_modes[difficulty]}'-->'{difficulty}'"
)
logger_sys.log_message("INFO: Dumping new save data")
dumped = yaml_handling.dump(player)
logger_sys.log_message("INFO: Creating new save")
with open(save_name, "w") as f:
f.write(dumped)
with open(save_name_backup, "w") as f:
f.write(dumped)
save_file = save_name
logger_sys.log_message("INFO: Opening save")
with open(save_file) as f:
error_loading = False
try:
player = yaml_handling.safe_load(f)
except Exception as error:
error_loading = True
previous_player = player
if type(player) is not type({}) and not error_loading:
error_loading = True
error = 'not a yaml file'
if error_loading:
cout(
COLOR_RED + "FATAL ERROR: " + COLOR_STYLE_BRIGHT +
"Save corrupted! Check logs files for further information" + COLOR_RESET_ALL
)
logger_sys.log_message(f"FATAL ERROR: Save '{save_file}' corrupted!")
logger_sys.log_message(
f"DEBUG: This could have been the result of closing the game at bad moments or " +
"a game bug. Please report the bug on the github repo: " +
"https://github.com/Dungeons-of-Kathallion/Bane-Of-Wargs/issues/new/choose"
)
logger_sys.log_message(f"DEBUG: error '{error}'")
time.sleep(5)
text_handling.exit_game()
play = 1
menu = False
logger_sys.log_message("INFO: Starting game and exiting menu")
elif choice == 'Manage Saves':
res = []
logger_sys.log_message(f"INFO: Searching for saves in the '{program_dir}/saves/' directory")
for search_for_saves in os.listdir(program_dir + '/saves/'):
if search_for_saves.startswith("save_"):
res.append(search_for_saves.replace("save_", "").replace(".yaml", ""))
text = "Please choose an action."
text_handling.print_speech_text_effect(text, preferences)
options = ['Edit Save', 'Manage Save Backups', 'Delete Save']
choice = terminal_handling.show_menu(options)
if choice == 'Edit Save':
text = "Please select a save to edit."
text_handling.print_speech_text_effect(text, preferences)
open_save = text_handling.select_save(res)
check_file = os.path.isfile(program_dir + "/saves/save_" + open_save + ".yaml")
if not check_file:
cout(
COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: Save file '" +
program_dir + "/saves/save_" + open_save + ".yaml" +
"'" + " does not exists" + COLOR_RESET_ALL
)
logger_sys.log_message(f"ERROR: Save file '{program_dir}/saves/save_{open_save}.yaml' does not exists")
play = 0
text = "Select an action for the selected save."
text_handling.print_speech_text_effect(text, preferences)
options = ['Rename Save', 'Manually Edit Save']
choice = terminal_handling.show_menu(options)
if choice == 'Rename Save':
rename_name = cinput("Select a new name for the save: ")
os.rename(
program_dir + "/saves/save_" + open_save + ".yaml",
program_dir + "/saves/save_" + rename_name + ".yaml"
)
logger_sys.log_message(
f"INFO: Renaming save file '{program_dir}/saves/save_{open_save}.yaml'" +
f" to '{program_dir}/saves/save_{rename_name}.yaml'"
)
else:
save_to_open = program_dir + "/saves/save_" + open_save + ".yaml"
try:
editor = os.environ['EDITOR']
except KeyError:
editor = 'nano'
logger_sys.log_message(f"INFO: Manually editing save file '{save_to_open}' with editor '{editor}'")
subprocess.call([editor, save_to_open])
elif choice == "Manage Save Backups":
text = "Please select a save to manage its backups."
text_handling.print_speech_text_effect(text, preferences)
open_save = text_handling.select_save(res)
check_file = os.path.isfile(program_dir + "/saves/save_" + open_save + ".yaml")
if not check_file:
cout(
COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: Save file '" +
program_dir + "/saves/save_" + open_save + ".yaml" +
"'" + " does not exists" + COLOR_RESET_ALL
)
logger_sys.log_message(f"ERROR: Save file '{program_dir}/saves/save_{open_save}.yaml' does not exists")
play = 0
text = "Select an action for the selected save."
text_handling.print_speech_text_effect(text, preferences)
options = ['Create Backup', 'Load Backup']
choice = terminal_handling.show_menu(options)
if choice == "Create Backup":
count = 0
finished = False
while count < 120 and not finished:
backup_name = program_dir + f"/saves/~{count} save_" + open_save + ".yaml"
if not os.path.isfile(backup_name):
with open(program_dir + "/saves/save_" + open_save + ".yaml", "r") as f:
data = yaml_handling.safe_load(f)
with open(backup_name, "w") as f:
f.write(yaml_handling.dump(data))
cout(f"Created backup of save at '{backup_name}'")
logger_sys.log_message(
f"INFO: Created backup of save at '{backup_name}'"
)
time.sleep(1.5)
finished = True
count += 1
if not finished:
cout(COLOR_YELLOW + "Could not create backup!" + COLOR_RESET_ALL)
logger_sys.log_message(
"WARNING: Could not create a backup of save " +
program_dir + "/saves/save_" + open_save + ".yaml"
)
logger_sys.log_message(
"DEBUG: This could happen because there're more than 120 backups " +
"of this save file, which is the maximum amount that can be handled by the game engine."
)
time.sleep(1.5)
else:
logger_sys.log_message(
f"INFO: Searching for backups of save '{program_dir}/saves/save_{open_save}.yaml'"
)
finished = False
backups = []
for i in range(120):
current_backup = program_dir + f"/saves/~{i} save_" + open_save + ".yaml"
if os.path.isfile(current_backup):
backups += [current_backup]
if backups == []:
logger_sys.log_message(
f"INFO: Found no backups of save '{program_dir}/saves/save_{open_save}.yaml'"
)
cout(COLOR_YELLOW + "Could not find any backup of this save file" + COLOR_RESET_ALL)
time.sleep(1.5)
finished = True
else:
logger_sys.log_message(
f"INFO: Found backups of save '{program_dir}/saves/save_{open_save}.yaml'" +
f": {backups}"
)
if not finished:
cout("Select a backup to load:")
backups_str = backups
count = 0
for i in backups_str:
backups_str[count] = i.split('saves/', 1)[1]
count += 1
selected_backup = terminal_handling.show_menu(backups)
with open(selected_backup, "r") as f:
data = yaml_handling.safe_load(f)
with open(program_dir + "/saves/save_" + open_save + ".yaml", "w") as f:
f.write(yaml_handling.dump(data))
logger_sys.log_message(
f"INFO: Loaded backup '{selected_backup}' data to save file '" +
f"{program_dir}/saves/save_{open_save}.yaml'"
)
else:
text = "Please select a save to delete."
text_handling.print_speech_text_effect(text, preferences)
open_save = text_handling.select_save(res)
check_file = os.path.isfile(program_dir + "/saves/save_" + open_save + ".yaml")
if not check_file:
cout(
COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: Save file '" +
program_dir + "/saves/save_" + open_save + ".yaml" +
"'" + " does not exists" + COLOR_RESET_ALL
)
logger_sys.log_message(f"ERROR: Save file '{program_dir}/saves/save_{open_save}.yaml' does not exists")
play = 0
check = cinput("Are you sure you want to delete the following save (y/n)")
if check.lower().startswith('y'):
logger_sys.log_message(
f"WARNING: Deleting save file '{program_dir}/saves/save_{open_save}.yaml'" +
f" and save file backup '{program_dir}/saves/~0 save_{open_save}.yaml'"
)
os.remove(program_dir + "/saves/save_" + open_save + ".yaml")
os.remove(program_dir + "/saves/~0 save_" + open_save + ".yaml")
elif choice == 'Preferences':
cout("Which type of editing do you want to use to update your preferences?")
which_type = terminal_handling.show_menu(['GUI Editing', 'Manual Editing'])
if which_type == 'GUI Editing':
preferences_menu = True
while preferences_menu:
text_handling.clear_prompt()
text_handling.print_title(preferences)
options = [
'Title Theme', 'Title Style', 'Game Speed', 'Game Updating',
'Game Data Analyzing', 'Logging Level', 'Enabled Plugins', 'Exit'
]
choice = terminal_handling.show_menu(options)
cout()
if choice == 'Title Theme':
choices = [
'blackwhite', 'purplepink', 'greenblue', 'darkblueblue',
'yellowred', 'pinkred', 'purpleblue', 'greenyellow',
'random', 'OFF'
]
preferences["theme"] = terminal_handling.show_menu(choices)
elif choice == 'Title Style':
choices = ['Vanilla Style', 'Alternative Style']
style = terminal_handling.show_menu(choices)
if style == choices[0]:
preferences["title style"] = 1
else:
preferences["title style"] = 2
elif choice == 'Game Speed':
choices = ['Normal Speed', 'Faster Speed']
speed = terminal_handling.show_menu(choices)
if speed == choices[0]:
preferences["speed up"] = False
else:
preferences["speed up"] = True
elif choice == 'Game Data Analyzing':
choices = ['Enabled', 'Disabled']
speed = terminal_handling.show_menu(choices)
if speed == choices[0]:
preferences["game data analyzing"] = True
else:
preferences["game data analyzing"] = False
elif choice == 'Game Updating':
cout("Which parameter you wish to change?")
parameter = terminal_handling.show_menu([
'Auto Updating', 'Download Branch', 'Download Organization/User',
'Download Repository', 'Test Settings'
])
if parameter == 'Auto Updating':
choices = ['Enable', 'Disable']
speed = terminal_handling.show_menu(choices)
if speed == choices[0]:
preferences["auto update"] = True
else:
preferences["auto update"] = False
elif parameter == 'Download Branch':
preferences["game data download"]["branch"] = cinput(
"Which github branch or tag you want the data to be downloaded from?\n"
)
elif parameter == 'Download Organization/User':
preferences["game data download"]["org"] = cinput(
"Which github organization or user you want the data to be downloaded from?\n"
)
elif parameter == 'Download Repository':
preferences["game data download"]["repository"] = cinput(
"Which github repository you want the data to be downloaded from?\n"
)
else:
temp_file = tempfile.mkdtemp() + '/.gitignore'
download = preferences["game data download"]
test = data_handling.fsspec_download(
'.gitignore', temp_file, download["branch"], download["repository"], download["org"]
)
if test:
cout("\nTest passed successfully!")
time.sleep(2)
else:
time.sleep(4)
elif choice == 'Logging Level':
choices = ['Full Logging', 'No Info', 'Only Errors']
logging = terminal_handling.show_menu(choices)
if logging == choices[0]:
preferences["logging level"] = 1
elif logging == choices[1]:
preferences["logging level"] = 2
else:
preferences["logging level"] = 3
elif choice == 'Enabled Plugins':
plugins = os.listdir(program_dir + "/plugins/")
plugins_data = {}
# Run checks so that we're sure that
# every plugin has his own `.game.BOW` file
for plugin in plugins:
file = f"{program_dir}/plugins/{plugin}/.game.BOW"
if not os.path.isfile(file):
with open(file, "w") as f:
f.write("True")
# Generate the data about the plugins
# (if each plugin is enabled or not)
for plugin in plugins:
file = f"{program_dir}/plugins/{plugin}/.game.BOW"
with open(file, "r") as f:
plugins_data[plugin] = f.readlines()[0]
# Plugin enabling loop starts here
plugin_changes = True
while plugin_changes:
# Generate the menu entries
options = []
for plugin in list(plugins_data):
status = plugins_data[plugin]
if status == "True":
status = "ON"
else:
status = "OFF"
options += [f"{plugin}; {status}"]
options += ['EXIT']
# Ask for the user which plugin
# should be enabled or not
text_handling.clear_prompt()
text_handling.print_title(preferences)
action_chosen = terminal_handling.show_menu(options)
if action_chosen == 'EXIT':
plugin_changes = False
else:
chosen_plugin = plugins[options.index(action_chosen)]
file = f"{program_dir}/plugins/{chosen_plugin}/.game.BOW"
if plugins_data[chosen_plugin] == "True":
plugins_data[chosen_plugin] = "False"
with open(file, "w") as f:
f.write("False")
else:
plugins_data[chosen_plugin] = "True"
with open(file, "w") as f:
f.write("True")
else:
preferences_menu = False
with open(program_dir + '/preferences.yaml', 'w') as f:
f.write(yaml_handling.dump(preferences))
elif which_type == 'Manual Editing':
logger_sys.log_message(f"INFO: Manually editing preferences '{program_dir}/preferences.yaml'")
logger_sys.log_message(f"DEBUG: Before editing preferences: {preferences}")
data_handling.open_file(program_dir + "/preferences.yaml")
with open(program_dir + '/preferences.yaml') as f:
new_preferences = yaml_handling.safe_load(f)
logger_sys.log_message(f"DEBUG: After editing preferences: {new_preferences}")
elif choice == 'Gameplay Guide':
first_timer = time.time()
logger_sys.log_message("INFO: Downloading game documentation")
text = "Downloading game documentation..."
text_handling.print_speech_text_effect(text, preferences)
# Download documentation files
file = 'Gameplay-Guide.md'
md_file = data_handling.wget_download(
'https://raw.githubusercontent.com/wiki/Dungeons-of-Kathallion/Bane-Of-Wargs/Gameplay-Guide.md'
)
last_timer = time.time()
time_for_process = round(last_timer - first_timer, 4)
logger_sys.log_message(f"INFO: Finished game documentation downloading process in {time_for_process} seconds")
text = "Finished downloading process..."
text_handling.print_speech_text_effect(text, preferences)
# Actually display the markdown file
# to the terminal with 'rich' module
error_occurred = False
text_handling.clear_prompt()
try:
md_text = Markdown(md_file)
console.print(md_text)
cinput()
except Exception as error:
error_occurred = True
cout(
COLOR_RED + COLOR_STYLE_BRIGHT + "ERROR: " + COLOR_RESET_ALL +
COLOR_RED + f"file '{file}' does not exists" + COLOR_RESET_ALL
)
logger_sys.log_message(f"ERROR: file '{file}' does not exists --> canceling gameplay guide markdown printing")
text_handling.clear_prompt()
elif choice == 'Check Logs':
# Get the logs directory content
# and save the names in a list
directory = f'{program_dir}/logs/'
directory_content = os.listdir(directory)
# Create the rich table
table = Table(title=f"LOGS FILES: ({directory})")
table.add_column("Input Number", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
# Add one by one every files in
# the logs directory
count = 0
for i in directory_content:
table.add_row(str(count), str(i))
count += 1
console.print(table)
# Get which log the player wants
# to open and display it in the UI
loop = True
while loop:
error_happened = False
which_log_file = cinput(f"{COLOR_GREEN}{COLOR_STYLE_BRIGHT}>{COLOR_RESET_ALL} ")
try:
which_log_file = directory_content[int(which_log_file)]
except Exception as error:
error_happened = True
cout(COLOR_YELLOW + "incorrect input" + COLOR_RESET_ALL)
if not error_happened:
loop = False
text_handling.clear_prompt()
with open(directory + which_log_file, 'r') as f:
content = f.read()
pydoc.pager(content)
elif choice == 'Credits':
# Get the credits file and
# display it in a pager style
with open(f"{program_dir}/game/docs/credits.txt") as f:
credits = f.read()
text_handling.print_moving_text(credits)
else:
text_handling.clear_prompt()
logger_sys.log_message(f"INFO: PROGRAM RUN END")
exit(0)
# function to search through the map file
def search(x, y):
logger_sys.log_message(f"INFO: Searching for map point corresponding to coordinates x:{x}, y:{y}")
global map_location
map_point_count = int(len(list(map)))
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"], point_i["y"]
if point_x == x and point_y == y:
map_location = i
return map_location
def add_gold(amount):
logger_sys.log_message(f"INFO: Adding to player {amount} gold")
player_gold = player["gold"]
player_gold += float(amount)
player["gold"] = round(player_gold, 2)
def remove_gold(amount):
logger_sys.log_message(f"INFO: Removing to player {amount} gold")
player_gold = player["gold"]
player_gold -= float(amount)
player["gold"] = round(player_gold, 2)
def check_for_key(direction):
logger_sys.log_message("INFO: Checking for key at every next locations possible")
map_point_count = len(list(map))
if direction == "north":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"], point_i["y"] - 1
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "south":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"], point_i["y"] + 1
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "east":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"] - 1, point_i["y"]
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "west":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"] + 1, point_i["y"]
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "north-east":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"] + 1, point_i["y"] + 1
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "north-west":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"] - 1, point_i["y"] + 1
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "south-east":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"] + 1, point_i["y"] - 1
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
elif direction == "south-west":
for i in range(0, map_point_count):
point_i = map["point" + str(i)]
point_x, point_y = point_i["x"] - 1, point_i["y"] - 1
if point_x == player["x"] and point_y == player["y"]:
future_map_location = i
if "key" in map["point" + str(future_map_location)]:
text = '='
text_handling.print_separator(text)
text = "You need the following key(s) to enter this location, if you decide to use them, you may loose them:"
text_handling.print_long_string(text)
keys_list = str(map["point" + str(future_map_location)]["key"]["required keys"])
logger_sys.log_message(f"INFO: Entering map point 'point{future_map_location}' requires keys: {keys_list}")
keys_list = keys_list.replace("'", '')
keys_list = keys_list.replace("[", ' -')
keys_list = keys_list.replace("]", '')
keys_list = keys_list.replace(", ", '\n -')
cout(keys_list)
keys_len = len(map["point" + str(future_map_location)]["key"]["required keys"])
text = '='
text_handling.print_separator(text)
options = ['Continue', 'Leave']
choice = terminal_handling.show_menu(options)
count = 0
have_necessary_keys = True
if choice == 'Continue':
while count < keys_len and have_necessary_keys:
chosen_key = map["point" + str(future_map_location)]["key"]["required keys"][int(count)]
if chosen_key not in player["inventory"]:
have_necessary_keys = False
else:
if map["point" + str(future_map_location)]["key"]["remove key"]:
player["inventory"].remove(chosen_key)
logger_sys.log_message(f"INFO: Removing from player inventory key '{chosen_key}'")
count += 1
if not have_necessary_keys:
logger_sys.log_message("INFO: Player don't have necessary keys: passing")
cout(" ")
text = COLOR_YELLOW + "You don't have the necessary key(s) to enter this locations"
text_handling.print_long_string(text)
time.sleep(1.5)
if have_necessary_keys:
logger_sys.log_message("INFO: Player has necessary keys: letting him pass")
if direction == "north":
player["y"] += 1
elif direction == "south":
player["y"] -= 1
elif direction == "east":
player["x"] += 1
elif direction == "west":
player["x"] -= 1
# Loading text replacements
logger_sys.log_message("INFO: Loading generic texts replacements")
save_file_name_text_replacements = save_file.replace(program_dir + '/saves/save_', '')
save_file_name_text_replacements = save_file_name_text_replacements.replace('.yaml', '')
if str(player["current mount"]) == ' ':
player_mount = None
player_mount_nick = None
else:
player_mount = player["mounts"][str(player["current mount"])]["mount"]
player_mount_nick = player["mounts"][str(player["current mount"])]["name"]
text_replacements_generic = {
"$name": save_file_name_text_replacements,
"$currency": player["gold"],
"$date": player["elapsed time game days"],
"$location": f'{player["x"]}, {player["y"]}',
"$coord_x": player["x"],
"$coord_y": player["y"],
"$location_zone": player["map zone"],
"$mount": player_mount,
"$mount_nick": player_mount_nick,
"$weapon": player["held item"],
"$chestplate": player["held chestplate"],
"$leggins": player["held leggings"],
"$boots": player["held boots"],
"$shield": player["held shield"],
"$health": player["health"],
"$max_health": player["max health"],
"$exp": player["xp"]
}
logger_sys.log_message(f"INFO: Loaded generic texts replacements: '{text_replacements_generic}'")
def check_for_item(item_name):
logger_sys.log_message(f"INFO: Checking if item '{item_name}' actually exists")
item_exist = False
if str(item_name) in list(item):
item_exist = True
return item_exist
# gameplay here:
def run(play):
if not preferences["speed up"]:
# clear text
text_handling.clear_prompt()