DHEIVER commited on
Commit
a6b8103
·
verified ·
1 Parent(s): 18afea2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -0
app.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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())