-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbunker.py
More file actions
1182 lines (1056 loc) · 51.4 KB
/
Copy pathbunker.py
File metadata and controls
1182 lines (1056 loc) · 51.4 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
# ============================================
# bunker.py - Fase del bunker (6 dias de supervivencia)
# ============================================
import pygame
from config import (
SCREEN_WIDTH, SCREEN_HEIGHT,
BUNKER_WALL, BUNKER_FLOOR, BUNKER_CEILING,
METAL_DOOR, METAL_DOOR_DARK, SHELF_COLOR, SHELF_DARK,
BOOK_COLORS, WHITE, BLACK, DARK_GRAY, LIGHT_GRAY,
MODAL_BG, MODAL_BORDER, MODAL_HEADER,
BUTTON_GREEN, BUTTON_GREEN_HOVER,
BUTTON_RED, BUTTON_RED_HOVER,
BUTTON_BLUE, BUTTON_BLUE_HOVER,
BUTTON_GRAY, BUTTON_GRAY_HOVER,
INPUT_BG, INPUT_BORDER, INPUT_ACTIVE, INPUT_TEXT,
ENDING_PERFECT, ENDING_PARTIAL, ENDING_FAILURE,
)
from entities import TextInput, draw_worker_sprite, PLAYER_WORKER_BUNKER_SIZE
from problems import get_bunker_problems, check_all_fields
# =========================================================================
# CONTENIDO EXTENSO DETALLADO EXTRAIDO DE LOS ARCHIVOS PDF RECOPILADOS
# =========================================================================
PDF_BOOK_DATA = {
"green": [
"--- LIBRO VERDE: INTERPOLACION ---",
"",
"1. POLINOMIOS DE LAGRANGE:",
"Formula: g(x) = S [ yi * Li(x) ]",
"Donde L0 = [(x - x1)(x - x2)] / [(x0 - x1)(x0 - x2)]",
"Se calcula cada coeficiente Li en el punto deseado y se",
"multiplica por su Yi. Ideal para intervalos no uniformes.",
"",
"2. NEWTON CON DIFERENCIAS DIVIDIDAS:",
"Formula: g(x) = D0 + D1*(x - x0) + D2*(x - x0)*(x - x1) + ...",
"Reglas para obtener D:",
" - D0 = y0",
" - D1 = (y1 - y0) / (x1 - x0)",
" - D2 = (D1_2 - D1_1) / (x2 - x0)",
"El numerador es la resta de dos diferencias de nivel anterior.",
"El denominador es la resta de los valores de X de los extremos.",
"",
"3. NEWTON HACIA ATRAS (Intervalos Uniformes):",
"Requiere 'h' constante (h = Xi+1 - Xi).",
"s = (x - Xn) / h <-- Xn representa el ULTIMO valor de la tabla.",
"¡'s' siempre resulta NEGATIVO!",
"Formula: g(x) = Yn + V1*s + V2*[s(s+1)/2!] + V3*[s(s+1)(s+2)/3!]",
"Las diferencias (V) se calculan de abajo hacia arriba (yi - yi-1).",
"",
"4. NEWTON HACIA ADELANTE (Intervalos Uniformes):",
"s = (x - X0) / h <-- X0 representa el PRIMER valor de la tabla.",
"¡'s' siempre resulta POSITIVO!",
"Formula: g(x) = Y0 + D1*s + D2*[s(s-1)/2!] + D3*[s(s-1)(s-2)/3!]",
"Las diferencias (D) se calculan de arriba hacia abajo."
],
"red": [
"--- LIBRO ROJO: ECUACIONES NO LINEALES ---",
"",
"1. METODO GRAFICO Y BISECTRIZ:",
"Grafico: Observar el cruce en el eje X.",
"Bisectriz: x = (a+b)/2. Raiz presente si f(a)*f(b) < 0.",
"",
"2. PUNTO FIJO (Sustituciones Sucesivas):",
"Despejar x de la ecuacion f(x)=0 para obtener x = g(x).",
"Formula iterativa: Xi+1 = g(Xi).",
"Ejemplo: f(x) = e^(-x) - x = 0 => x = e^(-x).",
"El metodo converge si la derivada |g'(x)| < 1.",
"",
"3. NEWTON RAPHSON:",
"Utiliza iterativamente las rectas tangentes.",
"Formula: Xi+1 = Xi - [ f(Xi) / f'(Xi) ]",
"Requiere calcular la derivada f'(x). Muy rapido si converge.",
"",
"4. FALSA POSICION (Regula-Falsi):",
"Une f(a) y f(b) con una linea recta.",
"Formula: Xr = b - [ f(b)*(b - a) ] / [ f(b) - f(a) ]",
"Criterio de busqueda:",
" - Si f(a)*f(Xr) < 0, la raiz esta en [a, Xr] => Hacer b = Xr.",
" - Si f(a)*f(Xr) > 0, la raiz esta en [Xr, b] => Hacer a = Xr.",
"",
"5. SECANTE:",
"Formula: Xi+1 = Xi - [ f(Xi)*(Xi - Xi-1) ] / [ f(Xi) - f(Xi-1) ]",
"Predice extrapolando una tangente. No requiere derivada pero usa 2 valores iniciales."
],
"blue": [
"--- LIBRO AZUL: ECUACIONES LINEALES ---",
"",
"REQUISITO: Matriz Diagonal Dominante.",
"El coeficiente en la diagonal principal debe ser mayor a la",
"suma de los demas coeficientes en su misma fila.",
"",
"1. METODO DE GAUSS-SEIDEL:",
"Formula: X_i^(k+1) = (B_i - S [A_ij * X_j]) / A_ii",
"Pasos:",
"1) Despejar la variable de la diagonal principal.",
"2) Evaluar con valores iniciales (ej. 0, 0, 0).",
"3) ¡REGLA CRITICA!: Al obtener una variable, usar ese NUEVO",
" valor INMEDIATAMENTE para calcular las demas variables",
" dentro de esa misma iteracion.",
"Errores: Ea = |a_actual - a_anterior|",
"",
"2. METODO DE JACOBI:",
"Formula identica a Gauss-Seidel pero DIFIERE en la regla de uso.",
"¡REGLA CRITICA!: NO usar valores nuevos inmediatamente.",
"Todas las variables de la nueva iteracion se calculan usando",
"ESTRICTAMENTE los valores de la iteracion anterior completa."
],
"purple": [
"--- LIBRO MORADO: MINIMOS CUADRADOS ---",
"",
"Se usa cuando los datos tienen errores/dispersion sustancial.",
"",
"1. LINEA RECTA: g(x) = a0 + a1*x",
"Sistema de Ecuaciones (2x2):",
" n*a0 + (Sx)*a1 = Sy",
" (Sx)*a0 + (Sx^2)*a1 = Sxy",
"",
"2. CUADRATICA: g(x) = a0 + a1*x + a2*x^2",
"Sistema extendido (3x3):",
" n*a0 + (Sx)*a1 + (Sx^2)*a2 = Sy",
" (Sx)*a0 + (Sx^2)*a1 + (Sx^3)*a2 = Sxy",
" (Sx^2)*a0 + (Sx^3)*a1 + (Sx^4)*a2 = Sx^2y",
"",
"3. CUBICA: g(x) = a0 + a1*x + a2*x^2 + a3*x^3",
"Sistema 4x4, requiriendo columnas de sumatorias hasta Sx^6.",
"",
"4. LINEAL Y CUADRATICA CON FUNCION:",
"Incorpora funciones base como e^x, sen(x), cos(x), ln(x).",
"Lineal: g(x) = a0 + a1*x + a2*f(x)",
"Cuadratica: g(x) = a0 + a1*x + a2*x^2 + a3*f(x)",
"Se arman las matrices usando Sf(x), Sx*f(x), Sf(x)^2, etc."
],
"yellow": [
"--- LIBRO AMARILLO: INTEGRACION Y E.D.O ---",
"",
"INTEGRACION NUMERICA:",
"Permite calcular el area bajo la curva (suma de cambios puntuales).",
"",
"1. REGLA TRAPEZOIDAL:",
"I = (b - a) * [ f(a) + f(b) ] / 2",
"",
"2. REGLA 1/3 DE SIMPSON:",
"I = (b - a) * [ f(x0) + 4*f(x1) + f(x2) ] / 6",
"",
"3. REGLA 3/8 DE SIMPSON:",
"I = (b - a) * [ f(x0) + 3*f(x1) + 3*f(x2) + f(x3) ] / 8",
"",
"ECUACIONES DIFERENCIALES ORDINARIAS (EDO):",
"Resolucion de problemas de valor inicial calculados en",
"intervalos paso a paso."
],
"darkbrown": [
"--- LIBRO CAFE: RUNGE-KUTTA ---",
"",
"METODOS DE RUNGE-KUTTA (RK):",
"Calculan E.D.O aproximando derivadas (pendientes) promediadas,",
"sin necesidad de derivacion analitica de orden superior.",
"",
"1. RK1 (Euler):",
"y_i+1 = y_i + f(x_i, y_i)*h",
"",
"2. RK2 (Heun):",
"Promedia dos pendientes (al inicio y final del intervalo).",
"",
"3. RK4 (Clasico):",
"Promedia cuatro pendientes ponderadas (k1, k2, k3, k4).",
" k1 = f(x_i, y_i)",
" k2 = f(x_i + h/2, y_i + k1*h/2)",
" k3 = f(x_i + h/2, y_i + k2*h/2)",
" k4 = f(x_i + h, y_i + k3*h)",
" y_i+1 = y_i + (1/6) * (k1 + 2k2 + 2k3 + k4) * h"
]
}
# ============================================
# MODAL DE PROBLEMA
# ============================================
class ProblemModal:
"""
Ventana emergente para resolver un problema matematico.
Incluye: enunciado, campo de texto, timer, botones, pistas de libros.
"""
def __init__(self, problem, time_seconds, books_collected, sound_manager):
self.problem = problem
self.time_remaining = time_seconds
self.time_total = time_seconds
self.books = books_collected
self.sound_manager = sound_manager
# Estado
self.paused = False
self.finished = False
self.result = None
self.show_hint = None
self.ready_to_exit = False
# Configuracion de Ventana Deslizable para PDFs
self.scroll_y = 0
self.max_scroll = 0
self.scroll_x = 0
self.max_scroll_x = 0
self.problem_scroll_y = 0
self.max_problem_scroll = 0
self.problem_view_rect = None
# Multiples campos de respuesta
self.fields = problem.get("fields", [])
self.text_inputs = []
self.active_field = 0
for i, field in enumerate(self.fields):
ti = TextInput(0, 0, 200, 30, font_size=18)
ti.active = (i == 0)
self.text_inputs.append(ti)
if not self.text_inputs:
self.text_inputs = [TextInput(0, 0, 280, 40)]
# Fuentes
self.font_title = pygame.font.SysFont("Arial", 20, bold=True)
self.font_text = pygame.font.SysFont("Arial", 16)
self.font_label = pygame.font.SysFont("Arial", 14, bold=True)
self.font_timer = pygame.font.SysFont("Consolas", 28, bold=True)
self.font_button = pygame.font.SysFont("Arial", 16, bold=True)
self.font_small = pygame.font.SysFont("Arial", 13)
# Geometria del modal
self.modal_rect = pygame.Rect(40, 30, SCREEN_WIDTH - 80, SCREEN_HEIGHT - 60)
# La ventana de PDF cubre casi toda la pantalla central-derecha para mejor lectura
self.reader_rect = pygame.Rect(
self.modal_rect.left + 120,
self.modal_rect.top + 45,
self.modal_rect.width - 135,
self.modal_rect.height - 60,
)
# Mensaje de resultado
self.result_message = ""
self.result_timer = 0
self.show_result = False
self.force_next_day = False
def update(self, events, dt):
if self.force_next_day:
self.force_next_day = False
return "correct"
if self.show_result:
if self.result == "correct":
if self.ready_to_exit:
return self.result
else:
self.result_timer -= dt
if self.result_timer <= 0:
return self.result
return None
if not self.paused and not self.show_result:
self.time_remaining -= dt
if self.time_remaining <= 0:
self.time_remaining = 0
self._set_result("timeout", "Se acabo el tiempo")
return None
if not self.show_result and not self.show_hint and self.active_field < len(self.text_inputs):
self.text_inputs[self.active_field].update(dt)
for event in events:
if event.type == pygame.MOUSEWHEEL and self.show_hint:
mouse = pygame.mouse.get_pos()
if self.reader_rect.collidepoint(mouse):
mods = pygame.key.get_mods()
if mods & pygame.KMOD_SHIFT:
self.scroll_x = max(0, min(self.max_scroll_x, self.scroll_x - event.y * 35))
else:
self.scroll_y = max(0, min(self.max_scroll, self.scroll_y - event.y * 25))
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
self._handle_click(mouse)
# Soporte de Scrolling con la rueda del mouse
if self.show_hint and self.reader_rect.collidepoint(mouse):
if event.button == 4: # Rueda Arriba
mods = pygame.key.get_mods()
if mods & pygame.KMOD_SHIFT:
self.scroll_x = max(0, self.scroll_x - 35)
else:
self.scroll_y = max(0, self.scroll_y - 25)
elif event.button == 5: # Rueda Abajo
mods = pygame.key.get_mods()
if mods & pygame.KMOD_SHIFT:
self.scroll_x = min(self.max_scroll_x, self.scroll_x + 35)
else:
self.scroll_y = min(self.max_scroll, self.scroll_y + 25)
elif self.problem_view_rect and self.problem_view_rect.collidepoint(mouse):
if event.button == 4: # Rueda Arriba
self.problem_scroll_y = max(0, self.problem_scroll_y - 25)
elif event.button == 5:
self.problem_scroll_y = min(self.max_problem_scroll, self.problem_scroll_y + 25)
if event.type == pygame.KEYDOWN:
if self.show_hint:
if event.key == pygame.K_UP:
self.scroll_y = max(0, self.scroll_y - 30)
elif event.key == pygame.K_DOWN:
self.scroll_y = min(self.max_scroll, self.scroll_y + 25)
elif event.key == pygame.K_LEFT:
self.scroll_x = max(0, self.scroll_x - 35)
elif event.key == pygame.K_RIGHT:
self.scroll_x = min(self.max_scroll_x, self.scroll_x + 35)
if not self.show_result and not self.show_hint:
if event.key == pygame.K_TAB:
self._switch_field((self.active_field + 1) % len(self.text_inputs))
elif event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
self._submit_answer()
else:
if self.active_field < len(self.text_inputs):
self.text_inputs[self.active_field].handle_event(event)
return None
def _switch_field(self, idx):
for i, ti in enumerate(self.text_inputs):
ti.active = (i == idx)
self.active_field = idx
def _handle_click(self, mouse):
if self.show_result:
if self.result == "correct":
btn_continue = pygame.Rect(self.modal_rect.centerx - 70, self.modal_rect.bottom - 55, 140, 38)
if btn_continue.collidepoint(mouse) and not self.show_hint:
self.sound_manager.play("select")
self.ready_to_exit = True
self._handle_book_clicks(mouse)
return
# Boton Entregar
btn_submit = pygame.Rect(self.modal_rect.centerx - 70, self.modal_rect.bottom - 55, 140, 38)
if btn_submit.collidepoint(mouse):
self.sound_manager.play("select")
self._submit_answer()
return
# Boton temporal: pasar dia sin responder (revision)
btn_skip_day = pygame.Rect(self.modal_rect.centerx + 90, self.modal_rect.bottom - 55, 170, 38)
if btn_skip_day.collidepoint(mouse):
self.sound_manager.play("select")
self.force_next_day = True
return
# Clic en campos de texto de respuestas
for i, ti in enumerate(self.text_inputs):
if ti.rect.collidepoint(mouse):
self._switch_field(i)
return
self._handle_book_clicks(mouse)
def _handle_book_clicks(self, mouse):
"""Abre o cierra los libros recolectados en el panel izquierdo."""
book_y = self.modal_rect.top + 90
color_order = ["green", "red", "blue", "purple", "yellow", "darkbrown"]
book_idx = 0
for color in color_order:
if self.books.get(color, 0) > 0:
book_rect = pygame.Rect(self.modal_rect.left + 15, book_y + book_idx * 55, 95, 45)
if book_rect.collidepoint(mouse):
self.sound_manager.play("select")
if self.show_hint == color:
self.show_hint = None
else:
self.show_hint = color
self.scroll_y = 0 # Reiniciar scroll al cambiar de libro
self.scroll_x = 0
return
book_idx += 1
def _submit_answer(self):
if self.show_result:
return
user_answers = [ti.get_value() for ti in self.text_inputs]
if all(a == "" for a in user_answers):
self._set_result("wrong", "No ingresaste una respuesta")
return
if check_all_fields(self.problem, user_answers):
self._set_result("correct", "Respuesta correcta")
else:
self._set_result("wrong", "Incorrecto")
def _set_result(self, result, message):
self.result = result
self.result_message = message
self.show_result = True
self.result_timer = 2.5
if result == "correct":
self.sound_manager.play("victoria")
else:
self.sound_manager.play("error")
def _get_correct_answers_lines(self):
"""Devuelve las respuestas correctas del problema actual para mostrarlas al calificar."""
lines = []
for field in self.fields:
label = self._safe_text(field.get("label", "")).strip()
answer = self._safe_text(field.get("answer", "")).strip()
if not label:
continue
lines.append(f"{label} {answer}" if answer else label)
return lines
def _safe_text(self, text):
"""Corrige mojibake frecuente en textos del problema/libros para mostrarlos limpios."""
if text is None:
return ""
fixed = str(text)
for _ in range(2):
try:
decoded = fixed.encode("latin1").decode("utf-8")
except (UnicodeEncodeError, UnicodeDecodeError):
break
if decoded == fixed:
break
fixed = decoded
replacements = {
"Є": "E",
"Ä": "E",
"∑": "∑",
"∑": "∑",
"²": "²",
"≠": "!=",
"≠": "!=",
"ÃŽâ€": "Δ",
"∆": "Δ",
"Ã": "x",
"—": "-",
"–": "-",
"raÃz": "raiz",
"Método": "Metodo",
"método": "metodo",
"Posición": "Posicion",
"Interpolación": "Interpolacion",
"Atrás": "Atras",
"DÃa": "Dia",
"á": "a",
"é": "e",
"Ã": "i",
"ó": "o",
"ú": "u",
"ñ": "n",
"Ã": "A",
"É": "E",
"Ã": "I",
"Ó": "O",
"Ú": "U",
"Ñ": "N",
"Â": "",
}
replacements.update({
"Є": "E",
"Ä": "E",
"∑": "∑",
"∑": "∑",
"∑": "∑",
"²": "²",
"²": "²",
"²": "²",
"≠": "!=",
"≠": "!=",
"≠": "!=",
"ÃŽâ€Â": "Δ",
"ÃŽâ€": "Δ",
"∆": "Δ",
"∆": "Δ",
"Δ": "Δ",
"×": "x",
"Ã": "x",
"â€â€": "-",
"–": "-",
"—": "-",
"–": "-",
"¡": "¡",
"raÃz": "raiz",
"Método": "Metodo",
"método": "metodo",
"Posición": "Posicion",
"Interpolación": "Interpolacion",
"Atrás": "Atras",
"DÃa": "Dia",
"á": "a",
"é": "e",
"Ã": "i",
"ó": "o",
"ú": "u",
"ñ": "n",
"Ã": "A",
"É": "E",
"Ã": "I",
"Ó": "O",
"Ú": "U",
"Ñ": "N",
"Â": "",
})
for bad, good in replacements.items():
fixed = fixed.replace(bad, good)
return fixed
def draw(self, surface):
overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 150))
surface.blit(overlay, (0, 0))
mr = self.modal_rect
mouse = pygame.mouse.get_pos()
pygame.draw.rect(surface, MODAL_BG, mr, border_radius=10)
pygame.draw.rect(surface, MODAL_BORDER, mr, 2, border_radius=10)
header = pygame.Rect(mr.left, mr.top, mr.width, 40)
pygame.draw.rect(surface, MODAL_HEADER, header, border_top_left_radius=10, border_top_right_radius=10)
topic = self._safe_text(self.problem.get("topic", "Problema"))
title = self.font_title.render(f"Metodo: {topic}", True, WHITE)
title_center_x = mr.left + (mr.width - 130) // 2
surface.blit(title, title.get_rect(center=(title_center_x, mr.top + 20)))
mins = int(self.time_remaining // 60)
secs = int(self.time_remaining % 60)
timer_color = (255, 80, 80) if self.time_remaining < 60 else WHITE
timer_text = self.font_timer.render(f"{mins:02d}:{secs:02d}", True, timer_color)
surface.blit(timer_text, (mr.right - 120, mr.top + 5))
# Libros
books_x = mr.left + 10
books_y = mr.top + 85
books_title = self.font_small.render("Libros:", True, LIGHT_GRAY)
surface.blit(books_title, (books_x, books_y - 15))
color_order = ["green", "red", "blue", "purple", "yellow", "darkbrown"]
color_names = {
"green": "Verde",
"red": "Rojo",
"blue": "Azul",
"purple": "Morado",
"yellow": "Amarillo",
"darkbrown": "Cafe",
}
book_idx = 0
for color in color_order:
count = self.books.get(color, 0)
if count > 0:
by = books_y + book_idx * 55
book_rect = pygame.Rect(books_x + 5, by, 95, 45)
is_selected = self.show_hint == color
bg_color = (70, 70, 85) if is_selected else (50, 50, 65)
pygame.draw.rect(surface, bg_color, book_rect, border_radius=5)
pygame.draw.rect(surface, BOOK_COLORS[color], book_rect, 2, border_radius=5)
icon = pygame.Rect(books_x + 10, by + 8, 18, 25)
pygame.draw.rect(surface, BOOK_COLORS[color], icon, border_radius=2)
name = self.font_small.render(self._safe_text(color_names[color]), True, WHITE)
surface.blit(name, (books_x + 33, by + 14))
book_idx += 1
# --- Contenido de la pregunta / Inputs (Centro) ---
content_x = mr.left + 130
content_w = mr.width - 170
content_y = mr.top + 52
content_h = mr.height - 140
if self.show_hint:
gap = 10
left_w = int(content_w * 0.58)
right_w = content_w - left_w - gap
self.problem_view_rect = pygame.Rect(content_x + 8, content_y, left_w - 16, content_h)
self.reader_rect = pygame.Rect(self.problem_view_rect.right + gap, content_y, right_w - 8, content_h)
else:
self.problem_view_rect = pygame.Rect(content_x + 8, content_y, content_w - 16, content_h)
problem_top = mr.top + 55
problem_text = self._safe_text(self.problem["text"])
raw_lines = problem_text.split("\n")
text_left = content_x + 20
wrap_w = self.problem_view_rect.width - 44
logical_y = problem_top
surface.set_clip(self.problem_view_rect)
# --- Contenido del enunciado dentro del recuadro principal ---
for raw_line in raw_lines:
if raw_line.strip() == "":
logical_y += 15
continue
draw_y = logical_y - self.problem_scroll_y
# Tablas estilo | x | y |
if "|" in raw_line:
cells = [self._safe_text(c.strip()) for c in raw_line.split("|") if c.strip() != ""]
available_w = max(220, wrap_w - 10)
cols = max(1, len(cells))
# Ancho uniforme por fila para que no "salte" entre renglones.
cell_w = max(95, int(available_w / cols))
cell_h = 30
for col_idx, cell_text in enumerate(cells):
cx = text_left + col_idx * cell_w
pygame.draw.rect(surface, (70, 70, 85), (cx, draw_y, cell_w, cell_h), 1)
lt = self.font_text.render(cell_text, True, (220, 255, 255))
surface.blit(lt, (cx + 8, draw_y + 5))
logical_y += cell_h
continue
words = raw_line.split()
current_l = ""
for word in words:
test = current_l + " " + word if current_l else word
if self.font_text.size(test)[0] < wrap_w:
current_l = test
else:
lt = self.font_text.render(self._safe_text(current_l), True, WHITE)
surface.blit(lt, (text_left, logical_y - self.problem_scroll_y))
logical_y += 20
current_l = word
if current_l:
lt = self.font_text.render(self._safe_text(current_l), True, WHITE)
surface.blit(lt, (text_left, logical_y - self.problem_scroll_y))
logical_y += 20
logical_y += 12
# --- Campos de respuesta dentro del mismo recuadro ---
if self.show_result and self.result == "correct":
proc_text = self._safe_text(self.problem.get("procedimiento", "Procedimiento no disponible."))
proc_lines = proc_text.split('\n')
for line in proc_lines:
lt = self.font_text.render(self._safe_text(line), True, (150, 255, 150))
surface.blit(lt, (text_left, logical_y - self.problem_scroll_y))
logical_y += 22
else:
fields_count = len(self.fields)
if fields_count > 0:
if fields_count <= 4:
cols = 2
else:
cols = 3
gap_x = 10
panel_inner_w = self.problem_view_rect.width - 34
col_w = max(130, (panel_inner_w - (cols - 1) * gap_x) // cols)
row_h = 44
for i, field in enumerate(self.fields):
row = i // cols
col = i % cols
base_x = text_left + col * (col_w + gap_x)
base_y = logical_y + row * row_h - self.problem_scroll_y
clean_label = self._safe_text(field["label"])
lbl = self.font_label.render(clean_label, True, (255, 215, 0))
surface.blit(lbl, (base_x, base_y + 6))
lbl_w = lbl.get_width() + 6
self.text_inputs[i].rect.x = base_x + lbl_w
self.text_inputs[i].rect.y = base_y + 2
self.text_inputs[i].rect.width = max(90, min(150, col_w - lbl_w - 6))
self.text_inputs[i].rect.height = 30
self.text_inputs[i].draw(surface)
rows = (fields_count + cols - 1) // cols
logical_y += rows * row_h + 4
surface.set_clip(None)
total_problem_height = max(0, (logical_y - problem_top) + 12)
self.max_problem_scroll = max(0, total_problem_height - self.problem_view_rect.height)
self.problem_scroll_y = min(self.problem_scroll_y, self.max_problem_scroll)
pygame.draw.rect(surface, (70, 70, 95), self.problem_view_rect, 1, border_radius=4)
if self.max_problem_scroll > 0:
pb_y = self.problem_view_rect.top + 8
pb_h = self.problem_view_rect.height - 16
pb_x_r = self.problem_view_rect.right - 6
p_ratio = self.problem_scroll_y / self.max_problem_scroll
p_thumb_h = max(20, int(pb_h * (self.problem_view_rect.height / max(total_problem_height, 1))))
p_thumb_y = pb_y + int((pb_h - p_thumb_h) * p_ratio)
pygame.draw.rect(surface, (130, 160, 210), (pb_x_r, p_thumb_y, 4, p_thumb_h), border_radius=2)
# --- Logica de Visualizacion: Campos de Entrada o Procedimiento Resuelto ---
if self.show_result and self.result == "correct":
rt = self.font_title.render("Respuesta correcta", True, (100, 255, 100))
surface.blit(rt, rt.get_rect(center=(content_x + content_w // 2, self.problem_view_rect.bottom + 28)))
answer_lines = self._get_correct_answers_lines()
if answer_lines:
ans_title = self.font_small.render("Respuestas correctas:", True, (170, 240, 170))
surface.blit(ans_title, (content_x + 12, self.problem_view_rect.bottom + 42))
ans_y = self.problem_view_rect.bottom + 60
for line in answer_lines[:6]:
ans_text = self.font_small.render(self._safe_text(line), True, (190, 255, 190))
surface.blit(ans_text, (content_x + 12, ans_y))
ans_y += 18
btn_continue = pygame.Rect(mr.centerx - 70, mr.bottom - 55, 140, 38)
c_hover = btn_continue.collidepoint(mouse)
c_color = BUTTON_GREEN_HOVER if c_hover else BUTTON_GREEN
pygame.draw.rect(surface, c_color, btn_continue, border_radius=8)
pygame.draw.rect(surface, WHITE, btn_continue, 2, border_radius=8)
c_text = self.font_button.render("Continuar", True, WHITE)
surface.blit(c_text, c_text.get_rect(center=btn_continue.center))
else:
# Boton Entregar
btn_submit = pygame.Rect(mr.centerx - 70, mr.bottom - 55, 140, 38)
s_hover = btn_submit.collidepoint(mouse)
s_color = BUTTON_GREEN_HOVER if s_hover else BUTTON_GREEN
pygame.draw.rect(surface, s_color, btn_submit, border_radius=8)
pygame.draw.rect(surface, WHITE, btn_submit, 2, border_radius=8)
s_text = self.font_button.render("Entregar", True, WHITE)
surface.blit(s_text, s_text.get_rect(center=btn_submit.center))
# Boton temporal para revision de dias
btn_skip_day = pygame.Rect(mr.centerx + 90, mr.bottom - 55, 170, 38)
skip_hover = btn_skip_day.collidepoint(mouse)
skip_color = BUTTON_BLUE_HOVER if skip_hover else BUTTON_BLUE
pygame.draw.rect(surface, skip_color, btn_skip_day, border_radius=8)
pygame.draw.rect(surface, WHITE, btn_skip_day, 2, border_radius=8)
skip_text = self.font_small.render("Pasar dia (temporal)", True, WHITE)
surface.blit(skip_text, skip_text.get_rect(center=btn_skip_day.center))
# --- VENTANA DESLIZANTE: LECTOR DE PDF (Derecha) ---
if self.show_hint and self.show_hint in PDF_BOOK_DATA:
pygame.draw.rect(surface, (28, 28, 38), self.reader_rect, border_radius=6)
pygame.draw.rect(surface, BOOK_COLORS[self.show_hint], self.reader_rect, 2, border_radius=6)
surface.set_clip(self.reader_rect.inflate(-10, -10))
lines = [self._safe_text(line) for line in PDF_BOOK_DATA[self.show_hint]]
start_idx = 0
for idx, line in enumerate(lines):
upper = line.upper()
if upper.startswith("2.") and "POLINOMIOS" in upper:
start_idx = idx
break
lines = lines[start_idx:]
text_y = self.reader_rect.top + 15 - self.scroll_y
for line in lines:
if line.startswith("---") or line.endswith("---"):
color = (255, 215, 0) # Oro para titulos de archivos
elif "Formula" in line or "g(x)" in line or "Ecuacion" in line or "k1 =" in line:
color = (120, 255, 255) # Cian para expresiones matematicas
else:
color = WHITE
lt = self.font_text.render(line, True, color)
surface.blit(lt, (self.reader_rect.left + 15 - self.scroll_x, text_y))
text_y += 22
# Calcular limites maximos de scroll dinamicamente
total_content_height = len(lines) * 24
self.max_scroll = max(0, total_content_height - self.reader_rect.height + 30)
max_line_width = 0
for line in lines:
line_w = self.font_text.size(line)[0]
if line_w > max_line_width:
max_line_width = line_w
visible_w = self.reader_rect.width - 34
self.max_scroll_x = max(0, max_line_width - visible_w)
self.scroll_x = min(self.scroll_x, self.max_scroll_x)
# Desactivar el recorte de pantalla
surface.set_clip(None)
if self.max_scroll > 0:
sb_x = self.reader_rect.right - 10
sb_y = self.reader_rect.top + 10
sb_h = self.reader_rect.height - 20
pygame.draw.rect(surface, (50, 50, 60), (sb_x, sb_y, 6, sb_h), border_radius=3)
scroll_ratio = self.scroll_y / self.max_scroll
thumb_h = max(30, int(sb_h * (self.reader_rect.height / total_content_height)))
thumb_y = sb_y + int((sb_h - thumb_h) * scroll_ratio)
pygame.draw.rect(surface, BOOK_COLORS[self.show_hint], (sb_x, thumb_y, 6, thumb_h), border_radius=3)
# Barra horizontal (arriba y abajo) para desplazamiento lateral
if self.max_scroll_x > 0:
hb_x = self.reader_rect.left + 10
hb_w = self.reader_rect.width - 20
hb_y_top = self.reader_rect.top + 4
hb_y_bottom = self.reader_rect.bottom - 8
pygame.draw.rect(surface, (50, 50, 60), (hb_x, hb_y_top, hb_w, 3), border_radius=1)
pygame.draw.rect(surface, (50, 50, 60), (hb_x, hb_y_bottom, hb_w, 3), border_radius=1)
x_ratio = self.scroll_x / self.max_scroll_x
thumb_w = max(22, int(hb_w * (visible_w / max(max_line_width, 1))))
thumb_x = hb_x + int((hb_w - thumb_w) * x_ratio)
pygame.draw.rect(surface, BOOK_COLORS[self.show_hint], (thumb_x, hb_y_top, thumb_w, 3), border_radius=1)
pygame.draw.rect(surface, BOOK_COLORS[self.show_hint], (thumb_x, hb_y_bottom, thumb_w, 3), border_radius=1)
# Indicador de pausa
if self.paused:
pause_overlay = pygame.Surface((mr.width - 4, 40), pygame.SRCALPHA)
pause_overlay.fill((0, 0, 0, 180))
surface.blit(pause_overlay, (mr.left + 2, mr.centery - 20))
pt = self.font_title.render("JUEGO EN PAUSA", True, (255, 215, 0))
surface.blit(pt, pt.get_rect(center=(mr.centerx, mr.centery)))
# Mostrar bloque de error
if self.show_result and self.result != "correct" and not self.show_hint:
answer_lines = self._get_correct_answers_lines()
overlay_h = 60 + (22 if answer_lines else 0) + (18 * min(len(answer_lines), 6))
result_overlay = pygame.Surface((mr.width - 4, overlay_h), pygame.SRCALPHA)
result_overlay.fill((80, 20, 20, 235))
surface.blit(result_overlay, (mr.left + 2, mr.centery + 40))
rt = self.font_title.render(self.result_message, True, (255, 100, 100))
surface.blit(rt, rt.get_rect(center=(mr.centerx, mr.centery + 70)))
if answer_lines:
y0 = mr.centery + 96
at = self.font_small.render("Respuestas correctas:", True, (255, 200, 200))
surface.blit(at, (mr.left + 20, y0))
y0 += 18
for line in answer_lines[:6]:
ans = self.font_small.render(self._safe_text(line), True, (255, 220, 220))
surface.blit(ans, (mr.left + 20, y0))
y0 += 18
# ============================================
# FASE DEL BUNKER (PANTALLA 3)
# ============================================
class BunkerPhase:
"""
Fase del bunker: 6 dias de supervivencia.
"""
def __init__(self, sound_manager):
self.sound_manager = sound_manager
self.reset({})
def reset(self, books_collected):
self.books = books_collected
self.current_day = 1
self.errors = 0
self.fail_streak = 0
self.days_completed = 0
self.total_days = 6
self.base_day_time = 20 * 60
self.day_bonus_increments = [5 * 60, 5 * 60, 10 * 60, 5 * 60, 5 * 60, 0]
self.time_bonus_pool = 0
self.max_failures_total = 3
self.max_failures_streak = 3
self.problems = get_bunker_problems()
self.water = 10
self.food = 10
self.show_arrow = True
self.arrow_timer = 0
self.modal = None
self.transitioning = False
self.transition_timer = 0
self.day_start_shown = False
self.message = ""
self.message_timer = 0
self.failure_pending = False
self.failure_timer = 0
self.font_title = pygame.font.SysFont("Arial", 28, bold=True)
self.font_subtitle = pygame.font.SysFont("Arial", 20)
self.font_text = pygame.font.SysFont("Arial", 16)
self.font_small = pygame.font.SysFont("Arial", 13)
self.font_day = pygame.font.SysFont("Arial", 36, bold=True)
self.font_day_top = pygame.font.SysFont("Arial", 28, bold=True)
self.font_message = pygame.font.SysFont("Arial", 22, bold=True)
self.sound_manager.play("hoja")
def init_with_books(self, books_collected):
self.reset(books_collected)
def _get_day_time(self, day_index):
return max(60, self.base_day_time + self.time_bonus_pool)
def update(self, events, dt):
if self.failure_pending:
self.failure_timer -= dt
self.message_timer -= dt
if self.failure_timer <= 0:
return ENDING_FAILURE
return None
if self.transitioning:
self.transition_timer -= dt
if self.message_timer > 0:
self.message_timer -= dt
if self.transition_timer <= 0:
self.transitioning = False
self.day_start_shown = False
self.arrow_timer = 0
self.water = max(0, self.water - 2)
self.food = max(0, self.food - 2)
self.sound_manager.play("hoja")
return None
if self.message_timer > 0:
self.message_timer -= dt
if self.modal:
result = self.modal.update(events, dt)
if result:
return self._handle_problem_result(result)
return None
if self.current_day > self.total_days:
if self.errors == 0:
return ENDING_PERFECT
else:
return ENDING_PARTIAL
self.arrow_timer += dt
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
door_rect = self._get_door_rect()
if door_rect.collidepoint(mouse) and self.modal is None:
self._open_problem()
return None
def _get_door_rect(self):
return pygame.Rect(SCREEN_WIDTH - 185, SCREEN_HEIGHT - 170, 120, 95)
def _open_problem(self):
day_index = min(self.current_day - 1, len(self.problems) - 1)
problem = self.problems[day_index]
time_sec = self._get_day_time(day_index)
self.modal = ProblemModal(problem, time_sec, self.books, self.sound_manager)
def _handle_problem_result(self, result):
self.modal = None
if result == "correct":
self.days_completed += 1
self.fail_streak = 0
day_idx = self.current_day - 1
if 0 <= day_idx < len(self.day_bonus_increments):
bonus_gain = self.day_bonus_increments[day_idx]
if self.current_day < self.total_days and bonus_gain > 0:
self.time_bonus_pool += bonus_gain
if self.current_day < self.total_days:
self.message = f"Correcto. Pasas al dia {self.current_day + 1}."
else:
self.message = "Correcto. Has completado el ultimo dia."
self.message_timer = 3.0
self.current_day += 1
self.transitioning = True
self.transition_timer = 2.0
else:
self.errors += 1
self.fail_streak += 1
if self.errors >= self.max_failures_total or self.fail_streak >= self.max_failures_streak:
if self.fail_streak >= self.max_failures_streak:
self.message = "Has fallado 3 dias seguidos. El juego termina."
else:
self.message = "Has fallado 3 veces. El juego termina."
self.message_timer = 4.0
self.failure_pending = True
self.failure_timer = 4.0
self.sound_manager.play("error")
return None
self.message = f"Error. Pasas al dia {self.current_day + 1} sin bonificacion."
self.message_timer = 4.0
self.current_day += 1
self.transitioning = True
self.transition_timer = 3.0
if self.current_day > self.total_days:
self.transitioning = True
self.transition_timer = 2.0
return None
def draw(self, surface):
self._draw_bunker_bg(surface)
self._draw_bunker_set_dressing(surface)
self._draw_character(surface)
self._draw_bookshelf(surface)
self._draw_door(surface)
self._draw_supplies(surface)
self._draw_day_hud(surface)
if self.modal is None and self.current_day <= self.total_days and not self.transitioning:
self._draw_arrow(surface)
if self.transitioning:
self._draw_transition(surface)
if self.message_timer > 0 and self.message:
self._draw_message(surface)
if self.failure_pending: