-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rubik_Cube.py
424 lines (373 loc) · 15.5 KB
/
Rubik_Cube.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# coding utf-8
import click
import numpy as np
import os
import random
import subprocess
import time
import sys
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
OS = sys.platform
vertices = (( 1, -1, -1), ( 1, 1, -1), (-1, 1, -1), (-1, -1, -1), ( 1, -1, 1), ( 1, 1, 1), (-1, -1, 1), (-1, 1, 1))
edges = ((0,1),(0,3),(0,4),(2,1),(2,3),(2,7),(6,3),(6,4),(6,7),(5,1),(5,4),(5,7))
surfaces = ((0, 1, 2, 3), (3, 2, 7, 6), (6, 7, 5, 4), (4, 5, 1, 0), (1, 5, 7, 2), (4, 0, 3, 6))
colors = ((0.8, 0, 0), (0, 0, 0.8), (1, 0.5, 0), (0, 0.8, 0), (1, 1, 1), (1, 1, 0))
moves = ("F", "R", "U", "B", "L", "D", "F'", "R'", "U'", "B'", "L'", "D'","F2", "R2", "U2", "B2", "L2", "D2", "F'2", "R'2", "U'2", "B'2", "L'2", "D'2")
class Cube():
def __init__(self, id, N, scale):
self.N = N
self.scale = scale
self.init_i = [*id]
self.current_i = [*id]
self.rot = [[1 if i==j else 0 for i in range(3)] for j in range(3)]
def isAffected(self, axis, slice, dir):
return self.current_i[axis] == slice
def update(self, axis, slice, dir):
if not self.isAffected(axis, slice, dir):
return
i, j = (axis+1) % 3, (axis+2) % 3
for k in range(3):
self.rot[k][i], self.rot[k][j] = -self.rot[k][j]*dir, self.rot[k][i]*dir
self.current_i[i], self.current_i[j] = (
self.current_i[j] if dir < 0 else self.N - 1 - self.current_i[j],
self.current_i[i] if dir > 0 else self.N - 1 - self.current_i[i] )
def transformMat(self):
scaleA = [[s*self.scale for s in a] for a in self.rot]
scaleT = [(p-(self.N-1)/2)*2.1*self.scale for p in self.current_i]
return [*scaleA[0], 0, *scaleA[1], 0, *scaleA[2], 0, *scaleT, 1]
def draw(self, col, surf, vert, animate, angle, axis, slice, dir):
glPushMatrix()
if animate and self.isAffected(axis, slice, dir):
glRotatef( angle*dir, *[1 if i==axis else 0 for i in range(3)] )
glMultMatrixf( self.transformMat() )
if OS == "darwin":
# Draw faces
glBegin(GL_QUADS)
for i in range(len(surf)):
glColor3fv(colors[i])
for j in surf[i]:
glVertex3fv(vertices[j])
glEnd()
# Draw edges
glBegin(GL_LINES)
glColor3fv((0,0,0))
for edge in edges:
for vertex in edge:
glVertex3fv(vertices[vertex])
glEnd()
else:
global face_vao, edge_vao
# draw faces
glBindVertexArray( face_vao )
glDrawArrays( GL_QUADS, 0, 6*4 )
glBindVertexArray( 0 )
#draw edges
glColor3f( 0, 0, 0 )
glBindVertexArray( edge_vao )
glDrawElements( GL_LINES, 2*12, GL_UNSIGNED_INT, None )
glBindVertexArray( 0 )
glPopMatrix()
class EntireCube():
def __init__(self, N, scale, steps, human):
self.N = N
cr = range(self.N)
self.cubes = [Cube((x, y, z), self.N, scale) for x in cr for y in cr for z in cr]
self.steps = steps
self.hist = ""
self.reset = False
self.solving = False
if human:
self.human = "-h"
else:
self.human = ""
if len(self.steps):
print("\nScrambling...")
def shuffle(self):
print("\nScrambling...")
# build steps
steps_idx = []
for _ in range(20):
rand = random.randint(0, len(moves)-1)
while len(steps_idx) and moves[rand][0] == moves[steps_idx[-1]][0]:
rand = random.randint(0, len(moves)-1)
steps_idx.append(rand)
#steps_idx = [random.randint(0, len(moves)-1) for _ in range(20)]
self.steps = [moves[idx] for idx in steps_idx]
print("Applying", " ".join(self.steps), ":")
if len(self.hist) == 0:
self.reset = True
self.solving = False
def solve(self):
print("\nSolving...")
if OS == "win32":
args = ("./Rubik.exe", self.human, self.hist)
else:
args = ("./Rubik", self.human, self.hist)
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read().decode()
if len(output):
self.steps = parse_steps(str(output).replace("\n", ""))
if len(self.steps):
self.hist = ""
self.reset = True
self.solving = True
print("Done\n")
else:
time.sleep(0.1)
else:
print("Error : No Solution")
time.sleep(0.3)
def mainloop(self):
rot_cube_map = {K_UP: (-1, 0), K_DOWN: (1, 0), K_LEFT: (0, -1), K_RIGHT: (0, 1)}
rot_slice_map = {K_l: (0, 0, -1), K_r: (0, 2, 1), K_d: (1, 0, -1),K_u: (1, 2, 1), K_b: (2, 0, -1), K_f: (2, 2, 1)}
rot_slice_map_prime = {K_l: (0, 0, 1), K_r: (0, 2, -1), K_d: (1, 0, 1), K_u: (1, 2, -1), K_b: (2, 0, 1), K_f: (2, 2, -1)}
ang_x, ang_y, rot_cube = 0, 0, (0, 0)
animate_rot, animate, animate_ang, animate_speed = False, False, 0, 15 if OS == "darwin" else 5
action = (0, 0, 0)
steps_counter = 1
arg = ""
curr = ""
last = ""
while True:
# Clean screen
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
# reset counter after solved
if self.reset:
steps_counter = 1
self.reset = False
# handle steps
if not animate and len(self.steps):
if not "2" in arg:
print("Step %d : %s" % (steps_counter, self.steps[0]))
curr = self.steps[0]
arg = ""
if curr[0] == "F":
key = K_f
elif curr[0] == "R":
key = K_r
elif curr[0] == "U":
key = K_u
elif curr[0] == "B":
key = K_b
elif curr[0] == "L":
key = K_l
elif curr[0] == "D":
key = K_d
if len(curr) >= 2:
arg = curr[1:]
if key in rot_slice_map and "'" in arg:
animate, action = True, rot_slice_map[key]
elif key in rot_slice_map_prime:
animate, action = True, rot_slice_map_prime[key]
if "2" in arg:
last = curr
self.steps[0] = curr[0] + arg.replace("2", "")
else:
self.steps.pop(0)
steps_counter += 1
if len(last):
curr = last
last = ""
if self.solving == False:
self.hist += curr + " "
# handle events
else:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
print("\nGoodBye !")
quit()
if event.type == KEYDOWN and event.key == K_RETURN:
self.solve()
if event.type == KEYDOWN:
curr_tab = [" ", " "]
edited = False
if not animate_rot and event.key in rot_cube_map:
animate_rot, rot_cube = True, rot_cube_map[event.key]
if not animate and event.key in rot_slice_map and pygame.key.get_mods() & KMOD_CTRL:
animate, action = True, rot_slice_map[event.key]
curr_tab[1] = "'"
edited = True
elif not animate and event.key in rot_slice_map_prime:
animate, action = True, rot_slice_map_prime[event.key]
edited = True
if edited:
if event.key == K_f:
curr_tab[0] = "F"
elif event.key == K_r:
curr_tab[0] = "R"
elif event.key == K_u:
curr_tab[0] = "U"
elif event.key == K_b:
curr_tab[0] = "B"
elif event.key == K_l:
curr_tab[0] = "L"
elif event.key == K_d:
curr_tab[0] = "D"
if self.solving == True:
steps_counter = 1
self.solving = False
print("\n")
print("Step %d : %s" % (steps_counter, "".join(curr_tab)))
steps_counter += 1
curr = "".join(curr_tab)
self.hist += curr + (" " if "'" in curr_tab[1] else "")
# animate rotations
if animate_rot:
ang_x += rot_cube[0]*animate_speed
ang_y += rot_cube[1]*animate_speed
if ang_x % 90 == 0 and ang_y % 90 == 0:
animate_rot = False
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -40)
glRotatef(ang_y, 0, 1, 0)
glRotatef(ang_x, 1, 0, 0)
# Show buttons
if len(self.steps) == 0 and ang_x % 360 == 0 and ang_y % 360 == 0:
if len(self.hist):
button("Solve", -25.4, 7, self.solve, self.cubes)
button("Scramble", -24.5, 9.5, self.shuffle, self.cubes)
# Print action on screen
drawText(-1, 8, curr)
# step animation
if animate:
if animate_ang >= 90:
for cube in self.cubes:
cube.update(*action)
animate, animate_ang = False, 0
for cube in self.cubes:
cube.draw(colors, surfaces, vertices, animate, animate_ang, *action)
if animate:
animate_ang += animate_speed
# Draw screen
pygame.display.flip()
pygame.time.wait(10)
def parse_steps(steps):
while steps[-1] == " ":
steps = steps[:-1]
steps_list = steps.split(" ")
for i, step in enumerate(steps_list):
step = step.replace("’", "'")
steps_list[i] = step
if len(step) == 0 or len(step) > 3 or step[0] not in "FRUBLD":
print("Error : Invalid step name : %s" % step)
return []
elif len(step) == 2 and step[1] not in "'2":
print("Error : Invalid step arg in %s" % step)
return []
elif len(step) == 3 and (step[1] not in "'2" or step[2] not in "2"):
print("Error : Invalid step arg in %s" % step)
return []
return steps_list
def drawText(x, y, textString, fore=(255,255,255,255), back=(0,0,0,255)):
global display
font = pygame.font.Font (None, 64)
textSurface = font.render(textString, True, fore, back)
textData = pygame.image.tostring(textSurface, "RGBA", True)
glRasterPos2d(x, y)
glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)
return glGetFloatv(GL_CURRENT_RASTER_POSITION), textSurface.get_width(), textSurface.get_height()
def button(msg,x,y,action,cubes):
pos, w, h = drawText(x, y, msg, back=(50,50,50,255))
x = pos[0]
y = display[1] - pos[1] - h
mouse = pygame.mouse.get_pos()
clicked = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
if clicked[0] == 1 and action != None:
# Clean screen
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
for cube in cubes:
cube.draw(colors, surfaces, vertices, False, 0, *(0, 0, 0))
# Draw screen
pygame.display.flip()
pygame.time.wait(10)
action()
@click.command()
@click.argument("steps", default="")
@click.option("-h", "human", is_flag=True)
def main(steps, human):
if len(steps):
steps = parse_steps(steps)
else:
steps = []
# Init
pygame.init()
global display
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
# Camera
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
# camera position/rotation
glTranslatef(-20, -15, 0)
glRotatef(25, 1, 0, 0)
glRotatef(-30, 0, 1, 0)
# enable depth test (less or equal)
glEnable( GL_DEPTH_TEST )
glDepthFunc( GL_LEQUAL )
# enable back face culling (front faces are drawn clockwise)
glEnable( GL_CULL_FACE )
glCullFace( GL_BACK )
glFrontFace( GL_CW )
# Modern OpenGL API :
if OS != "darwin":
global face_vao, edge_vao
# define the vertex buffers vor the faces
attribute_array = []
for face in range(len(surfaces)):
for vertex in surfaces[face ]:
attribute_array.append( vertices[vertex] )
attribute_array.append( colors[face] )
face_vbos = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, face_vbos)
glBufferData( GL_ARRAY_BUFFER, np.array( attribute_array, dtype=np.float32 ), GL_STATIC_DRAW )
glBindBuffer(GL_ARRAY_BUFFER, 0)
# define the vertex array object for the faces
face_vao = glGenVertexArrays( 1 )
glBindVertexArray( face_vao )
glBindBuffer(GL_ARRAY_BUFFER, face_vbos)
glVertexPointer( 3, GL_FLOAT, 6*4, None )
glEnableClientState( GL_VERTEX_ARRAY )
glColorPointer( 3, GL_FLOAT, 6*4, ctypes.cast(3*4, ctypes.c_void_p) )
glEnableClientState( GL_COLOR_ARRAY )
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray( 0 )
# define the vertex buffer for the edges
edge_vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, edge_vbo)
glBufferData( GL_ARRAY_BUFFER, np.array( vertices, dtype=np.float32 ), GL_STATIC_DRAW )
glBindBuffer(GL_ARRAY_BUFFER, 0)
# define the vertex array object for the edges
edge_vao = glGenVertexArrays( 1 )
glBindVertexArray( edge_vao )
glBindBuffer(GL_ARRAY_BUFFER, edge_vbo)
glVertexPointer( 3, GL_FLOAT, 0, None )
glEnableClientState( GL_VERTEX_ARRAY )
glBindBuffer(GL_ARRAY_BUFFER, 0)
edge_ibo = glGenBuffers(1)
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, edge_ibo )
glBufferData( GL_ELEMENT_ARRAY_BUFFER, np.array( edges, dtype=np.uint32 ), GL_STATIC_DRAW )
glBindVertexArray( 0 )
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 )
# Build Rubik's Cube and run loop
NewEntireCube = EntireCube(3, 1.5, steps, human)
NewEntireCube.mainloop()
if __name__ == '__main__':
print("\n" + "#" * 27 + "\n| Actions : | Options : |\n" + "#" * 27 + \
"\n| F : Front | ' : reverse |\n| R : Right | 2 : double |\n| U : Up |" + \
"#" * 14 + "\n| B : Back |\n| L : Left |\n| D : Down |\n" + \
"#" * 13 + "\n")
# Compile solver
if not os.path.exists("Rubik") or not os.path.exists("Rubik.exe"):
args = ("go", "build")
popen = subprocess.Popen(args)
# Run
main()
pygame.quit()
quit()