-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1776 lines (1504 loc) · 59.2 KB
/
main.py
File metadata and controls
1776 lines (1504 loc) · 59.2 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
# ============================================================================
# MAIN.PY - PSIC-O-TRONIC
# Motor principal del juego
# ============================================================================
import time
import gc
import network
import ujson
from machine import Pin, I2C
# Módulos propios
from lcd_chars import load_custom_chars, convert_text, get_lives_display, wrap_text
from config import (
is_wifi_configured, get_wifi_config, load_stats, get_stats_summary,
clear_wifi_config
)
from wifi_portal import run_wifi_portal, connect_saved_wifi
from gemini_api import get_oracle
from game_modes import GameSession, InitialsInput, MODE_CLASSIC, MODE_SURVIVAL
from audio import init_audio, play as play_sound
# Sistema OTA
try:
from ota_update import ota_manager, reboot as ota_reboot
OTA_AVAILABLE = True
except ImportError:
OTA_AVAILABLE = False
print("[MAIN] OTA no disponible")
# Hardware
from i2c_lcd import I2cLcd
# ============================================================================
# CONFIGURACIÓN HARDWARE
# ============================================================================
PIN_BTN_UP = 4
PIN_BTN_SELECT = 5
PIN_BTN_DOWN = 6
PIN_LED_UP = 7
PIN_LED_SELECT = 15
PIN_LED_DOWN = 16
PIN_LED_NOTIFY = 17
PIN_SPEAKER = 9
PIN_I2C_SDA = 1
PIN_I2C_SCL = 2
# Timing
FRAME_DELAY = 0.08
DEBOUNCE_MS = 280
# ============================================================================
# ESTADOS DEL JUEGO
# ============================================================================
class State:
BOOT = 0
FIRST_TIME_WELCOME = 1
WIFI_CHECK = 2
WIFI_PORTAL = 3
INTRO = 4
MENU = 5
MODE_SELECT = 6
PLAYER_SELECT = 7
QUOTA_SELECT = 8
STORY_INTRO = 9
PASS_DEVICE = 10
FETCHING = 11
MESSAGE_ANIM = 12
READING = 13
CHOOSING = 14
FEEDBACK = 15
CHAPTER_COMPLETE = 16
INITIALS_INPUT = 17
GAME_OVER = 18
STATS = 19
HOW_TO_PLAY = 20
WIFI_SETTINGS = 21
CREDITS = 22
PAUSE = 23
ERROR = 24
# OTA Updates
OTA_CHECK = 25
OTA_INFO = 26
OTA_UPDATING = 27
OTA_RESULT = 28
OTA_POPUP = 29 # Popup automático de actualización disponible
OTA_AUTO_CHECK = 30 # Verificación automática al inicio
# ============================================================================
# CLASE PRINCIPAL
# ============================================================================
class PsicOTronic:
"""Motor principal del juego PSIC-O-TRONIC"""
def __init__(self):
# Cargar versión desde version.json
self.version = self._load_version()
print("\n" + "="*40)
print(f" PSIC-O-TRONIC v{self.version}")
print("="*40)
# Inicializar hardware
self._init_gpio()
self._init_lcd()
self._init_audio()
# Estado
self.state = State.BOOT
self.prev_state = -1
self.frame = 0
# Menús
self.menu_idx = 0
self.mode_idx = 0
self.player_count = 1
self.quota_idx = 2 # Default: 5 casos
self.quota_options = [3, 5, 7, 10, 15, 999]
self.help_page = 0
# Sesión de juego
self.session = None
self.oracle = get_oracle()
# Para scroll de texto
self.opt_scroll = 0
# Para mostrar respuesta correcta al fallar
self.correct_answer_text = ""
self.feedback_scroll_idx = 0
self.feedback_lines = []
# Input de iniciales
self.initials_input = None
# LED blinking
self.blink_counter = 0
self.blink_state = False
# Estado antes de pausa
self.pre_pause_state = None
# Manejo de errores
self.error_msg = ""
self.error_detail = ""
self.error_scroll = 0
self.error_menu_idx = 0
# OTA automático al inicio
self._ota_checked_on_boot = False
self._ota_popup_dismissed = False # Si el usuario ya rechazó en esta sesión
# Buffer LCD para evitar flickering
self.lcd_buffer = [[' ' for _ in range(20)] for _ in range(4)]
self.lcd_shadow = [[' ' for _ in range(20)] for _ in range(4)]
def _load_version(self):
"""Carga la versión desde version.json"""
try:
with open('/version.json', 'r') as f:
data = ujson.load(f)
return data.get('version', '1.0')
except:
return '1.0' # Fallback si no se puede leer
def _init_gpio(self):
"""Inicializa pines GPIO"""
print("[INIT] GPIO...")
self.btn_up = Pin(PIN_BTN_UP, Pin.IN, Pin.PULL_UP)
self.btn_select = Pin(PIN_BTN_SELECT, Pin.IN, Pin.PULL_UP)
self.btn_down = Pin(PIN_BTN_DOWN, Pin.IN, Pin.PULL_UP)
self.led_up = Pin(PIN_LED_UP, Pin.OUT)
self.led_select = Pin(PIN_LED_SELECT, Pin.OUT)
self.led_down = Pin(PIN_LED_DOWN, Pin.OUT)
self.led_notify = Pin(PIN_LED_NOTIFY, Pin.OUT)
self._leds_off()
print("[INIT] GPIO OK")
def _init_audio(self):
"""Inicializa sistema de audio"""
print("[INIT] Audio...")
self.audio = init_audio(PIN_SPEAKER)
print("[INIT] Audio OK")
def _init_lcd(self):
"""Inicializa LCD"""
print("[INIT] LCD...")
i2c = I2C(1, sda=Pin(PIN_I2C_SDA), scl=Pin(PIN_I2C_SCL), freq=400000)
devs = i2c.scan()
if not devs:
print("[ERROR] No LCD found!")
while True:
self.led_notify.value(1)
time.sleep(0.1)
self.led_notify.value(0)
time.sleep(0.1)
self.lcd = I2cLcd(i2c, devs[0], 4, 20)
load_custom_chars(self.lcd)
self.lcd.clear()
print(f"[INIT] LCD OK @ {hex(devs[0])}")
def _leds_off(self):
"""Apaga todos los LEDs"""
self.led_up.value(0)
self.led_select.value(0)
self.led_down.value(0)
self.led_notify.value(0)
def _leds_menu(self):
"""LEDs para navegación de menú"""
self.led_up.value(1)
self.led_down.value(1)
self.led_select.value(self.blink_state)
def _leds_select_only(self):
"""Solo LED select parpadeando"""
self.led_up.value(0)
self.led_down.value(0)
self.led_select.value(self.blink_state)
def _leds_scroll(self, can_up, can_down):
"""LEDs para scroll"""
self.led_up.value(1 if can_up else 0)
self.led_down.value(1 if can_down else 0)
self.led_select.value(self.blink_state)
def _update_blink(self):
"""Actualiza estado de parpadeo"""
self.blink_counter += 1
if self.blink_counter >= 6:
self.blink_counter = 0
self.blink_state = not self.blink_state
# === INPUT ===
_last_btn_time = 0
def _get_input(self):
"""Lee input de botones con debounce, incluyendo combo UP+DOWN para BACK"""
now = time.ticks_ms()
if time.ticks_diff(now, self._last_btn_time) < DEBOUNCE_MS:
return None
up_pressed = self.btn_up.value() == 0
down_pressed = self.btn_down.value() == 0
select_pressed = self.btn_select.value() == 0
if not up_pressed and not down_pressed and not select_pressed:
return None
# Si UP o DOWN presionado, esperar para detectar combo
if up_pressed or down_pressed:
time.sleep(0.05)
up_pressed = self.btn_up.value() == 0
down_pressed = self.btn_down.value() == 0
if up_pressed and down_pressed:
self._last_btn_time = now
return 'BACK'
cmd = None
if select_pressed:
cmd = 'SELECT'
elif up_pressed:
cmd = 'UP'
elif down_pressed:
cmd = 'DOWN'
if cmd:
self._last_btn_time = now
return cmd
# === LCD HELPERS (CON BUFFER PARA EVITAR FLICKERING) ===
def _lcd_clear_buffer(self):
"""Limpia el buffer (no la pantalla física)"""
for y in range(4):
for x in range(20):
self.lcd_buffer[y][x] = ' '
def _lcd_clear(self):
"""Limpia el buffer - alias para compatibilidad"""
self._lcd_clear_buffer()
def _lcd_put(self, x, y, text):
"""Escribe texto en el buffer"""
if y < 0 or y >= 4:
return
safe = convert_text(text)
for i, char in enumerate(safe):
if 0 <= x + i < 20:
self.lcd_buffer[y][x + i] = char
def _lcd_centered(self, y, text):
"""Escribe texto centrado en el buffer"""
safe = convert_text(text)
x = max(0, (20 - len(safe)) // 2)
self._lcd_put(x, y, safe)
def _lcd_render(self):
"""Vuelca buffer a LCD físico, solo escribe lo que cambió"""
for y in range(4):
for x in range(20):
if self.lcd_buffer[y][x] != self.lcd_shadow[y][x]:
self.lcd.move_to(x, y)
self.lcd.putchar(self.lcd_buffer[y][x])
self.lcd_shadow[y][x] = self.lcd_buffer[y][x]
def _lcd_force_clear(self):
"""Limpia LCD físico completamente y sincroniza buffers"""
self.lcd.clear()
for y in range(4):
for x in range(20):
self.lcd_shadow[y][x] = ' '
self.lcd_buffer[y][x] = ' '
def _lcd_lines(self, lines):
"""Escribe múltiples líneas centradas"""
self._lcd_clear_buffer()
for i, line in enumerate(lines[:4]):
self._lcd_centered(i, line)
self._lcd_render()
def _wrap_text(self, text, width=20):
"""Divide texto en lineas (delegado a lcd_chars.wrap_text)"""
return wrap_text(text, width)
# === EFECTOS ===
def _effect_crt_intro(self):
"""Intro simple sin parpadeos"""
self._lcd_clear()
self._lcd_centered(0, "====================")
self._lcd_centered(1, " PSIC-O-TRONIC")
self._lcd_centered(2, f" ver {self.version}")
self._lcd_centered(3, "====================")
def _effect_message_alert(self):
"""Alerta de mensaje sin parpadeo"""
self._lcd_clear()
self._lcd_centered(0, "+------------------+")
self._lcd_centered(1, "* MENSAJE ENTRANTE *")
self._lcd_centered(2, "")
self._lcd_centered(3, "+------------------+")
self._lcd_render()
self.led_notify.value(1)
time.sleep(0.8)
self.led_notify.value(0)
# === ESTADOS DEL JUEGO ===
def _update_boot(self, key):
"""Estado: Boot"""
self._effect_crt_intro()
time.sleep(1)
# Verificar si necesita wipe por actualización
from config import check_and_wipe_if_needed, file_exists
wiped = check_and_wipe_if_needed()
if wiped:
# Si se hizo wipe, mostrar mensaje
self._lcd_clear()
self._lcd_centered(0, "ACTUALIZACION 2.3")
self._lcd_centered(1, "Datos reseteados")
self._lcd_centered(2, "Config limpia")
time.sleep(3)
# Detectar si es primera vez (no existe config.json)
if not file_exists("/config.json"):
self.state = State.FIRST_TIME_WELCOME
else:
self.state = State.WIFI_CHECK
def _update_first_time_welcome(self, key):
"""Estado: Bienvenida primera vez"""
# Inicializar página si no existe
if not hasattr(self, '_welcome_page'):
self._welcome_page = 0
self._lcd_clear()
# Mostrar pantalla según página actual
if self._welcome_page == 0:
# Pantalla 1: Bienvenida
self._lcd_centered(0, "BIENVENIDO A")
self._lcd_centered(1, "PSIC-O-TRONIC!")
self._lcd_put(0, 3, " [OK] Continuar")
elif self._welcome_page == 1:
# Pantalla 2: Instrucciones
self._lcd_put(0, 0, "Primero debes")
self._lcd_put(0, 1, "configurar:")
self._lcd_put(0, 2, "1. Red WiFi")
self._lcd_put(0, 3, "2. API de Gemini")
elif self._welcome_page == 2:
# Pantalla 3: Abrir portal
self._lcd_put(0, 0, "Se abrira el Portal")
self._lcd_put(0, 1, "Web de")
self._lcd_put(0, 2, "configuracion.")
self._lcd_put(0, 3, " [OK] Abrir")
self._leds_select_only()
# Avanzar página al presionar SELECT
if key == 'SELECT':
self._welcome_page += 1
if self._welcome_page > 2:
# Ir al portal WiFi
self.state = State.WIFI_PORTAL
self._welcome_page = 0
def _update_wifi_check(self, key):
"""Estado: Verificar WiFi"""
self._lcd_lines([
"Verificando",
"conexión WiFi...",
"",
""
])
if is_wifi_configured():
self._lcd_lines([
"Conectando a",
"red guardada...",
"",
""
])
success, result = connect_saved_wifi(timeout=10)
if success:
self._lcd_lines([
"WiFi conectado!",
f"IP: {result}",
"",
""
])
time.sleep(1)
self.state = State.INTRO
else:
self._lcd_lines([
"Error conexión",
"Abriendo portal",
"de configuracion",
""
])
time.sleep(2)
self.state = State.WIFI_PORTAL
else:
self.state = State.WIFI_PORTAL
def _update_wifi_portal(self, key):
"""Estado: Portal cautivo WiFi"""
def lcd_callback(lines):
self._lcd_lines(lines)
def check_cancel():
return self.btn_select.value() == 0 and self.btn_up.value() == 0
result = run_wifi_portal(lcd_callback=lcd_callback, check_button=check_cancel)
if result and result.get("connected"):
self._lcd_lines([
"Configuración",
"guardada!",
"",
"Reiniciando..."
])
time.sleep(2)
import machine
machine.reset()
else:
self.state = State.INTRO
def _update_intro(self, key):
"""Estado: Intro animada"""
step = self.frame // 5
if step < 8:
self._lcd_clear()
self._lcd_centered(0, "====================")
self._lcd_centered(1, " PSIC-O-TRONIC")
self._lcd_centered(2, f" ver {self.version}")
# Barra de carga
progress = min(20, step * 3)
bar = chr(0) * progress + "." * (20 - progress)
self._lcd_put(0, 3, bar)
# LEDs secuenciales
step_led = self.frame % 16
self.led_up.value(1 if step_led < 4 else 0)
self.led_select.value(1 if 4 <= step_led < 8 else 0)
self.led_down.value(1 if 8 <= step_led < 12 else 0)
self.led_notify.value(1 if step_led >= 12 else 0)
else:
self._leds_off()
play_sound('boot')
# Verificar actualizaciones si OTA está disponible y no se ha checkeado
if OTA_AVAILABLE and not self._ota_checked_on_boot:
self.state = State.OTA_AUTO_CHECK
else:
self.state = State.MENU
self.menu_idx = 0
def _update_menu(self, key):
"""Estado: Menú principal"""
options = ["Jugar", "Estadisticas", "Como Jugar", "Abrir Portal Web"]
# Añadir opción OTA si está disponible
if OTA_AVAILABLE:
if ota_manager.has_update():
options.append("Actualizar [!]")
else:
options.append("Actualizar")
options.append("Creditos")
self._lcd_clear()
self._lcd_centered(0, "== MENU ==")
# Mostrar 3 opciones visibles
start = max(0, min(self.menu_idx - 1, len(options) - 3))
for i in range(3):
idx = start + i
if idx < len(options):
prefix = ">" if idx == self.menu_idx else " "
label = options[idx]
if idx != self.menu_idx and len(label) > 18:
label = label[:17] + "~"
else:
label = label[:18]
self._lcd_put(1, i + 1, prefix + label)
# Indicadores de scroll con LEDs
can_up = self.menu_idx > 0
can_down = self.menu_idx < len(options) - 1
self._leds_scroll(can_up, can_down)
if key == 'UP':
self.menu_idx = (self.menu_idx - 1) % len(options)
play_sound('click')
elif key == 'DOWN':
self.menu_idx = (self.menu_idx + 1) % len(options)
play_sound('click')
elif key == 'BACK':
self.state = State.INTRO
self.frame = 0
elif key == 'SELECT':
play_sound('beep')
selected = options[self.menu_idx]
if selected == "Jugar":
self.state = State.MODE_SELECT
self.mode_idx = 0
elif selected == "Estadisticas":
self.state = State.STATS
elif selected == "Como Jugar":
self.state = State.HOW_TO_PLAY
self.help_page = 0
elif selected == "Abrir Portal Web":
self.state = State.WIFI_SETTINGS
elif selected.startswith("Actualizar"):
self.state = State.OTA_CHECK
self.frame = 0
elif selected == "Creditos":
self.state = State.CREDITS
def _update_mode_select(self, key):
"""Estado: Selección de modo"""
modes = ["Clasico", "Survival", "Mi Consulta", "Volver"]
self._lcd_clear()
self._lcd_centered(0, "MODO DE JUEGO")
# Mostrar 3 opciones visibles (líneas 1-3)
# Calcular ventana de scroll
if self.mode_idx < 2:
start = 0
elif self.mode_idx >= len(modes) - 1:
start = max(0, len(modes) - 3)
else:
start = self.mode_idx - 1
for row, i in enumerate(range(start, min(start + 3, len(modes)))):
prefix = ">" if i == self.mode_idx else " "
self._lcd_put(1, row + 1, f"{prefix}{modes[i]}")
# Indicadores de scroll con LEDs
can_up = self.mode_idx > 0
can_down = self.mode_idx < len(modes) - 1
self._leds_scroll(can_up, can_down)
if key == 'UP' and can_up:
self.mode_idx -= 1
elif key == 'DOWN' and can_down:
self.mode_idx += 1
elif key == 'BACK':
self.state = State.MENU
self.menu_idx = 0
elif key == 'SELECT':
if self.mode_idx == 2: # Mi Consulta
self._launch_career_mode()
elif self.mode_idx == 3: # Volver al Menu
self.state = State.MENU
self.menu_idx = 0
else:
self.state = State.PLAYER_SELECT
def _launch_career_mode(self):
"""Lanza el modo Mi Consulta"""
from career_mode import run_career_mode
run_career_mode(
self.lcd,
self.btn_up,
self.btn_select,
self.btn_down,
self.led_up,
self.led_select,
self.led_down,
self.led_notify
)
# Volver al menu principal - limpiar memoria
self.state = State.MENU
self.menu_idx = 0
self.mode_idx = 0
self.frame = 0
self._lcd_force_clear()
gc.collect() # Liberar memoria del career mode
def _update_player_select(self, key):
"""Estado: Selección de jugadores"""
self._lcd_clear()
self._lcd_centered(0, "JUGADORES")
self._lcd_centered(1, f"<< {self.player_count} >>")
self._lcd_put(0, 3, " [^v]Cambiar [OK]>")
self._leds_menu()
if key == 'UP' and self.player_count < 4:
self.player_count += 1
elif key == 'DOWN' and self.player_count > 1:
self.player_count -= 1
elif key == 'BACK':
self.state = State.MODE_SELECT
elif key == 'SELECT':
mode = MODE_SURVIVAL if self.mode_idx == 1 else MODE_CLASSIC
if mode == MODE_SURVIVAL:
self._start_game(mode)
else:
self.state = State.QUOTA_SELECT
def _update_quota_select(self, key):
"""Estado: Selección de cuota"""
val = self.quota_options[self.quota_idx]
val_str = "INFINITO" if val == 999 else str(val)
self._lcd_clear()
self._lcd_centered(0, "CASOS A RESOLVER")
self._lcd_centered(1, f"<< {val_str} >>")
self._lcd_put(0, 3, " [^v]Cambiar [OK]>")
self._leds_menu()
if key == 'UP':
self.quota_idx = min(len(self.quota_options) - 1, self.quota_idx + 1)
elif key == 'DOWN':
self.quota_idx = max(0, self.quota_idx - 1)
elif key == 'BACK':
self.state = State.PLAYER_SELECT
elif key == 'SELECT':
self._start_game(MODE_CLASSIC)
def _start_game(self, mode):
"""Inicia una nueva partida"""
quota = self.quota_options[self.quota_idx] if mode == MODE_CLASSIC else 999
self.session = GameSession(mode, self.player_count, quota)
self.session.start()
self.state = State.PASS_DEVICE
def _update_story_intro(self, key):
"""Estado: Intro de capítulo (historia)
NOTA: Este estado es parte del modo historia que está en desarrollo.
Los métodos necesarios aún no están implementados en GameSession.
"""
# TODO: Implementar get_chapter_intro() en GameSession
# intro = self.session.get_chapter_intro()
# Fallback temporal: mostrar mensaje genérico
self._lcd_clear()
self._lcd_centered(0, "MODO HISTORIA")
self._lcd_centered(1, "En desarrollo")
self._lcd_centered(2, "")
self._lcd_centered(3, "[OK] Continuar")
self._leds_select_only()
if key == 'SELECT':
self.state = State.PASS_DEVICE
def _update_pass_device(self, key):
"""Estado: Pasar dispositivo"""
player = self.session.get_current_player()
self._lcd_clear()
self._lcd_put(0, 0, self.session.get_status_line())
self._lcd_centered(1, "TURNO DE")
self._lcd_centered(2, f"JUGADOR {player['id']}")
self._lcd_centered(3, "[OK] Conectar")
self._leds_select_only()
if key == 'SELECT':
self.state = State.FETCHING
self.frame = 0
def _update_fetching(self, key):
"""Estado: Obteniendo caso"""
# Mostrar animación
antenna = ["^", "|", "/", "-", "\\", "|"][(self.frame // 4) % 6]
dots = "." * ((self.frame // 6) % 4)
self._lcd_clear()
self._lcd_centered(0, "+------------------+")
self._lcd_centered(1, f" CONECTANDO {antenna}")
self._lcd_put(0, 2, f" Línea psiquiátrica{dots}"[:20])
self._lcd_centered(3, "+------------------+")
self.led_notify.value(self.blink_state)
# Primera frame: hacer la petición
if self.frame == 1:
gc.collect()
modifier = self.session.get_prompt_modifier()
self.session.scenario = self.oracle.get_scenario(
mode=self.session.mode,
story_modifier=modifier
)
# Comprobar error
if self.session.scenario is None:
self.state = State.ERROR
self.error_msg = self.oracle.last_error or "Error desconocido"
self.error_detail = ""
self.led_notify.value(0)
return
# Preparar texto con nuevo formato
sender = self.session.scenario.get('remitente', 'Anónimo')
msg = self.session.scenario.get('mensaje', 'Error')
msg = msg.lstrip('!?¡¿ ') # Quitar signos al inicio
# Formato: DE: nombre + salto + MSG: texto
header = f"DE: {sender}"
body = f"MSG: {msg}"
# Wrap del cuerpo del mensaje
body_lines = self._wrap_text(body)
self.session.scroll_lines = [header] + body_lines
self.session.scroll_idx = 0
self.state = State.MESSAGE_ANIM
self.frame = 0
def _update_message_anim(self, key):
"""Estado: Animación de mensaje simple"""
step = self.frame // 4
# Sonido al inicio
if self.frame == 1:
play_sound('mensaje')
if step < 4:
# Mostrar mensaje entrante
self._lcd_clear()
self._lcd_centered(0, "+------------------+")
self._lcd_centered(1, "* MENSAJE ENTRANTE *")
self._lcd_centered(3, "+------------------+")
self.led_notify.value((self.frame // 3) % 2)
else:
self.led_notify.value(0)
self.state = State.READING
self.session.scroll_idx = 0
def _update_reading(self, key):
"""Estado: Leyendo mensaje (4 líneas completas)"""
# Detectar pausa (UP + DOWN a la vez)
if self.btn_up.value() == 0 and self.btn_down.value() == 0:
self.pre_pause_state = State.READING
self.state = State.PAUSE
return
self._lcd_clear()
# Mostrar 4 líneas visibles (aprovechando toda la pantalla)
lines = self.session.scroll_lines
idx = self.session.scroll_idx
for i in range(4):
if idx + i < len(lines):
self._lcd_put(0, i, lines[idx + i])
# Solo LEDs para indicar scroll (sin iconos en pantalla)
can_up = idx > 0
can_down = (idx + 4) < len(lines)
self._leds_scroll(can_up, can_down)
if key == 'UP' and can_up:
self.session.scroll_idx -= 1
elif key == 'DOWN' and can_down:
self.session.scroll_idx += 1
elif key == 'SELECT':
self.state = State.CHOOSING
self.session.selected_option = 0
self.opt_scroll = 0
def _update_choosing(self, key):
"""Estado: Eligiendo respuesta (4 opciones)"""
# Detectar pausa (UP + DOWN a la vez)
if self.btn_up.value() == 0 and self.btn_down.value() == 0:
self.pre_pause_state = State.CHOOSING
self.state = State.PAUSE
return
self._lcd_clear()
opts = self.session.scenario.get('opciones', [])
# Mostrar 4 opciones (una por línea)
for i in range(min(4, len(opts))):
text = convert_text(opts[i])
prefix = ">" if i == self.session.selected_option else " "
# Scroll horizontal para opcion larga (19 chars con prefijo)
max_visible = 19
if i == self.session.selected_option and len(text) > max_visible:
wait_frames = 8
scroll_speed = 3
max_offset = len(text) - max_visible
if self.opt_scroll < wait_frames:
offset = 0
else:
offset = ((self.opt_scroll - wait_frames) // scroll_speed) % (max_offset + wait_frames)
if offset > max_offset:
offset = 0
text = text[offset:offset + max_visible]
else:
if len(text) > max_visible:
text = text[:max_visible - 1] + "~"
else:
text = text[:max_visible]
self._lcd_put(0, i, "%s%s" % (prefix, text))
can_up = self.session.selected_option > 0
can_down = self.session.selected_option < len(opts) - 1
self._leds_scroll(can_up, can_down)
if key == 'UP' and can_up:
self.session.selected_option -= 1
self.opt_scroll = 0
elif key == 'DOWN' and can_down:
self.session.selected_option += 1
self.opt_scroll = 0
elif key == 'SELECT':
# Manejo especial para error 403 (API key bloqueada)
if self.session.scenario.get('tema_corto') == 'error_403':
selected = self.session.selected_option
if selected == 0: # Abrir Portal Web
self.state = State.WIFI_SETTINGS
elif selected == 1: # Reintentar
self.state = State.FETCHING
self.frame = 0
else: # Volver al Menu
self.state = State.MENU
self.menu_idx = 0
else:
# Flujo normal del juego
# Guardar respuesta correcta antes de procesar
correct_idx = self.session.scenario.get('correcta', 0)
opts = self.session.scenario.get('opciones', [])
if 0 <= correct_idx < len(opts):
self.correct_answer_text = opts[correct_idx]
else:
self.correct_answer_text = ""
self.session.process_answer(self.session.selected_option)
self.feedback_scroll_idx = 0
self.state = State.FEEDBACK
self.frame = 0
def _update_feedback(self, key):
"""Estado: Mostrando feedback con scroll para textos largos"""
blink = (self.frame // 4) % 2 == 0
# Sonido al inicio
if self.frame == 1:
if self.session.last_result_ok:
play_sound('correcto')
else:
play_sound('incorrecto')
# Preparar líneas de contenido en primera frame
if self.frame <= 1:
self.feedback_lines = []
self.feedback_scroll_idx = 0
if self.session.last_result_ok:
# ACIERTO: Título + feedback_win
self.feedback_lines.append("== CORRECTO ==")
self.feedback_lines.append("")
fb_lines = self._wrap_text(self.session.last_feedback)
self.feedback_lines.extend(fb_lines)
else:
# ERROR: Título + respuesta correcta + feedback_lose
self.feedback_lines.append("== INCORRECTO ==")
self.feedback_lines.append("")
self.feedback_lines.append("Correcta era:")
correct_lines = self._wrap_text(self.correct_answer_text)
self.feedback_lines.extend(correct_lines)
self.feedback_lines.append("")
self.feedback_lines.append("Resultado:")
fb_lines = self._wrap_text(self.session.last_feedback)
self.feedback_lines.extend(fb_lines)
self._lcd_clear()
# LED de error parpadea
if not self.session.last_result_ok:
self.led_notify.value(blink)
# Mostrar con scroll (3 líneas de contenido + 1 de controles)
idx = self.feedback_scroll_idx
for i in range(3):
if idx + i < len(self.feedback_lines):
self._lcd_centered(i, self.feedback_lines[idx + i])
# Indicadores de scroll y continuar
can_up = idx > 0
can_down = (idx + 3) < len(self.feedback_lines)
if can_up or can_down:
arrows = ""
if can_up:
arrows += "[^]"
if can_down:
arrows += "[v]"
self._lcd_put(0, 3, arrows)
self._lcd_put(14, 3, "[OK]>")
self._leds_scroll(can_up, can_down)
else:
self._lcd_centered(3, "[OK] Continuar")
self._leds_select_only()
# Manejar scroll
if key == 'UP' and can_up:
self.feedback_scroll_idx -= 1
return
elif key == 'DOWN' and can_down:
self.feedback_scroll_idx += 1
return
if key == 'SELECT':
self.led_notify.value(0)
game_state = self.session.check_game_state()
if game_state == "win":
self.state = State.GAME_OVER
# NOTA: chapter_complete está comentado porque el modo historia no está implementado
# elif game_state == "chapter_complete":
# self.state = State.CHAPTER_COMPLETE
elif game_state == "game_over":
# Comprobar si es récord
if self.session.mode == MODE_SURVIVAL:
stats = load_stats()
if self.session.total_score > stats.get("survival_record", 0):
self.initials_input = InitialsInput()
self.state = State.INITIALS_INPUT
return
self.state = State.GAME_OVER
else:
if self.session.next_turn():
self.state = State.PASS_DEVICE
else:
self.state = State.GAME_OVER