-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdungeon_pygame.py
More file actions
2823 lines (2417 loc) · 110 KB
/
dungeon_pygame.py
File metadata and controls
2823 lines (2417 loc) · 110 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
# Définition des constantes pour la mise en page
# SCREEN_WIDTH, SCREEN_HEIGHT = 1920, 1080
from __future__ import annotations
import math
import os
import pickle
import re
import sys
import time
from copy import copy
from dataclasses import dataclass
from pathlib import Path
from random import choice, randint
from typing import List, Optional, Tuple
import pygame
from pygame import Surface
# ============================================
# 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, Monster, Sprite
from dnd_5e_core.equipment import Weapon, Armor, HealingPotion, Equipment, SpeedPotion, Potion, StrengthPotion
from dnd_5e_core.spells import Spell
from dnd_5e_core.classes import Level
from dnd_5e_core.combat import SpecialAbility, ActionType, Action
from dnd_5e_core.mechanics import DamageDice
from dnd_5e_core.ui import cprint, Color, color
# Import pygame-specific wrappers from game_entity
from game_entity import (GameEntity, GameMonster, GameItem, create_game_monster, create_game_character, create_game_weapon, create_dungeon_monster, create_dungeon_item, GameCharacter)
# Note: Data directory is now in dnd-5e-core/data and will be auto-detected
# Import Treasure (not in dnd-5e-core yet, keep from dao_classes for now)
try:
from dao_classes import Treasure
except ImportError:
# Fallback: simple Treasure class
@dataclass
class Treasure:
x: int
y: int
item: object = None
from algo.brehensam import in_view_range
from algo.lee import parcours_largeur, parcours_a_star
# Import from persistence module
from persistence import get_roster, save_character, load_character
# Import D&D 5e rules from package
from dnd_5e_core.mechanics import XP_LEVELS
# Import populate functions
# Import data loaders from dnd-5e-core (note: they're called request_* not load_*)
from dnd_5e_core.data.loaders import request_monster
from dnd_5e_core.data import load_weapon, load_armor, load_spell, load_equipment
# Import legacy functions still needed
from populate_functions import request_armor, request_weapon, request_spell, populate, request_monster_other
print("✅ [MIGRATION v2] dungeon_pygame.py - Using dnd-5e-core package")
print()
# Compatibility alias
load_xp_levels = lambda: XP_LEVELS
from populate_rpg_functions import load_potions_collections, load_weapon_image_name, load_armor_image_name, load_potion_image_name
from tools.cell_bits_dnd import DOORSPACE, TRAPPED, STAIR_UP, STAIR_DN
from tools.common import generate_cave, generate_dungeon, GREEN, resource_path, get_save_game_path, read, MAX_LEVELS
from tools.parse_json_dungeon import parse_dungeon_json
from tools import cell_bits_dnd as cb
from tools.parsing_json_monsters import get_monster_counts
print("✅ [MIGRATION v2] dungeon_pygame.py - Using dnd-5e-core package")
print()
SCREEN_WIDTH, SCREEN_HEIGHT = 1280, 720
STATS_WIDTH, ACTIONS_HEIGHT = 600, 200
STATS_HEIGHT = 250
# Paramètres de la map
UNIT_SIZE = 5
JSON_UNIT_SIZE = 10
# Paramètres de l'écran
TILE_SIZE = 32
FPS = 60
# Autres paramètres
ICON_SIZE = 32
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (200, 200, 200)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
PINK = (255, 0, 255)
ORANGE = (255, 165, 0)
# Directions
UP, DOWN, LEFT, RIGHT = (0, -1), (0, 1), (-1, 0), (1, 0)
DIRECTIONS = [UP, DOWN, LEFT, RIGHT]
ROUND_DURATION = 6 # Duration of a round in seconds
# Global variables
room_no = 0
screen = None # Will be initialized in main_game_loop
def put_inlay(image: pygame.Surface, number: int, center=False, color=WHITE):
# Police pour le texte
font = pygame.font.Font(None, 18)
# Créer la surface du texte
text_surface = font.render(str(number), True, color)
# Définir la position du texte sur l'image (par exemple, en bas à droite)
text_rect = text_surface.get_rect()
if center:
text_rect.center = image.get_rect().center
else:
text_rect.topleft = image.get_rect().topleft
# Ajouter le texte sur l'image
image.blit(text_surface, text_rect)
# Définition de la fonction pour afficher une info-bulle
def draw_tooltip(description, surface, x, y):
font = pygame.font.Font(None, 18)
text = font.render(description, True, BLACK)
text_rect = text.get_rect()
text_rect.topleft = (x, y)
# Créer une surface pour le rectangle d'arrière-plan
tooltip_surface = pygame.Surface((text_rect.width + 10, text_rect.height + 10), pygame.SRCALPHA) # SRCALPHA pour la transparence
tooltip_surface.fill((150, 150, 150, 150)) # Remplir avec une couleur grise semi-transparente
# Dessiner le texte sur la surface d'arrière-plan
tooltip_surface.blit(text, (5, 5)) # Décalage de 5 pixels pour laisser un espace
# Dessiner la surface d'arrière-plan sur l'écran principal
surface.blit(tooltip_surface, (text_rect.left - 5, text_rect.top - 5)) # Décalage de 5 pixels pour centrer le texte dans le rectangle
@dataclass
class Room:
id: int
x: int
y: int
w: int
h: int
inhabited: bool
features: str
monsters: List[GameMonster]
treasure: Optional[Treasure] = None
def __repr__(self):
x, y, X, Y = self.x, self.y, self.x + self.w // JSON_UNIT_SIZE - 1, self.y + self.h // JSON_UNIT_SIZE - 1
desc: str = f'Room #{self.hero.id} - start: {(x, y)} - end: {(X, Y)} - area: {self.area}\n'
if self.features:
desc += f'Features: {self.features}\n' if self.features else 'Nothing special in this room'
if self.monsters:
desc += f'{len(self.monsters)} monsters: {[monster.name for monster in self.monsters]}\n'
if self.treasure:
desc += f'Treasure: {self.treasure.gold} gp and 1 item\n'
return desc
@property
def inner_positions(self):
return [(x, y) for x in range(self.x, self.x + self.w // JSON_UNIT_SIZE) for y in range(self.y, self.y + self.h // JSON_UNIT_SIZE)]
@property
def area(self):
return self.w * self.h
class Level:
level_no: int
world_map: List[List[int]]
map_height: int
map_width: int
monsters: List[Monster]
treasures: List[Treasure]
fountains: List[Sprite]
items: List[Equipment | HealingPotion]
cells_count: int
explored_tiles: set[tuple]
visible_tiles: set[tuple]
doors: dict
fullname: str
rooms: List[Room]
start_pos: tuple
wandering_monsters: List[dict] = []
def __init__(self, level_no: int, name: str = ''):
self.level_no = level_no
self.monsters = []
self.fountains = []
self.world_map, self.cells_count, self.doors, self.fullname, self.rooms, self.start_pos = self.load_maze(level=level_no)
self.map_height = len(self.world_map)
self.map_width = max([len(self.world_map[i]) for i in range(self.map_height)])
self.items = []
self.explored_tiles = set()
self.visible_tiles = set()
self.treasures = []
def room_at(self, pos: tuple) -> Optional[Room]:
for room in self.rooms:
if room and pos in room.inner_positions:
return room
return None
def is_stair(self, x, y):
return self.world_map[y][x] in ['<', '>']
def load_maze(self, level: int) -> tuple[list[str] | list[list[str]], int, dict, str, list[Room], tuple | None]:
"""
Charge le labyrinthe depuis le fichier level.txt
nom : nom du fichier contenant le labyrinthe (sans l’extension .txt)
Valeur de retour :
- un tuple avec les données du labyrinthe (maze, n_cells, doors, level_fullname, rooms, hero_start_pos)
"""
map_type = 'cave'
map_type = 'dungeon'
map_type = 'dungeon.json'
level_fullname: str = ''
doors: dict = {}
stair_up: tuple = None
stair_down: tuple = None
if map_type == 'cave':
# min_value, max_value = (level - 3) * 4, (level - 3) * 8
min_value, max_value = (level + 1) * 4, (level + 1) * 8
width, height = randint(min_value, max_value), randint(min_value, max_value)
n_cells = (width * height) // 3
maze = generate_cave(width, height, n_cells)
elif map_type == 'dungeon':
min_value, max_value = (level + 1) * 10, (level + 1) * 20
width, height = randint(min_value, max_value), randint(min_value, max_value)
num_chambers = int(math.sqrt(width * height)) // 6
cprint(f'num chambers: {num_chambers}')
maze = generate_dungeon(width, height, num_chambers, 3, 10)
maze = [['.' if cell else '#' for cell in row] for row in maze]
n_cells = sum([row.count('.') for row in maze])
else:
abs_path = os.path.abspath(os.path.dirname(__file__))
abs_project_path = os.path.abspath(os.path.join(abs_path, os.pardir))
dungeon_levels = [f for f in os.listdir(os.path.join(abs_path, 'maze')) if f.endswith(f"{level:02}.json")]
json_filename = choice(dungeon_levels)
pattern = r' \d+\.json'
level_fullname = re.sub(pattern, '', json_filename)
# json_filename = 'dungeon.json' # generated by perl script (room+corridors without extras)
dungeon = parse_dungeon_json(json_filename)
cells = dungeon['cell'] if 'cell' in dungeon else dungeon['cells']
maze = [['.' if cell & cb.OPENSPACE else '#' for cell in row] for row in cells]
width, height = len(maze[0]), len(maze)
if 'door' in dungeon:
doors = {(door['col'], door['row']): False for door in dungeon['door']}
else:
doors = {(x, y): False for x in range(width) for y in range(height) if cells[y][x] & DOORSPACE}
door_traps = [(x, y) for x in range(width) for y in range(height) if cells[y][x] & TRAPPED]
stair_up = [(x, y) for x in range(width) for y in range(height) if cells[y][x] & STAIR_UP][0]
stair_down = [(x, y) for x in range(width) for y in range(height) if cells[y][x] & STAIR_DN][0]
# Parse corridor events
corridor_features = dungeon['corridor_features'] if 'corridor_features' in dungeon else {}
corridor_events: dict = {}
if corridor_features:
for feature_label, feature_detail in corridor_features.items():
for mark in feature_detail['marks']:
x, y = mark['col'], mark['row']
corridor_events[(x, y)] = feature_detail['detail']
# Parse wandering monsters
for monsters_detail in dungeon['wandering_monsters'].values():
monsters_dict = get_monster_counts(text=monsters_detail)
monsters: List[str] = []
for monster_name, monster_count in monsters_dict.items():
for _ in range(monster_count):
monsters.append(monster_name)
self.wandering_monsters += [monsters]
# Parse room events
room_traps: dict = {}
room_door_traps: dict = {}
rooms: List[Room] = []
for i, room in enumerate(dungeon['rooms']):
if room:
inhabited: bool = False
room_features: str = ''
monsters_in_room: dict = {}
if 'contents' in room:
# print(room)
if 'detail' in room['contents']:
details = room['contents']['detail']
if 'trap' in details:
room_traps[i] = details['trap']
if 'room_features' in details:
room_features = details['room_features']
if 'inhabited' in room['contents']:
inhabited: bool = True
monsters_in_room: dict = get_monster_counts(room['contents']['inhabited'])
if 'doors' in room:
for _dir, door_lst in room['doors'].items():
for door in door_lst:
if 'trap' in door:
x, y = door['col'], door['row']
room_door_traps[(x, y)] = door['trap']
monsters: List[Monster] = []
if monsters_in_room:
for monster_name in monsters_in_room:
# Load monster from dnd-5e-core
monster = request_monster(monster_name.lower().replace(' ', '-'))
# If not found, skip
if monster is None:
continue
# Add monster if found
if monster:
monsters.append(monster)
else:
cprint(f'unknown monster {Color.RED}{monster_name}{Color.END}!')
# Note: monsters will be wrapped with GameMonster and added to self.monsters by place_monsters()
room = Room(id=room['id'], inhabited=inhabited, features=room_features, monsters=monsters, x=room['col'], y=room['row'], w=room['width'], h=room['height'])
rooms.append(room)
n_cells = sum([row.count('.') for row in maze])
if not stair_up and not stair_down:
cprint(f'no stair defined in dungeon!')
walkable_cells = [(x, y) for y in range(height) for x in range(width) if maze[y][x] == '.']
stair_up = choice(walkable_cells)
walkable_cells.remove(stair_up)
stair_down = choice(walkable_cells)
hero_start_pos: Optional[tuple] = None
if level > 1:
maze[stair_up[1]][stair_up[0]] = '<'
else:
hero_start_pos: tuple = stair_up
if level < MAX_LEVELS:
maze[stair_down[1]][stair_down[0]] = '>'
return maze, n_cells, doors, level_fullname, rooms, hero_start_pos
def load(self, pos: tuple):
"""
Chargement des entités du donjon (monstres et trésors)
:param level:
:return:
"""
open_positions: List[tuple] = [(x, y) for x in range(self.map_width) for y in range(self.map_height) if self.world_map[y][x] == '.' and (x, y) != pos and (x, y) not in self.doors]
f_x, f_y = choice(open_positions)
f: Sprite = Sprite(id=-1, x=f_x, y=f_y, old_x=f_x, old_y=f_y, image_name='fountain.png')
self.fountains.append(f)
open_positions.remove((f_x, f_y))
for room in self.rooms:
if room and room.inhabited:
room_positions = [(x, y) for x, y in room.inner_positions if (x, y) in open_positions]
self.place_treasure(room, room_positions)
# self.place_monsters(room, room_positions, monster_candidates)
self.place_monsters(room, room_positions)
self.treasures.append(room.treasure)
@property
def walkable_tiles(self):
closed_doors: List[tuple] = [pos for pos, is_open in self.doors.items() if not is_open]
return [(x, y) for y in range(self.map_height) for x in range(self.map_width) if self.world_map[y][x] in ['.', '<', '>'] and (x, y) not in closed_doors]
@property
def obstacles(self):
closed_doors: List[tuple] = [pos for pos, is_open in self.doors.items() if not is_open]
return [(x, y) for y in range(self.map_height) for x in range(self.map_width) if self.world_map[y][x] == '#' or (x, y) in closed_doors]
@property
def carte(self) -> List[List[int]]:
obstacles = [*self.obstacles] # + [(e.x, e.y) for e in enemies if e != enemy]
carte = [[1] * self.map_width for _ in range(self.map_height)]
for y in range(self.map_height):
for x in range(self.map_width):
if (x, y) in obstacles:
carte[y][x] = 0
return carte
def place_treasure(self, room: Room, room_positions: List[tuple]):
# print(f'room {room.id}: {len(room_positions)} positions - area: {room.area}')
gold: int = randint(50, 300) * self.level_no
has_item: bool = randint(1, 3) == 2
# print(room)
t_x, t_y = choice(room_positions)
room_positions.remove((t_x, t_y))
room.treasure = Treasure(id=-1, x=t_x, y=t_y, old_x=t_x, old_y=t_y, image_name='treasure.png', gold=gold, has_item=has_item)
def place_monsters_old(self, room: Room, room_positions: List[tuple], monster_candidates: List[Monster]):
cr_total: int = 0
monster_room_candidates = list(filter(lambda m: m.challenge_rating <= self.level_no / 4, monster_candidates))
max_monster = room.area // 600
i = 0
while cr_total < self.level_no / 4 and monster_room_candidates and room_positions and i < max_monster:
monster_type: Monster = choice(monster_room_candidates)
m: Monster = request_monster(monster_type.index)
m_x, m_y = choice(room_positions)
monster_id = len(self.monsters) + 1
game_monster: GameMonster = create_dungeon_monster(monster=m, x=m_x, y=m_y, monster_id=monster_id)
room_positions.remove((m_x, m_y))
room.monsters.append(game_monster)
self.monsters.append(m)
cr_total += m.challenge_rating
remaining_cr = self.level_no / 4 - cr_total
monster_room_candidates = list(filter(lambda m: m.challenge_rating <= remaining_cr, monster_candidates))
i += 1
def place_monsters(self, room, room_positions):
"""Place monsters in the room and wrap them with GameMonster for positioning"""
wrapped_monsters = []
monster_id_offset = len(self.monsters)
for i, monster_data in enumerate(room.monsters):
if room_positions:
x, y = choice(room_positions)
room_positions.remove((x, y))
# Check if already a GameMonster (from saved state)
if hasattr(monster_data, 'entity'):
# Already wrapped, just update position
game_monster = monster_data
game_monster.x, game_monster.y = x, y
game_monster.old_x, game_monster.old_y = x, y
else:
# Raw Monster object, wrap it with GameMonster for positioning
monster_id = monster_id_offset + i + 1
game_monster = create_dungeon_monster(monster_data, x=x, y=y, monster_id=monster_id)
wrapped_monsters.append(game_monster)
# Replace room.monsters with wrapped versions
room.monsters = wrapped_monsters
# Add to level.monsters
self.monsters.extend(wrapped_monsters)
def place_monsters_bad(self, room, room_positions):
"""Place monsters in the room and wrap them with GameEntity for positioning"""
for i, monster_data in enumerate(room.monsters):
if room_positions:
x, y = choice(room_positions)
room_positions.remove((x, y))
# Check if already a GameEntity (from saved state)
if hasattr(monster_data, 'entity'):
# Already wrapped, just update position
game_monster = monster_data
game_monster.x, game_monster.y = x, y
game_monster.old_x, game_monster.old_y = x, y
if not hasattr(game_monster, 'id') or game_monster.id == -1:
game_monster.id = len(self.monsters) + 1
else:
# Raw Monster object, wrap it with GameEntity for positioning
monster_id = len(self.monsters) + 1
game_monster = create_dungeon_monster(monster_data, x=x, y=y, monster_id=monster_id)
# Replace pure Monster with GameMonster in room
room.monsters[i] = game_monster
# Add to level monsters (should be GameMonster)
if monster_data in self.monsters:
# Replace with wrapped version
idx = self.monsters.index(monster_data)
self.monsters[idx] = game_monster
else:
self.monsters.append(game_monster)
class Game:
world_map: List[List[int]]
map_width: int
map_height: int
screen_width: int
screen_height: int
view_port_width: int
view_port_height: int
hero: GameCharacter
dungeon_level: int
action_rects: dict
levels: List[Level]
level: Level
school_images: dict
xp_levels: List[int]
timer: int
last_round_time: float
ready_spell: Optional[Spell]
target_pos: tuple
round_no: int
last_combat_round: int
target_pos: Optional[tuple]
def __init__(self, hero: Character | GameCharacter, actions_panel=False, start_level=1):
self.ready_spell = None
self.target_pos = None
self.round_no = 0
self.last_combat_round = 0
self.last_round_time = time.time()
self.timer = 0
# Chargement de la carte
self.actions_panel = actions_panel
self.dungeon_level = start_level
self.level = Level(start_level)
self.levels = [self.level]
self.world_map = self.level.world_map
self.map_height = self.level.map_height
self.map_width = self.level.map_width
self.walls = [(x, y) for y in range(self.map_height) for x in range(self.map_width) if self.world_map[y][x] == '#']
# Redimensionnement de l'écran
self.view_port_width = SCREEN_WIDTH - STATS_WIDTH
self.view_port_height = SCREEN_HEIGHT
self.screen_width = SCREEN_WIDTH
self.screen_height = SCREEN_HEIGHT
self.action_rects = {}
# Initialisation du personnage
open_positions: List[tuple] = [(x, y) for x in range(self.map_width) for y in range(self.map_height) if self.world_map[y][x] == '.']
hero_x, hero_y = self.level.start_pos
open_positions.remove((hero_x, hero_y))
# Convert Character to GameCharacter if necessary
if isinstance(hero, Character):
# Get character image based on class
from main import get_char_image
image_name = get_char_image(hero.class_type) if hasattr(hero, 'class_type') else None
self.hero = create_game_character(hero, x=hero_x, y=hero_y, image_name=image_name, char_id=1)
else:
# Already a GameCharacter, just update position
self.hero = hero
self.hero.x, self.hero.y = hero_x, hero_y
self.hero.old_x, self.hero.old_y = hero_x, hero_y
if self.hero.id == -1:
self.hero.id = 1
# No need to duplicate position - use properties instead
# Position is accessed via game.x/y which redirect to game.hero.x/y
self.level.explored_tiles.add((self.hero.x, self.hero.y))
self.update_visible_tiles()
self.level.load(pos=self.pos)
# Load XP Levels
self.xp_levels = load_xp_levels()
@property
def x(self) -> int:
"""Hero's X position (delegates to hero.x)"""
return self.hero.x
@x.setter
def x(self, value: int):
"""Set hero's X position"""
self.hero.old_x = self.hero.x
self.hero.x = value
@property
def y(self) -> int:
"""Hero's Y position (delegates to hero.y)"""
return self.hero.y
@y.setter
def y(self, value: int):
"""Set hero's Y position"""
self.hero.old_y = self.hero.y
self.hero.y = value
@property
def old_x(self) -> int:
"""Hero's previous X position"""
return self.hero.old_x
@old_x.setter
def old_x(self, value: int):
"""Set hero's previous X position"""
self.hero.old_x = value
@property
def old_y(self) -> int:
"""Hero's previous Y position"""
return self.hero.old_y
@old_y.setter
def old_y(self, value: int):
"""Set hero's previous Y position"""
self.hero.old_y = value
@property
def id(self) -> int:
"""Hero's ID"""
return self.hero.id
@property
def pos(self):
"""Current position as (x, y) tuple"""
return self.hero.x, self.hero.y
@property
def time_elapsed(self):
return self.round_no * ROUND_DURATION
# @property
# def days(self):
# return self.time_elapsed // (24 * 60 * 60)
#
# @property
# def hours(self):
# return (self.time_elapsed % (24 * 60 * 60)) // (60 * 60)
#
# @property
# def minutes(self):
# return (self.time_elapsed % (60 * 60)) // 60
#
# @property
# def seconds(self):
# return self.time_elapsed % 60
#
# @property
# def date_print(self):
# return f'{self.days}j {self.hours}h {self.minutes}m {self.seconds}s'
@property
def gregorian_calendar(self) -> str:
time_elapsed = self.time_elapsed
days = int(time_elapsed // (24 * 60 * 60))
time_elapsed %= (24 * 60 * 60)
hours = int(time_elapsed // (60 * 60))
time_elapsed %= (60 * 60)
minutes = int(time_elapsed // 60)
time_elapsed %= 60
seconds = int(time_elapsed)
return f'{days}j {hours}h {minutes}m {seconds}s'
def load_token_images(self, token_images_dir: str) -> dict:
token_images = {}
for filename in os.listdir(token_images_dir):
monster_name, _ = os.path.splitext(filename)
image_path = os.path.join(token_images_dir, filename)
original_image = pygame.image.load(image_path)
# Resize the image to 280x280 pixels
token_images[monster_name] = pygame.transform.scale(original_image, (105, 105))
return token_images
# Define a method to calculate the view window
def calculate_view_window(self):
view_width = self.view_port_width // TILE_SIZE
view_height = self.view_port_height // TILE_SIZE
viewport_x = max(0, min(self.hero.x - view_width // 2, self.map_width - view_width))
viewport_y = max(0, min(self.hero.y - view_height // 2, self.map_height - view_height))
# Calculate the new view port rectangle
view_port_rect = pygame.Rect(viewport_x * TILE_SIZE, viewport_y * TILE_SIZE, self.view_port_width, self.view_port_height)
# cprint(viewport_x, viewport_y, view_width, view_height, view_port_rect)
return viewport_x, viewport_y, view_width, view_height
def draw_mini_map(self, screen):
"""
Draw a mini-map on a separate surface.
Shows all explored tiles (no fog of war on mini-map for better navigation).
Currently visible tiles are shown brighter than explored-but-not-visible tiles.
"""
# Set the size of the mini-map
mini_map_width = 300
mini_map_height = 250
# Create a new surface for the mini-map
OFFSET_X, OFFSET_Y = SCREEN_WIDTH - STATS_WIDTH + 10, 3 * (SCREEN_HEIGHT // 4) - 80
mini_map_rect = pygame.Rect(OFFSET_X, OFFSET_Y, mini_map_width, mini_map_height)
# Calculate the scale factor to fit the map onto the mini-map
scale_x = mini_map_width / self.map_width
scale_y = mini_map_height / self.map_height
# Create a new surface for the mini-map
mini_map_surface = pygame.Surface((mini_map_width, mini_map_height))
# Draw the map tiles onto the mini-map surface
for y in range(self.map_height):
for x in range(self.map_width):
# Check if tile has been explored (not visible_tiles, but explored_tiles)
if (x, y) not in self.level.explored_tiles:
# Never explored - draw black
color = BLACK
else:
# Explored tile - determine color based on tile type
tile = self.world_map[y][x]
if tile == '#':
base_color = (128, 128, 128) # Wall color
elif tile in ('<', '>'):
base_color = (0, 0, 255) # Stairs color
elif any(f.pos == (x, y) for f in self.level.fountains):
base_color = (0, 255, 0) # Fountain color
else:
base_color = (64, 64, 64) # Floor color
# If currently visible, show brighter; if just explored, show dimmer
if (x, y) in self.level.visible_tiles:
color = base_color # Full brightness
else:
# Dimmed version (50% brightness) for explored but not currently visible
color = tuple(int(c * 0.5) for c in base_color)
pygame.draw.rect(mini_map_surface, color, (x * scale_x, y * scale_y, scale_x, scale_y))
# Draw the player's position on the mini-map
player_x, player_y = self.hero.x, self.hero.y
pygame.draw.circle(mini_map_surface, RED, (int(player_x * scale_x), int(player_y * scale_y)), 5)
# Draw the treasure positions on the mini-map
for treasure in self.level.treasures:
if treasure.pos not in self.level.explored_tiles:
continue
treasure_x, treasure_y = treasure.x, treasure.y
pygame.draw.circle(mini_map_surface, (255, 255, 0), (int(treasure_x * scale_x), int(treasure_y * scale_y)), 3)
# Blit the mini-map onto the main game screen
screen.blit(mini_map_surface, (OFFSET_X, OFFSET_Y))
return mini_map_surface
def draw_map(self, path, screen):
# Load tile sprites
photo_wall = pygame.image.load(f"{path}/sprites/TilesDungeon/Wall.png")
photo_floor = pygame.image.load(f"{path}/sprites/TilesDungeon/Tile.png")
photo_downstairs = pygame.image.load(f"{path}/sprites/DownStairs.png")
photo_upstairs = pygame.image.load(f"{path}/sprites/UpStairs.png")
photo_door_closed = pygame.image.load(f"{path}/sprites/door_closed_2.png")
photo_door_open = pygame.image.load(f"{path}/sprites/door_open_2.png")
# Calculate the view window
view_x, view_y, view_width, view_height = self.calculate_view_window()
# Debug counters
visible_count = 0
explored_count = 0
unknown_count = 0
# Draw only the portion of the map that falls within the view window
for y in range(view_y, view_y + view_height):
for x in range(view_x, view_x + view_width):
tile_x, tile_y = (x - view_x) * TILE_SIZE, (y - view_y) * TILE_SIZE
if (x, y) in self.level.visible_tiles:
visible_count += 1
# Currently visible tiles - full brightness
if self.world_map[y][x] == '#':
screen.blit(photo_wall, (tile_x, tile_y))
elif self.world_map[y][x] == '<':
screen.blit(photo_upstairs, (tile_x, tile_y))
elif self.world_map[y][x] == '>':
screen.blit(photo_downstairs, (tile_x, tile_y))
elif (x, y) in self.level.doors:
# Draw a door tile
photo_door = photo_door_open if self.level.doors[(x, y)] else photo_door_closed
screen.blit(photo_door, (tile_x, tile_y))
elif self.world_map[y][x] == '.':
# Draw floor tile for walkable areas
screen.blit(photo_floor, (tile_x, tile_y))
elif (x, y) in self.level.explored_tiles:
explored_count += 1
# Already explored but not currently visible - draw darker version
if self.world_map[y][x] == '#':
# Draw wall darker
dark_wall = photo_wall.copy()
dark_wall.fill((128, 128, 128, 128), special_flags=pygame.BLEND_RGBA_MULT)
screen.blit(dark_wall, (tile_x, tile_y))
elif self.world_map[y][x] == '.':
# Draw floor darker
dark_floor = photo_floor.copy()
dark_floor.fill((128, 128, 128, 128), special_flags=pygame.BLEND_RGBA_MULT)
screen.blit(dark_floor, (tile_x, tile_y))
else:
# For other tiles (stairs, doors), just draw darker gray
screen.fill((50, 50, 50), (tile_x, tile_y, TILE_SIZE, TILE_SIZE))
else:
unknown_count += 1
# Draw a black square for unexplored tiles
screen.fill(BLACK, (tile_x, tile_y, TILE_SIZE, TILE_SIZE))
# Debug only once per second to avoid spam
# import time
# if not hasattr(self, '_last_draw_debug') or time.time() - self._last_draw_debug > 1.0:
# print(f"[DEBUG draw_map] Rendered - visible: {visible_count}, explored: {explored_count}, unknown: {unknown_count}")
# self._last_draw_debug = time.time()
def feet_inches_to_m_cm(self, height_feet: int, height_inches: int) -> tuple[float, float]:
total_inches = height_feet * 12 + height_inches
height_meters = total_inches * 2.54 // 100
height_centimeters = total_inches * 2.54 % 100
return height_meters, height_centimeters
# Fonction pour dessiner la feuille de stats du personnage
def draw_character_stats(self, screen):
stats_rect = pygame.Rect(self.view_port_width, 0, STATS_WIDTH, self.view_port_height)
pygame.draw.rect(screen, GRAY, stats_rect)
font = pygame.font.Font(None, 20)
pygame.display.set_caption(f"Time: {self.gregorian_calendar} - Dungeon Level: {self.dungeon_level} ({self.level.fullname})")
height_feet, height_inches = map(int, self.hero.height.split("'"))
height_meters, height_centimeters = map(round, self.feet_inches_to_m_cm(height_feet, height_inches))
weapon: Weapon = None
armor: Armor = None
for item in self.hero.inventory:
if not item or isinstance(item, Potion):
continue
# Only check equipped for items that can be equipped (weapons/armor)
if hasattr(item, 'equipped') and item.equipped:
if isinstance(item, Weapon):
weapon = item
elif isinstance(item, Armor):
armor = item
ranged_weapon_info: str = f' ({self.hero.weapon.range.normal}")' if self.hero.weapon and self.hero.weapon.range else ''
if not hasattr(self.hero, 'speed'):
self.hero.speed = 25 if self.hero.race.index in ['dwarf', 'halfling', 'gnome'] else 30
# Calculate XP for next level with bounds checking
if self.hero.level < 20 and self.hero.level < len(self.xp_levels):
next_level_xp = self.xp_levels[self.hero.level]
elif self.hero.level > 0 and (self.hero.level - 1) < len(self.xp_levels):
next_level_xp = self.xp_levels[self.hero.level - 1]
else:
next_level_xp = self.hero.xp # Max level or no XP data
stat_texts = [f"Nom: {self.hero.name}", f"Race: {self.hero.race.name}", f"Classe: {self.hero.class_type.name}", f"Niveau: {self.hero.level}", f"XP: {self.hero.xp} / {next_level_xp}", f"Santé: {self.hero.hit_points}/{self.hero.max_hit_points} ({self.hero.status if not self.hero.is_dead else 'DEAD'})", # damage_dice: str = f'{self.hero.weapon.damage_dice}' if not w.damage_dice.bonus else f'{w.damage_dice.dice} + {w.damage_dice.bonus}'
f"Attaque (x{self.hero.multi_attacks}): {weapon.damage_dice.dice}{ranged_weapon_info}" if weapon else f"Attaque: 1d2", # f"Défense: {self.hero.armor.ac}",
f"Défense: {self.hero.armor_class}" if armor else "Défense: 10", f'Déplacement: {self.hero.speed}"', # f"Potions: {self.hero.potions}",
f"Gold: {self.hero.gold}", f"Taille: {height_meters}m{height_centimeters:2d}", f"Poids: {round(int(self.hero.weight.split(' ')[0]) * 0.453592)} kg", f"Age: {self.hero.age // 52}", # Ajoutez d'autres statistiques ici
]
if not hasattr(self.hero, 'st_advantages'): self.hero.st_advantages = []
if hasattr(self.hero, 'haste_timer') and self.hero.hasted:
has_st_advantage = lambda x: f' ** ({math.ceil((60 - (time.time() - self.hero.haste_timer)))}" left)' if x in self.hero.st_advantages else ''
else:
has_st_advantage = lambda x: f' **' if x in self.hero.st_advantages else ''
str_effect_timer = f' ({math.ceil((3600 - (time.time() - self.hero.str_effect_timer)) // 60)}\' left)' if self.hero.str_effect_modifier != -1 else ''
abilities_texts = [f"Force: {self.hero.strength}{has_st_advantage('str')}{str_effect_timer}", f"Dextérité: {self.hero.dexterity}{has_st_advantage('dex')}", f"Constitution: {self.hero.constitution}{has_st_advantage('con')}", f"Intelligence: {self.hero.intelligence}{has_st_advantage('int')}", f"Sagesse: {self.hero.wisdom}{has_st_advantage('wis')}", f"Charisme: {self.hero.charism}{has_st_advantage('cha')}"]
spells_texts = []
if self.hero.is_spell_caster:
slots: str = '/'.join(map(str, self.hero.sc.spell_slots))
spells_texts.append(f"Spell slots: {self.hero.sc.spell_slots[0] if self.hero.class_type.index == 'warlock' else slots}") # known_spells: int = len(self.hero.sc.learned_spells) # learned_spells: List[Spell] = [s for s in self.hero.sc.learned_spells] # learned_spells.sort(key=lambda s: s.level) # for s in learned_spells: # spells_texts.append(f"L{s.level}: {str(s)}")
for i, text in enumerate(stat_texts):
text_surface = font.render(text, True, (0, 0, 0))
text_rect = text_surface.get_rect()
text_rect.topleft = (stats_rect[0] + 20, stats_rect[1] + 20 + i * 20) # Ajuster la position en fonction de la marge
screen.blit(text_surface, text_rect)
for i, text in enumerate(abilities_texts):
text_surface = font.render(text, True, (0, 0, 0))
text_rect = text_surface.get_rect()
text_rect.topleft = (stats_rect[0] + 210, stats_rect[1] + 20 + i * 20) # Ajuster la position en fonction de la marge
screen.blit(text_surface, text_rect)
for i, text in enumerate(spells_texts):
text_surface = font.render(text, True, (0, 0, 0))
text_rect = text_surface.get_rect()
text_rect.topleft = (stats_rect[0] + 210, stats_rect[1] + 150 + i * 20) # Ajuster la position en fonction de la marge
screen.blit(text_surface, text_rect)
def draw_spell_book(self, screen, sprites):
# Obtenir les coordonnées de la souris
mouse_x, mouse_y = pygame.mouse.get_pos()
# Stocker les informations de l'info-bulle
tooltip_text = None
# learned_spells: List[Spell] = [s for s in self.hero.sc.learned_spells]
# learned_spells.sort(key=lambda s: s.level)
max_spell_level: int = max([s.level for s in self.hero.sc.learned_spells])
for i in range(max_spell_level + 1):
spells_by_level = [s for s in self.hero.sc.learned_spells if s.level == i]
for j, spell in enumerate(spells_by_level):
icon_x = self.view_port_width + 210 + j * 40
# icon_y = 204 + 70 + i * 40
icon_y = 170 + i * 40
# spells_texts.append(f"L{s.level}: {str(s)}")
image: Surface = sprites[spell.id].convert_alpha()
put_inlay(image=image, number=spell.level)
# Define the transparency level (0 to 255, 0 = fully transparent, 255 = fully opaque)
transparency_level = 255 if self.hero.sc.spell_slots[i - 1] or spell.is_cantrip else 128
# Set the transparency level of the image
image.set_alpha(transparency_level)
screen.blit(image, (icon_x, icon_y))
# Test if the spell is memorized
if self.ready_spell and self.ready_spell == spell:
# Draw a blue rectangle around the icon
pygame.draw.rect(screen, BLUE, (icon_x - 2, icon_y - 2, ICON_SIZE + 2, ICON_SIZE + 2), 2)
# Vérifier si la souris survole la case
if pygame.Rect(icon_x, icon_y, ICON_SIZE, ICON_SIZE).collidepoint(mouse_x, mouse_y):
# Stocker la description de l'objet pour l'info-bulle
# tooltip_text = f'{spell.name}\n{spell.desc[0]}'
tooltip_text = f'{spell.name} ({spell.range}")'
# Afficher l'info-bulle avec la description du sort
if tooltip_text:
draw_tooltip(tooltip_text, screen, mouse_x + 10, mouse_y)
def draw_inventory(self, screen, sprites):
global item_sprites_dir
# # Afficher le titre de l'inventaire
# draw_text("Inventaire", font, BLACK, screen, 10, 10)
# Obtenir les coordonnées de la souris
mouse_x, mouse_y = pygame.mouse.get_pos()
# Stocker les informations de l'info-bulle
tooltip_text = None
# Afficher les cases de l'inventaire
for i, item in enumerate(self.hero.inventory):
# Calculer les coordonnées de l'image dans la case
icon_x = self.view_port_width + 10 + (i % 5) * 40
icon_y = 214 + 70 + (i // 5) * 40
# Afficher l'icône de l'objet s'il y en a un dans la case
if item is not None:
try:
# Check if item has an id and if it's in sprites dictionary
if not hasattr(item, 'id') or item.id is None:
# Item doesn't have an ID - assign one and create sprite
item.id = max(sprites.keys()) + 1 if sprites else 1
# Create a fallback sprite for this item
item_image_name = get_item_image_name(item)
try:
sprites[item.id] = pygame.image.load(f"{item_sprites_dir}/{item_image_name}").convert_alpha()
except:
# Ultimate fallback - colored square based on item type
fallback_surface = pygame.Surface((ICON_SIZE, ICON_SIZE))
if 'Potion' in item.__class__.__name__:
fallback_surface.fill((255, 0, 255)) # Magenta for potions
elif 'Weapon' in item.__class__.__name__:
fallback_surface.fill((192, 192, 192)) # Silver
elif 'Armor' in item.__class__.__name__:
fallback_surface.fill((139, 69, 19)) # Brown
else:
fallback_surface.fill((255, 255, 0)) # Yellow
sprites[item.id] = fallback_surface
image: Surface = sprites[item.id]
image.set_colorkey(PINK)
screen.blit(image, (icon_x, icon_y))
frame_color: tuple = BLUE if isinstance(item, Armor | Weapon) and item.equipped else WHITE
pygame.draw.rect(screen, frame_color, (icon_x, icon_y, ICON_SIZE, ICON_SIZE), 2)
# Vérifier si la souris survole la case
if pygame.Rect(icon_x, icon_y, ICON_SIZE, ICON_SIZE).collidepoint(mouse_x, mouse_y):
# Stocker la description de l'objet pour l'info-bulle
if isinstance(item, Armor):
tooltip_text = f"{item.name} (AC {item.armor_class['base']})"
elif isinstance(item, Weapon):
tooltip_text = f"{item.name} ({item.damage_dice.dice})"
elif isinstance(item, HealingPotion):
tooltip_text = f"{item.name} ({item.hit_dice})"
elif isinstance(item, SpeedPotion):
tooltip_text = f"{item.name} ({item.duration} s)"
elif isinstance(item, StrengthPotion):
tooltip_text = f"{item.name} {item.value} ({item.duration // 60} min)"
else:
tooltip_text = f'{item.name}'
except KeyError as e:
# Log the error for debugging
print(f"Warning: Item {item.name if hasattr(item, 'name') else 'unknown'} with ID {item.id if hasattr(item, 'id') else 'None'} not found in sprites dictionary")
except Exception as e:
print(f"Error displaying item: {e}")
# Dessiner un cadre vide pour les cases vides
else:
pygame.draw.rect(screen, GRAY, (icon_x, icon_y, ICON_SIZE, ICON_SIZE), 2)
# Afficher l'info-bulle avec la description de l'objet
if tooltip_text:
draw_tooltip(tooltip_text, screen, mouse_x + 10, mouse_y)
# Fonction pour dessiner le panneau de commande d'actions
def draw_action_panel(self, screen):
""" left: La position horizontale du coin supérieur gauche du rectangle.
top: La position verticale du coin supérieur gauche du rectangle.
width: La largeur du rectangle.
height: La hauteur du rectangle.
"""
# actions_rect = pygame.Rect(0, self.map_height * TILE_SIZE, self.screen_width, ACTIONS_HEIGHT)
actions_rect = pygame.Rect(0, self.view_port_height, self.screen_width, ACTIONS_HEIGHT)
left, top, width, height = actions_rect
pygame.draw.rect(screen, (200, 200, 200), actions_rect)
# left, top, width, height = MAP_HEIGHT, 0, STATS_WIDTH, 300
# pygame.draw.rect(screen, (200, 200, 200), (left, top, width, height)) # Fond du panneau d'actions
font = pygame.font.Font(None, 24)
action_texts = ["Attaquer", "Utiliser objet", "Sorts", "Inventaire"# Ajoutez d'autres actions ici
]
action_count = len(action_texts)
action_height = height // action_count # Calcul de la hauteur de chaque action
for i, action_text in enumerate(action_texts):
text_surface = font.render(action_text, True, (0, 0, 0))
text_rect = text_surface.get_rect()
text_rect.center = (left + width // 2, top + i * action_height + action_height // 2)
# Définir les marges intérieures
margin_x = 10
margin_y = 5
# Calculer les nouvelles coordonnées du rectangle pour centrer les marges intérieures