-
Notifications
You must be signed in to change notification settings - Fork 0
/
menus.py
894 lines (768 loc) · 41.7 KB
/
menus.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
from utils import clear_screen
from rich.table import Table
from vars import console
import random
import json
import time
import vars
import sys
import os
# Show menu with Save and Load options
def show_menu():
from player import check_level_up
from game import stop_music
while True:
clear_screen()
console.print(vars.message["ui"]["top_lines"]["game_menu"])
console.print()
console.print(vars.message["ui"]['stats']['player']["title"])
console.print()
weapon = vars.player['equipped']['weapon']
armor = vars.player['equipped']['armor']
accessory = vars.player['equipped']['accessory']
weapon_attack = weapon['attack'] if weapon and 'attack' in weapon else 0
armor_defense = armor['defense'] if armor and 'defense' in armor else 0
level = vars.message['ui']['stats']['player']['level'].format(level=vars.player['level'], remaining_exp=check_level_up())
if (vars.player['health'] > vars.player['max_health'] * (4/5)):
health = vars.message['ui']['stats']['player']["health1"].format(health=vars.player['health'], max_health=vars.player['max_health'])
elif (vars.player['health'] < vars.player['max_health'] * (4/5) and vars.player['health'] > vars.player['max_health'] * (3/5)):
health = vars.message['ui']['stats']['player']["health2"].format(health=vars.player['health'], max_health=vars.player['max_health'])
elif (vars.player['health'] < vars.player['max_health'] * (3/5) and vars.player['health'] > vars.player['max_health'] * (2/5)):
health = vars.message['ui']['stats']['player']["health3"].format(health=vars.player['health'], max_health=vars.player['max_health'])
elif (vars.player['health'] < vars.player['max_health'] * (2/5) and vars.player['health'] > vars.player['max_health'] * (1/5)):
health = vars.message['ui']['stats']['player']["health4"].format(health=vars.player['health'], max_health=vars.player['max_health'])
else:
health = vars.message['ui']['stats']['player']["health5"].format(health=vars.player['health'], max_health=vars.player['max_health'])
if (vars.player['mana'] > vars.player['max_mana'] * (4/5)):
mana = vars.message['ui']['stats']['player']["mana1"].format(mana=vars.player['mana'], max_mana=vars.player['max_mana'])
elif (vars.player['mana'] < vars.player['max_mana'] * (4/5) and vars.player['mana'] > vars.player['max_mana'] * (3/5)):
mana = vars.message['ui']['stats']['player']["mana2"].format(mana=vars.player['mana'], max_mana=vars.player['max_mana'])
elif (vars.player['mana'] < vars.player['max_mana'] * (3/5) and vars.player['mana'] > vars.player['max_mana'] * (2/5)):
mana = vars.message['ui']['stats']['player']["mana3"].format(mana=vars.player['mana'], max_mana=vars.player['max_mana'])
elif (vars.player['mana'] < vars.player['max_mana'] * (2/5) and vars.player['mana'] > vars.player['max_mana'] * (1/5)):
mana = vars.message['ui']['stats']['player']["mana4"].format(mana=vars.player['mana'], max_mana=vars.player['max_mana'])
else:
mana = vars.message['ui']['stats']['player']["mana5"].format(mana=vars.player['mana'], max_mana=vars.player['max_mana'])
if vars.player['attack'] == vars.player['base_attack']:
attack = vars.message['ui']['stats']['player']["attack1"].format(attack=vars.player['attack'], weapon_attack=weapon_attack)
elif vars.player['attack'] > vars.player['base_attack']:
attack = vars.message['ui']['stats']['player']["attack2"].format(attack=vars.player['attack'], weapon_attack=weapon_attack)
else:
attack = vars.message['ui']['stats']['player']["attack3"].format(attack=vars.player['attack'], weapon_attack=weapon_attack)
if vars.player['defense'] == vars.player['base_defense']:
defense = vars.message['ui']['stats']['player']["defense1"].format(defense=vars.player['defense'], armor_defense=armor_defense)
elif vars.player['defense'] > vars.player['base_defense']:
defense = vars.message['ui']['stats']['player']["defense2"].format(defense=vars.player['defense'], armor_defense=armor_defense)
else:
defense = vars.message['ui']['stats']['player']["defense3"].format(defense=vars.player['defense'], armor_defense=armor_defense)
if vars.player['agility'] == vars.player['base_agility']:
agility = vars.message['ui']['stats']['player']["agility1"].format(agility=vars.player['agility'])
elif vars.player['agility'] > vars.player['base_agility']:
agility = vars.message['ui']['stats']['player']["agility2"].format(agility=vars.player['agility'])
else:
agility = vars.message['ui']['stats']['player']["agility3"].format(agility=vars.player['agility'])
if vars.player['wisdom'] == vars.player['base_wisdom']:
wisdom = vars.message['ui']['stats']['player']["wisdom1"].format(wisdom=vars.player['wisdom'])
elif vars.player['wisdom'] > vars.player['base_wisdom']:
wisdom = vars.message['ui']['stats']['player']["wisdom2"].format(wisdom=vars.player['wisdom'])
else:
wisdom = vars.message['ui']['stats']['player']["wisdom3"].format(wisdom=vars.player['wisdom'])
if vars.player['awareness'] == vars.player['base_awareness']:
awareness = vars.message['ui']['stats']['player']["awareness1"].format(awareness=vars.player['awareness'])
elif vars.player['awareness'] > vars.player['base_awareness']:
awareness = vars.message['ui']['stats']['player']["awareness2"].format(awareness=vars.player['awareness'])
else:
awareness = vars.message['ui']['stats']['player']["awareness3"].format(awareness=vars.player['awareness'])
gold = vars.message['ui']['stats']['player']["gold"].format(gold=vars.player['gold'])
exp = vars.message['ui']['stats']['player']["exp"].format(exp=vars.player['exp'])
equipped_weapon = vars.message['ui']['stats']['player']["equipped_weapon"].format(weapon=weapon["name"] if weapon else "")
equipped_armor = vars.message['ui']['stats']['player']["equipped_armor"].format(armor=armor["name"] if armor else "")
equipped_accessory = vars.message['ui']['stats']['player']["equipped_accessory"].format(accessory=accessory["name"] if accessory else "")
status_title = vars.message["ui"]["stats"]["player"]["status_effects"].format(
status=", ".join(
f" "+f"{effect['effect']} (Duration: {effect['duration']})"
for effect in vars.player['status_effects']
) if vars.player['status_effects'] else " No status effects"
)
# Limit to the first 5 effects and pad with empty strings
status_fields = [
f"{effect['effect']} (Duration: {effect['duration']})"
for effect in vars.player['status_effects'][:5]
]
status_fields += [""] * (5 - len(status_fields))
enemies_killed = vars.message['ui']['stats']['game']["enemies_killed"].format(count=vars.player['enemies_killed'])
items_collected = vars.message['ui']['stats']['game']["items_collected"].format(count=vars.player['items_collected'])
shops_visited = vars.message['ui']['stats']['game']["shops_visited"].format(count=len(vars.player['shops_visited']))
gold_collected = vars.message['ui']['stats']['game']["gold_collected"].format(count=vars.player['gold_collected'])
items_purchased = vars.message['ui']['stats']['game']["items_purchased"].format(count=vars.player['items_purchased'])
element_array = [
level,
health,
mana,
"",
attack,
defense,
agility,
wisdom,
awareness,
gold,
exp,
"",
status_title,
*status_fields,
enemies_killed,
items_collected,
shops_visited,
gold_collected,
items_purchased
]
first_column = element_array[:12]
second_column = element_array[12:]
# Create a table with two columns
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
# Define two columns with specified widths
table.add_column("First Column", width=int(vars.settings["dungeon_width"] / 1.75 ))
table.add_column("Second Column", width=int(vars.settings["dungeon_width"] / 2 ))
# Calculate the number of rows needed based on the minimum
rows = max(vars.settings["min_rows"] - 4, len(first_column), len(second_column))
# Add rows to the table, including padding if necessary
for row in range(rows):
# Get the item from each column if it exists; otherwise, use an empty string
first_item = first_column[row] if row < len(first_column) else ""
second_item = second_column[row] if row < len(second_column) else ""
# Add a row to the table
table.add_row(first_item, second_item)
# Print the table (assumes you have a console object)
console.print(table)
console.print(equipped_weapon)
console.print(equipped_armor)
console.print(equipped_accessory)
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["menu_options"])
# Input handling code
choice = console.input(vars.message["input"]["cursor"]).upper()
if choice == 'S':
save_game()
elif choice == 'L':
load_game()
elif choice == 'E':
confirm = console.input(vars.message["input"]["sure_quit"]).upper()
if confirm == 'Y':
console.print*()
console.print(vars.message["game_over"]["thank_you"])
stop_music()
sys.exit()
else:
continue
elif choice == '':
break
# Save game state to a JSON file
def save_game():
from utils import get_limited_input
clear_screen()
console.print(vars.message["ui"]["top_lines"]["save_game"])
console.print()
console.print(vars.message['input']['save_name'])
save_name = get_limited_input(f"{vars.message['notification']['cursor']}", 12).strip()
if not save_name:
return
# Define the directory where you want to save the file
save_directory = "saves"
save_name = ''.join(c for c in save_name if c.isalnum() or c in (' ', '_', '-')).rstrip()
# Ensure the directory exists
os.makedirs(save_directory, exist_ok=True)
# Combine the directory path with the filename
save_filename = os.path.join(save_directory, f"{save_name}.json")
if os.path.exists(save_filename):
overwrite = console.input(vars.message["input"]["override_save"]).upper()
if overwrite != 'Y':
console.print(vars.message["notification"]["save_canceled"])
time.sleep(vars.settings["delay_save_game"])
return
# Convert shops_visited to a list for JSON serialization
player_copy = vars.player.copy()
player_copy['shops_visited'] = list(vars.player['shops_visited'])
# Convert items_on_floor keys to strings
items_on_floor_serializable = {f"{k[0]},{k[1]}": v for k, v in vars.items_on_floor.items()}
game_state = {
'player': player_copy,
'dungeon': vars.dungeon,
'enemies': [enemy.to_dict() for enemy in vars.enemies],
'projectiles': vars.projectiles,
'rooms': vars.rooms,
'secret_rooms': vars.secret_rooms,
'items_on_floor': items_on_floor_serializable
}
try:
with open(save_filename, 'w') as f:
json.dump(game_state, f, indent=4)
console.print(vars.message["notification"]["save_successful"].format(filename=save_filename))
except Exception as e:
console.print(vars.message["error"]["save_error"].format(error=e))
time.sleep(vars.settings["delay_save_game"])
def load_game():
from enemy import Enemy
from utils import clear_screen
clear_screen()
console.print(vars.message["ui"]["top_lines"]["load_game"])
console.print()
# Define the directory where save files are located
save_directory = './saves'
save_files = [f for f in os.listdir(save_directory) if f.endswith('.json')]
if not save_files:
console.print(vars.message["ui"]["middle_lines"]["no_save_file_found"])
#time.sleep(vars.settings["delay_load_game"])
#return
else:
console.print(vars.message["ui"]["middle_lines"]["available_save_files"])
console.print()
# Create a table with three columns for the save files
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
table.add_column("Save Files 1", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Save Files 2", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Save Files 3", width=int(vars.settings["dungeon_width"] / 3))
# Populate the table with save files in three-column format
save_rows = [
f"[bold cyan]{idx + 1}.{' ' if idx + 1 < 10 else ''}[/bold cyan] {file}"
for idx, file in enumerate(save_files)
]
# Calculate the number of rows needed for three columns
rows = max(vars.settings["min_rows"], (len(save_rows) + 2) // 3)
# Add rows to the table
for i in range(rows):
col1 = save_rows[i * 3] if i * 3 < len(save_rows) else ""
col2 = save_rows[i * 3 + 1] if i * 3 + 1 < len(save_rows) else ""
col3 = save_rows[i * 3 + 2] if i * 3 + 2 < len(save_rows) else ""
table.add_row(col1, col2, col3)
# Print the table and prompt for choice
console.print(table)
console.print(vars.message["ui"]['bottom_lines']['instructions']["load_game_options"])
# Get user input
choice = console.input(vars.message["input"]["cursor"])
if choice.isdigit():
choice = int(choice)
if 1 <= choice <= len(save_files):
selected_file = save_files[choice - 1]
full_path = os.path.join(save_directory, selected_file) # Full path to load
try:
with open(full_path, 'r') as f:
game_state = json.load(f)
vars.player = game_state['player']
# Convert shops_visited back to a set
vars.player['shops_visited'] = set(vars.player['shops_visited'])
vars.dungeon = game_state['dungeon']
vars.enemies = [Enemy.from_dict(e) for e in game_state['enemies']]
vars.enemies = [e for e in vars.enemies if e is not None]
vars.projectiles = game_state['projectiles']
vars.rooms = game_state['rooms']
vars.secret_rooms = game_state.get('secret_rooms', [])
# Convert items_on_floor keys back to tuples
vars.items_on_floor = {tuple(map(int, k.split(','))): v for k, v in game_state.get('items_on_floor', {}).items()}
clear_screen()
console.print(vars.message["ui"]["top_lines"]["load_game"])
console.print()
console.print(vars.message["ui"]["middle_lines"]["available_save_files"])
console.print()
console.print(table)
console.print(vars.message["ui"]['bottom_lines']['instructions']["load_game_options"])
console.print(vars.message["notification"]["load_successful"].format(file=selected_file))
except Exception as e:
console.print(vars.message["error"]["load_error"].format(error=e))
time.sleep(vars.settings["delay_load_game"])
elif choice.upper() == 'D':
delete_save()
elif choice == "":
time.sleep(vars.settings["delay_load_game"])
return
def delete_save():
clear_screen()
console.print(vars.message["ui"]["top_lines"]["delete_save_file"])
console.print()
# List save files in the "./saves" directory
save_directory = './saves'
save_files = [f for f in os.listdir(save_directory) if f.endswith('.json')]
if not save_files:
console.print(vars.message["ui"]["middle_lines"]["no_save_file"])
#time.sleep(vars.settings["delay_delete_save"])
#return
else:
console.print(vars.message["ui"]["middle_lines"]["which_file_to_delete"])
console.print()
# Create a table with three columns for the save files
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
table.add_column("Save Files 1", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Save Files 2", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Save Files 3", width=int(vars.settings["dungeon_width"] / 3))
# Populate the table with save files in three-column format
save_rows = [
f"[bold cyan]{idx + 1}.{' ' if idx + 1 < 10 else ''}[/bold cyan] {file}"
for idx, file in enumerate(save_files)
]
# Calculate the number of rows needed for three columns
rows = max(vars.settings["min_rows"], (len(save_rows) + 2) // 3)
# Add rows to the table
for i in range(rows):
col1 = save_rows[i * 3] if i * 3 < len(save_rows) else ""
col2 = save_rows[i * 3 + 1] if i * 3 + 1 < len(save_rows) else ""
col3 = save_rows[i * 3 + 2] if i * 3 + 2 < len(save_rows) else ""
table.add_row(col1, col2, col3)
console.print(table)
console.print(vars.message["ui"]['bottom_lines']['instructions']["delete_file_options"])
choice = console.input(vars.message["input"]["cursor"])
if choice.isdigit():
choice = int(choice)
if 1 <= choice <= len(save_files):
selected_file = save_files[choice - 1]
full_path = os.path.join(save_directory, selected_file) # Full path to delete
clear_screen()
console.print(vars.message["ui"]['top_lines']["delete_save_file"])
console.print()
console.print(vars.message["ui"]["middle_lines"]["which_file_to_delete"])
console.print()
console.print(table)
console.print(vars.message["ui"]['bottom_lines']['instructions']["delete_file_options"])
confirm = console.input(vars.message["input"]["delete_file"].format(file=selected_file)).upper()
if confirm == 'Y':
try:
os.remove(full_path)
console.print(vars.message["ui"]["middle_lines"]["file_deleted"].format(file=selected_file))
load_game()
except Exception as e:
console.print(vars.message["error"]["delete_error"].format(error=e))
else:
console.print(vars.message["warning"]["deletion_canceled"])
elif choice == len(save_files) + 1:
console.print()
elif choice == "":
load_game()
else:
delete_save()
time.sleep(vars.settings["delay_delete_save"])
def use_item_screen():
from projectiles import fire_ranged_weapon
from battle import apply_status_effect
from items import equip_item
clear_screen()
console.print(vars.message["ui"]["top_lines"]["inventory"])
console.print()
# Create a table with three columns for the inventory display
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
# Define three columns with a specified width
table.add_column("Column 1", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Column 2", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Column 3", width=int(vars.settings["dungeon_width"] / 3))
# Check if the inventory is empty
if vars.player['inventory']:
# Populate the table with items from the inventory
columns = 3
# Calculate the required rows to either fit the inventory or meet min_rows
rows = max(vars.settings["min_rows"] + 2, (len(vars.player['inventory']) + columns - 1) // columns)
for row in range(rows):
row_data = []
for col in range(columns):
idx = row * columns + col
if idx < len(vars.player['inventory']):
item = vars.player['inventory'][idx]
# Add formatted string with index and item name
row_data.append(f"[bright_cyan]{idx + 1}.[/bright_cyan] {item['name']:<25}")
else:
# If there's no item for this cell, add an empty string
row_data.append("")
# Add the row data to the table
table.add_row(*row_data)
else:
# Populate the table with empty rows to meet the minimum row count
for _ in range(vars.settings["min_rows"] + 1):
table.add_row("", "", "")
# Display "no items" message below the table
console.print(" You have no items to use.")
# Print the table and divider
console.print(table)
# If there are no items, exit the function after displaying the message
if not vars.player['inventory']:
console.print(vars.message["ui"]['bottom_lines']['instructions']["use_item_options"])
time.sleep(vars.settings["delay_cannot_use"])
return
console.print(vars.message["ui"]['bottom_lines']['instructions']["use_item_options"])
# User input for item selection
choice = console.input(vars.message["input"]["cursor"]).upper()
if choice == '':
return
elif choice.isdigit() and 1 <= int(choice) <= len(vars.player['inventory']):
clear_screen()
console.print(vars.message["ui"]["top_lines"]["inventory"])
console.print()
console.print(table)
console.print(vars.message["ui"]['bottom_lines']['instructions']["use_item_options"])
item = vars.player['inventory'][int(choice) - 1]
if not item.get('identified', True):
console.print(vars.message["notification"]["need_to_identify"])
time.sleep(vars.settings["delay_need_to_identify"])
use_item_screen()
if item['type'] in ['potion', 'tool', 'scroll']:
if 'heal' in item:
vars.player['health'] = min(vars.player['max_health'], vars.player['health'] + item['heal'])
console.print(vars.message["notification"]["recovered_hp"].format(item=item['heal']))
vars.player['inventory'].pop(int(choice) - 1)
if 'charge' in item:
vars.player['mana'] = min(vars.player['max_mana'], vars.player['mana'] + item['charge'])
console.print(vars.message["notification"]["recovered_mp"].format(item=item['charge']))
vars.player['inventory'].pop(int(choice) - 1)
if 'effect' in item:
apply_status_effect(vars.player, item['effect'])
vars.player['inventory'].pop(int(choice) - 1)
time.sleep(vars.settings["delay_use_item"])
use_item_screen()
elif item['type'] == 'weapon' and item.get('range', False):
fire_ranged_weapon(item)
elif item['type'] in ['weapon', 'armor', 'accessory']:
equip_item(item)
vars.player['inventory'].pop(int(choice) - 1)
else:
console.print(vars.message["notification"]["cannot_use_item"])
time.sleep(vars.settings["delay_cannot_use"])
use_item_screen()
else:
use_item_screen()
def show_item_details(item):
clear_screen()
console.print(vars.message["ui"]["top_lines"]["item_details"])
console.print()
# Determine the initial content to be displayed based on the item type
if item['type'] in ['weapon', 'armor', 'accessory']:
if not item.get('identified', True):
details_text = item['flavor_text_unidentified']
else:
details_text = item['flavor_text_identified']
else:
details_text = item['flavor_text']
# Print the item details
console.print(" " + details_text)
console.print()
# Calculate the current height based on printed lines and add padding if needed
content_lines = details_text.count('\n') + 4 # Adjust for title and spacing around it
padding_needed = max(0, vars.settings["min_rows"] + 4 - content_lines)
# Add padding lines to reach the minimum height
for _ in range(padding_needed):
console.print()
def use_specific_item(item):
from battle import apply_status_effect
from items import equip_item
if item['type'] == 'potion':
if 'heal' in item:
vars.player['health'] = min(vars.player['max_health'], vars.player['health'] + item['heal'])
console.print(f"You healed for {item['heal']} health!")
if 'effect' in item:
apply_status_effect(vars.player, item['effect'])
vars.player['inventory'].remove(item)
elif item['type'] in ['weapon', 'armor', 'accessory']:
equip_item(item)
vars.player['inventory'].remove(item)
else:
console.print("You cannot use this item.")
time.sleep(vars.settings["delay_use_item"])
def identify_item():
unidentified_items = [item for item in vars.player['inventory'] if not item.get('identified', True)]
if not unidentified_items:
console.print("You have no items to identify.")
return
console.print("Unidentified items:")
for idx, item in enumerate(unidentified_items):
console.print(f"{idx+1}. {item['name']}")
choice = console.input("Enter the number of the item to identify or hit enter to go back: ").upper()
if choice == '':
return
elif choice.isdigit() and 1 <= int(choice) <= len(unidentified_items):
item = unidentified_items[int(choice)-1]
item['identified'] = True
# Restore original name
original_item = next((i for i in vars.items if i['type'] == item['type'] and i.get('effect') == item.get('effect') and i.get('attack') == item.get('attack') and i.get('defense') == item.get('defense') and i.get('heal') == item.get('heal') and i.get('mana') == item.get('mana')), None)
if original_item:
item['name'] = original_item['name']
console.print(f"You have identified the {item['name']}!")
else:
console.print("Item identification failed.")
def sell_items():
while True:
clear_screen()
console.print(vars.message["ui"]["top_lines"]["inventory"])
console.print()
# Create a table with three columns for the inventory display
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
# Define three columns with specified widths
table.add_column("Column 1", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Column 2", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Column 3", width=int(vars.settings["dungeon_width"] / 3))
if vars.player['inventory']:
# Calculate the required rows to either fit the inventory or meet min_rows
columns = 3
rows = max(vars.settings["min_rows"], (len(vars.player['inventory']) + columns - 1) // columns)
# Populate the table rows with items from the inventory
for row in range(rows):
row_data = []
for col in range(columns):
idx = row * columns + col
if idx < len(vars.player['inventory']):
item = vars.player['inventory'][idx]
# Add formatted string with index and item name
sell_price = item.get('value', 10) // 2
row_data.append(f"[bright_cyan]{idx+1}.[/bright_cyan] {item['name']:<5} - Sell for [bold yellow]{sell_price} gold[/bold yellow]")
else:
# If no item for this cell, add an empty string for alignment
row_data.append("")
# Add the row to the table
table.add_row(*row_data)
# Print the table and prompt for input
console.print(table)
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["sell_item_options"])
choice = console.input(vars.message["input"]["cursor"]).upper()
if choice == '':
clear_screen()
break
elif choice.isdigit() and 1 <= int(choice) <= len(vars.player['inventory']):
item = vars.player['inventory'].pop(int(choice)-1)
sell_price = item.get('value', 10) // 2
vars.player['gold'] += sell_price
vars.player['gold_collected'] += sell_price
clear_screen()
console.print(vars.message["ui"]["top_lines"]["inventory"])
console.print()
console.print(table)
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["sell_item_options"])
console.print(vars.message["notification"]["sold_item"].format(item=item['name'], price=sell_price))
time.sleep(vars.settings["delay_sold"])
else:
clear_screen()
else:
# Add empty rows to meet the minimum row count if inventory is empty
for _ in range(vars.settings["min_rows"]):
table.add_row("", "", "")
clear_screen()
console.print(vars.message["ui"]["top_lines"]["inventory"])
console.print()
console.print(vars.message["ui"]['middle_lines']["nothing_to_sell"])
console.print(table)
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["return_options"])
console.input(vars.message["input"]["cursor"]).upper()
break
def identify_service(buffer):
unidentified_items = [item for item in vars.player['inventory'] if not item.get('identified', True)]
if not unidentified_items:
console.print("You have no unidentified items.")
time.sleep(vars.settings["delay_no_unidentified"])
return
# Calculate identification price
weapon_prices = [item['value'] for item in vars.items if item['type'] == 'weapon']
average_weapon_price = sum(weapon_prices) / len(weapon_prices)
identify_price = int(average_weapon_price * 0.75)
console.print(f"Identification service costs [bold yellow]{identify_price} gold[/bold yellow] per item.")
console.print("Unidentified items:")
for idx, item in enumerate(unidentified_items):
console.print(f"[bright_cyan]{idx+1}.[/bright_cyan] {item['name']}")
choice = console.input("Enter the number of the item to identify or hit return to cancel: ")
if choice == '':
return
elif choice.isdigit() and 1 <= int(choice) <= len(unidentified_items):
if vars.player['gold'] >= identify_price:
vars.player['gold'] -= identify_price
item = unidentified_items[int(choice)-1]
item['identified'] = True
# Restore original name
original_item = next((i for i in vars.items if i['type'] == item['type'] and i.get('effect') == item.get('effect') and i.get('attack') == item.get('attack') and i.get('defense') == item.get('defense') and i.get('heal') == item.get('heal') and i.get('mana') == item.get('mana')), None)
if original_item:
item['name'] = original_item['name']
console.print(f"You have identified the {item['name']}!")
else:
console.print("Item identification failed.")
else:
console.print("You don't have enough gold!")
time.sleep(vars.settings["delay_not_enough_gold"])
clear_screen()
console.print(buffer)
identify_service(buffer)
else:
clear_screen()
console.print(buffer)
identify_service(buffer)
# Enter shop
def enter_shop(shop_position):
shop_id = f"{vars.player['floor']}_{shop_position}"
first_visit = shop_id not in vars.player['shops_visited']
if first_visit:
vars.player['shops_visited'].add(shop_id)
# Generate and store random shop items for this shop on first visit
shop_items = random.sample([item for item in vars.items if item['type'] != 'money'], max(int(random.randint(3,13) / vars.player["level"]), 3))
vars.player['shops_items'][shop_id] = shop_items
else:
# Retrieve the previously stored items for this shop
shop_items = vars.player['shops_items'].get(shop_id, [])
# Construct static buffer with shop line and greeting
buffer = f"{vars.message['ui']['top_lines']['dungeon_shop']}\n\n{greet_player(first_visit)}\n\n"
# Start the interaction loop
while True:
clear_screen()
console.print(buffer)
# Create a table with two columns
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
table.add_column("Shop Items", width=int(vars.settings["dungeon_width"]))
# Prepare shop items for the first column
shop_rows = [
f" [bold cyan]{idx + 1}.[/bold cyan] {item['name']:<25} - [bold yellow]{item.get('value', 10)} gold[/bold yellow]"
for idx, item in enumerate(shop_items)
]
# Calculate the number of rows needed based on the minimum
rows = max(vars.settings["min_rows"] - 5, len(shop_rows))
# Add rows to the table, including padding if necessary
for row in range(rows):
# Get the item from each column if it exists; otherwise, use an empty string
first_item = shop_rows[row] if row < len(shop_rows) else ""
# Add a row to the table
table.add_row(first_item)
# Print the table
console.print(table)
# Display player's gold and prompt for choice
console.print()
console.print(f" You have [bold yellow]{vars.player['gold']} gold[/bold yellow].")
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["shop_options"])
# Get player input for buying items or other options
choice = console.input(vars.message["input"]["cursor"]).upper()
if choice == '': # Exit the shop
break
elif choice == 'S':
clear_screen()
console.print(buffer)
console.print(table)
console.print()
console.print(f" You have [bold yellow]{vars.player['gold']} gold[/bold yellow].")
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["shop_options"])
sell_items()
elif choice == 'I':
clear_screen()
console.print(buffer)
console.print(table)
console.print()
console.print(f" You have [bold yellow]{vars.player['gold']} gold[/bold yellow].")
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["shop_options"])
buffer2 = f"{buffer}\n{table}\n\n You have [bold yellow]{vars.player['gold']} gold[/bold yellow].\n\n{vars.message['ui']['bottom_lines']['instructions']['shop_options']}"
identify_service(buffer2)
elif choice.isdigit() and 1 <= int(choice) <= len(shop_items):
# Buy item directly if a valid number is entered
idx = int(choice) - 1
item = shop_items[idx]
price = item.get('value', 10)
if vars.player['gold'] >= price:
vars.player['gold'] -= price
item = item.copy()
if item['type'] in ['weapon', 'armor', 'accessory']:
item['identified'] = True
item['name'] = f"{item['name'].capitalize()}"
vars.player['items_purchased'] += 1
vars.player['inventory'].append(item)
# Remove the bought item from shop_items and persist this update
del shop_items[idx]
vars.player['shops_items'][shop_id] = shop_items # Update the shop inventory for persistence
console.print(f"You bought [bold #9127e3]{item['name']}[/bold #9127e3]!")
else:
console.print("You don't have enough gold!")
time.sleep(vars.settings["delay_not_enough_gold"])
def greet_player(first_visit):
player_class = determine_player_class()
if first_visit:
greeting = f"[bold #9127e3]{random.choice(vars.message['shop']['greeting'].get(player_class, ['Welcome to my shop!']))}[/bold #9127e3]\n"
else:
greeting = f"[bold #9127e3]{random.choice(vars.message['shop']['generic'])}[/bold #9127e3]\n"
greeting += f"[bold #9127e3]{random.choice(vars.message['shop']['look_at_my_wares'])}[/bold #9127e3]"
return greeting
def determine_player_class():
weapon = vars.player['equipped']['weapon']
if weapon:
name = weapon.get('name', '').lower()
if 'staff' in name or 'wand' in name:
vars.player['class'] = 'Mage'
elif 'sword' in name or 'axe' in name:
vars.player['class'] = 'Warrior'
elif 'dagger' in name or 'bow' in name or 'crossbow' in name:
vars.player['class'] = 'Assassin'
return vars.player['class']
# Show inventory with flavor text
def show_inventory():
from items import equip_item
while True:
clear_screen()
console.print(vars.message["ui"]["top_lines"]["inventory"])
console.print()
# Create a table with three columns for the inventory display
table = Table(show_header=False, box=None, show_lines=False, expand=False, padding=(0, 1))
# Define three columns with specified widths
table.add_column("Column 1", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Column 2", width=int(vars.settings["dungeon_width"] / 3))
table.add_column("Column 3", width=int(vars.settings["dungeon_width"] / 3))
if vars.player['inventory']:
# Calculate the required rows to either fit the inventory or meet min_rows
columns = 3
rows = max(vars.settings["min_rows"] + 1, (len(vars.player['inventory']) + columns - 1) // columns)
# Populate the table rows with items from the inventory
for row in range(rows):
row_data = []
for col in range(columns):
idx = row * columns + col
if idx < len(vars.player['inventory']):
item = vars.player['inventory'][idx]
# Add formatted string with index and item name
row_data.append(f"[bright_cyan]{idx+1}.[/bright_cyan] {item['name']:<25}")
else:
# If no item for this cell, add an empty string for alignment
row_data.append("")
# Add the row to the table
table.add_row(*row_data)
# Print the table and prompt for input
console.print(table)
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["use_item_options"])
choice = console.input(vars.message["input"]["cursor"]).upper()
if choice == '':
break
elif choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(vars.player['inventory']):
item = vars.player['inventory'][idx]
show_item_details(item)
console.print(vars.message["ui"]['bottom_lines']['instructions']["inventory_options"])
action = console.input(vars.message["input"]["cursor"]).upper()
if action == 'E':
if item["type"] in ['armor', 'weapon', 'accessory']:
if not item.get('identified', True):
console.print("You need to identify this item before you can equip it.")
time.sleep(vars.settings["delay_need_to_identify"])
else:
equip_item(item)
elif item["type"] in ['scroll', 'potion', 'tool']:
console.print("You cannot equip this item. You should use it instead.")
elif action == 'U':
if item["type"] in ['armor', 'weapon', 'accessory']:
console.print("You cannot use this item. You should equip it instead.")
time.sleep(vars.settings["delay_need_to_identify"])
elif item["type"] in ['scroll', 'potion', 'tool']:
use_specific_item(item)
else:
console.print("You cannot use this item. You should sell it in a shop.")
elif action == '':
continue
else:
clear_screen()
else:
# Add empty rows to meet the minimum row count if inventory is empty
for _ in range(vars.settings["min_rows"]):
table.add_row("", "", "")
console.print(vars.message["ui"]["middle_lines"]["inventory_empty"])
console.print(table)
console.print()
console.print(vars.message["ui"]['bottom_lines']['instructions']["return_options"])
console.input(vars.message["input"]["cursor"]).upper()
break