Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,151 +1,134 @@
|
|
|
|
1 |
import numpy as np
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
5 |
-
""
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
for i in range(6):
|
18 |
-
self.cube[i] = np.full((3, 3), i)
|
19 |
-
|
20 |
-
self.color_names = {
|
21 |
-
0: "Branco",
|
22 |
-
1: "Amarelo",
|
23 |
-
2: "Verde",
|
24 |
-
3: "Azul",
|
25 |
-
4: "Vermelho",
|
26 |
-
5: "Laranja"
|
27 |
-
}
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
if
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
|
|
|
|
|
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
else:
|
56 |
-
raise ValueError("Número de face inválido")
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
2: [(0,2), (4,3), (1,0), (5,1)], # Frente
|
65 |
-
3: [(0,0), (5,3), (1,2), (4,1)], # Traseira
|
66 |
-
4: [(0,1), (2,1), (1,1), (3,3)], # Direita
|
67 |
-
5: [(0,3), (3,1), (1,3), (2,3)] # Esquerda
|
68 |
-
}
|
69 |
-
|
70 |
-
# Obter as faces e bordas afetadas
|
71 |
-
affected = adjacent_faces[face_num]
|
72 |
-
temp_values = []
|
73 |
-
|
74 |
-
# Guardar valores temporários
|
75 |
-
for face, edge in affected:
|
76 |
-
if edge == 0:
|
77 |
-
temp_values.append(self.cube[face][0].copy())
|
78 |
-
elif edge == 1:
|
79 |
-
temp_values.append(self.cube[face][:,2].copy())
|
80 |
-
elif edge == 2:
|
81 |
-
temp_values.append(self.cube[face][2].copy())
|
82 |
-
else: # edge == 3
|
83 |
-
temp_values.append(self.cube[face][:,0].copy())
|
84 |
-
|
85 |
-
# Rotacionar valores
|
86 |
-
if clockwise:
|
87 |
-
temp_values = [temp_values[-1]] + temp_values[:-1]
|
88 |
-
else:
|
89 |
-
temp_values = temp_values[1:] + [temp_values[0]]
|
90 |
-
|
91 |
-
# Atualizar faces
|
92 |
-
for (face, edge), new_values in zip(affected, temp_values):
|
93 |
-
if edge == 0:
|
94 |
-
self.cube[face][0] = new_values
|
95 |
-
elif edge == 1:
|
96 |
-
self.cube[face][:,2] = new_values
|
97 |
-
elif edge == 2:
|
98 |
-
self.cube[face][2] = new_values
|
99 |
-
else: # edge == 3
|
100 |
-
self.cube[face][:,0] = new_values
|
101 |
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
if
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
import random
|
112 |
-
moves = []
|
113 |
-
for _ in range(num_moves):
|
114 |
-
face = random.randint(0, 5)
|
115 |
-
direction = random.choice([True, False])
|
116 |
-
if direction:
|
117 |
-
self.rotate_face_clockwise(face)
|
118 |
-
moves.append(f"Rotação horária da face {self.color_names[face]}")
|
119 |
-
else:
|
120 |
-
self.rotate_face_counterclockwise(face)
|
121 |
-
moves.append(f"Rotação anti-horária da face {self.color_names[face]}")
|
122 |
-
return moves
|
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 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
import numpy as np
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
from rubiks_cube import RubiksCube # Assumindo que a classe está em rubiks_cube.py
|
5 |
|
6 |
+
def num_to_color(num):
|
7 |
+
colors = {
|
8 |
+
0: "#FFFFFF", # Branco
|
9 |
+
1: "#FFFF00", # Amarelo
|
10 |
+
2: "#00FF00", # Verde
|
11 |
+
3: "#0000FF", # Azul
|
12 |
+
4: "#FF0000", # Vermelho
|
13 |
+
5: "#FFA500" # Laranja
|
14 |
+
}
|
15 |
+
return colors.get(num, "#CCCCCC")
|
16 |
+
|
17 |
+
def create_cube_visualization(cube_state):
|
18 |
+
fig, ax = plt.subplots(4, 3, figsize=(10, 12))
|
19 |
+
plt.subplots_adjust(hspace=0.4, wspace=0.4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
# Desabilitar eixos
|
22 |
+
for row in ax:
|
23 |
+
for col in row:
|
24 |
+
col.set_xticks([])
|
25 |
+
col.set_yticks([])
|
26 |
|
27 |
+
# Posições das faces no layout planificado
|
28 |
+
face_positions = [
|
29 |
+
(1, 1), # Face superior (branco)
|
30 |
+
(2, 1), # Face frontal (verde)
|
31 |
+
(1, 2), # Face direita (vermelho)
|
32 |
+
(1, 0), # Face esquerda (laranja)
|
33 |
+
(3, 1), # Face inferior (amarelo)
|
34 |
+
(2, 2), # Face traseira (azul)
|
35 |
+
]
|
36 |
|
37 |
+
# Desenhar cada face
|
38 |
+
for face_idx, (row, col) in enumerate(face_positions):
|
39 |
+
if row < 4 and col < 3:
|
40 |
+
face = cube_state[face_idx]
|
41 |
+
for i in range(3):
|
42 |
+
for j in range(3):
|
43 |
+
color = num_to_color(face[i, j])
|
44 |
+
ax[row, col].add_patch(plt.Rectangle((j/3, (2-i)/3), 1/3, 1/3, facecolor=color, edgecolor='black'))
|
45 |
+
ax[row, col].set_xlim(0, 1)
|
46 |
+
ax[row, col].set_ylim(0, 1)
|
47 |
+
ax[row, col].set_title(f'Face {cube.color_names[face_idx]}')
|
48 |
|
49 |
+
# Remover subplots vazios
|
50 |
+
for row in range(4):
|
51 |
+
for col in range(3):
|
52 |
+
if (row, col) not in face_positions:
|
53 |
+
fig.delaxes(ax[row, col])
|
|
|
|
|
54 |
|
55 |
+
return fig
|
56 |
+
|
57 |
+
def process_moves(cube, moves, current_state):
|
58 |
+
"""Processa os movimentos solicitados e retorna a visualização atualizada"""
|
59 |
+
moves_list = moves.strip().split('\n')
|
60 |
+
output_text = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
for move in moves_list:
|
63 |
+
move = move.strip().lower()
|
64 |
+
try:
|
65 |
+
if move.startswith('r'): # rotação horária
|
66 |
+
face = int(move[1])
|
67 |
+
cube.rotate_face_clockwise(face)
|
68 |
+
output_text.append(f"Rotação horária da face {cube.color_names[face]}")
|
69 |
+
elif move.startswith('l'): # rotação anti-horária
|
70 |
+
face = int(move[1])
|
71 |
+
cube.rotate_face_counterclockwise(face)
|
72 |
+
output_text.append(f"Rotação anti-horária da face {cube.color_names[face]}")
|
73 |
+
except:
|
74 |
+
output_text.append(f"Movimento inválido: {move}")
|
75 |
|
76 |
+
fig = create_cube_visualization(cube.cube)
|
77 |
+
status = "Resolvido!" if cube.is_solved() else "Não resolvido"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
+
return fig, "\n".join(output_text), status
|
80 |
+
|
81 |
+
def scramble_cube(cube, n_moves):
|
82 |
+
"""Embaralha o cubo com n movimentos"""
|
83 |
+
moves = cube.scramble(int(n_moves))
|
84 |
+
fig = create_cube_visualization(cube.cube)
|
85 |
+
status = "Resolvido!" if cube.is_solved() else "Não resolvido"
|
86 |
+
return fig, "\n".join(moves), status
|
87 |
+
|
88 |
+
# Criar instância do cubo
|
89 |
+
cube = RubiksCube()
|
90 |
|
91 |
+
# Criar interface Gradio
|
92 |
+
with gr.Blocks(title="Cubo Mágico") as demo:
|
93 |
+
gr.Markdown("# Simulador de Cubo Mágico")
|
94 |
+
gr.Markdown("""
|
95 |
+
### Como usar:
|
96 |
+
1. Use o botão 'Embaralhar' para misturar o cubo
|
97 |
+
2. Digite movimentos no formato:
|
98 |
+
- r0 (rotação horária da face 0)
|
99 |
+
- l0 (rotação anti-horária da face 0)
|
100 |
+
onde o número representa a face:
|
101 |
+
0: Branco, 1: Amarelo, 2: Verde, 3: Azul, 4: Vermelho, 5: Laranja
|
102 |
+
""")
|
103 |
|
104 |
+
with gr.Row():
|
105 |
+
with gr.Column():
|
106 |
+
n_moves = gr.Slider(minimum=1, maximum=20, value=5, step=1, label="Número de movimentos para embaralhar")
|
107 |
+
scramble_btn = gr.Button("Embaralhar")
|
108 |
+
moves_input = gr.Textbox(label="Digite os movimentos (um por linha)", lines=5)
|
109 |
+
move_btn = gr.Button("Executar Movimentos")
|
110 |
+
|
111 |
+
with gr.Column():
|
112 |
+
cube_plot = gr.Plot()
|
113 |
+
output_text = gr.Textbox(label="Movimentos realizados", lines=5)
|
114 |
+
status_text = gr.Textbox(label="Status")
|
115 |
|
116 |
+
# Conectar os botões às funções
|
117 |
+
scramble_btn.click(
|
118 |
+
fn=lambda n: scramble_cube(cube, n),
|
119 |
+
inputs=[n_moves],
|
120 |
+
outputs=[cube_plot, output_text, status_text]
|
121 |
+
)
|
122 |
|
123 |
+
move_btn.click(
|
124 |
+
fn=lambda m, s: process_moves(cube, m, s),
|
125 |
+
inputs=[moves_input, status_text],
|
126 |
+
outputs=[cube_plot, output_text, status_text]
|
127 |
+
)
|
128 |
|
129 |
+
# Mostrar estado inicial
|
130 |
+
init_fig = create_cube_visualization(cube.cube)
|
131 |
+
cube_plot.update(value=init_fig)
|
132 |
+
|
133 |
+
# Iniciar a aplicação
|
134 |
+
demo.launch()
|