MarcosAutuori commited on
Commit
c79a44e
·
verified ·
1 Parent(s): a2f6240

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -44
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import gradio as gr
2
  import time
3
 
4
- # Dados idênticos ao jogo original
5
  GRID_NUMBERS = [
6
  10, 12, 14, 15, 16, 18, 20, 21,
7
  24, 25, 27, 28, 30, 32, 35, 36,
@@ -12,6 +12,7 @@ KEYBOARD_KEYS = [2, 3, 4, 5, 6, 7, 8, 9, 10]
12
  MAX_TIME = 150
13
 
14
  def get_empty_state():
 
15
  return {
16
  "solved": [False] * 32,
17
  "selected_idx": None,
@@ -31,9 +32,9 @@ def format_grid_button(idx, solved_list, selected_idx):
31
 
32
  def handle_game_logic(state, action_type, value=None):
33
  if state["game_over"]:
34
- return state, gr.update()
35
 
36
- feedback = ""
37
 
38
  if action_type == "select_target":
39
  state["selected_idx"] = value
@@ -42,10 +43,12 @@ def handle_game_logic(state, action_type, value=None):
42
 
43
  elif action_type == "select_factor":
44
  if state["selected_idx"] is None:
45
- feedback = "Selecione um número na grade primeiro!"
46
  else:
47
- state["current_factors"].append(value)
48
- feedback = f"Fatores: {' x '.join(map(str, state['current_factors']))}"
 
 
49
 
50
  if len(state["current_factors"]) == 2:
51
  a, b = state["current_factors"]
@@ -53,31 +56,31 @@ def handle_game_logic(state, action_type, value=None):
53
 
54
  if a * b == target:
55
  state["solved"][state["selected_idx"]] = True
56
- feedback = "✔️ Correto!"
57
  state["selected_idx"] = None
58
  state["current_factors"] = []
59
  else:
60
- feedback = "❌ Incorreto! Tente novamente."
61
  state["current_factors"] = []
62
 
63
- # Atualiza Score e Verifica Fim de Jogo
64
  elapsed = int(time.time() - state["start_time"])
65
  state["score"] = max(0, MAX_TIME - elapsed)
66
 
67
  if all(state["solved"]):
68
  state["game_over"] = True
69
- feedback = f"🏆 JOGO CONCLUÍDO! Pontuação Final: {state['score']}"
70
 
71
  return state, feedback
72
 
73
- with gr.Blocks(css=".grid-btn { height: 80px !important; font-size: 20px !important; }") as demo:
74
  state = gr.State(get_empty_state())
75
 
76
- gr.Markdown(f"# 🎮 Fatoração Interativa v1.4 EN\n**Objetivo:** Selecione um número e então seus dois fatores.")
77
 
78
  with gr.Row():
79
- with gr.Column(scale=2):
80
- # Grade 4x8
81
  grid_buttons = []
82
  for r in range(4):
83
  with gr.Row():
@@ -87,53 +90,49 @@ with gr.Blocks(css=".grid-btn { height: 80px !important; font-size: 20px !import
87
  grid_buttons.append(btn)
88
 
89
  with gr.Column(scale=1):
90
- # Painel de Status
91
- status_box = gr.Textbox(label="Status do Jogo", value="Selecione um número na grade", interactive=False)
92
- score_display = gr.Number(label="Pontos (Tempo)", value=MAX_TIME, interactive=False)
93
 
94
- gr.Markdown("### Teclado Numérico")
 
95
  keyboard_btns = []
96
  with gr.Row():
97
- for i, val in enumerate(KEYBOARD_KEYS):
98
- if i % 3 == 0 and i > 0:
99
- gr.Markdown("---") # Quebra de linha visual
100
- kb_btn = gr.Button(str(val), variant="secondary")
101
  keyboard_btns.append(kb_btn)
102
 
103
- reset_btn = gr.Button("Reiniciar Jogo", variant="stop")
104
 
105
- # Eventos da Grade
 
 
 
 
 
 
 
106
  for i, btn in enumerate(grid_buttons):
107
  btn.click(
108
  fn=lambda s, idx=i: handle_game_logic(s, "select_target", idx),
109
  inputs=[state],
110
  outputs=[state, status_box]
111
- ).then(
112
- fn=lambda s: [format_grid_button(j, s["solved"], s["selected_idx"]) for j in range(32)],
113
- inputs=[state],
114
- outputs=grid_buttons
115
- ).then(
116
- fn=lambda s: s["score"], inputs=[state], outputs=[score_display]
117
- )
118
 
119
- # Eventos do Teclado
120
- for btn in keyboard_btns:
121
- btn.click(
122
- fn=lambda s, v=int(btn.value) if isinstance(btn.value, str) else btn.value: handle_game_logic(s, "select_factor", int(btn.value)),
 
123
  inputs=[state],
124
  outputs=[state, status_box]
125
- ).then(
126
- fn=lambda s: [format_grid_button(j, s["solved"], s["selected_idx"]) for j in range(32)],
127
- inputs=[state],
128
- outputs=grid_buttons
129
- ).then(
130
- fn=lambda s: s["score"], inputs=[state], outputs=[score_display]
131
- )
132
 
133
- # Reset
134
  def reset_all():
135
  new_state = get_empty_state()
136
- return [new_state, "Jogo reiniciado!"] + [gr.update(value=str(GRID_NUMBERS[j]), variant="secondary", interactive=True) for j in range(32)] + [MAX_TIME]
 
137
 
138
  reset_btn.click(
139
  fn=reset_all,
 
1
  import gradio as gr
2
  import time
3
 
4
+ # Dados baseados na sua versão 1.4 EN
5
  GRID_NUMBERS = [
6
  10, 12, 14, 15, 16, 18, 20, 21,
7
  24, 25, 27, 28, 30, 32, 35, 36,
 
12
  MAX_TIME = 150
13
 
14
  def get_empty_state():
15
+ """Inicializa o estado conforme o script original"""
16
  return {
17
  "solved": [False] * 32,
18
  "selected_idx": None,
 
32
 
33
  def handle_game_logic(state, action_type, value=None):
34
  if state["game_over"]:
35
+ return state, "Fim de jogo! Reinicie para jogar novamente."
36
 
37
+ feedback = "Selecione um número na grade..."
38
 
39
  if action_type == "select_target":
40
  state["selected_idx"] = value
 
43
 
44
  elif action_type == "select_factor":
45
  if state["selected_idx"] is None:
46
+ feedback = "⚠️ Selecione um número na grade primeiro!"
47
  else:
48
+ state["current_factors"].append(int(value))
49
+ # Mostra os fatores atuais
50
+ factors_str = " x ".join(map(str, state["current_factors"]))
51
+ feedback = f"Calculando: {factors_str}"
52
 
53
  if len(state["current_factors"]) == 2:
54
  a, b = state["current_factors"]
 
56
 
57
  if a * b == target:
58
  state["solved"][state["selected_idx"]] = True
59
+ feedback = f"✔️ {a} x {b} = {target}! Correto!"
60
  state["selected_idx"] = None
61
  state["current_factors"] = []
62
  else:
63
+ feedback = f"❌ {a} x {b} = {a*b} (Errado para {target}). Tente de novo!"
64
  state["current_factors"] = []
65
 
66
+ # Atualiza Score e Verifica Conclusão
67
  elapsed = int(time.time() - state["start_time"])
68
  state["score"] = max(0, MAX_TIME - elapsed)
69
 
70
  if all(state["solved"]):
71
  state["game_over"] = True
72
+ feedback = f"🏆 PARABÉNS! Você completou a grade com {state['score']} pontos!"
73
 
74
  return state, feedback
75
 
76
+ with gr.Blocks(title="Interactive Factorization v1.4", css=".grid-btn { height: 70px !important; }") as demo:
77
  state = gr.State(get_empty_state())
78
 
79
+ gr.Markdown(f"# 🎮 Interactive Factorization - Marcos Autúori")
80
 
81
  with gr.Row():
82
+ with gr.Column(scale=3):
83
+ # Grade de Números (4x8)
84
  grid_buttons = []
85
  for r in range(4):
86
  with gr.Row():
 
90
  grid_buttons.append(btn)
91
 
92
  with gr.Column(scale=1):
93
+ # Painel Lateral de Status
94
+ status_box = gr.Textbox(label="Instruções / Feedback", value="Clique em um número azul para começar", interactive=False)
95
+ score_display = gr.Number(label="Pontuação", value=MAX_TIME, interactive=False)
96
 
97
+ gr.Markdown("### Teclado de Fatores")
98
+ # Criamos os botões do teclado e vinculamos a lógica
99
  keyboard_btns = []
100
  with gr.Row():
101
+ for val in KEYBOARD_KEYS:
102
+ kb_btn = gr.Button(str(val), variant="secondary", min_width=50)
 
 
103
  keyboard_btns.append(kb_btn)
104
 
105
+ reset_btn = gr.Button("Reiniciar Partida", variant="stop")
106
 
107
+ # --- MAPEAMENTO DE EVENTOS ---
108
+
109
+ # Função auxiliar para atualizar visualmente toda a interface
110
+ def update_ui(s):
111
+ updates = [format_grid_button(i, s["solved"], s["selected_idx"]) for i in range(32)]
112
+ return updates + [s["score"]]
113
+
114
+ # Clique na Grade
115
  for i, btn in enumerate(grid_buttons):
116
  btn.click(
117
  fn=lambda s, idx=i: handle_game_logic(s, "select_target", idx),
118
  inputs=[state],
119
  outputs=[state, status_box]
120
+ ).then(fn=update_ui, inputs=[state], outputs=grid_buttons + [score_display])
 
 
 
 
 
 
121
 
122
+ # Clique no Teclado (Correção da Closure aqui)
123
+ for kb_btn in keyboard_btns:
124
+ # Usamos o próprio valor do botão como entrada para garantir que o número correto seja enviado
125
+ kb_btn.click(
126
+ fn=lambda s, v=kb_btn.value: handle_game_logic(s, "select_factor", v),
127
  inputs=[state],
128
  outputs=[state, status_box]
129
+ ).then(fn=update_ui, inputs=[state], outputs=grid_buttons + [score_display])
 
 
 
 
 
 
130
 
131
+ # Função de Reset
132
  def reset_all():
133
  new_state = get_empty_state()
134
+ updates = [gr.update(value=str(num), variant="secondary", interactive=True) for num in GRID_NUMBERS]
135
+ return [new_state, "Jogo reiniciado!"] + updates + [MAX_TIME]
136
 
137
  reset_btn.click(
138
  fn=reset_all,