Repository navigation
Expand file tree
/
Copy pathgui.py
More file actions
575 lines (483 loc) · 22.2 KB
/
Copy pathgui.py
File metadata and controls
575 lines (483 loc) · 22.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
"""
gui.py — Interfaz gráfica con Tkinter para el juego de combate.
Se integra con los objetos reales del sistema de combate.
"""
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from combate import Combate, registrar_victoria
from api_client import obtener_clima_actual, modificador_clima, describir_clima
from efectos import EFECTOS
# ── Tipos disponibles (importar subclases) ─────────────────────────
from guerrero import Guerrero
from mago import Mago
from arquero import Arquero
from sanador import Sanador
from asesino import Asesino
TIPOS_CLASES = {
"Guerrero": Guerrero,
"Mago": Mago,
"Arquero": Arquero,
"Sanador": Sanador,
"Asesino": Asesino,
}
def iniciar_gui(personajes_lista):
"""Punto de entrada de la GUI. Recibe la lista real de personajes."""
root = tk.Tk()
root.title("⚔️ Juego de Combate por Turnos — Steampunk")
root.geometry("950x700")
root.configure(bg="#1a1a2e")
root.resizable(True, True)
app = AppCombate(root, personajes_lista)
root.mainloop()
class AppCombate:
"""Clase principal de la aplicación gráfica."""
BG_COLOR = "#1a1a2e"
FG_COLOR = "#eaeaea"
ACCENT = "#e94560"
ACCENT2 = "#0f3460"
CARD_BG = "#16213e"
def __init__(self, root, personajes):
self.root = root
self.personajes = personajes
self._construir_ui()
def _construir_ui(self):
"""Construye la interfaz principal."""
# ── Título ──
titulo_frame = tk.Frame(self.root, bg=self.ACCENT, pady=8)
titulo_frame.pack(fill=tk.X)
tk.Label(
titulo_frame, text="⚔️ JUEGO DE COMBATE POR TURNOS ⚔️",
font=("Segoe UI", 18, "bold"), bg=self.ACCENT, fg="white"
).pack()
tk.Label(
titulo_frame, text="— Universo Steampunk —",
font=("Segoe UI", 10), bg=self.ACCENT, fg="#ffcccc"
).pack()
# ── Frame principal ──
main_frame = tk.Frame(self.root, bg=self.BG_COLOR)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# ── Panel izquierdo: lista de personajes ──
left_frame = tk.LabelFrame(
main_frame, text="📋 Personajes", font=("Segoe UI", 12, "bold"),
bg=self.CARD_BG, fg=self.FG_COLOR, padx=10, pady=10
)
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
# Listbox con scroll
list_container = tk.Frame(left_frame, bg=self.CARD_BG)
list_container.pack(fill=tk.BOTH, expand=True)
self.listbox = tk.Listbox(
list_container, font=("Consolas", 10), bg="#0d1b2a", fg="#a8d8ea",
selectbackground=self.ACCENT, selectforeground="white",
height=15, relief=tk.FLAT, bd=0
)
scrollbar = ttk.Scrollbar(list_container, orient=tk.VERTICAL, command=self.listbox.yview)
self.listbox.configure(yscrollcommand=scrollbar.set)
self.listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Info del personaje seleccionado
self.info_label = tk.Label(
left_frame, text="Selecciona un personaje para ver detalles",
font=("Segoe UI", 9), bg=self.CARD_BG, fg="#777",
wraplength=350, justify=tk.LEFT, anchor="w"
)
self.info_label.pack(fill=tk.X, pady=(5, 0))
self.listbox.bind("<<ListboxSelect>>", self._on_select_personaje)
# ── Panel central: botones ──
center_frame = tk.Frame(main_frame, bg=self.BG_COLOR, padx=10)
center_frame.pack(side=tk.LEFT, fill=tk.Y)
botones = [
("➕ Crear Personaje", self.boton_crear_personaje),
("⚔️ Iniciar Combate", self.boton_iniciar_combate),
("💾 Guardar", self.boton_guardar),
("📂 Cargar", self.boton_cargar),
("🗑️ Eliminar", self.boton_eliminar),
]
for texto, comando in botones:
btn = tk.Button(
center_frame, text=texto, command=comando,
font=("Segoe UI", 11, "bold"), bg=self.ACCENT2, fg="white",
activebackground=self.ACCENT, activeforeground="white",
relief=tk.FLAT, cursor="hand2", width=18, pady=6
)
btn.pack(pady=4)
# ── Panel derecho: log ──
right_frame = tk.LabelFrame(
main_frame, text="📜 Log del Sistema", font=("Segoe UI", 12, "bold"),
bg=self.CARD_BG, fg=self.FG_COLOR, padx=10, pady=10
)
right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(5, 0))
self.log_text = tk.Text(
right_frame, font=("Consolas", 9), bg="#0d1b2a", fg="#a8d8ea",
height=20, wrap=tk.WORD, relief=tk.FLAT, bd=0, state=tk.DISABLED
)
log_scroll = ttk.Scrollbar(right_frame, orient=tk.VERTICAL, command=self.log_text.yview)
self.log_text.configure(yscrollcommand=log_scroll.set)
self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
log_scroll.pack(side=tk.RIGHT, fill=tk.Y)
# Actualizar lista
self._actualizar_lista()
self._log("Sistema iniciado. ¡Crea personajes y empieza a combatir!")
def _log(self, mensaje):
"""Añade un mensaje al log del sistema."""
self.log_text.configure(state=tk.NORMAL)
self.log_text.insert(tk.END, mensaje + "\n")
self.log_text.see(tk.END)
self.log_text.configure(state=tk.DISABLED)
def _actualizar_lista(self):
"""Actualiza el listbox con los personajes actuales."""
self.listbox.delete(0, tk.END)
for p in self.personajes:
efectos_str = ""
if p.efectos_activos:
efectos_str = " " + "".join(
EFECTOS.get(e["tipo"], {}).get("emoji", "❓") for e in p.efectos_activos
)
self.listbox.insert(tk.END, f"[{p.tipo}] {p.nombre} — ❤️ {p.vida}/{p.vida_max}{efectos_str}")
def _on_select_personaje(self, event):
"""Muestra detalles del personaje seleccionado."""
sel = self.listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self.personajes):
p = self.personajes[idx]
self.info_label.configure(text=str(p))
# ── Acciones de botones ───────────────────────────────────────
def boton_crear_personaje(self):
"""Diálogo para crear un nuevo personaje."""
nombre = simpledialog.askstring(
"Crear Personaje", "Nombre del personaje (mín. 2 caracteres):",
parent=self.root
)
if not nombre or len(nombre.strip()) < 2:
messagebox.showwarning("Error", "El nombre debe tener al menos 2 caracteres.")
return
nombre = nombre.strip()
# Ventana para elegir tipo
tipo_win = tk.Toplevel(self.root)
tipo_win.title("Elegir Tipo")
tipo_win.geometry("300x300")
tipo_win.configure(bg=self.BG_COLOR)
tipo_win.transient(self.root)
tipo_win.grab_set()
tk.Label(
tipo_win, text="Elige el tipo de personaje:",
font=("Segoe UI", 12, "bold"), bg=self.BG_COLOR, fg=self.FG_COLOR
).pack(pady=10)
tipo_elegido = tk.StringVar()
for tipo_nombre in TIPOS_CLASES:
btn = tk.Radiobutton(
tipo_win, text=tipo_nombre, variable=tipo_elegido, value=tipo_nombre,
font=("Segoe UI", 11), bg=self.BG_COLOR, fg=self.FG_COLOR,
selectcolor=self.ACCENT2, activebackground=self.BG_COLOR,
activeforeground=self.ACCENT
)
btn.pack(anchor="w", padx=30, pady=2)
def confirmar():
t = tipo_elegido.get()
if not t:
messagebox.showwarning("Error", "Selecciona un tipo.")
return
clase = TIPOS_CLASES[t]
nuevo = clase(nombre)
self.personajes.append(nuevo)
self._actualizar_lista()
self._log(f"➕ Creado: [{t}] {nombre}")
tipo_win.destroy()
tk.Button(
tipo_win, text="✅ Crear", command=confirmar,
font=("Segoe UI", 11, "bold"), bg=self.ACCENT, fg="white",
relief=tk.FLAT, cursor="hand2", width=15, pady=4
).pack(pady=15)
def boton_iniciar_combate(self):
"""Abre ventana de combate para seleccionar dos personajes."""
if len(self.personajes) < 2:
messagebox.showwarning("Error", "Necesitas al menos 2 personajes para combatir.")
return
# Ventana de selección
sel_win = tk.Toplevel(self.root)
sel_win.title("Seleccionar Combatientes")
sel_win.geometry("400x400")
sel_win.configure(bg=self.BG_COLOR)
sel_win.transient(self.root)
sel_win.grab_set()
tk.Label(
sel_win, text="Selecciona dos personajes:",
font=("Segoe UI", 12, "bold"), bg=self.BG_COLOR, fg=self.FG_COLOR
).pack(pady=10)
tk.Label(sel_win, text="Personaje 1:", font=("Segoe UI", 10), bg=self.BG_COLOR, fg=self.FG_COLOR).pack()
p1_var = tk.StringVar()
nombres = [f"{p.nombre} ({p.tipo})" for p in self.personajes]
combo1 = ttk.Combobox(sel_win, textvariable=p1_var, values=nombres, state="readonly", width=30)
combo1.pack(pady=5)
tk.Label(sel_win, text="Personaje 2:", font=("Segoe UI", 10), bg=self.BG_COLOR, fg=self.FG_COLOR).pack()
p2_var = tk.StringVar()
combo2 = ttk.Combobox(sel_win, textvariable=p2_var, values=nombres, state="readonly", width=30)
combo2.pack(pady=5)
def iniciar():
idx1 = combo1.current()
idx2 = combo2.current()
if idx1 == -1 or idx2 == -1:
messagebox.showwarning("Error", "Selecciona ambos personajes.")
return
if idx1 == idx2:
messagebox.showwarning("Error", "Los personajes deben ser distintos.")
return
sel_win.destroy()
self.ventana_combate(self.personajes[idx1], self.personajes[idx2])
tk.Button(
sel_win, text="⚔️ Iniciar Combate", command=iniciar,
font=("Segoe UI", 11, "bold"), bg=self.ACCENT, fg="white",
relief=tk.FLAT, cursor="hand2", width=20, pady=6
).pack(pady=20)
def ventana_combate(self, p1, p2):
"""Ventana secundaria para el combate turno a turno."""
# Preparar combate
combate = Combate(p1, p2)
combate.clima = obtener_clima_actual()
combate.mod_clima = modificador_clima(combate.clima)
# Restaurar personajes
p1.vida = p1.vida_max
p2.vida = p2.vida_max
p1.efectos_activos = []
p2.efectos_activos = []
p1.recarga_actual = 0
p2.recarga_actual = 0
# Crear ventana
win = tk.Toplevel(self.root)
win.title(f"⚔️ {p1.nombre} vs {p2.nombre}")
win.geometry("800x600")
win.configure(bg=self.BG_COLOR)
win.transient(self.root)
# ── Header con clima ──
header = tk.Frame(win, bg="#0f3460", pady=6)
header.pack(fill=tk.X)
clima_desc = describir_clima(combate.clima)
tk.Label(
header, text=clima_desc, font=("Segoe UI", 9),
bg="#0f3460", fg="#a8d8ea", justify=tk.LEFT
).pack()
# ── Panel de combatientes ──
fighters_frame = tk.Frame(win, bg=self.BG_COLOR, pady=10)
fighters_frame.pack(fill=tk.X, padx=20)
# P1
p1_frame = tk.LabelFrame(
fighters_frame, text=f"🟢 {p1.nombre} ({p1.tipo})",
font=("Segoe UI", 11, "bold"), bg=self.CARD_BG, fg="#4ecca3", padx=15, pady=10
)
p1_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
p1_hp_label = tk.Label(
p1_frame, text=f"❤️ {p1.vida}/{p1.vida_max}",
font=("Segoe UI", 12), bg=self.CARD_BG, fg=self.FG_COLOR
)
p1_hp_label.pack()
p1_bar = ttk.Progressbar(p1_frame, maximum=p1.vida_max, value=p1.vida, length=250)
p1_bar.pack(pady=5)
p1_stats = tk.Label(
p1_frame, text=f"⚔️ ATK: {p1.ataque} | 🛡️ DEF: {p1.defensa}",
font=("Segoe UI", 9), bg=self.CARD_BG, fg="#888"
)
p1_stats.pack()
p1_efectos_label = tk.Label(
p1_frame, text="🌀 Efectos: Ninguno",
font=("Segoe UI", 9), bg=self.CARD_BG, fg="#888"
)
p1_efectos_label.pack()
# P2
p2_frame = tk.LabelFrame(
fighters_frame, text=f"🔴 {p2.nombre} ({p2.tipo})",
font=("Segoe UI", 11, "bold"), bg=self.CARD_BG, fg="#e94560", padx=15, pady=10
)
p2_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(5, 0))
p2_hp_label = tk.Label(
p2_frame, text=f"❤️ {p2.vida}/{p2.vida_max}",
font=("Segoe UI", 12), bg=self.CARD_BG, fg=self.FG_COLOR
)
p2_hp_label.pack()
p2_bar = ttk.Progressbar(p2_frame, maximum=p2.vida_max, value=p2.vida, length=250)
p2_bar.pack(pady=5)
p2_stats = tk.Label(
p2_frame, text=f"⚔️ ATK: {p2.ataque} | 🛡️ DEF: {p2.defensa}",
font=("Segoe UI", 9), bg=self.CARD_BG, fg="#888"
)
p2_stats.pack()
p2_efectos_label = tk.Label(
p2_frame, text="🌀 Efectos: Ninguno",
font=("Segoe UI", 9), bg=self.CARD_BG, fg="#888"
)
p2_efectos_label.pack()
# ── Log de combate ──
log_frame = tk.LabelFrame(
win, text="📜 Log de Combate", font=("Segoe UI", 10, "bold"),
bg=self.CARD_BG, fg=self.FG_COLOR, padx=10, pady=5
)
log_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=(5, 5))
combat_log = tk.Text(
log_frame, font=("Consolas", 9), bg="#0d1b2a", fg="#a8d8ea",
height=10, wrap=tk.WORD, relief=tk.FLAT, bd=0, state=tk.DISABLED
)
combat_scroll = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=combat_log.yview)
combat_log.configure(yscrollcommand=combat_scroll.set)
combat_log.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
combat_scroll.pack(side=tk.RIGHT, fill=tk.Y)
# ── Botones de acción ──
btn_frame = tk.Frame(win, bg=self.BG_COLOR, pady=8)
btn_frame.pack(fill=tk.X, padx=20)
turno_label = tk.Label(
btn_frame, text=f"📌 Turno 1 — Turno de {p1.nombre}",
font=("Segoe UI", 11, "bold"), bg=self.BG_COLOR, fg=self.FG_COLOR
)
turno_label.pack()
# Estado
state = {"turno": 1, "terminado": False}
def log_combat(msg):
combat_log.configure(state=tk.NORMAL)
combat_log.insert(tk.END, msg + "\n")
combat_log.see(tk.END)
combat_log.configure(state=tk.DISABLED)
def actualizar_ui():
p1_hp_label.configure(text=f"❤️ {p1.vida}/{p1.vida_max}")
p2_hp_label.configure(text=f"❤️ {p2.vida}/{p2.vida_max}")
p1_bar.configure(value=max(0, p1.vida))
p2_bar.configure(value=max(0, p2.vida))
# Efectos
ef1 = ", ".join(
f"{EFECTOS.get(e['tipo'], {}).get('emoji', '❓')}{e['tipo']}({e['turnos']}t)"
for e in p1.efectos_activos
) if p1.efectos_activos else "Ninguno"
ef2 = ", ".join(
f"{EFECTOS.get(e['tipo'], {}).get('emoji', '❓')}{e['tipo']}({e['turnos']}t)"
for e in p2.efectos_activos
) if p2.efectos_activos else "Ninguno"
p1_efectos_label.configure(text=f"🌀 Efectos: {ef1}")
p2_efectos_label.configure(text=f"🌀 Efectos: {ef2}")
def get_atacante_defensor():
if state["turno"] % 2 == 1:
return p1, p2
return p2, p1
def procesar_efectos_y_paralisis(atacante, defensor):
"""Aplica efectos y verifica parálisis. Devuelve True si debe saltarse turno."""
mensajes_efectos = atacante.aplicar_efectos()
for msg in mensajes_efectos:
log_combat(f" {msg}")
actualizar_ui()
if not atacante.esta_vivo():
log_combat(f"\n💀 {atacante.nombre} ha caído por efectos de estado!")
registrar_victoria(defensor.nombre)
finalizar_combate(defensor)
return True
paralizado = any(e["tipo"] == "paralisis" for e in atacante.efectos_activos)
if paralizado:
log_combat(f"⚡ {atacante.nombre} está paralizado y no puede actuar!")
atacante.reducir_recarga()
avanzar_turno()
return True
return False
def accion_atacar():
if state["terminado"]:
return
atacante, defensor = get_atacante_defensor()
if procesar_efectos_y_paralisis(atacante, defensor):
return
resultado = atacante.atacar(defensor)
log_combat(f"\n{resultado['mensaje']}")
if resultado.get("critico"):
log_combat("💥💥💥 ¡¡GOLPE CRÍTICO!! 💥💥💥")
messagebox.showinfo("💥 ¡CRÍTICO!", f"¡{atacante.nombre} asesta un golpe crítico!")
atacante.reducir_recarga()
actualizar_ui()
if not defensor.esta_vivo():
log_combat(f"\n💀 {defensor.nombre} ha sido derrotado!")
registrar_victoria(atacante.nombre)
finalizar_combate(atacante)
return
avanzar_turno()
def accion_habilidad():
if state["terminado"]:
return
atacante, defensor = get_atacante_defensor()
if procesar_efectos_y_paralisis(atacante, defensor):
return
resultado = atacante.usar_habilidad(defensor, combate.mod_clima)
if "error" in resultado:
log_combat(f"\n{resultado['mensaje']}")
messagebox.showwarning("Habilidad", resultado["mensaje"])
return # No consume turno si falla
log_combat(f"\n{resultado['mensaje']}")
if resultado.get("efecto"):
messagebox.showinfo("✨ Habilidad Especial",
f"{atacante.nombre} usa {atacante.habilidad_nombre}!\nEfecto: {resultado['efecto']}")
atacante.reducir_recarga()
actualizar_ui()
if not defensor.esta_vivo():
log_combat(f"\n💀 {defensor.nombre} ha sido derrotado!")
registrar_victoria(atacante.nombre)
finalizar_combate(atacante)
return
avanzar_turno()
def avanzar_turno():
state["turno"] += 1
atacante, _ = get_atacante_defensor()
turno_label.configure(text=f"📌 Turno {state['turno']} — Turno de {atacante.nombre}")
# Mostrar estado habilidad
hab_estado = "Lista ✅" if atacante.puede_usar_habilidad() else f"Recarga: {atacante.recarga_actual}t ⏳"
hab_btn.configure(text=f"✨ {atacante.habilidad_nombre} ({hab_estado})")
def finalizar_combate(ganador):
state["terminado"] = True
atk_btn.configure(state=tk.DISABLED)
hab_btn.configure(state=tk.DISABLED)
self._actualizar_lista()
self._log(f"🏆 {ganador.nombre} gana el combate!")
messagebox.showinfo(
"🏆 ¡Combate Terminado!",
f"¡{ganador.nombre} ({ganador.tipo}) gana!\n"
f"❤️ HP restante: {ganador.vida}/{ganador.vida_max}"
)
atacante_inicio, _ = get_atacante_defensor()
hab_estado = "Lista ✅" if atacante_inicio.puede_usar_habilidad() else f"Recarga: {atacante_inicio.recarga_actual}t ⏳"
atk_btn = tk.Button(
btn_frame, text="⚔️ Atacar", command=accion_atacar,
font=("Segoe UI", 12, "bold"), bg="#e94560", fg="white",
activebackground="#ff6b81", relief=tk.FLAT, cursor="hand2", width=18, pady=6
)
atk_btn.pack(side=tk.LEFT, padx=10, expand=True)
hab_btn = tk.Button(
btn_frame, text=f"✨ {atacante_inicio.habilidad_nombre} ({hab_estado})",
command=accion_habilidad,
font=("Segoe UI", 12, "bold"), bg="#0f3460", fg="white",
activebackground="#1a508b", relief=tk.FLAT, cursor="hand2", width=28, pady=6
)
hab_btn.pack(side=tk.LEFT, padx=10, expand=True)
# Log clima
log_combat(describir_clima(combate.clima))
log_combat(f"\n⚔️ ¡Comienza el combate entre {p1.nombre} y {p2.nombre}!\n")
def boton_guardar(self):
"""Guarda los personajes actuales en JSON."""
from persistencia import guardar_personajes
guardar_personajes(self.personajes)
self._log("💾 Personajes guardados en personajes.json")
messagebox.showinfo("Guardado", f"✅ {len(self.personajes)} personajes guardados.")
def boton_cargar(self):
"""Carga los personajes desde JSON."""
from persistencia import cargar_personajes
cargados = cargar_personajes()
if cargados:
self.personajes.clear()
self.personajes.extend(cargados)
self._actualizar_lista()
self._log(f"📂 {len(cargados)} personajes cargados desde JSON.")
messagebox.showinfo("Cargado", f"✅ {len(cargados)} personajes cargados.")
else:
messagebox.showwarning("Cargar", "No se encontraron personajes guardados.")
def boton_eliminar(self):
"""Elimina el personaje seleccionado."""
sel = self.listbox.curselection()
if not sel:
messagebox.showwarning("Error", "Selecciona un personaje para eliminar.")
return
idx = sel[0]
p = self.personajes[idx]
if messagebox.askyesno("Eliminar", f"¿Eliminar a {p.nombre} ({p.tipo})?"):
self._log(f"🗑️ Eliminado: [{p.tipo}] {p.nombre}")
self.personajes.pop(idx)
self._actualizar_lista()