-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
2423 lines (1993 loc) · 102 KB
/
Copy pathmain.py
File metadata and controls
2423 lines (1993 loc) · 102 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
# ====================================================================================
# PyCAPGE - Python Classic Adventure Point and Click Game Engine v-1.0 by Garba
# ====================================================================================
# main.py - 2 enero 2026
import pygame
import sys
import os
import math
import heapq
import warnings
import gc
import json
import datetime
import yaml
# --- NUEVOS IMPORTS ---
from config import CONFIG, PLAYER_CONFIG, CHAR_DEFS, CREDITS_TEXT, TEXT_CONFIG, UI_FONT_PATH, UI_HEIGHT, GAME_AREA_HEIGHT, GLOBAL_STATE, SOUNDS
from config import ITEM_NAMES, OBJ_DESCS, SCENE_NAMES, GAME_MSGS, MENU_TEXTS, TITLE_TEXTS, VERBS_LOCALIZED, CINE_TEXTS, DIALOGUE_TEXTS, VERB_KEYS
# Importar desde carpetas
from scenes.variables import GAME_STATE, GameState # Ahora está en scenes/
from scenes.intro import IntroManager # Ahora está en scenes/
from scenes.ending import EndingManager # Ahora está en scenes/
import scenes.scenes as scenes # Importamos el módulo scenes dentro de la carpeta scenes
from engine.resources import RES_MANAGER
from engine.classes import (
TRANSITION_FADE, TRANSITION_SLIDE_LEFT, TRANSITION_SLIDE_RIGHT,
TRANSITION_SLIDE_UP, TRANSITION_SLIDE_DOWN, TRANSITION_ZOOM, TRANSITION_NONE,
AnimatedHotspot, AnimatedCharacter, SceneManager, DialogueSystem,
TitleMenu, SaveLoadUI, LanguageUI, SystemMenu, TextBox, VerbMenu,
Inventory, DebugConsole, CreditsWindow, MapSystem, Movement, CutsceneManager, update_graphics_metrics, get_sharp_font, draw_text_sharp
)
globals().update(CONFIG) # Esto inyecta automáticamente todo el diccionario en el ámbito global del archivo. Perdon a los puristas.
# Ignorar advertencias
warnings.filterwarnings("ignore", category=UserWarning, module="pygame")
# ==========================================
# CARGA DEL DICCIONARIO GLOBAL
# ==========================================
def load_translations(filename="es.yaml"):
# Construimos la ruta completa: carpeta "languages" + nombre de archivo
full_path = os.path.join("languages", filename)
try:
with open(full_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
except Exception as e:
print(f"[CRITICAL ERROR] Could not load translation {full_path}: {e}")
sys.exit() # Cerramos el juego si no hay textos
# ==========================================
# GESTOR DE CAMBIO DE IDIOMA
# ==========================================
CURRENT_LANG_FILE = "es.yaml" # Variable para saber cuál tenemos cargado
# EN main.py
def reload_game_texts(filename):
global CURRENT_LANG_FILE, VERB_KEYS
# 1. Cargar datos
data = load_translations(filename)
CURRENT_LANG_FILE = filename
# 2. Actualizar diccionarios globales (Referencia directa a config.py)
ITEM_NAMES.clear(); ITEM_NAMES.update(data["items"])
OBJ_DESCS.clear(); OBJ_DESCS.update(data["descriptions"])
SCENE_NAMES.clear(); SCENE_NAMES.update(data["scenes"])
GAME_MSGS.clear(); GAME_MSGS.update(data["system_messages"])
VERBS_LOCALIZED.clear(); VERBS_LOCALIZED.update(data["verbs"])
MENU_TEXTS.clear(); MENU_TEXTS.update(data["menus"])
TITLE_TEXTS.clear(); TITLE_TEXTS.update(data["titles"])
CINE_TEXTS.clear(); CINE_TEXTS.update(data["cinematics"])
DIALOGUE_TEXTS.clear(); DIALOGUE_TEXTS.update(data.get("dialogues", {}))
GAME_MSGS["VERB_USE"] = VERBS_LOCALIZED.get("USE", "USE")
VERB_KEYS = list(VERBS_LOCALIZED.keys())
GLOBAL_STATE["current_lang_file"] = filename
print(f"[SYSTEM] Language changed to: {filename}")
# 3. ACTUALIZAR OBJETOS VIVOS (Usando métodos refresh)
# Menu Sistema (F2)
if 'system_menu' in globals() and system_menu:
system_menu.refresh_texts() # <--- MÉTODO NUEVO EFICIENTE
# Menu Título
if 'title_menu' in globals() and title_menu:
title_menu.refresh_texts()
# Verbos
if 'verb_menu' in globals() and verb_menu:
verb_menu.refresh_verbs()
verb_menu.clear_selection()
# Mapa
if 'map_system' in globals() and map_system:
map_system.refresh_map_labels()
# Escena Actual
if 'scene_manager' in globals() and scene_manager.current_scene:
current_s = scene_manager.current_scene
# Nombre escena
if current_s.id in SCENE_NAMES: current_s.name = SCENE_NAMES[current_s.id]
# Hotspots
for hs in current_s.hotspots.hotspots:
if hasattr(hs, 'label_id') and hs.label_id in ITEM_NAMES: hs.label = ITEM_NAMES[hs.label_id]
elif hs.name in ITEM_NAMES: hs.label = ITEM_NAMES[hs.name]
# Ambientales
for anim in current_s.ambient_anims:
if hasattr(anim, 'label_id') and anim.label_id in ITEM_NAMES: anim.label = ITEM_NAMES[anim.label_id]
# Inventario
if 'inventory' in globals() and inventory:
for item in inventory.items:
if item.label_id and item.label_id in ITEM_NAMES: item.name = ITEM_NAMES[item.label_id]
elif item.id in ITEM_NAMES: item.name = ITEM_NAMES[item.id]
inventory.update_visible()
# --- MODIFICACIÓN DEL INICIO TEXTOS DINÁMICOS---
reload_game_texts("es.yaml")
# Variables Globales de UI y Sistema
TEXT_DISPLAY_TIMER = 0
INFO_TEXT_TIMER = 0
SCREEN_OVERLAY_TEXT = ""
CURRENT_CURSOR_STATE = "WALK"
CURRENT_ACTION_ANIM = None
MUSIC_STOP_TIME = 0.0
LAST_EXIT_CLICK_TIME = 0 # --- NUEVO: Variable para el doble clic ---
DOUBLE_CLICK_THRESHOLD = 400 # Milisegundos para considerar doble clic
# ==========================================
# GESTOR DE RECURSOS PRE-CACHE
# ==========================================
# enviado a otro fichero
# Variable para saber QUIÉN está hablando (objeto o None para narrador)
CURRENT_SPEAKER_REF = None
CURRENT_TEXT_POS = None
# ==========================================
# GUARDAR PARTIDAS
# ==========================================
SAVE_FILE_NAME = "savegame.json"
SAVE_GAME_DIR = "games"
# ==========================================
# CONFIGURACIÓN DE DIÁLOGOS
# ==========================================
DIALOGUE_STYLE = {
"BG_COLOR": (0, 0, 0),
"TEXT_COLOR": (170, 170, 170),
"HIGHLIGHT_COLOR": (255, 255, 85),
"CHOSEN_COLOR": (100, 100, 100),
"FONT_SIZE": 26,
"LINE_SPACING": 30,
"MAX_LINES": 4,
"MARGIN_LEFT": 20,
"MARGIN_TOP": 15,
"AREA_Y": GAME_AREA_HEIGHT,
"AREA_HEIGHT": UI_HEIGHT,
# --- NUEVA CONFIGURACIÓN DE FLECHAS (GLOBAL) ---
"SCROLL_BTN_SIZE": 30, # Tamaño del cuadrado del botón
"SCROLL_X_MARGIN": 50, # Distancia desde el borde derecho de la pantalla
"SCROLL_Y_OFFSET": 20, # Separación vertical entre las flechas
# Colores estilo SCUMM (Igual que el inventario)
"BTN_BG": (68, 68, 68), # Gris Fondo
"BTN_BORDER_LIGHT": (102, 102, 102), # Borde luz (Arriba/Izq)
"BTN_BORDER_DARK": (34, 34, 34), # Borde sombra (Abajo/Der)
"ARROW_COLOR": (255, 255, 170) # Amarillo pálido
}
# ==========================================
# INICIALIZACIÓN Y SONIDOS
# ==========================================
pygame.init()
# 1. La Ventana Real (El marco de Windows) -> Usa WINDOW_WIDTH / HEIGHT
# muy borroso pero rapido con : window_flags = pygame.RESIZABLE | pygame.SCALED
window_flags = pygame.RESIZABLE
real_window = pygame.display.set_mode((CONFIG["WINDOW_WIDTH"], CONFIG["WINDOW_HEIGHT"]), window_flags)
pygame.display.set_caption("PyCAPGE - Python Classic Adventure Point and Click Game Engine by Garba")
# =====================================================
# PANTALLA DE CARGA
# =====================================================
# Creamos una fuente temporal básica del sistema
loading_font = pygame.font.SysFont(None, 20)
loading_text = loading_font.render("Loading ...", True, (200, 200, 200)) # Gris clarito
real_window.fill((0, 0, 0)) # Limpiamos en negro
text_x = CONFIG["WINDOW_WIDTH"] // 2 - loading_text.get_width() // 2
text_y = CONFIG["WINDOW_HEIGHT"] // 2
real_window.blit(loading_text, (text_x, text_y))
# ¡IMPORTANTE! Forzamos la actualización de la pantalla AHORA MISMO
pygame.display.flip()
# 2. El Lienzo Virtual (Tu juego interno) -> Usa GAME_WIDTH / HEIGHT
# AQUÍ ESTABA EL ERROR ANTES, ahora ya existe la clave correcta.
screen = pygame.Surface((CONFIG["GAME_WIDTH"], CONFIG["GAME_HEIGHT"]))
clock = pygame.time.Clock()
# Variables para gestionar el escalado del ratón
scale_factor = 1.0
offset_x = 0
offset_y = 0
# --- GESTOR DE SONIDOS GLOBAL ---
if CONFIG["ENABLE_SOUND"]:
try:
if not pygame.mixer.get_init(): pygame.mixer.init()
# --- SONIDOS DE PASOS ---
step_types = {
"step": "step.ogg",
"step_wood": "step_wood.ogg",
"step_grass": "step_grass.ogg",
"step_rug": "step_rug.ogg"
}
for key, filename in step_types.items():
path = os.path.join("snd", filename)
if os.path.exists(path):
s = pygame.mixer.Sound(path)
s.set_volume(0.4) # Volumen de pasos
SOUNDS[key] = s # AHORA ESTO FUNCIONARÁ PORQUE SOUNDS YA EXISTE
else:
# Fallback: Si falta uno específico, usamos el default si existe
if key != "step" and "step" in SOUNDS:
SOUNDS[key] = SOUNDS["step"]
else:
print(f"[WARNING] Missing sound: {filename}")
# --- OTROS SONIDOS ---
medal_path = os.path.join("snd", "medal.ogg")
if os.path.exists(medal_path):
SOUNDS["medal"] = pygame.mixer.Sound(medal_path)
SOUNDS["medal"].set_volume(0.5)
# Añade aquí el resto de sonidos puntuales (church-bell, etc)...
except Exception as e:
print(f"[ERROR] Loading sounds: {e}")
# ==========================================
# NUEVAS FUNCIONES DE MÚSICA DE ESCENA
# ==========================================
def play_scene_music(music_file_name, duration_s=0.0, volume=1.0, loops=None):
"""Carga y reproduce una canción de fondo (BGM).
duration_s (float): Tiempo en segundos que debe sonar. 0.0 para reproducir indefinidamente.
volume (float): Volumen (0.0 a 1.0).
loops (int, opcional): -1 para infinito, 0 para una vez. Si es None, se calcula automático.
"""
global MUSIC_STOP_TIME
if not CONFIG["ENABLE_SOUND"]:
return
# Detener cualquier música actual
pygame.mixer.music.stop()
# 1. Ajustar el volumen
pygame.mixer.music.set_volume(max(0.0, min(1.0, volume)))
music_path = os.path.join("snd", music_file_name)
if os.path.exists(music_path):
try:
pygame.mixer.music.load(music_path)
# 2. DETERMINAR LOOPS
# Si pasamos el argumento 'loops' manualmente, lo usamos.
# Si no, usamos la lógica antigua (duración 0 = infinito).
if loops is not None:
final_loops = loops
else:
final_loops = -1 if duration_s <= 0 else 0
pygame.mixer.music.play(final_loops)
# 3. Configurar el temporizador
if duration_s > 0:
current_time_s = pygame.time.get_ticks() / 1000.0
MUSIC_STOP_TIME = current_time_s + duration_s
else:
MUSIC_STOP_TIME = 0.0
debug_log(f"[MUSIC] Playing: {music_file_name} (Vol: {volume}, Loops: {final_loops})")
except pygame.error as e:
print(f"[ERROR] Could not play music {music_file_name}: {e}")
else:
print(f"[ERROR] Music file not found: {music_path}")
def stop_scene_music():
"""Detiene la música de fondo y resetea el temporizador global."""
global MUSIC_STOP_TIME
if pygame.mixer.music.get_busy():
pygame.mixer.music.stop()
debug_log("[MUSIC] Background music stopped.")
MUSIC_STOP_TIME = 0.0
# ==========================================
# HERRAMIENTAS DE DEBUG
# ==========================================
def draw_debug_overlay(screen, scene, character, movement):
if not CONFIG["DEBUG_MODE"]: return
font = pygame.font.Font(UI_FONT_PATH, 12)
overlay = pygame.Surface((CONFIG["GAME_WIDTH"], CONFIG["GAME_HEIGHT"]), pygame.SRCALPHA)
cam_x = scene.camera_x
# ---------------------------------------------------------
# 1. ELEMENTOS VISIBLES EN AMBOS MODOS
# ---------------------------------------------------------
# A) DIBUJAR SALIDAS (ROJO)
for exit_zone in scene.exits:
screen_rect = exit_zone.rect.copy()
screen_rect.x -= cam_x
if not CONFIG["SHOW_HINTS_ONLY"]:
pygame.draw.rect(overlay, (255, 0, 0, 60), screen_rect)
pygame.draw.rect(overlay, (255, 0, 0), screen_rect, 2)
if not CONFIG["SHOW_HINTS_ONLY"]:
txt = font.render(f"EXIT -> {exit_zone.target_scene}", True, (255, 255, 255))
overlay.blit(txt, (screen_rect.x, screen_rect.y - 15))
# B) DIBUJAR HOTSPOTS (CYAN)
for hs in scene.hotspots.hotspots:
screen_rect = hs.rect.copy()
screen_rect.x -= cam_x
if screen.get_rect().colliderect(screen_rect):
if not CONFIG["SHOW_HINTS_ONLY"]:
pygame.draw.rect(overlay, (0, 255, 255, 60), screen_rect)
pygame.draw.rect(overlay, (0, 255, 255), screen_rect, 2)
label_text = hs.label if CONFIG["SHOW_HINTS_ONLY"] else f"ID: {hs.name}"
txt = font.render(label_text, True, (0, 255, 255))
overlay.blit(txt, (screen_rect.x, screen_rect.y - 15))
# ---------------------------------------------------------
# 2. ELEMENTOS SOLO VISIBLES EN DEBUG COMPLETO
# ---------------------------------------------------------
if not CONFIG["SHOW_HINTS_ONLY"]:
# --- NUEVO: DIBUJAR AMBIENT ANIMATIONS (ROSA) ---
# Esto te permitirá ver la colisión sólida que hemos arreglado
if hasattr(scene, 'ambient_anims'):
for anim in scene.ambient_anims:
screen_rect = anim.rect.copy()
screen_rect.x -= cam_x
# Si es sólido, pintamos la caja de colisión calculada (aprox)
if anim.solid:
# Simulamos el inflate(0, -4) visualmente
col_rect = screen_rect.inflate(0, -4)
pygame.draw.rect(overlay, (255, 0, 255, 60), col_rect) # Relleno
pygame.draw.rect(overlay, (255, 0, 255), col_rect, 2) # Borde
txt = font.render(f"SOLID AMBIENT", True, (255, 0, 255))
overlay.blit(txt, (col_rect.x, col_rect.y - 15))
# C) CAMINO (AMARILLO)
if movement.path and len(movement.path) > 0:
char_screen_center = (character.rect.centerx - cam_x, character.rect.bottom)
points = [char_screen_center]
for p in movement.path:
points.append((p[0] - cam_x, p[1]))
if len(points) > 1:
pygame.draw.lines(overlay, (255, 255, 0), False, points, 3)
for p in points:
pygame.draw.circle(overlay, (255, 255, 0), p, 3)
# D) RECTANGULO DEL PERSONAJE (VERDE)
char_screen_rect = character.rect.copy()
char_screen_rect.x -= cam_x
pygame.draw.rect(overlay, (0, 255, 0), char_screen_rect, 1)
# E) MOUSE Y SUELO
screen_mx, screen_my = get_virtual_mouse_pos()
world_mx = screen_mx + cam_x
walkable = scene.walkable_area.is_walkable(world_mx, screen_my)
color = (0, 255, 0) if walkable else (255, 0, 0)
pygame.draw.circle(overlay, color, (screen_mx, screen_my), 5)
coord_text = font.render(f"X: {int(world_mx)} | Y: {screen_my}", True, (255, 255, 0))
pygame.draw.rect(overlay, (0, 0, 0, 180), (screen_mx + 10, screen_my - 25, coord_text.get_width() + 6, 18))
overlay.blit(coord_text, (screen_mx + 13, screen_my - 24))
# F) HUD SUPERIOR
info_str = f"FPS:{int(clock.get_fps())} | CAM_X:{int(cam_x)}"
debug_txt = font.render(info_str, True, (255, 255, 0))
pygame.draw.rect(screen, (0,0,0), (0, 0, CONFIG["GAME_WIDTH"], 20))
screen.blit(debug_txt, (10, 3))
screen.blit(overlay, (0,0))
# ==========================================
# FUNCIONES DE AYUDA Y DEBUG
# ==========================================
def enable_debug():
"""Activa el modo Debug completo (Técnico)"""
CONFIG["DEBUG_MODE"] = True
CONFIG["SHOW_HINTS_ONLY"] = False # Muestra TODO
debug_log("Debug Mode: ON (FULL)")
def enable_game_help():
"""Activa solo las ayudas visuales (Hotspots)"""
CONFIG["DEBUG_MODE"] = True
CONFIG["SHOW_HINTS_ONLY"] = True # Solo muestra Hotspots/Salidas
debug_log("Game Help: ON (HINTS ONLY)")
# ==========================================
# 1. UTILIDADES Y CURSOR
# ==========================================
# a tomar por culo
pygame.mouse.set_visible(False)
CURSOR_IMGS = {}
def init_cursor():
pygame.mouse.set_visible(False)
load_cursor_images()
def load_cursor_images():
cursor_files = {
"WALK": ("m_walk.gif", "m_walk2.gif"),
"LOOK AT": ("m_look.gif", "m_look2.gif"),
"TALK TO": ("m_talk.gif", "m_talk2.gif"),
"PICK UP": ("m_take.gif", "m_take2.gif"),
"GIVE": ("m_take.gif", "m_take2.gif"),
"USE": ("m_use.gif", "m_use2.gif"),
"OPEN": ("m_use.gif", "m_use2.gif"),
"CLOSE": ("m_use.gif", "m_use2.gif"),
"PUSH": ("m_use.gif", "m_use2.gif"),
"PULL": ("m_use.gif", "m_use2.gif"),
"DEFAULT": ("m_triangle.gif", "m_triangle.gif")
}
debug_log("--- LOADING CURSORS ---")
for verb, (file_normal, file_active) in cursor_files.items():
path_norm = os.path.join("cursor", file_normal)
path_act = os.path.join("cursor", file_active)
try:
imgs = []
if os.path.exists(path_norm):
imgs.append(pygame.image.load(path_norm).convert_alpha())
else:
print(f"[ERROR] Missing normal cursor: {file_normal}")
continue
if os.path.exists(path_act):
imgs.append(pygame.image.load(path_act).convert_alpha())
else:
imgs.append(imgs[0])
CURSOR_IMGS[verb] = imgs
except Exception as e:
print(f"[ERROR] Error loading cursor{verb}: {e}")
# Fíjate que ahora pasamos 'target_surface' que será la ventana final
def draw_cursor(target_surface, is_active=False):
global CURRENT_CURSOR_STATE
# --- CORRECCIÓN CRÍTICA: COORDENADAS REALES ---
# Como ahora dibujamos el cursor al final sobre la 'real_window',
# necesitamos la posición real del ratón en la pantalla, no la virtual del juego.
mx, my = pygame.mouse.get_pos()
# ----------------------------------------------
# --- MODO CLÁSICO (Cruz) ---
if CONFIG.get("CURSOR_STYLE") == "CLASSIC":
color = (255, 255, 255)
size = 10
thickness = 2
pygame.draw.line(target_surface, color, (mx - size, my), (mx + size, my), thickness)
pygame.draw.line(target_surface, color, (mx, my - size), (mx, my + size), thickness)
return
# --- MODO MODERN (IMÁGENES) ---
pair = None
# Elegir imagen según el estado
if CURRENT_STATE in [GameState.TITLE, GameState.SAVELOAD, GameState.LANGUAGE, GameState.MAP, GameState.ENDING]:
pair = CURSOR_IMGS.get("WALK")
else:
pair = CURSOR_IMGS.get(CURRENT_CURSOR_STATE)
if not pair:
pair = CURSOR_IMGS.get("DEFAULT")
if pair:
img = pair[1] if is_active else pair[0]
# Centramos la imagen en la punta del ratón
off_x = -img.get_width() // 2
off_y = -img.get_height() // 2
target_surface.blit(img, (mx + off_x, my + off_y))
else:
# Fallback (Círculo de emergencia si no hay imagen)
color = (0, 255, 0) if is_active else (255, 0, 0)
pygame.draw.circle(target_surface, color, (mx, my), 5)
pygame.draw.circle(target_surface, color, (mx, my), 5)
def get_virtual_mouse_pos():
"""
Convierte la posición real del ratón a virtual con seguridad.
"""
global scale_factor, offset_x, offset_y
# Protección contra valores no inicializados o ventana minimizada
if scale_factor == 0: return 0, 0
mouse_x, mouse_y = pygame.mouse.get_pos()
# Restar offset y dividir por escala
virtual_x = (mouse_x - offset_x) / scale_factor
virtual_y = (mouse_y - offset_y) / scale_factor
# CLAMP: Forzamos a que el valor esté DENTRO del juego (0 a 800/638).
# Esto evita que el código detecte clics en las bandas negras.
virtual_x = max(0, min(CONFIG["GAME_WIDTH"] - 1, int(virtual_x)))
virtual_y = max(0, min(CONFIG["GAME_HEIGHT"] - 1, int(virtual_y)))
return virtual_x, virtual_y
def draw_overlay_text(screen, text, speaker=None, camera_x=0):
if not text: return
# --- Configuración Base ---
screen_w = CONFIG["GAME_WIDTH"]
margin = 20
style = CONFIG.get("NARRATION_STYLE", "LUCAS")
# Tamaño base de la fuente
base_size = TEXT_CONFIG[TEXT_CONFIG["CURRENT_SIZE"]]
# Color
text_color = (255, 255, 255)
if speaker and hasattr(speaker, "text_color"):
text_color = speaker.text_color
# --- Cálculo de Posición Virtual ---
center_x = screen_w // 2
bottom_y = 200
if CURRENT_TEXT_POS is not None:
center_x = CURRENT_TEXT_POS[0]
bottom_y = CURRENT_TEXT_POS[1]
elif style == "SUBTITLE":
center_x = screen_w // 2
bottom_y = CONFIG["GAME_HEIGHT"] - 195
elif style == "SIERRA":
center_x = screen_w // 2
bottom_y = 150
else: # LUCAS
if speaker:
center_x = speaker.rect.centerx - camera_x
# Altura visual para poner el texto sobre la cabeza
visual_height = speaker.rect.height
if hasattr(speaker, 'cached_surface') and speaker.cached_surface:
visual_height = speaker.cached_surface.get_height()
obj_top_y = speaker.rect.bottom - visual_height
bottom_y = obj_top_y - 10
else:
center_x = screen_w // 2
bottom_y = 200
# --- Word Wrapping (Calculado con fuente dummy para layout) ---
# Usamos una fuente dummy temporal para calcular saltos de línea logicamente
dummy_font = pygame.font.Font(TEXT_CONFIG["FONT_NAME"], base_size)
max_text_width = 500
words = text.split(' ')
lines = []
current_line = []
for word in words:
test_line = ' '.join(current_line + [word])
if dummy_font.size(test_line)[0] < max_text_width:
current_line.append(word)
else:
lines.append(' '.join(current_line))
current_line = [word]
lines.append(' '.join(current_line))
# --- Renderizado HD ---
# Calculamos la altura total para ir subiendo
line_height = base_size + 4 # Un poco de espaciado
total_height = len(lines) * line_height
start_y = bottom_y - total_height
# Clamp para que no se salga por arriba
if start_y < margin: start_y = margin
for i, line in enumerate(lines):
line_y = start_y + (i * line_height)
# Clamp horizontal (Virtual)
line_w = dummy_font.size(line)[0]
line_x = center_x
if line_x - (line_w // 2) < margin: line_x = margin + (line_w // 2)
if line_x + (line_w // 2) > screen_w - margin: line_x = screen_w - margin - (line_w // 2)
# LLAMADA A LA FUNCIÓN NÍTIDA
# Nota: screen se ignora, pintamos en real_window
draw_text_sharp(
text=line,
virtual_x=line_x,
virtual_y=line_y,
base_size=base_size,
color=text_color,
align="midtop", # Centrado horizontalmente
shadow=True
)
def load_and_open_map(lista_nodos_data, imagen_fondo="mapa1.jpg"):
global map_system
# ... (código de carga de fondo) ...
# --- quito textos su hubiereÍ ---
global SCREEN_OVERLAY_TEXT, TEXT_DISPLAY_TIMER
SCREEN_OVERLAY_TEXT = "" # Borra el texto pendiente
TEXT_DISPLAY_TIMER = 0 # Resetea el tiempo
map_system.nodes = []
for datos in lista_nodos_data:
# Ahora los datos deben ser: (SCENE_ID, x, y, spawnx, spawny, icon)
scene_id, mx, my, sx, sy, icon = datos # <--- ESTO ES CORRECTO (Pide 6)
map_system.add_node(scene_id, mx, my, sx, sy, icon)
# Abrimos mapa pasando el ID de la escena actual
map_system.open_map(scene_manager.current_scene.id)
# ==========================================
# SISTEMA DE CUTSCENES (CINEMÁTICAS)
# ==========================================
def set_state(new_state):
global CURRENT_STATE
CURRENT_STATE = new_state
# Si cambiamos a un modo que no sea explorar, limpiamos selecciones
if new_state != GameState.EXPLORE:
verb_menu.clear_selection()
inventory.active_item = None
def sync_states():
global CURRENT_STATE
if save_load_ui.active:
CURRENT_STATE = GameState.SAVELOAD
return
if language_ui.active:
CURRENT_STATE = GameState.LANGUAGE
return
# Si estamos en el Título, DETENEMOS la función aquí.
# Así evitamos que el código de abajo nos mande a jugar automáticamente.
if CURRENT_STATE == GameState.TITLE:
return
if ending_manager.active:
CURRENT_STATE = GameState.ENDING
return
if CURRENT_STATE == GameState.TITLE or CURRENT_STATE == GameState.INTRO:
return
# 1. PRIORIDAD TOTAL: Si hay cutscene, nos quedamos en cutscene
if cutscene_manager.active:
CURRENT_STATE = GameState.CUTSCENE
return
# 2. Resto de estados (Mapa, Diálogo, Exploración)
if map_system.active:
CURRENT_STATE = GameState.MAP
elif dialogue_system.active:
CURRENT_STATE = GameState.DIALOGUE
else:
# Aquí es donde te estaba forzando a entrar al juego sin permiso
CURRENT_STATE = GameState.EXPLORE
# ==========================================
# 6. INICIALIZACIÓN Y CARGA DE CONTENIDO
# ==========================================
debug_console = DebugConsole()
credits_window = CreditsWindow()
def reset_game_ui_state():
"""Limpia selecciones de verbos, inventario y detiene al jugador."""
if 'verb_menu' in globals():
verb_menu.clear_selection()
if 'inventory' in globals():
inventory.active_item = None
if 'movement' in globals():
movement.stop()
print("[SYSTEM] UI Reset complete (Verbs, Inventory, Movement cleared).")
def debug_log(*args):
# ... (código existente de debug_log) ...
if debug_console is None: print("[PRE-INIT]", *args)
else: debug_console.log(*args)
init_cursor()
# --- AQUÍ ESTÁN LOS CAMBIOS CRÍTICOS ---
scene_manager = SceneManager()
# AHORA EL PLAYER SE CARGA USANDO EL ID DE LA CONFIGURACIÓN
player = AnimatedCharacter(
400, 300,
char_id=PLAYER_CONFIG["CHAR_ID"],
text_color=PLAYER_CONFIG["TEXT_COLOR"]
)
# ¡¡¡LÍNEA NUEVA OBLIGATORIA!!!
# Registramos al jugador en el manager para siempre
movement = Movement()
textbox = TextBox()
verb_menu = VerbMenu()
inventory = Inventory()
cutscene_manager = CutsceneManager()
system_menu = SystemMenu()
title_menu = TitleMenu()
dialogue_system = DialogueSystem()
save_load_ui = SaveLoadUI()
language_ui = LanguageUI()
scene_manager.set_ui_callback(reset_game_ui_state) # Le pasamos la función de limpieza al SceneManager
scene_manager.set_player(player) # CONEXIÓN JUGADOR (Recuerda lo que mencioné en el reporte):
# intro está en otro file
intro_manager = IntroManager(
set_state_callback=set_state, # Función para cambiar estado
play_music_callback=play_scene_music, # Función para tocar música
scene_manager_ref=scene_manager, # Objeto scene_manager
get_texts_callback=lambda: CINE_TEXTS # Lambda para obtener textos actuales
)
# ending está en otro file
ending_manager = EndingManager(
set_state_callback=set_state, # Para volver al Título al acabar
play_music_callback=play_scene_music, # Para poner la música de créditos
get_texts_callback=lambda: CINE_TEXTS
)
# Inicializamos el sistema de mapas
map_system = MapSystem("mapa1.jpg")
# Estados del juego
# CURRENT_STATE = GameState.EXPLORE #para arrancar en el juego
CURRENT_STATE = GameState.TITLE #para arrancar en el titulo
# ==========================================
# 7. FUNCIONES DE LÓGICA
# ==========================================
def game_play_event(texto=None, play_sound=None, flag=None, delete_item=None, anim=None, text_time=None, speaker=None, pos=None): # <--- AÑADIDO pos=None
global SCREEN_OVERLAY_TEXT, TEXT_DISPLAY_TIMER, CURRENT_ACTION_ANIM, CURRENT_SPEAKER_REF, CURRENT_TEXT_POS
if texto:
SCREEN_OVERLAY_TEXT = texto
CURRENT_SPEAKER_REF = speaker
CURRENT_TEXT_POS = pos # <--- AÑADIDO: Guardamos la posición personalizada
# Cálculo automático del tiempo
if text_time is None:
speed_val = TEXT_CONFIG[TEXT_CONFIG["CURRENT_SPEED"]]
TEXT_DISPLAY_TIMER = max(1.5, len(texto) * speed_val)
else:
TEXT_DISPLAY_TIMER = text_time
# --- BLOQUE DE SONIDO MEJORADO (SOPORTA LISTAS Y CARGA DINÁMICA) ---
if play_sound and CONFIG["ENABLE_SOUND"]:
# 1. Convertimos a lista si es solo un texto, para tratarlo todo igual
sonidos_a_reproducir = []
if isinstance(play_sound, list):
sonidos_a_reproducir = play_sound
else:
sonidos_a_reproducir = [play_sound]
# 2. Recorremos la lista y reproducimos cada uno
for sonido_nombre in sonidos_a_reproducir:
s = SOUNDS.get(sonido_nombre)
# Si no está en memoria, intentamos cargarlo
if not s:
path_to_sound = os.path.join("snd", sonido_nombre)
if os.path.exists(path_to_sound):
try:
s = pygame.mixer.Sound(path_to_sound)
SOUNDS[sonido_nombre] = s # Guardar en caché
except Exception as e:
print(f"[SOUND ERROR] Failed to load {sonido_nombre}: {e}")
else:
print(f"[SOUND ERROR] Not found: {path_to_sound}")
# Si logramos tener el objeto sonido, play!
if s:
s.play()
if flag:
GAME_STATE[flag] = True
debug_log(f"[STATE] Variable '{flag}' activated.")
if delete_item:
inventory.remove_item(delete_item)
inventory.active_item = None
if anim:
CURRENT_ACTION_ANIM = anim
# texto al debug
if texto:
debug_log(f"[EVENT] Text: {texto[:20]}...") # Muestra los primeros 20 caracteres
if flag:
debug_log(f"[EVENT] Flag activated: {flag}")
if play_sound:
debug_log(f"[EVENT] play_sound:{play_sound}")
def smart_move_to(target_x, target_y, callback=None):
global SCREEN_OVERLAY_TEXT, TEXT_DISPLAY_TIMER, INFO_TEXT_TIMER, CURRENT_ACTION_ANIM
current_scene = scene_manager.get_current_scene()
if not current_scene or not current_scene.pathfinder:
movement.stop()
return
path = current_scene.pathfinder.find_path(player.rect.centerx, player.rect.bottom, target_x, target_y)
if not path:
nearest = current_scene.pathfinder.find_nearest_walkable(target_x, target_y, max_radius=120)
if nearest:
path = current_scene.pathfinder.find_path(player.rect.centerx, player.rect.bottom, nearest[0], nearest[1])
if path:
movement.set_path(path, cb=callback) # <--- CAMBIAR 'on_arrival' POR 'cb'
verb_menu.clear_selection()
SCREEN_OVERLAY_TEXT = ""
TEXT_DISPLAY_TIMER = 0
INFO_TEXT_TIMER = 0
CURRENT_ACTION_ANIM = None
else:
movement.stop()
textbox.set_text(GAME_MSGS["CANNOT_REACH"])
def cutscene_face_wrapper(direction):
if direction == "camera" or direction == "down":
player.face_camera()
# Aquí puedes añadir más direcciones si player.face_point es accesible
def cutscene_anim_wrapper(anim_name):
global CURRENT_ACTION_ANIM
CURRENT_ACTION_ANIM = anim_name
def cutscene_say_wrapper(text, duration):
# wrapper para llamar a game_play_event forzando que hable el player
game_play_event(texto=text, text_time=duration, speaker=player)
def cutscene_text_check():
# Devuelve el tiempo restante del texto para saber si acabó
return TEXT_DISPLAY_TIMER
# INYECTAMOS LAS DEPENDENCIAS
cutscene_manager.set_dependencies(
smart_move_func=smart_move_to, # Función de movimiento inteligente
say_func=cutscene_say_wrapper, # Función para hablar
face_func=cutscene_face_wrapper, # Función para mirar a cámara
set_anim_func=cutscene_anim_wrapper,# Función para forzar animación
check_text_timer=cutscene_text_check # Función para chequear tiempo texto
)
# ===========================================
def handle_scene_switch(exit_zone):
# 1. Limpieza agresiva de textos
global SCREEN_OVERLAY_TEXT, TEXT_DISPLAY_TIMER
SCREEN_OVERLAY_TEXT = ""
TEXT_DISPLAY_TIMER = 0
# 2. Cambio de escena
scene_manager.change_scene_with_effect(
exit_zone.target_scene,
exit_zone.spawn_point
)
movement.stop()
def execute_hotspot_action(hotspot, verb):
global SCREEN_OVERLAY_TEXT, TEXT_DISPLAY_TIMER, CURRENT_ACTION_ANIM, INFO_TEXT_TIMER, CURRENT_SPEAKER_REF, CURRENT_TEXT_POS
# 1. ORIENTACIÓN (Si el objeto tiene 'facing', giramos al player)
if hasattr(hotspot, 'facing') and hotspot.facing:
direction = hotspot.facing.lower()
if direction == "left": player.set_animation("idle_left")
elif direction == "right": player.set_animation("idle_right")
elif direction == "up": player.set_animation("idle_up")
elif direction == "down": player.set_animation("idle_down")
elif verb != "WALK":
# Si no tiene facing definido, por defecto mira a la cámara al interactuar
player.face_camera()
# 2. GESTIÓN DE ANIMACIONES DEL PLAYER (Pull, Pick, Give...)
if verb == "PULL": CURRENT_ACTION_ANIM = "pull"
elif verb == "PICK UP": CURRENT_ACTION_ANIM = "pick"
elif verb == "GIVE": CURRENT_ACTION_ANIM = "give"
elif verb in ["PUSH", "OPEN", "CLOSE", "USE"]: CURRENT_ACTION_ANIM = "push"
# 3. OBTENER LA ACCIÓN Y TRADUCIR
res = hotspot.actions.get(verb)
# --- [CORRECCIÓN CLAVE] ---
# Traducimos INMEDIATAMENTE si es una cadena de texto.
# Esto soluciona que salga "BONFIRE_LOOK" en vez del texto real.
if isinstance(res, str):
# Busca la clave en OBJ_DESCS. Si no existe, usa la clave tal cual.
res = OBJ_DESCS.get(res, res)
# --------------------------
# CASO A: Es una FUNCIÓN (lambda, etc.)
if callable(res):
res()
# Si la función no setea tiempos, ponemos uno por defecto para evitar bloqueos
if INFO_TEXT_TIMER == 0: INFO_TEXT_TIMER = 0.5
verb_menu.clear_selection()
return
# CASO B: Es RECOGER (PICK UP)
if verb == "PICK UP" and hasattr(hotspot, 'flag_name') and hotspot.flag_name:
if CONFIG["ENABLE_SOUND"] and "medal" in SOUNDS: SOUNDS["medal"].play()
# Añadir al inventario
label_key = getattr(hotspot, 'label_id', None)
inventory.add_item(
hotspot.name,
hotspot.label,
hotspot.image_file if hasattr(hotspot, 'image_file') else "default_obj.png", # Protección si Ambient no tiene image_file
hotspot.actions,
label_id=label_key
)
GAME_STATE[hotspot.flag_name] = True
# Matar objeto (Si es Sprite lo mata, si es Ambient lo quitamos de la lista)
if isinstance(hotspot, pygame.sprite.Sprite):
hotspot.kill()
elif hasattr(scene_manager.current_scene, 'ambient_anims') and hotspot in scene_manager.current_scene.ambient_anims:
scene_manager.current_scene.ambient_anims.remove(hotspot)
# Actualizar Pathfinding si era sólido
if getattr(hotspot, 'solid', False):
current_s = scene_manager.get_current_scene()
# Regenerar obstaculos
obs_list = []
for hs in current_s.hotspots.hotspots:
if getattr(hs, "solid", False): obs_list.append(hs.rect.inflate(10, 10))
for anim in current_s.ambient_anims:
if getattr(anim, "solid", False): obs_list.append(anim.rect.inflate(0, -4))
current_s.pathfinder.obstacles = obs_list
# Feedback de texto (Traducido si es necesario)
custom_text = hotspot.actions.get("PICK UP")
if isinstance(custom_text, str):
custom_text = OBJ_DESCS.get(custom_text, custom_text)
SCREEN_OVERLAY_TEXT = custom_text if custom_text else f"{GAME_MSGS['PICKED_UP']}{hotspot.label}."
CURRENT_SPEAKER_REF = player
CURRENT_TEXT_POS = None
TEXT_DISPLAY_TIMER = 3.0
verb_menu.clear_selection()
return
# CASO C: Es TEXTO (Look At, etc.)
if res:
SCREEN_OVERLAY_TEXT = res # 'res' ya viene traducido del paso 3
CURRENT_SPEAKER_REF = player
CURRENT_TEXT_POS = None
# Cálculo de tiempo dinámico según longitud
TEXT_DISPLAY_TIMER = max(2.0, len(str(res)) * 0.08)
verb_traducido = VERBS_LOCALIZED.get(verb, verb)
textbox.set_text(f"{verb_traducido} {hotspot.label}")
# CASO D: NO HAY ACCIÓN DEFINIDA
else:
# Solo mostrar error si no es caminar
if verb != "WALK":
SCREEN_OVERLAY_TEXT = GAME_MSGS["CANNOT_DO"]
CURRENT_SPEAKER_REF = player
CURRENT_TEXT_POS = None
TEXT_DISPLAY_TIMER = 2.0
CURRENT_ACTION_ANIM = None
verb_menu.clear_selection()
def play_object_animation(object_name, texto_feedback=None):
"""Busca el objeto y activa su animación one-shot."""
scene = scene_manager.get_current_scene()