DHEIVER commited on
Commit
e190eb7
·
verified ·
1 Parent(s): 64ae922

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -136
app.py CHANGED
@@ -1,151 +1,134 @@
 
1
  import numpy as np
 
 
2
 
3
- class RubiksCube:
4
- def __init__(self):
5
- """
6
- Inicializa um cubo mágico resolvido.
7
- Faces são numeradas de 0-5:
8
- 0: Branco (topo)
9
- 1: Amarelo (base)
10
- 2: Verde (frente)
11
- 3: Azul (traseira)
12
- 4: Vermelho (direita)
13
- 5: Laranja (esquerda)
14
- """
15
- # Criar um cubo 3x3x3 com cores padrão
16
- self.cube = np.zeros((6, 3, 3), dtype=int)
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
- def get_face(self, face_num):
30
- """Retorna uma face específica do cubo."""
31
- if 0 <= face_num < 6:
32
- return self.cube[face_num].copy()
33
- raise ValueError("Número de face inválido")
34
 
35
- def set_face(self, face_num, new_state):
36
- """Define o estado de uma face específica."""
37
- if 0 <= face_num < 6 and new_state.shape == (3, 3):
38
- self.cube[face_num] = new_state.copy()
39
- else:
40
- raise ValueError("Face inválida ou dimensões incorretas")
 
 
 
41
 
42
- def rotate_face_clockwise(self, face_num):
43
- """Rotaciona uma face no sentido horário."""
44
- if 0 <= face_num < 6:
45
- self.cube[face_num] = np.rot90(self.cube[face_num], k=-1)
46
- self._update_adjacent_faces(face_num, clockwise=True)
47
- else:
48
- raise ValueError("Número de face inválido")
 
 
 
 
49
 
50
- def rotate_face_counterclockwise(self, face_num):
51
- """Rotaciona uma face no sentido anti-horário."""
52
- if 0 <= face_num < 6:
53
- self.cube[face_num] = np.rot90(self.cube[face_num], k=1)
54
- self._update_adjacent_faces(face_num, clockwise=False)
55
- else:
56
- raise ValueError("Número de face inválido")
57
 
58
- def _update_adjacent_faces(self, face_num, clockwise=True):
59
- """Atualiza as faces adjacentes após uma rotação."""
60
- # Definição das faces adjacentes e suas bordas afetadas para cada face
61
- adjacent_faces = {
62
- 0: [(2,0), (4,0), (3,0), (5,0)], # Topo
63
- 1: [(2,2), (5,2), (3,2), (4,2)], # Base
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
- def is_solved(self):
103
- """Verifica se o cubo está resolvido."""
104
- for face in range(6):
105
- if not np.all(self.cube[face] == face):
106
- return False
107
- return True
 
 
 
 
 
 
 
108
 
109
- def scramble(self, num_moves=20):
110
- """Embaralha o cubo com um número específico de movimentos aleatórios."""
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
- def get_state_str(self):
125
- """Retorna uma representação string do estado atual do cubo."""
126
- state = []
127
- for face in range(6):
128
- face_str = f"Face {self.color_names[face]}:\n"
129
- face_str += str(self.cube[face])
130
- state.append(face_str)
131
- return "\n\n".join(state)
 
 
 
132
 
133
- # Exemplo de uso
134
- if __name__ == "__main__":
135
- # Criar um novo cubo
136
- cube = RubiksCube()
 
 
 
 
 
 
 
 
137
 
138
- print("Estado inicial do cubo:")
139
- print(cube.get_state_str())
 
 
 
 
 
 
 
 
 
140
 
141
- # Embaralhar o cubo
142
- moves = cube.scramble(5)
143
- print("\nMovimentos realizados:")
144
- for move in moves:
145
- print(move)
 
146
 
147
- print("\nEstado após embaralhar:")
148
- print(cube.get_state_str())
 
 
 
149
 
150
- # Verificar se está resolvido
151
- print("\nCubo está resolvido?", cube.is_solved())
 
 
 
 
 
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()