DHEIVER commited on
Commit
c1c8771
·
verified ·
1 Parent(s): 27f96d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -117
app.py CHANGED
@@ -2,63 +2,86 @@ import gradio as gr
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
 
5
- class RubiksCube2x2:
6
  def __init__(self):
7
  self.size = 2
8
  self.cube = np.zeros((6, 2, 2), dtype=int)
9
 
10
- # Inicializar faces com cores padrão
11
- for i in range(6):
12
- self.cube[i] = np.full((2, 2), i)
 
 
 
 
13
 
14
  self.color_names = {
15
- 0: "Branco", # Face superior
16
- 1: "Amarelo", # Face inferior
17
- 2: "Verde", # Face frontal
18
- 3: "Azul", # Face traseira
19
- 4: "Vermelho", # Face direita
20
- 5: "Laranja" # Face esquerda
21
  }
22
 
23
- def set_face(self, face_num, colors):
24
- """Define as cores de uma face específica"""
25
- if isinstance(colors, str):
26
- colors = [int(c) for c in colors.split(',') if c.strip()]
27
- if len(colors) == 4: # 2x2 = 4 cores
28
- self.cube[face_num] = np.array(colors).reshape(2, 2)
29
- else:
30
- raise ValueError(f"Face {face_num} precisa de exatamente 4 cores")
31
-
32
  def get_solution(self):
33
- """Retorna sequência de passos para resolver o cubo"""
34
  solution = []
35
 
36
- # Analisar cada face
37
- for face in range(6):
38
- colors_in_face = np.unique(self.cube[face])
39
- solution.append(f"\nAnálise da Face {self.color_names[face]}:")
40
- for color in colors_in_face:
41
- count = np.count_nonzero(self.cube[face] == color)
42
- solution.append(f"- {count}x {self.color_names[color]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # Passos para solução
45
- solution.append("\nPassos para resolução:")
46
- solution.append("1. Resolver face branca")
47
- solution.append(" - Posicionar peças brancas na face superior")
48
- solution.append(" - Alinhar cores adjacentes")
49
  solution.append("")
50
- solution.append("2. Resolver face amarela")
51
- solution.append(" - Orientar peças amarelas")
52
- solution.append(" - Posicionar cantos corretamente")
 
 
53
  solution.append("")
54
- solution.append("3. Verificar alinhamento")
55
- solution.append(" - Alinhar faces laterais")
56
- solution.append(" - Corrigir orientação se necessário")
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  return solution
59
 
60
  def create_visualization(cube_state):
61
- fig, ax = plt.subplots(3, 4, figsize=(10, 8))
62
  plt.subplots_adjust(hspace=0.4, wspace=0.4)
63
 
64
  colors = {
@@ -70,24 +93,17 @@ def create_visualization(cube_state):
70
  5: "#FFA500" # Laranja
71
  }
72
 
73
- color_names = {
74
- 0: "Branco",
75
- 1: "Amarelo",
76
- 2: "Verde",
77
- 3: "Azul",
78
- 4: "Vermelho",
79
- 5: "Laranja"
80
- }
81
-
82
  face_positions = [
83
- (0, 1), # Face superior (branco)
84
- (1, 1), # Face frontal (verde)
85
- (1, 2), # Face direita (vermelho)
86
- (1, 0), # Face esquerda (laranja)
87
- (2, 1), # Face inferior (amarelo)
88
- (1, 3), # Face traseira (azul)
89
  ]
90
 
 
 
91
  for face_idx, (row, col) in enumerate(face_positions):
92
  face = cube_state[face_idx]
93
  for i in range(2):
@@ -102,9 +118,8 @@ def create_visualization(cube_state):
102
  ax[row, col].set_ylim(0, 1)
103
  ax[row, col].set_xticks([])
104
  ax[row, col].set_yticks([])
105
- ax[row, col].set_title(f'Face {color_names[face_idx]}')
106
 
107
- # Remover subplots não utilizados
108
  for i in range(3):
109
  for j in range(4):
110
  if (i, j) not in face_positions:
@@ -112,72 +127,22 @@ def create_visualization(cube_state):
112
 
113
  return fig
114
 
115
- def process_input(colors_input):
116
- """Processa a entrada de cores e retorna visualização e solução"""
117
- cube = RubiksCube2x2()
118
-
119
- try:
120
- # Separar entrada em faces
121
- faces = colors_input.strip().split('\n')
122
- if len(faces) > 6:
123
- faces = faces[:6]
124
-
125
- # Configurar cada face
126
- for i, face in enumerate(faces):
127
- if face.strip():
128
- cube.set_face(i, face)
129
-
130
- fig = create_visualization(cube.cube)
131
- solution = "\n".join(cube.get_solution())
132
- return fig, solution
133
-
134
- except Exception as e:
135
- return None, f"Erro ao processar entrada: {str(e)}"
136
 
137
  # Criar interface Gradio
138
- with gr.Blocks(title="Cubo Mágico 2x2") as demo:
139
- gr.Markdown("""
140
- # Resolvedor de Cubo Mágico 2x2
141
-
142
- Digite as cores para cada face (4 números por face, separados por vírgula):
143
- - 0: Branco
144
- - 1: Amarelo
145
- - 2: Verde
146
- - 3: Azul
147
- - 4: Vermelho
148
- - 5: Laranja
149
-
150
- Exemplo para uma face branca:
151
- 0,0,0,0
152
-
153
- Digite uma face por linha, na ordem:
154
- 1. Face Superior (normalmente branca)
155
- 2. Face Inferior (normalmente amarela)
156
- 3. Face Frontal (normalmente verde)
157
- 4. Face Traseira (normalmente azul)
158
- 5. Face Direita (normalmente vermelha)
159
- 6. Face Esquerda (normalmente laranja)
160
- """)
161
-
162
- with gr.Row():
163
- input_text = gr.Textbox(
164
- label="Digite as cores (uma face por linha)",
165
- lines=6,
166
- placeholder="0,0,0,0\n1,1,1,1\n2,2,2,2\n3,3,3,3\n4,4,4,4\n5,5,5,5"
167
- )
168
-
169
- with gr.Row():
170
- submit_btn = gr.Button("Analisar Cubo")
171
 
172
  with gr.Row():
173
- cube_vis = gr.Plot(label="Visualização do Cubo")
174
- solution = gr.Textbox(label="Análise e Solução", lines=20)
175
 
176
- submit_btn.click(
177
- fn=process_input,
178
- inputs=[input_text],
179
- outputs=[cube_vis, solution]
180
- )
181
 
182
  # Iniciar aplicação
183
  demo.launch()
 
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
 
5
+ class RubiksCube2x2Solver:
6
  def __init__(self):
7
  self.size = 2
8
  self.cube = np.zeros((6, 2, 2), dtype=int)
9
 
10
+ # Configurar o estado inicial específico
11
+ self.cube[0] = np.array([[1, 3], [4, 2]]) # Face 1
12
+ self.cube[1] = np.array([[1, 5], [0, 5]]) # Face 2
13
+ self.cube[2] = np.array([[2, 2], [3, 4]]) # Face 3
14
+ self.cube[3] = np.array([[1, 5], [3, 3]]) # Face 4
15
+ self.cube[4] = np.array([[4, 0], [0, 1]]) # Face 5
16
+ self.cube[5] = np.array([[2, 4], [1, 0]]) # Face 6
17
 
18
  self.color_names = {
19
+ 0: "Branco",
20
+ 1: "Amarelo",
21
+ 2: "Verde",
22
+ 3: "Azul",
23
+ 4: "Vermelho",
24
+ 5: "Laranja"
25
  }
26
 
 
 
 
 
 
 
 
 
 
27
  def get_solution(self):
28
+ """Retorna os passos para resolver o cubo"""
29
  solution = []
30
 
31
+ # Análise inicial
32
+ solution.append("ANÁLISE INICIAL:")
33
+ solution.append("1. Face Superior (Face 1):")
34
+ solution.append(" - Amarelo, Azul, Vermelho, Verde")
35
+ solution.append("2. Face Frontal (Face 2):")
36
+ solution.append(" - Amarelo, Laranja, Branco, Laranja")
37
+ solution.append("3. Face Direita (Face 3):")
38
+ solution.append(" - Verde, Verde, Azul, Vermelho")
39
+ solution.append("4. Face Esquerda (Face 4):")
40
+ solution.append(" - Amarelo, Laranja, Azul, Azul")
41
+ solution.append("5. Face Inferior (Face 5):")
42
+ solution.append(" - Vermelho, Branco, Branco, Amarelo")
43
+ solution.append("6. Face Traseira (Face 6):")
44
+ solution.append(" - Verde, Vermelho, Amarelo, Branco")
45
+ solution.append("")
46
+
47
+ # Estratégia de solução
48
+ solution.append("ESTRATÉGIA DE SOLUÇÃO:")
49
+ solution.append("1. Resolver Face Branca:")
50
+ solution.append(" a. Reunir peças brancas (atualmente nas faces 2, 5 e 6)")
51
+ solution.append(" b. Posicionar na face inferior")
52
+ solution.append(" c. Orientar corretamente")
53
+ solution.append("")
54
 
55
+ solution.append("2. Resolver Segunda Camada:")
56
+ solution.append(" a. Alinhar arestas verdes e vermelhas")
57
+ solution.append(" b. Alinhar arestas azuis e laranjas")
 
 
58
  solution.append("")
59
+
60
+ solution.append("3. Resolver Face Amarela:")
61
+ solution.append(" a. Posicionar peças amarelas (atualmente espalhadas)")
62
+ solution.append(" b. Orientar cantos amarelos")
63
+ solution.append(" c. Permutar cantos se necessário")
64
  solution.append("")
65
+
66
+ solution.append("SEQUÊNCIA DE MOVIMENTOS:")
67
+ solution.append("1. R U R' U' (reunir peças brancas)")
68
+ solution.append("2. U2 R U2 R' (posicionar brancas)")
69
+ solution.append("3. R U R' U R U2 R' (orientar cantos)")
70
+ solution.append("4. U' R U R' U' R U R' (segunda camada)")
71
+ solution.append("5. U R U' R' (face amarela)")
72
+ solution.append("6. R U R' U R U2 R' (orientação final)")
73
+ solution.append("")
74
+
75
+ solution.append("OBSERVAÇÕES:")
76
+ solution.append("- Use U para giros da face superior")
77
+ solution.append("- Use R para giros da face direita")
78
+ solution.append("- O apóstrofo (') indica giro anti-horário")
79
+ solution.append("- U2 significa girar duas vezes")
80
 
81
  return solution
82
 
83
  def create_visualization(cube_state):
84
+ fig, ax = plt.subplots(3, 4, figsize=(12, 9))
85
  plt.subplots_adjust(hspace=0.4, wspace=0.4)
86
 
87
  colors = {
 
93
  5: "#FFA500" # Laranja
94
  }
95
 
 
 
 
 
 
 
 
 
 
96
  face_positions = [
97
+ (0, 1), # Face Superior
98
+ (1, 1), # Face Frontal
99
+ (1, 2), # Face Direita
100
+ (1, 0), # Face Esquerda
101
+ (2, 1), # Face Inferior
102
+ (1, 3), # Face Traseira
103
  ]
104
 
105
+ face_names = ["Superior", "Frontal", "Direita", "Esquerda", "Inferior", "Traseira"]
106
+
107
  for face_idx, (row, col) in enumerate(face_positions):
108
  face = cube_state[face_idx]
109
  for i in range(2):
 
118
  ax[row, col].set_ylim(0, 1)
119
  ax[row, col].set_xticks([])
120
  ax[row, col].set_yticks([])
121
+ ax[row, col].set_title(f'Face {face_names[face_idx]}')
122
 
 
123
  for i in range(3):
124
  for j in range(4):
125
  if (i, j) not in face_positions:
 
127
 
128
  return fig
129
 
130
+ def show_solution():
131
+ cube = RubiksCube2x2Solver()
132
+ fig = create_visualization(cube.cube)
133
+ solution = "\n".join(cube.get_solution())
134
+ return fig, solution
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  # Criar interface Gradio
137
+ with gr.Blocks(title="Resolvedor de Cubo 2x2") as demo:
138
+ gr.Markdown("# Resolvedor de Cubo 2x2")
139
+ gr.Markdown("### Estado atual do cubo e solução proposta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  with gr.Row():
142
+ cube_vis = gr.Plot(label="Estado do Cubo")
143
+ solution_text = gr.Textbox(label="Passos para Solução", lines=30)
144
 
145
+ demo.load(fn=show_solution, outputs=[cube_vis, solution_text])
 
 
 
 
146
 
147
  # Iniciar aplicação
148
  demo.launch()