Example code

Here are a some examples of how to use the Cube Puzzle Library. These examples are given in the form of interactive Python sessions. They can also be found in the software archive, which you can retrieve in the Download section.

The following example does not require any visual context. It creates a 2x2x2 cube, performs some rotations to scramble the cube, calls the solve() method of the Solver class to generate a solution and finally prints the solution using the Singmaster notation:

Sam-Jordans-Computer:/ samjordan$ python
Python 2.4.3 (#1, Jul 25 2008, 12:46:58) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # example20.py
... from cubepuzzle.cube import Cube
>>> from cubepuzzle.notation import Notation
>>> from cubepuzzle.shared import Face, Rotation
>>> from cubepuzzle.solver import Solver
>>> mycube = Cube(2)
>>> rot1 = Rotation(Face.left, 1, True, 1)
>>> rot2 = Rotation(Face.up, 1, True, 2)
>>> rot3 = Rotation(Face.front, 1, False, 1)
>>> rot4 = Rotation(Face.right, 1, True, 1)
>>> rotations = [rot1, rot2, rot1, rot3, rot4, rot2, rot3]
>>> mycube.rotate_slices(rotations)
>>> solver = Solver()
>>> success, solution, unused = solver.solve(mycube)
>>> notation = Notation(2, "Singmaster")
>>> notation.print_rotations(solution)
L' B' D2 B' R D' R' D' B' D B D
>>>
The next example is a graphical example, therefore it does only work, if the VTK graphics library is installed. The program opens a standard VTK window and displays a 5x5x5 cube on a blue background. The user interaction facilities are those provided by the VTK software: the cube can be rotated and zoomed as a whole using the mouse. More advanced interaction is available in the Cube Puzzle Library and is demonstrated in other examples, which are found in the software archive.
Sam-Jordans-Computer:/ samjordan$ python
Python 2.4.3 (#1, Jul 25 2008, 12:46:58) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # example33.py
... import vtk
>>> from cubepuzzle.display import CubeObjectData, CubeObject
>>> from cubepuzzle.display import CubeDisplay
>>> properties = CubeObjectData()
>>> properties.size = 5
>>> mycube = CubeObject(properties)
>>> mydisp = CubeDisplay(mycube, elevation=45, azimuth=-45,
...                      dolly=0.75)
>>> mydisp.set_backgroundcolor((0.0, 0.0, 0.50))
>>> renwin = vtk.vtkRenderWindow()
>>> renwin.AddRenderer(mydisp.get_renderer())
>>> renwinint = vtk.vtkRenderWindowInteractor()
>>> renwinint.SetRenderWindow(renwin)
>>> renwinint.Initialize()
>>> renwinint.Start()
>>> del mycube
>>> del mydisp
>>> del renwinint
>>> del renwin
>>>