Esempio n. 1
0
def solveCube():  
  cube = request.json['cube']
  technique = "Beginner"
  if technique == 'Beginner':
    steps = utils.solve(cube, 'Beginner')
  elif technique == "CFOP":
    steps = utils.solve(cube, 'CFOP')
  elif technique == "Kociemba":
    steps = utils.solve(cube, 'Kociemba')
  output = [str(i) for i in steps]
  return jsonify({'result': output})
def solve():
    print("solving...")
    cube_string = ""

    # convert cube to string
    for row in range(3):
        for col in range(3):
            cube_string += char_cube[5][row][col]
    for side in range(4):
        for row in range(3):
            for col in range(3):
                cube_string += char_cube[side][row][col]
    for row in range(3):
        for col in range(3):
            cube_string += char_cube[4][row][col]

    # solve cube
    if (not (is_cube_solved())):
        solve_steps = utils.solve(cube_string, 'Kociemba')
    else:
        solve_steps = []

    total_steps = execute_steps(solve_steps)
    print(solve_steps)
    print(cube_string)
    print('Finished solving. Total steps: ', total_steps)
def solve(cube_string):

    turns = utils.solve(cube_string, 'Kociemba') #list
    
    i = 1
    string = ""
    for m in turns:
        move = str(m)
        if "'" in move:
            direction = "counter-clockwise"
        else:
            direction = "clockwise"
            
        if '2' in move:
            num = "twice"
        else:
            num = "once"
            
        if "L" in move:
            face = "left"
        elif "F" in move:
            face = "front"
        elif "R" in move:
            face = "right"
        elif "B" in move:
            face = "back"
        elif "U" in move:
            face = "upper"
        elif "D" in move:
            face = "bottom"
        
        string += (str(i) + ") " + "Turn the " + face + " face " + num + " " + direction + "\n")
        i += 1
        
    return(print(string)) 
Esempio n. 4
0
def kociemba(cube):   #face F doit etre rouge
    solution = utils.solve(cube, 'Kociemba')
    s=str(solution)
    s=s.replace('[','')
    s=s.replace(']','')
    liste=s.split(', ')
    return liste
Esempio n. 5
0
def solve_all(cube):
    for m in methods:
        print('Start process :',m)
        start = time.time()
        solution = utils.solve(cube, m)
        end = time.time()
        print('Time of process :',end - start,'s')
        print(solution)
def solve_and_exit():
    colors = ''
    for cube_side in CUBE_SIDES:
        for row in cube_side.rows:
            for color in row:
                # Get the first letter of each color to convert to a
                # format rubik_solver understands
                colors += color[0].lower()

    # Output the rubik_solver solutions to the console
    # It would be possible to show this using `turtle` too
    print(utils.solve(colors, 'Beginner'))
    print(utils.solve(colors, 'CFOP'))
    print(utils.solve(colors, 'Kociemba'))

    # Exit the program
    raise SystemExit()
Esempio n. 7
0
def callback(data):
    global pub

    rospy.loginfo("Solving with Kociemba")
    msg = StringArray()
    steps = utils.solve(data.data, 'Kociemba')
    for s in steps:
        msg.steps.append(str(s))
    pub.publish(msg)
    rospy.loginfo("Done")
Esempio n. 8
0
 def post(self, request):
     cube_state = request.data['cube_state']
     alg = request.data['alg']
     cube = Cube()
     cube.set_state(cube_state)
     solve = utils.solve(str(cube), alg)
     res = {
         "solve": ",".join(map(str, solve))
     }
     return Response(data=res, status=status.HTTP_200_OK)
Esempio n. 9
0
def api_solve():
    colors = request.args.get("colors")
    print(colors.lower())
    try:
        rotations = utils.solve(colors.lower(), 'Kociemba')
        return jsonify({
            "status": True,
            "rotations": [str(i) for i in rotations]
        })
    except:
        return jsonify({"status": False})
Esempio n. 10
0
def solve(cube):
    #call the solver
    sol_raw = utils.solve(cube, 'Kociemba')
    sol = []
    #initial orientation of the cube (can not be changed)
    faces = {'U': 'Y', 'L': 'B', 'F': 'R', 'R': 'G', 'B': 'O', 'D': 'W'}

    #rename the face with the center color
    #and decompose double rotation as two signle rotations
    for move in sol_raw:
        move_string = faces[move.face]
        if move.counterclockwise:
            move_string = move_string + "'"
        sol.append(move_string)
        if move.double:
            sol.append(move_string)
    #translate the solution into moves that the robot can execute
    moves = []
    for m in sol:
        f = m[0]  # the face we want do be facing down
        print(faces)
        if faces['U'] == f:
            faces = rotate_front_CW(faces)
            moves.append('FCW')
            faces = rotate_front_CW(faces)
            moves.append('FCW')
        elif faces['L'] == f:
            faces = rotate_front_CCW(faces)
            moves.append('FCCW')
        elif faces['F'] == f:
            faces = rotate_upper_CCW(faces)
            moves.append('UCCW')
            faces = rotate_front_CW(faces)
            moves.append('FCW')
        elif faces['R'] == f:
            faces = rotate_front_CW(faces)
            moves.append('FCW')
        elif faces['B'] == f:
            faces = rotate_upper_CW(faces)
            moves.append('UCW')
            faces = rotate_front_CW(faces)
            moves.append('FCW')
        if "'" in m:
            faces = rotate_upper_CCW(faces)
            moves.append('MCCW')
        else:
            faces = rotate_upper_CW(faces)
            moves.append('MCW')
    print("solved in {} moves".format(len(moves)))
    return moves
def api_solve():
    colors = request.args.get("colors")
    print(colors.lower())

    algorithm = request.args.get("algorithm")
    if algorithm is None:
        algorithm = "Kociemba"

    try:
        rotations = utils.solve(colors.lower(), algorithm)
        return jsonify({
            "status": True,
            "rotations": [str(i) for i in rotations]
        })
    except:
        return jsonify({"status": False})
Esempio n. 12
0
    def LSE_scramble(self):
        self.cube = SOLVED_CUBE
        corners = random.choice(range(4))
        if corners == 1 or corners == 3:
            permn = random.choice(o_6)
        else:
            permn = random.choice(a_6)
        flip = random.choice(range(4))
        orient = random.sample(range(6), flip * 2)
        m2 = random.choice(range(2))
        LSE_pieces = np.array([[1, 37], [3, 10], [7, 19], [5, 28], [46, 25],
                               [52, 43]])
        LSE_pieces_new = LSE_pieces
        for i in orient:
            LSE_pieces_new[i] = perm.Permutation(0, 1)(LSE_pieces[i])
        LSE_pieces_new = permn(LSE_pieces_new)

        edge_perm_list = perm.Permutation(53).list()
        for i in range(12):
            edge_perm_list[np.asarray(LSE_pieces).reshape(12)[i]] = np.asarray(
                LSE_pieces_new).reshape(12)[i]

        scramble_perm = perm.Permutation(11, 20, 29, 38)(6, 8, 2, 0)(
            18, 27, 36, 9)**corners * perm.Permutation(edge_perm_list)

        self.cube = scramble_perm(self.cube)
        if m2 == 1:
            self.cube = M2(self.cube)
        order = scramble_perm.order()
        inv_scramble = (scramble_perm**(order - 2))(self.cube)
        empty = ""

        # scramble = ida_lse(full_to_mu(self.cube))
        non_M2_scramble = utils.solve(empty.join(inv_scramble), "Kociemba")
        M2_scramble = []
        if m2 == 1:
            for mv in non_M2_scramble + ["M2"]:
                M2_scramble.append(
                    mv)  # couldn't directly append M2 so did it this way
            self.cube = M2(self.cube)
        else:
            M2_scramble = non_M2_scramble
        self.print_cube()
        self.scramble.set(M2_scramble)
Esempio n. 13
0
def solve(cubeInStringForm):
    solution = utils.solve(cubeInStringForm, 'Kociemba')
    newSol = []
    clearSerialBuffer()
    sleep(3)
    for step in solution:
        newSol.append(str(step))
    newSol = updateSol(newSol)

    ind = int(0)
    for move in newSol:
        print("Current move: ", move)
        ser.write(b'%s.' % reverseDict[move].encode('utf-8'))
        sleep(.5)
        while ser.in_waiting == 0:
            pass
        data = ser.readline().decode('utf-8').strip()
        if data == 'done':
            ser.flush()
            ind += 1
Esempio n. 14
0
def main(video: Union[str, int]):
    cap = cv2.VideoCapture(video)
    state = CubeState()

    while True:
        try:
            process_frame(cap, state)
        except KeyboardInterrupt:
            print('User interrupt')
            break
        except VideoDone:
            break
        except AllSidesFound:
            print('All sides found')
            encoded_state = state.encode()
            solution = utils.solve(encoded_state, 'Kociemba')
            print(f'Solution: {solution}')
            break

    # When everything is done, release the capture
    cap.release()
    cv2.destroyAllWindows()
Esempio n. 15
0
def hello():
  cube = 'oobywyywogbbogrgbgrbbyrgogrygwrbwggoryyrobboywowrywrww'
  step = utils.solve(str(cube), 'Beginner')
  return 'success'
Esempio n. 16
0
 def validate(self, data):
     data['solution'] = rubik_utils.solve(data.get('positions', ''),
                                          'Kociemba')
     return data
Esempio n. 17
0
from rubik_solver import utils
f=open("str.txt","r")
a=f.readline()
ff=open('solve.txt',"w")
c=utils.solve(cube, 'CFOP')
for i in c:
    ff.write(i)
message("Select White as front face and Red as top face")
cv2.destroyAllWindows()
faces.append(obtainColors(mask))

message("Select Green as front face and White as top face")
cv2.destroyAllWindows()

cap.release()
send = ''
for i in faces:
    for j in i:
        send += j
    print(i)

print(send)
solution = utils.solve(send, 'Kociemba')
#from rubik.cube import Cube not used
#print(Cube(send))

#Libraries used to acces to comunication
import socket
import array as arr

# Dictionary of cube moves
movesDict = {
    "D": 0,
    "D2": 1,
    "D'": 2,
    "L": 3,
    "L2": 4,
    "L'": 5,
Esempio n. 19
0
def begin(cube):
    return u.solve(cube, 'Beginner')
Esempio n. 20
0
# Name:        module1
# Purpose:
#
# Author:      Jean
#
# Created:     24/04/2019
# Copyright:   (c) Jean 2019
# Licence:     <your licence>
#-------------------------------------------------------------------------------
from rubik_solver import utils
import time

methods = ['Beginner', 'CFOP', 'Kociemba']
cube = 'wowgybwyogygybyoggrowbrgywrborwggybrbwororbwborgowryby'

for m in methods:
    print('Start process :', m)
    start = time.time()
    solution = utils.solve(cube, m)
    end = time.time()
    print('Time of process :', end - start, 's')
    print(solution)


def main():
    pass


if __name__ == '__main__':
    main()
Esempio n. 21
0
from rubik_solver import utils
f = open("str.txt", "r")
a = f.readline()
ff = open('solve.txt', "w")
c = utils.solve(cube, 'Kociemba')
for i in c:
    ff.write(i)
Esempio n. 22
0
w = y = b = g = r = o = 0
sides = ["w", "y", "b", "g", "r", "o"]
sideNums = [0, 0, 0, 0, 0, 0]
for i in cube:
    sideNums[sides.index(i)] += 1

maxTiles = max(sideNums[sides.index("w")], sideNums[sides.index("y")],
               sideNums[sides.index("b")], sideNums[sides.index("g")],
               sideNums[sides.index("r")], sideNums[sides.index("o")])
# print("Max:", maxTiles)

port1 = "com4"
port2 = "com10"
a_algo = []
if maxTiles == 9:
    solve = utils.solve(cube, 'Kociemba')  # this gets a solve alg
    algo = []  # this creates an empty list
    for i in solve:  #this will go through your solve
        tmp = str(i)  # it converts the solve instance to a string
        if len(tmp) == 1:  # this will add a space on single clockwise moves
            tmp += " "
            a_algo.append(tmp)
        elif tmp[1] == "'":
            for i in range(2):
                a_algo.append(tmp[0] + " ")
        elif tmp[1] == "2":
            for i in range(1):
                a_algo.append(tmp[0] + " ")

        algo.append(tmp)  # this will add the single move to the algo list
    print(
Esempio n. 23
0
    def test_solve(self):
        c = Cube()
        with self.assertRaises(TypeError):
            utils.solve(c, None)

        with self.assertRaises(ValueError):
            utils.solve(None, "INVALID SOLVER")

        with self.assertRaises(ValueError):
            utils.solve(None, MockSolver)

        with self.assertRaises(ValueError):
            utils.solve(None, self.solve_methods[0])

        with self.assertRaises(ValueError):
            utils.solve(1, self.solve_methods[0])

        for method in self.solve_methods:
            for i in range(10):
                c = Cube()
                ref_solution = method(c).solution()
                s1 = utils.solve(c, method)
                self.assertEqual(ref_solution,
                                 s1,
                                 msg="Failed with Cubie.Cube and method %s" %
                                 method.__class__.__name__)
                # Test with NaiveCube
                s2 = utils.solve(c.to_naive_cube(), method)
                self.assertEqual(ref_solution,
                                 s2,
                                 msg="Failed with Cubie.Cube and method %s" %
                                 method.__class__.__name__)

                # Test with string representation
                s3 = utils.solve(c.to_naive_cube().get_cube(), method)
                self.assertEqual(ref_solution,
                                 s3,
                                 msg="Failed with Cubie.Cube and method %s" %
                                 method.__class__.__name__)
Esempio n. 24
0
        if (entrada != ''):
            cara_o = entrada
    elif color == "w":
        cara_w = cara[::-1]
        print('Comprobacion de que la cara es correcta:')
        print(cara_w)
        entrada = raw_input(
            'Introduce la secuencia de colores correcta o pulsa enter...')
        if (entrada != ''):
            cara_w = entrada

cube = cara_y + cara_b + cara_r + cara_g + cara_o + cara_w

print(cube)

movements = utils.solve(cube, 'Kociemba')

print(movements)

ack = arduino.readline()
print('ACK: ' + ack)

print('COMENZANDO A RESOLVER EL CUBO...')

for mov in movements:
    print(str(mov))
    arduino.write(str(mov))
    ack = arduino.readline()
    print(ack)

arduino.write('E')
# folder = 'imgs/FullColor'
# folder = 'imgs/Mi_cubo'
folder = f'imgs/{sys.argv[1]}'
paths = {
    'Y': f'{folder}/rubik_amarillo.jpg',
    'W': f'{folder}/rubik_blanco.jpg',
    'R': f'{folder}/rubik_rojo.jpg',
    'O': f'{folder}/rubik_naranja.jpg',
    'B': f'{folder}/rubik_azul.jpg',
    'G': f'{folder}/rubik_verde.jpg',
}
print(" ------------ ESCANEANDO CUBO... ------------ ")
cube = vision.RubiksCube(paths)
print(cube)
print(" ------------ RESOLVIENDO CUBO... ----------- ")
solution_list = utils.solve(cube.to_solve_string(), 'Kociemba')
solution_list = [str(move) for move in solution_list]
solution_string = " ".join(solution_list)
print(f'SOLUCIÓN: {solution_string}')
print(f'{len(solution_list)}')

#        O B B
#        O Y B
#        R Y R

# G Y W  G G Y  B O Y  O Y Y
# B B W  G R B  W G O  G O R
# O W W  B Y G  O W R  Y R W

#        R R W
#        O W R
Esempio n. 26
0
from rubik_solver import utils
cube = 'wowgybwyogygybyoggrowbrgywrborwggybrbwororbwborgowryby'
print(utils.solve(cube, 'Kociemba'))
Esempio n. 27
0
                string = get_color(i[0], i[1], df).split(" ")
                dic['color'].append(string[4])
            if np.array_equal(color, bluec):
                blue = dic['color']
                print("blue : ", blue)
            elif np.array_equal(color, redc):
                red = dic['color']
                print("red : ", red)
            elif np.array_equal(color, yellowc):
                yellow = dic['color']
                print("yellow : ", yellow)
            elif np.array_equal(color, greenc):
                green = dic['color']
                print("green : ", green)
            elif np.array_equal(color, whitec):
                white = dic['color']
                print("white : ", white)
            elif np.array_equal(color, orangec):
                orange = dic['color']
                print("orange : ", orange)
            dic['pow'] = []
            dic['color'] = []

    cv2.imshow("ggwp", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

cube = yellow + blue + red + green + orange + white
cube = ''.join(cube)
utils.solve(cube, 'Beginner')
Esempio n. 28
0
def kocem(cube):
    return u.solve(cube, 'Kociemba')
Esempio n. 29
0
cube = 'wowgybwyogygybyoggrowbrgywrborwggybrbwororbwborgowryby'

from rubik_solver import utils

print("\nKociemba:\n {}".format(utils.solve(cube, 'Kociemba')))
'''

Kociemba solver needs the following cubies at place:

4 (Upper center): YELLOW
13 (Left center): BLUE
22 (Front center): RED
31 (Right center): GREEN
40 (Back center): ORANGE
49 (Down center): WHITE


----------------
| 0 | 1 | 2 |
----------------
| 3 | 4 | 5 |
----------------
| 6 | 7 | 8 |
----------------
-------------------------------------------------------------
| 9 | 10 | 11 | 18 | 19 | 20 | 27 | 28 | 29 | 36 | 37 | 38 |
-------------------------------------------------------------
| 12 | 13 | 14 | 21 | 22 | 23 | 30 | 31 | 32 | 39 | 40 | 41 |
-------------------------------------------------------------
| 15 | 16 | 17 | 24 | 25 | 26 | 33 | 34 | 35 | 42 | 43 | 44 |
-------------------------------------------------------------
Esempio n. 30
0
def cfop_new(cube):
    return u.solve(cube, 'CFOP')