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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -33
app.py CHANGED
@@ -1,7 +1,7 @@
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,7 +12,6 @@ KEYBOARD_KEYS = [2, 3, 4, 5, 6, 7, 8, 9, 10]
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,7 +31,7 @@ def format_grid_button(idx, solved_list, selected_idx):
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
 
@@ -46,9 +45,8 @@ def handle_game_logic(state, action_type, value=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"]
@@ -60,27 +58,40 @@ def handle_game_logic(state, action_type, value=None):
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,28 +101,26 @@ with gr.Blocks(title="Interactive Factorization v1.4", css=".grid-btn { height:
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),
@@ -119,25 +128,20 @@ with gr.Blocks(title="Interactive Factorization v1.4", css=".grid-btn { height:
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,
139
- outputs=[state, status_box] + grid_buttons + [score_display]
140
- )
141
 
142
  if __name__ == "__main__":
143
  demo.launch()
 
1
  import gradio as gr
2
  import time
3
 
4
+ # Dados extraídos do seu factorization_game.py
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
  return {
16
  "solved": [False] * 32,
17
  "selected_idx": None,
 
31
 
32
  def handle_game_logic(state, action_type, value=None):
33
  if state["game_over"]:
34
+ return state, "Fim de jogo! Reinicie para jogar."
35
 
36
  feedback = "Selecione um número na grade..."
37
 
 
45
  feedback = "⚠️ Selecione um número na grade primeiro!"
46
  else:
47
  state["current_factors"].append(int(value))
 
48
  factors_str = " x ".join(map(str, state["current_factors"]))
49
+ feedback = f"Multiplicando: {factors_str}"
50
 
51
  if len(state["current_factors"]) == 2:
52
  a, b = state["current_factors"]
 
58
  state["selected_idx"] = None
59
  state["current_factors"] = []
60
  else:
61
+ feedback = f"❌ {a} x {b} = {a*b} (Errado para {target})."
62
  state["current_factors"] = []
63
 
 
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"🏆 COMPLETO! Pontuação: {state['score']}"
70
 
71
  return state, feedback
72
 
73
+ # CSS customizado para garantir retângulos idênticos
74
+ custom_css = """
75
+ .grid-btn {
76
+ min-width: 70px !important;
77
+ height: 70px !important;
78
+ font-size: 18px !important;
79
+ margin: 2px !important;
80
+ }
81
+ .kb-btn {
82
+ min-width: 50px !important;
83
+ height: 50px !important;
84
+ }
85
+ """
86
+
87
+ with gr.Blocks(title="Factorization Game v1.4", css=custom_css) as demo:
88
  state = gr.State(get_empty_state())
89
 
90
+ gr.Markdown("# 🎮 Interactive Factorization v1.4 EN\n**Desenvolvedor:** Marcos Autúori")
91
 
92
  with gr.Row():
93
+ with gr.Column(scale=4):
94
+ # Grade 4x8 Uniforme
95
  grid_buttons = []
96
  for r in range(4):
97
  with gr.Row():
 
101
  grid_buttons.append(btn)
102
 
103
  with gr.Column(scale=1):
104
+ status_box = gr.Textbox(label="Status", value="Selecione um número", interactive=False)
105
+ score_display = gr.Number(label="Pontos", value=MAX_TIME, interactive=False)
 
106
 
107
+ gr.Markdown("### Fatores")
 
108
  keyboard_btns = []
109
+ # Organiza o teclado em 3 linhas para melhor visual no painel lateral
110
+ for r_kb in range(3):
111
+ with gr.Row():
112
+ for c_kb in range(3):
113
+ val = KEYBOARD_KEYS[r_kb * 3 + c_kb]
114
+ kb_btn = gr.Button(str(val), variant="secondary", elem_classes="kb-btn")
115
+ keyboard_btns.append(kb_btn)
116
 
117
+ reset_btn = gr.Button("Reiniciar", variant="stop")
 
 
118
 
 
119
  def update_ui(s):
120
  updates = [format_grid_button(i, s["solved"], s["selected_idx"]) for i in range(32)]
121
  return updates + [s["score"]]
122
 
123
+ # Eventos da Grade
124
  for i, btn in enumerate(grid_buttons):
125
  btn.click(
126
  fn=lambda s, idx=i: handle_game_logic(s, "select_target", idx),
 
128
  outputs=[state, status_box]
129
  ).then(fn=update_ui, inputs=[state], outputs=grid_buttons + [score_display])
130
 
131
+ # Eventos do Teclado (Correção de loop/closure)
132
  for kb_btn in keyboard_btns:
 
133
  kb_btn.click(
134
  fn=lambda s, v=kb_btn.value: handle_game_logic(s, "select_factor", v),
135
  inputs=[state],
136
  outputs=[state, status_box]
137
  ).then(fn=update_ui, inputs=[state], outputs=grid_buttons + [score_display])
138
 
 
139
  def reset_all():
140
  new_state = get_empty_state()
141
  updates = [gr.update(value=str(num), variant="secondary", interactive=True) for num in GRID_NUMBERS]
142
  return [new_state, "Jogo reiniciado!"] + updates + [MAX_TIME]
143
 
144
+ reset_btn.click(fn=reset_all, outputs=[state, status_box] + grid_buttons + [score_display])
 
 
 
145
 
146
  if __name__ == "__main__":
147
  demo.launch()