-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_ncurses.py
More file actions
2849 lines (2451 loc) · 99.3 KB
/
main_ncurses.py
File metadata and controls
2849 lines (2451 loc) · 99.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
DnD 5th Edition API - NCurses Interface v2
✅ MIGRATED VERSION - Using dnd-5e-core package instead of dao_classes
"""
import curses
import time
import os
import sys
import pickle
import json
from typing import List
from random import seed, randint, choice
# ============================================
# MIGRATION: Add dnd-5e-core to path (development mode)
# ============================================
_parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_dnd_5e_core_path = os.path.join(_parent_dir, 'dnd-5e-core')
if os.path.exists(_dnd_5e_core_path) and _dnd_5e_core_path not in sys.path:
sys.path.insert(0, _dnd_5e_core_path)
# ============================================
# MIGRATION: Import from dnd-5e-core package
# ============================================
from dnd_5e_core.entities import Character
from dnd_5e_core.equipment import Weapon, Armor, Cost, HealingPotion
# Note: Data directory is now in dnd-5e-core/data and will be auto-detected
# No need to call set_data_directory() anymore
from tools.common import get_save_game_path
from populate_functions import (populate, request_monster, request_armor, request_weapon, request_equipment, request_equipment_category)
print("✅ [MIGRATION v2] Successfully loaded with dnd-5e-core package")
print(" Game logic: dnd-5e-core")
print(" Data loading: populate_functions.py")
print()
# Define functions that are in main.py but we need without PyQt5
def load_potions_collections():
"""Load healing potions - stub for now"""
return []
def get_roster(characters_dir: str):
"""Load roster from character files"""
import os
import pickle
roster = []
if not os.path.exists(characters_dir):
return roster
try:
char_file_list = os.scandir(characters_dir)
for entry in char_file_list:
if entry.is_file() and entry.name.endswith(".dmp"):
try:
with open(entry, "rb") as f1:
roster.append(pickle.load(f1))
except Exception:
pass
except Exception:
pass
return roster
def load_party(_dir: str):
"""Load party from file"""
import os
import pickle
party = []
party_file = os.path.join(_dir, "party.dmp")
if os.path.exists(party_file):
try:
with open(party_file, "rb") as f1:
party = pickle.load(f1)
except Exception:
pass
return party if party else []
def save_party(party, _dir: str):
"""Save party to file"""
import os
import pickle
os.makedirs(_dir, exist_ok=True)
party_file = os.path.join(_dir, "party.dmp")
with open(party_file, "wb") as f1:
pickle.dump(party, f1)
def save_character(char, _dir: str):
"""Save character to file"""
import os
import pickle
os.makedirs(_dir, exist_ok=True)
char_file = os.path.join(_dir, f"{char.name}.dmp")
with open(char_file, "wb") as f1:
pickle.dump(char, f1)
def load_character_collections():
"""Charge les collections de création de personnage depuis les fichiers JSON et dnd_5e_core"""
from dnd_5e_core.data import list_races, list_classes, load_race, load_class, load_names, load_human_names, list_subraces, load_subrace, list_spells, load_spell
# Races
races = [load_race(r) for r in list_races()]
subraces = [load_subrace(s) for s in list_subraces()]
classes = [load_class(c) for c in list_classes()]
alignments = [
"Lawful Good", "Neutral Good", "Chaotic Good",
"Lawful Neutral", "True Neutral", "Chaotic Neutral",
"Lawful Evil", "Neutral Evil", "Chaotic Evil"
]
# Noms
names = {}
for race in list_races():
if race == "human":
continue
names[race] = load_names(race)
human_names = load_human_names()
# Sorts (optionnel)
spells = [load_spell(s) for s in list_spells()]
return races, subraces, classes, alignments, [], [], names, human_names, spells
def load_dungeon_collections():
"""Load dungeon collections without PyQt5 dependency"""
monster_names = populate(collection_name="monsters", key_name="results")
monsters = [request_monster(name) for name in monster_names]
armor_names = populate(collection_name="armors", key_name="equipment")
armors = [request_armor(name) for name in armor_names]
weapon_names = populate(collection_name="weapons", key_name="equipment")
weapons = [request_weapon(name) for name in weapon_names]
equipment_names = populate(collection_name="equipment", key_name="results")
equipments = [request_equipment(name) for name in equipment_names]
equipment_category_names = populate(collection_name="equipment-categories", key_name="results")
equipment_categories = [request_equipment_category(name) for name in equipment_category_names]
healing_potions = load_potions_collections()
return monsters, armors, weapons, equipments, equipment_categories, healing_potions
# Correction indentation XP_LEVELS et TRAINING_GROUNDS
from dnd_5e_core.mechanics import (
XP_LEVELS,
generate_encounter_distribution,
ENCOUNTER_TABLE,
ENCOUNTER_GOLD_TABLE,
get_encounter_gold,
)
from dnd_5e_core.mechanics.encounter_builder import select_monsters_by_encounter_table
# Import UI helpers
from ui_helpers import delete_character_prompt_ok
# Import project-specific functions from main
from main import (
create_new_character,
explore_dungeon,
generate_random_character
)
import main
# Compatibility aliases
load_xp_levels_func = XP_LEVELS
generate_encounter_levels = generate_encounter_distribution
load_encounter_table = lambda: ENCOUNTER_TABLE
load_encounter_gold_table = lambda: ENCOUNTER_GOLD_TABLE
generate_encounter = select_monsters_by_encounter_table
MIN_COLS = 80
MIN_LINES = 24
SAVE_FILE = 'save_game.json'
MAX_ROSTER = 100 # Maximum number of characters allowed
POTION_INITIAL_PACK = 15
class Location:
"""Represents a game location"""
CASTLE = 'castle'
EDGE_OF_TOWN = 'edge_of_town'
TAVERN = 'tavern'
INN = 'inn'
TEMPLE = 'temple'
TRADING_POST = 'trading_post'
TRAINING_GROUNDS = 'training_grounds'
DUNGEON = 'dungeon'
class DnDCursesUI:
def __init__(self, stdscr):
self.stdscr = stdscr
# Initialize game data
self.game_path = get_save_game_path()
self.characters_dir = f"{self.game_path}/characters"
# Load game resources
self.xp_levels: List[int] = []
self.monsters = []
self.armors = []
self.weapons = []
self.equipments = []
self.equipment_categories = []
self.potions = []
# Game state
self.roster: List[Character] = []
self.party: List[Character] = []
self.location = Location.CASTLE
# UI state
self.mode = 'main_menu'
self.menu_cursor = 0
self.location_cursor = 0
self.castle_cursor = 0
self.edge_cursor = 0
self.party_cursor = 0
self.tavern_cursor = 0
self.inn_cursor = 0
self.temple_cursor = 0
self.training_cursor = 0
self.roster_cursor = 0
self.char_status_cursor = 0
self.trading_cursor = 0
self.trading_action_cursor = 0
self.buy_cursor = 0
self.sell_cursor = 0
self.reorder_cursor = 0
self.char_select_cursor = 0
self.inventory_item_cursor = 0 # For character inventory management
self.spell_cursor = 0 # For spell viewing
self.cheat_cursor = 0 # For cheat menu
# Submenu cursors
self.character_to_rest = None
self.character_selected = None
self.character_trading = None
self.character_viewing = None
self.reorder_selected = None
# Dungeon exploration
self.dungeon_message = ""
self.dungeon_step = 0
self.dungeon_log = []
# Game data collections
self.races = []
self.subraces = []
self.classes = []
self.alignments = []
self.proficiencies = []
self.names = {}
self.human_names = {}
self.spells = []
self.encounter_table = {}
self.encounter_gold_table = []
self.available_crs = []
# Message system
self.messages: List[str] = []
self.panel_message: str = ""
self.panel_message_time: float = 0
# Previous mode tracking
self.previous_mode = None
self.previous_location = None
def push_message(self, msg: str) -> None:
"""Add message to scrolling log"""
self.messages.append(msg)
if len(self.messages) > 100:
self.messages.pop(0)
def push_panel(self, msg: str) -> None:
"""Set panel message (shown for 2 seconds)"""
self.panel_message = msg
self.panel_message_time = time.time()
def get_panel_message(self) -> str:
"""Get current panel message if still valid"""
if self.panel_message and time.time() - self.panel_message_time < 2:
return self.panel_message
return ""
def check_bounds(self):
"""Ensure terminal is large enough"""
lines, cols = self.stdscr.getmaxyx()
while cols < MIN_COLS or lines < MIN_LINES:
try:
self.stdscr.erase()
self.stdscr.addstr(0, 0, f"Terminal too small. Minimum: {MIN_COLS}x{MIN_LINES}")
self.stdscr.addstr(1, 0, f"Current: {cols}x{lines}")
self.stdscr.addstr(2, 0, "Resize to continue...")
self.stdscr.refresh()
except curses.error:
pass
time.sleep(0.5)
lines, cols = self.stdscr.getmaxyx()
def load_game_data(self):
"""Load all game data"""
self.push_message("Loading game data...")
# Load XP levels
self.xp_levels = self.load_xp_levels()
# Load databases
self.monsters, self.armors, self.weapons, self.equipments, self.equipment_categories, self.potions = load_dungeon_collections()
# Filter out None values
self.armors = list(filter(lambda a: a, self.armors))
self.weapons = list(filter(lambda w: w, self.weapons))
# Debug: Log data loaded
if self.monsters:
self.push_message(f"Loaded {len(self.monsters)} monsters")
else:
self.push_message("WARNING: No monsters loaded!")
if self.weapons:
self.push_message(f"Loaded {len(self.weapons)} weapons")
else:
self.push_message("WARNING: No weapons loaded!")
if self.armors:
self.push_message(f"Loaded {len(self.armors)} armors")
else:
self.push_message("WARNING: No armors loaded!")
# Create directories if they don't exist
os.makedirs(self.characters_dir, exist_ok=True)
os.makedirs(self.game_path, exist_ok=True)
# Load roster
self.roster = get_roster(self.characters_dir)
self.push_message(f"Loaded {len(self.roster)} characters from roster")
# Load party
self.party = load_party(_dir=self.game_path)
self.push_message(f"Loaded {len(self.party)} characters in party")
# Load encounter tables if available
self.encounter_table = load_encounter_table()
self.encounter_gold_table = load_encounter_gold_table()
if self.encounter_table:
self.push_message(f"Loaded encounter table")
else:
self.push_message("WARNING: No encounter table loaded!")
# Load character collections (races, classes, spells, etc.)
try:
self.races, self.subraces, self.classes, self.alignments, _, _, self.names, self.human_names, self.spells = load_character_collections()
# Debug: Check what was loaded
if self.races and self.classes:
self.push_message(f"✓ Loaded {len(self.races)} races, {len(self.classes)} classes, {len(self.spells)} spells")
else:
self.push_message(f"⚠ WARNING: races={len(self.races or [])}, classes={len(self.classes or [])}")
except Exception as e:
self.push_message(f"✗ ERROR loading character collections: {str(e)[:50]}")
# Initialize empty to avoid errors
self.races = []
self.subraces = []
self.classes = []
self.alignments = []
self.names = {}
self.human_names = {}
self.spells = []
self.names = {}
self.human_names = {}
self.spells = []
if self.monsters:
from fractions import Fraction
self.available_crs = [Fraction(str(m.challenge_rating)) for m in self.monsters]
self.push_message(f"Available CRs: {len(self.available_crs)}")
else:
self.available_crs = []
self.push_message("WARNING: No CRs available (no monsters)!")
def load_xp_levels(self) -> List[int]:
"""Load XP levels from file"""
try:
# Placeholder - adapt to your actual implementation
return [0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000, 85000, 100000, 120000, 140000, 165000, 195000, 225000, 265000, 305000, 355000]
except Exception:
return []
def draw_header(self, title: str, lines: int, cols: int):
"""Draw common header"""
try:
# Title bar
title_bar = f" {title} ".center(cols, "=")
self.stdscr.addstr(0, 0, title_bar[:cols - 1], curses.A_REVERSE | curses.A_BOLD)
# Party info if exists
if self.party:
party_info = f"Party: {len(self.party)} | Location: {self.location}"
self.stdscr.addstr(1, 0, party_info[:cols - 1])
except curses.error:
pass
def draw_footer(self, instructions: str, lines: int, cols: int):
"""Draw footer with instructions"""
try:
separator = "─" * min(cols - 1, 100)
self.stdscr.addstr(lines - 3, 0, separator[:cols - 1])
# Panel message
panel_msg = self.get_panel_message()
if panel_msg:
self.stdscr.addstr(lines - 2, 0, f">>> {panel_msg}"[:cols - 1], curses.A_BOLD)
# Instructions
self.stdscr.addstr(lines - 1, 0, instructions[:cols - 1], curses.A_REVERSE)
except curses.error:
pass
def draw_main_menu(self, lines: int, cols: int):
"""Draw main menu"""
self.check_bounds()
try:
self.draw_header("D&D 5E - Main Menu", lines, cols)
options = ['Start New Game', 'Load Game', 'Cheat Menu', 'Options', 'Quit']
start_y = 4
for idx, opt in enumerate(options):
marker = '►' if idx == self.menu_cursor else ' '
self.stdscr.addstr(start_y + idx, 2, f"{marker} {opt}")
self.draw_footer("[↑/↓] Navigate [Enter] Select [q] Quit", lines, cols)
except curses.error:
pass
def draw_location_menu(self, lines: int, cols: int):
"""Draw location selection menu"""
self.check_bounds()
try:
if self.location == Location.CASTLE:
self.draw_castle_menu(lines, cols)
elif self.location == Location.EDGE_OF_TOWN:
self.draw_edge_menu(lines, cols)
except curses.error:
pass
def draw_castle_menu(self, lines: int, cols: int):
"""Draw castle menu"""
try:
self.draw_header("CASTLE", lines, cols)
options = ["Gilgamesh's Tavern", "Adventurer's Inn", "Temple of Cant", "Boltac's Trading Post", "Edge of Town", "Save & Exit"]
start_y = 4
self.stdscr.addstr(start_y, 2, "What would you like to do?", curses.A_BOLD)
for idx, opt in enumerate(options):
marker = '►' if idx == self.castle_cursor else ' '
self.stdscr.addstr(start_y + 2 + idx, 4, f"{marker} {opt}")
# Display party info
if self.party:
party_y = start_y + 2 + len(options) + 2
self.stdscr.addstr(party_y, 2, "Current Party:", curses.A_UNDERLINE)
for idx, char in enumerate(self.party[:5]): # Show max 5
char_info = f" {char.name} - Lvl {char.level} - HP: {char.hit_points}/{char.max_hit_points}"
self.stdscr.addstr(party_y + 1 + idx, 2, char_info[:cols - 3])
self.draw_footer("[↑/↓] Navigate [Enter] Select [Esc] Back", lines, cols)
except curses.error:
pass
def draw_edge_menu(self, lines: int, cols: int):
"""Draw edge of town menu"""
try:
self.draw_header("EDGE OF TOWN", lines, cols)
options = ["Training Grounds", "Enter Maze", "Castle", "Leave Game"]
start_y = 4
self.stdscr.addstr(start_y, 2, "Where would you like to go?", curses.A_BOLD)
for idx, opt in enumerate(options):
marker = '►' if idx == self.edge_cursor else ' '
self.stdscr.addstr(start_y + 2 + idx, 4, f"{marker} {opt}")
self.draw_footer("[↑/↓] Navigate [Enter] Select [Esc] Back", lines, cols)
except curses.error:
pass
def draw_reorder_party(self, lines: int, cols: int):
"""Draw party reorder interface in ncurses"""
try:
self.draw_header("REORDER PARTY", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, "Select character to move:", curses.A_BOLD)
for idx, char in enumerate(self.party):
marker = '►' if idx == self.reorder_cursor else ' '
char_info = f"{marker} {idx + 1}. {char.name} - Lvl {char.level} {char.class_type.name}"
self.stdscr.addstr(start_y + 2 + idx, 4, char_info[:cols - 5])
if hasattr(self, 'reorder_selected') and self.reorder_selected is not None:
y = start_y + 2 + len(self.party) + 2
self.stdscr.addstr(y, 2, f"Moving: {self.party[self.reorder_selected].name}", curses.A_REVERSE)
self.stdscr.addstr(y + 1, 2, "Select new position (↑/↓ then Enter)")
self.draw_footer("[↑/↓] Navigate [Enter] Select/Confirm [Esc] Cancel", lines, cols)
except curses.error:
pass
def draw_char_select_menu(self, lines: int, cols: int, char_list, title):
"""Draw character selection menu"""
try:
self.draw_header(title, lines, cols)
start_y = 4
if char_list:
display_start = max(0, self.char_select_cursor - 10)
for idx, char in enumerate(char_list[display_start:display_start + 15]):
actual_idx = display_start + idx
marker = '►' if actual_idx == self.char_select_cursor else ' '
status = f" ({char.status})" if char.status != "OK" else ""
char_info = f"{marker} {char.name} - Lvl {char.level} {char.class_type.name}{status}"
self.stdscr.addstr(start_y + idx, 2, char_info[:cols - 3])
else:
self.stdscr.addstr(start_y, 2, "(No characters available)")
self.draw_footer("[↑/↓] Navigate [Enter] View Status [Esc] Back", lines, cols)
except curses.error:
pass
def draw_dungeon_explore(self, lines: int, cols: int):
"""Draw dungeon exploration interface"""
try:
self.draw_header("DUNGEON EXPLORATION", lines, cols)
start_y = 3
# Calculate column widths - split screen in half
party_col_start = 2
party_col_width = (cols - 4) // 2
monster_col_start = party_col_start + party_col_width + 2
monster_col_width = cols - monster_col_start - 2
# Party status (left side)
self.stdscr.addstr(start_y, party_col_start, "PARTY STATUS:", curses.A_BOLD | curses.A_UNDERLINE)
y = start_y + 1
for idx, char in enumerate(self.party[:6]):
hp_ratio = char.hit_points / max(char.max_hit_points, 1)
hp_bar_length = int(hp_ratio * 10)
hp_bar = f"[{'█' * hp_bar_length}{'·' * (10 - hp_bar_length)}]"
# Color based on HP
if hp_ratio > 0.66:
color = curses.color_pair(1) # Green
elif hp_ratio > 0.33:
color = curses.color_pair(3) # Yellow
else:
color = curses.color_pair(2) # Red
status_str = f" [{char.status}]" if char.status != "OK" else ""
char_info = f"{idx + 1}. {char.name}: {hp_bar} {char.hit_points}/{char.max_hit_points} HP{status_str}"
self.stdscr.addstr(y, party_col_start + 2, char_info[:party_col_width - 2], color)
y += 1
party_height = y - start_y # Track party section height
# Monster status (right side) - only show if in combat
if hasattr(self, 'dungeon_state') and self.dungeon_state.get('monsters'):
monsters = self.dungeon_state.get('alive_monsters', self.dungeon_state.get('monsters', []))
if monsters:
self.stdscr.addstr(start_y, monster_col_start, "MONSTER STATUS:", curses.A_BOLD | curses.A_UNDERLINE)
# Calculate how many monsters fit in the same height as party
max_monster_rows = party_height - 1 # -1 for header
monsters_per_col = max(6, max_monster_rows) # At least 6 per column
# Split monsters into columns if needed
num_cols = (len(monsters) + monsters_per_col - 1) // monsters_per_col
num_cols = min(num_cols, 2) # Max 2 columns to avoid overflow
col_width = monster_col_width // num_cols if num_cols > 1 else monster_col_width
for col_idx in range(num_cols):
start_idx = col_idx * monsters_per_col
end_idx = min(start_idx + monsters_per_col, len(monsters))
col_monsters = monsters[start_idx:end_idx]
col_x = monster_col_start + (col_idx * col_width)
mon_y = start_y + 1
for idx, monster in enumerate(col_monsters):
if mon_y >= start_y + party_height:
break # Don't exceed party height
# Calculate monster HP bar
hp_ratio = monster.hit_points / max(monster.max_hit_points, 1)
hp_bar_length = int(hp_ratio * 8) # Shorter bar for monsters
hp_bar = f"[{'█' * hp_bar_length}{'·' * (8 - hp_bar_length)}]"
# Color based on HP
if hp_ratio > 0.66:
color = curses.color_pair(1) # Green
elif hp_ratio > 0.33:
color = curses.color_pair(3) # Yellow
else:
color = curses.color_pair(2) # Red
# Display monster info
monster_name = monster.name if hasattr(monster, 'name') else str(monster)
monster_info = f"{monster_name[:15]}: {hp_bar} {monster.hit_points}/{monster.max_hit_points}"
self.stdscr.addstr(mon_y, col_x, monster_info[:col_width - 1], color)
mon_y += 1
# Dungeon log (last 12 messages) - start after party/monster section
log_y = start_y + party_height + 1
if log_y < lines - 3:
self.stdscr.addstr(log_y, 2, "COMBAT LOG:", curses.A_BOLD | curses.A_UNDERLINE)
log_y += 1
display_log = self.dungeon_log[-12:] if len(self.dungeon_log) > 12 else self.dungeon_log
for msg in display_log:
if log_y >= lines - 3:
break
# Colorize specific keywords
if "KILLED" in msg or "DEAD" in msg or "DEFEAT" in msg:
self.stdscr.addstr(log_y, 4, msg[:cols - 5], curses.color_pair(2))
elif "VICTORY" in msg or "earned" in msg:
self.stdscr.addstr(log_y, 4, msg[:cols - 5], curses.color_pair(1))
elif "attacks" in msg or "launches" in msg:
self.stdscr.addstr(log_y, 4, msg[:cols - 5], curses.color_pair(3))
else:
self.stdscr.addstr(log_y, 4, msg[:cols - 5])
log_y += 1
# Current message
if self.dungeon_message:
self.stdscr.addstr(lines - 3, 2, self.dungeon_message[:cols - 3], curses.A_BOLD)
# Footer depends on whether all party is dead
all_party_dead = all(c.hit_points <= 0 for c in self.party)
if all_party_dead:
self.draw_footer("[Enter] Return to Castle", lines, cols)
else:
self.draw_footer("[Enter] Continue [Esc] Flee Combat", lines, cols)
except curses.error:
pass
def draw_party_roster(self, lines: int, cols: int):
"""Draw party and roster management"""
try:
self.draw_header("Party & Roster Management", lines, cols)
start_y = 3
# Party section
self.stdscr.addstr(start_y, 2, "CURRENT PARTY", curses.A_UNDERLINE | curses.A_BOLD)
if self.party:
for idx, char in enumerate(self.party):
marker = '►' if idx == self.party_cursor and self.party_cursor < len(self.party) else ' '
char_info = f"{marker} {char.name} - Lvl {char.level} {char.class_type.name} - HP: {char.hit_points}/{char.max_hit_points}"
self.stdscr.addstr(start_y + 1 + idx, 4, char_info[:cols - 5])
else:
self.stdscr.addstr(start_y + 1, 4, "(No characters in party)")
# Roster section
roster_y = start_y + len(self.party) + 3
self.stdscr.addstr(roster_y, 2, "AVAILABLE ROSTER", curses.A_UNDERLINE | curses.A_BOLD)
available_roster = [c for c in self.roster if c not in self.party and c.status == "OK"]
if available_roster:
display_start = max(0, self.party_cursor - len(self.party) - 5)
for idx, char in enumerate(available_roster[display_start:display_start + 10]):
actual_idx = idx + len(self.party)
marker = '►' if actual_idx == self.party_cursor else ' '
char_info = f"{marker} {char.name} - Lvl {char.level} {char.class_type.name}"
self.stdscr.addstr(roster_y + 1 + idx, 4, char_info[:cols - 5])
else:
self.stdscr.addstr(roster_y + 1, 4, "(No available characters)")
self.draw_footer("[↑/↓] Navigate [Enter] Add/Remove [Esc] Back", lines, cols)
except curses.error:
pass
def draw_tavern_menu(self, lines: int, cols: int):
"""Draw Gilgamesh's Tavern menu"""
try:
self.draw_header("GILGAMESH'S TAVERN", lines, cols)
options = ["Add Member", "Remove Member", "Character Status", "Reorder", "Divvy Gold", "Disband Party", "Exit Tavern"]
start_y = 4
self.stdscr.addstr(start_y, 2, "What would you like to do?", curses.A_BOLD)
for idx, opt in enumerate(options):
marker = '►' if idx == self.tavern_cursor else ' '
self.stdscr.addstr(start_y + 2 + idx, 4, f"{marker} {opt}")
# Show party
if self.party:
party_y = start_y + 2 + len(options) + 2
self.stdscr.addstr(party_y, 2, "Current Party:", curses.A_UNDERLINE)
for idx, char in enumerate(self.party[:6]): # Show all 6 members
char_info = f" {idx + 1}. {char.name} - Lvl {char.level} - HP: {char.hit_points}/{char.max_hit_points} - Gold: {char.gold}"
self.stdscr.addstr(party_y + 1 + idx, 2, char_info[:cols - 3])
self.draw_footer("[↑/↓] Navigate [Enter] Select [Esc] Back", lines, cols)
except curses.error:
pass
def draw_inn_menu(self, lines: int, cols: int):
"""Draw Adventurer's Inn menu"""
try:
self.draw_header("ADVENTURER'S INN", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, "Welcome to Adventurer's Inn!", curses.A_BOLD)
self.stdscr.addstr(start_y + 1, 2, "Who will Enter?")
if self.party:
for idx, char in enumerate(self.party):
marker = '►' if idx == self.inn_cursor else ' '
char_info = f"{marker} {char.name} - HP: {char.hit_points}/{char.max_hit_points} - Gold: {char.gold}GP"
self.stdscr.addstr(start_y + 3 + idx, 4, char_info[:cols - 5])
else:
self.stdscr.addstr(start_y + 3, 4, "(No characters in party)")
self.draw_footer("[↑/↓] Navigate [Enter] Select Room [Esc] Exit Inn", lines, cols)
except curses.error:
pass
def draw_inn_rooms(self, lines: int, cols: int, character):
"""Draw room selection for Inn"""
try:
self.draw_header(f"ADVENTURER'S INN - {character.name}", lines, cols)
rooms = [("The Stables (Free!)", 0, 0), ("A Cot (10 GP / Week)", 10, 1), ("Economy Room (100 GP / Week)", 100, 3), ("Merchant Suites (200 GP / Week)", 200, 7), ("The Royal Suites (500 GP / Week)", 500, 10)]
start_y = 4
self.stdscr.addstr(start_y, 2, f"Welcome {character.name}!", curses.A_BOLD)
self.stdscr.addstr(start_y + 1, 2, f"HP: {character.hit_points}/{character.max_hit_points} Gold: {character.gold}GP")
for idx, (room_name, fee, weeks) in enumerate(rooms):
marker = '►' if idx == self.inn_cursor else ' '
affordable = "" if fee <= character.gold else " (Can't afford)"
self.stdscr.addstr(start_y + 3 + idx, 4, f"{marker} {room_name}{affordable}"[:cols - 5])
self.draw_footer("[↑/↓] Navigate [Enter] Rest [Esc] Back", lines, cols)
except curses.error:
pass
def draw_temple_menu(self, lines: int, cols: int):
"""Draw Temple of Cant menu"""
try:
self.draw_header("TEMPLE OF CANT", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, "Temple of Cant -- Praise God!!!", curses.A_BOLD)
# Show characters that need healing/resurrection
cures_costs = {"PARALYZED": 100, "STONED": 200, "DEAD": 250, "ASHES": 500}
candidates = [(c, cures_costs.get(c.status, 0) * c.level) for c in self.roster if c.status in cures_costs]
if candidates:
self.stdscr.addstr(start_y + 2, 2, "Who do You Want to Save?")
for idx, (char, cost) in enumerate(candidates):
marker = '►' if idx == self.temple_cursor else ' '
char_info = f"{marker} {char.name} - Status: {char.status} - Cost: {cost}GP"
self.stdscr.addstr(start_y + 4 + idx, 4, char_info[:cols - 5])
else:
self.stdscr.addstr(start_y + 2, 2, "No more character to save HERE!")
self.draw_footer("[↑/↓] Navigate [Enter] Select [Esc] Exit Temple", lines, cols)
except curses.error:
pass
def draw_trading_post_menu(self, lines: int, cols: int):
"""Draw Boltac's Trading Post character selection"""
try:
self.draw_header("BOLTAC'S TRADING POST", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, "Welcome to Boltac's!", curses.A_BOLD)
self.stdscr.addstr(start_y + 1, 2, "Everyday, Everything Low Price!!")
self.stdscr.addstr(start_y + 3, 2, "Who will Enter?")
if self.party:
for idx, char in enumerate(self.party):
marker = '►' if idx == self.trading_cursor else ' '
char_info = f"{marker} {char.name} - Gold: {char.gold}GP"
self.stdscr.addstr(start_y + 5 + idx, 4, char_info[:cols - 5])
else:
self.stdscr.addstr(start_y + 5, 4, "(No characters in party)")
self.draw_footer("[↑/↓] Navigate [Enter] Select [Esc] Exit", lines, cols)
except curses.error:
pass
def draw_trading_actions(self, lines: int, cols: int, character):
"""Draw trading actions for selected character"""
try:
self.draw_header(f"BOLTAC'S TRADING POST - {character.name}", lines, cols)
options = ["Buy", "Sell", "Pool Gold", "Exit"]
start_y = 4
self.stdscr.addstr(start_y, 2, f"Hello, {character.name}!", curses.A_BOLD)
self.stdscr.addstr(start_y + 1, 2, f"Gold: {character.gold}GP")
for idx, opt in enumerate(options):
marker = '►' if idx == self.trading_action_cursor else ' '
self.stdscr.addstr(start_y + 3 + idx, 4, f"{marker} {opt}")
self.draw_footer("[↑/↓] Navigate [Enter] Select [Esc] Back", lines, cols)
except curses.error:
pass
def _get_buy_items_list(self, character):
"""Get consistent list of items available for purchase"""
items = []
try:
from boltac_shop import get_boltac_shop
shop = get_boltac_shop()
# Get all weapons and armors (unlimited stock)
all_weapons = shop.get_all_weapons()
all_armors = shop.get_all_armors()
# Filter by proficiencies (compare by index)
prof_weapon_indices = {w.index for w in character.prof_weapons if hasattr(w, 'index')}
prof_armor_indices = {a.index for a in character.prof_armors if hasattr(a, 'index')}
weapons = [w for w in all_weapons if hasattr(w, 'index') and w.index in prof_weapon_indices]
armors = [a for a in all_armors if hasattr(a, 'index') and a.index in prof_armor_indices]
# Sort by cost
items.extend(sorted(weapons, key=lambda i: i.cost.value if hasattr(i.cost, 'value') else 0))
items.extend(sorted(armors, key=lambda i: i.cost.value if hasattr(i.cost, 'value') else 0))
# Add magic items (limited stock)
for item, stock in shop.get_magic_items_in_stock():
if stock > 0:
items.append(item)
except Exception as e:
# Fallback to old system
if self.weapons:
items.extend(sorted(self.weapons, key=lambda i: i.cost.value if hasattr(i.cost, 'value') else 0))
if hasattr(character, 'prof_armors') and character.prof_armors:
items.extend(sorted(character.prof_armors, key=lambda i: i.cost.value if hasattr(i.cost, 'value') else 0))
return items
def draw_buy_items(self, lines: int, cols: int, character):
"""Draw buy items menu - uses BoltacShop"""
try:
self.draw_header(f"BUY ITEMS - {character.name}", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, f"Gold: {character.gold}GP", curses.A_BOLD)
# Get items from helper
items = self._get_buy_items_list(character)
if items:
display_start = max(0, self.buy_cursor - 10)
for idx, item in enumerate(items[display_start:display_start + 15]):
actual_idx = display_start + idx
marker = '►' if actual_idx == self.buy_cursor else ' '
# Check proficiency by index
prof_label = ""
if isinstance(item, Weapon) and hasattr(item, 'index'):
try:
prof_weapon_indices = {w.index for w in character.prof_weapons if hasattr(w, 'index')}
if item.index not in prof_weapon_indices:
prof_label = " [NOT PROF]"
except:
pass
# Get cost display
if hasattr(item, 'cost') and item.cost:
if hasattr(item.cost, 'value'):
cost_gp = item.cost.value // 100
cost_display = f"{cost_gp} gp" if cost_gp > 0 else f"{item.cost.value} cp"
elif hasattr(item.cost, 'quantity') and hasattr(item.cost, 'unit'):
cost_display = f"{item.cost.quantity} {item.cost.unit}"
else:
cost_display = str(item.cost)
else:
cost_display = "0 gp"
# Check if affordable
cost_value = item.cost.value if hasattr(item, 'cost') and hasattr(item.cost, 'value') else 0
affordable = "" if character.gold * 100 >= cost_value else " (No gold)"
# Check stock
stock_text = ""
try:
from boltac_shop import get_boltac_shop
shop = get_boltac_shop()
stock = shop.get_item_stock(item)
if stock == 0:
stock_text = " [OUT]"
elif stock > 0 and stock != -1:
stock_text = f" [{stock}]"
except:
pass
item_line = f"{marker} {item.name} ({cost_display}){prof_label}{affordable}{stock_text}"
# Color code
if stock_text and "OUT" in stock_text:
self.stdscr.addstr(start_y + 2 + idx, 2, item_line[:cols - 3], curses.color_pair(2))
elif prof_label or affordable:
self.stdscr.addstr(start_y + 2 + idx, 2, item_line[:cols - 3], curses.color_pair(2))
else:
self.stdscr.addstr(start_y + 2 + idx, 2, item_line[:cols - 3])
else:
self.stdscr.addstr(start_y + 2, 2, "No items available")
self.draw_footer("[↑/↓] Navigate [Enter] Buy [Esc] Back", lines, cols)
except curses.error:
pass
def _get_sell_items_list(self, character):
"""Get consistent list of items available for sale from inventory"""
return [item for item in character.inventory if item]
def draw_sell_items(self, lines: int, cols: int, character):
"""Draw sell items menu - matches main.py logic"""
try:
self.draw_header(f"SELL ITEMS - {character.name}", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, f"Gold: {character.gold}GP", curses.A_BOLD)
# Get character inventory using helper
inventory_items = self._get_sell_items_list(character)
if inventory_items:
display_start = max(0, self.sell_cursor - 10)
for idx, item in enumerate(inventory_items[display_start:display_start + 15]):
actual_idx = display_start + idx
marker = '►' if actual_idx == self.sell_cursor else ' '
# Check proficiency (like main.py line 1310)
# Already imported at top: from dnd_5e_core.equipment import Weapon, Armor
prof_label = " [NOT PROF]" if isinstance(item, Weapon) and hasattr(character, 'prof_weapons') and item not in character.prof_weapons else ""
# Check equipped (like main.py line 1311)
equipped_label = " (Equipped)" if (isinstance(item, Weapon) or isinstance(item, Armor)) and hasattr(item, 'equipped') and item.equipped else ""
# Handle different cost types (like main.py line 1312-1313)
# Already imported at top: from dnd_5e_core.equipment import Cost
if hasattr(item, 'cost'):
if isinstance(item.cost, Cost):
cost = str(item.cost)
elif isinstance(item.cost, dict):
cost = f"{item.cost.get('quantity', '?')} {item.cost.get('unit', 'gp')}"
else:
cost = f"{item.cost} gp"
else:
cost = "?? gp"
item_line = f"{marker} {item.name} ({cost}){equipped_label}{prof_label}"
# Color code if equipped or not proficient
if equipped_label:
self.stdscr.addstr(start_y + 2 + idx, 2, item_line[:cols - 3], curses.color_pair(3)) # Yellow
elif prof_label:
self.stdscr.addstr(start_y + 2 + idx, 2, item_line[:cols - 3], curses.color_pair(2)) # Red
else:
self.stdscr.addstr(start_y + 2 + idx, 2, item_line[:cols - 3])
else:
self.stdscr.addstr(start_y + 2, 2, "No items in inventory")
self.draw_footer("[↑/↓] Navigate [Enter] Sell [Esc] Back", lines, cols)
except curses.error:
pass
def draw_cheat_menu(self, lines: int, cols: int):
"""Draw cheat menu for debugging/testing"""
try:
self.draw_header("CHEAT MENU", lines, cols)
start_y = 4
self.stdscr.addstr(start_y, 2, "⚠️ Developer Tools - Use with Caution ⚠️", curses.A_BOLD | curses.color_pair(3))
options = ["Revive All Dead Characters", "Full Heal All Characters", "Add 1000 Gold to All Characters", "Level Up All Characters", "Return to Main Menu"]
start_y += 3
for idx, opt in enumerate(options):
marker = '►' if idx == self.cheat_cursor else ' '
self.stdscr.addstr(start_y + idx, 4, f"{marker} {opt}")
# Show current party/roster status
status_y = start_y + len(options) + 2
if self.party: