Zum Inhalt

Cube

Cube

Represents a Rubikscube to be solved by the solver

__init__(self) special

Initializes a new cube that is solved and has the colors set in DEFAULT_FACE_COLORS

Source code in core/solver/Cube.py
142
143
144
145
146
147
148
149
150
def __init__(self):
    """
    Initializes a new cube that is solved and has the colors set in DEFAULT_FACE_COLORS
    """
    self.cubies: Dict[str, Cubie] = {}
    for x in Cube.CUBIES:
        self.cubies[x] = Cubie()
        for f in x:
            self.cubies[x].faces[f] = Cube.DEFAULT_FACE_COLORS[f]

apply_move(self, move)

Applies a single move to the cube

Parameters:

Name Type Description Default
move Move

Move to execute

required
Source code in core/solver/Cube.py
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
def apply_move(self, move: Move):
    """
    Applies a single move to the cube

    Args:
        move (Move): Move to execute
    """
    logger.debug("Doing Move: {}".format(move))

    changes = move.changes()
    if move.inverse:
        changes = [(t, f) for (f, t) in changes]
    original_cubies = {}
    for start, end in changes:
        n_f_cubie = Cube.get_cubie_name(start)
        f_cubie = original_cubies[n_f_cubie] if n_f_cubie in original_cubies else self.cubies[n_f_cubie]
        t_cubie = self.cubies[Cube.get_cubie_name(end)]
        original_cubies[Cube.get_cubie_name(end)] = deepcopy(t_cubie)
        for f_face, t_face in zip(start, end):
            t_cubie.faces[t_face] = f_cubie.faces[f_face]

    if (move.twice):
        self.apply_move(Move(move.face))

    logger.debug(self.print(False))

apply_moves(self, moves, face='F')

Applies moves to the cube with the given face used as front.

Parameters:

Name Type Description Default
moves List[str]

Moves to apply

required
face str

Moves will be applied relative to this face

'F'

Returns:

Type Description
List[str]

List[str]: List of moves that were applied to the front face.

Source code in core/solver/Cube.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def apply_moves(self, moves: List[str], face: str = 'F') -> List[str]:
    """
    Applies moves to the cube with the given face used as front.

    Args:
        moves (List[str]): Moves to apply
        face (str, optional): Moves will be applied relative to this face

    Returns:
        List[str]: List of moves that were applied to the front face. 
    """
    result = []
    for move_str in moves:
        move = Move(move_str).for_face(face)
        self.apply_move(move)
        result.append(move.__str__())
    return result

color_face(self, color)

Gets the face that has the given color

Parameters:

Name Type Description Default
color TileColor

Color to be found

required

Returns:

Type Description
str

str: Face having the provided color

Source code in core/solver/Cube.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def color_face(self, color: TileColor) -> str:
    """
    Gets the face that has the given color

    Args:
        color (TileColor): Color to be found

    Returns:
        str: Face having the provided color
    """
    return {
        self.cubies['U'].faces['U']: 'U',
        self.cubies['L'].faces['L']: 'L',
        self.cubies['F'].faces['F']: 'F',
        self.cubies['R'].faces['R']: 'R',
        self.cubies['B'].faces['B']: 'B',
        self.cubies['D'].faces['D']: 'D'
        }[color]

cubie_by_colors(self, *args)

Finds the cubie with the provided colors

Parameters:

Name Type Description Default
*args TileColor

Colors to search for

()

Returns:

Type Description
Cubie

Cubie: Cubie with the provided colors

Source code in core/solver/Cube.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def cubie_by_colors(self, *args: TileColor) -> Cubie:
    """
    Finds the cubie with the provided colors

    Args:
        *args (TileColor): Colors to search for

    Returns:
        Cubie: Cubie with the provided colors
    """
    colors = set(args)
    for cubie in self.cubies.values():
        face_colors = set(cubie.faces.values())
        if colors == face_colors:
            return cubie

face_color(self, face)

Gets the color of a face on this cube

Parameters:

Name Type Description Default
face str

Face to be inspected

required

Returns:

Type Description
TileColor

TileColor: Color of the face

Source code in core/solver/Cube.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def face_color(self, face: str) -> TileColor:
    """
    Gets the color of a face on this cube

    Args:
        face (str): Face to be inspected 

    Returns:
        TileColor: Color of the face
    """
    return {
        'U': self.cubies['U'].faces['U'],
        'L': self.cubies['L'].faces['L'],
        'F': self.cubies['F'].faces['F'],
        'R': self.cubies['R'].faces['R'],
        'B': self.cubies['B'].faces['B'],
        'D': self.cubies['D'].faces['D']
        }[face]

from_3d_representation(cube_3d) staticmethod

Converts a cube in 3d representation into a cube in dict representation

Parameters:

Name Type Description Default
cube_3d Cube3D

The cube in 3d representation

required

Returns: The cube in dict representation

Source code in core/solver/Cube.py
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
@staticmethod
def from_3d_representation(cube_3d: Cube3D) -> 'Cube':
    """
    Converts a cube in 3d representation into a cube in dict representation
    Args:
        cube_3d: The cube in 3d representation

    Returns: The cube in dict representation
    """
    cube_1d = Cube()

    facelets = np.full((len(Facelets, )), TileColor.NONE)

    for face_position in FacePosition:

        if face_position == FacePosition.YELLOW:
            # for yellow, "up" is the green side
            top_vector = FacePosition.GREEN.to_vector()

        elif face_position == FacePosition.WHITE:
            # for white, "up" is the blue side
            top_vector = FacePosition.BLUE.to_vector()

        else:
            # for all other faces, yellow is up
            top_vector = FacePosition.YELLOW.to_vector()

        face_vector = face_position.to_vector()
        third_vector = np.cross(face_vector, top_vector)

        face_x_vector = third_vector * -1
        face_y_vector = top_vector * -1

        face_2d = cube_3d.get_2d_face(face_position,
                                   (face_vector, top_vector, third_vector),
                                   (face_x_vector, face_y_vector),
                                   offset=np.array([1, 1, 0]))

        facelets[Cube.INDICES[face_position][0]:Cube.INDICES[face_position][1]] = face_2d.flatten()

    for facelet, color in zip(list(Facelets), facelets):
        cube_1d.set_face(facelet, TileColor(color))

    assert len(Facelets) == len(facelets)
    # assert all(map(lambda x: x == 9, (counter := Counter(facelets)).values())), counter
    Cube.validate(cube_1d)
    return cube_1d

from_string(self, input)

Reads the colors of the cube from the input string and sets them. The provided string is interpreted in the following order:

            ----------------
            | 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 |
-------------------------------------------------------------
            ----------------
            | 45 | 46 | 47 |
            ----------------
            | 48 | 49 | 50 |
            ----------------
            | 51 | 52 | 53 |
            ----------------

The color shorthands are:

  • [o]range
  • [b]lue
  • [r]ed
  • [w]hite
  • [y]ellow
  • [g]reen
Source code in core/solver/Cube.py
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
def from_string(self, input: str):
    """
    Reads the colors of the cube from the input string and sets them.
    The provided string is interpreted in the following order: 

    ```
                ----------------
                | 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 |
    -------------------------------------------------------------
                ----------------
                | 45 | 46 | 47 |
                ----------------
                | 48 | 49 | 50 |
                ----------------
                | 51 | 52 | 53 |
                ----------------
    ```
    The color shorthands are:

    - [o]range
    - [b]lue
    - [r]ed
    - [w]hite
    - [y]ellow
    - [g]reen
    """
    assert len(input) == len(Facelets)

    for face, color in zip(Facelets, input):
        self.set_face(face, TileColor.from_string(color.upper()))
    return self

get_cubie_name(cubie_name) staticmethod

Gets the cubie name as it is used in the cubies dictionry

Parameters:

Name Type Description Default
cubie_name [type]

name parts of the cubie

required

Returns:

Type Description
str

str: Corrected cubie name

Source code in core/solver/Cube.py
219
220
221
222
223
224
225
226
227
228
229
230
@staticmethod
def get_cubie_name(cubie_name) -> str:
    """
    Gets the cubie name as it is used in the cubies dictionry 

    Args:
        cubie_name ([type]): name parts of the cubie

    Returns:
        str: Corrected cubie name 
    """
    return ''.join(sorted(cubie_name))

get_face(self, face)

Gets the color of a facelet

Parameters:

Name Type Description Default
face Facelets

Facelet to find

required

Returns:

Type Description
TileColor

TileColor: Color of the facelet

Source code in core/solver/Cube.py
195
196
197
198
199
200
201
202
203
204
205
206
def get_face(self, face: Facelets) -> TileColor:
    """
    Gets the color of a facelet

    Args:
        face (Facelets): Facelet to find

    Returns:
        TileColor: Color of the facelet
    """
    (cubie, face) = face.value
    return self.cubies[cubie].faces[face]

print(self, to_console=True)

Generates a 2D ASCII graphic of the current cube

Parameters:

Name Type Description Default
to_console bool

Whether the output should also be printed to console

True
Source code in core/solver/Cube.py
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
    def print(self, to_console: bool = True):
        """
        Generates a 2D ASCII graphic of the current cube

        Args:
            to_console (bool, optional): Whether the output should also be printed to console
        """
        template = '''
               ----------------
               | ULB | UB | URB |
               ----------------
               | UL | U | UR |
               ----------------
               | ULF | UF | URF |
               ----------------
-------------------------------------------------------------
| LUB | LU | LUF | FLU | FU | FRU | RFU | RU | RBU | BUR | BU | BUL |
-------------------------------------------------------------
| LB | L | LF | FL | F | FR | RF | R | RB | BR | B | BL |
-------------------------------------------------------------
| LDB | LD | LDF | FLD | FD | FRD | RFD | RD | RBD | BDR | BD | BDL |
-------------------------------------------------------------
               ----------------
               | DFL | DF | DFR |
               ----------------
               | DL | D | DR |
               ----------------
               | DBL | DB | DBR |
               ----------------'''

        for x in Facelets:
            template = template.replace(' ' + x.name + ' ', ' ' + self.get_face(x).as_color() + ' ', 1)

        if(to_console):
            print(template)

        return template

set_face(self, face, color)

Sets the color of a facelet

Parameters:

Name Type Description Default
face Facelets

facelet to set

required
color TileColor

color to set

required
Source code in core/solver/Cube.py
208
209
210
211
212
213
214
215
216
217
def set_face(self, face: Facelets, color: TileColor) -> None:
    """
    Sets the color of a facelet

    Args:
        face (Facelets): facelet to set
        color (TileColor): color to set
    """
    (cubie, face) = face.value
    self.cubies[cubie].faces[face] = color

to_cubestring(self)

Returns a 1D representation of the cube that can be used by kociemba solver.

Note

The representation is very different from how the cube is initialized. The order in which the faces are outputted is different. And instead of outputting a color for each facelett, each facelett gets represented by the face that has the identical color.

Returns:

Type Description
str

str: Representation of the cube compatible with the kocimba solver

Source code in core/solver/Cube.py
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
def to_cubestring(self) -> str:
    """
    Returns a 1D representation of the cube that can be used by kociemba solver.

    Note:
        The representation is very different from how the cube is initialized. 
        The order in which the faces are outputted is different.
        And instead of outputting a color for each facelett, each facelett gets represented by the face that has the identical color.

    Returns:
        str: Representation of the cube compatible with the kocimba solver
    """
    # "URFDLB"
    side_order = [ 
        range(0,9),
        range(27,36),
        range(18,27),
        range(45,54),
        range(9,18),
        range(36,45)
    ]
    result = ''
    facelets = [x for x in Facelets]

    for side in side_order:
        for facelet in side:
            result += self.color_face(self.get_face(facelets[facelet]))

    return result

validate(cube) staticmethod

Validates that the cube is valid

Parameters:

Name Type Description Default
cube Cube

Cube to check

required
Source code in core/solver/Cube.py
370
371
372
373
374
375
376
377
378
379
380
381
382
@staticmethod
def validate(cube: "Cube"):
    """
    Validates that the cube is valid

    Args:
        cube (Cube): Cube to check
    """
    def valid_cubie(cubie: Cubie) -> bool:
        return len(cubie.faces.values()) == len(set(cubie.faces.values()))

    for cubie in cube.cubies.values():
        assert valid_cubie(cubie), cubie

Facelets

An enumeration.