0

using python i'd like to draw a rubik's cube based on this picture http://vixra.files.wordpress.com/2010/0 ... s-cube.jpg

this is my current code http://pastebin.com/MfF07ze4

but i'd like the code to have at least 5 for loops and 5 functions that will aid in the creation of the cube. also i need help with the algorithms in creating the 3 points for the 1x1 cubes of the rubik's cube.

Aiko As
  • 13
  • 7

1 Answers1

2

I don't have the drawingpanel module, so this is untested:

from drawingpanel import *
panel = DrawingPanel(600, 600)
from math import *
import numpy as np

class Projection(object):
    def __init__(self, origin, dx, dy, dz):
        self.o = np.matrix([origin[0], origin[1], 0.])
        self.p = np.matrix([
                    [dx[0], dx[1], 0.],
                    [dy[0], dy[1], 0.],
                    [dz[0], dz[1], 0.]
                ])

    def proj(self, x, y, z):
        res = self.o + np.matrix([x, y, z]) * self.p
        return (res[0,0], res[0,1])

This is a simple isometric 3d-to-2d projection - it takes a 3d coordinate and returns the corresponding 2d screen coordinate.

proj = Projection((175,130), ( 50, -24), (-50, -24), (  0,  70)).proj

I create a specific projection - based on your image, I make the front corner of the cube the origin at (175,130). +X runs to the top right corner of the cube, and I make that corner point (3,0,0) to make it easy to subdivide the cube, which means that the screen projection of (1,0,0) is (215, 106), making dx (50, -24); then similarly for +Y to the top left corner and +Z to the bottom front corner.

def make_poly_pts(*args):
    return [coord for pt in args for coord in proj(*pt)]

This is a utility function - it takes a list of 3d points and returns a list of [x1, y1, x2, y2, ... xN, yN] coordinates to feed to create_polygon.

# allow for a gap between stickers
offs = 0.05
ooffs = 1. - offs

# draw top face (XY)
panel.canvas.create_polygon(*make_poly_pts((0,0,0), (3,0,0), (3,3,0), (0,3,0)), outline='black', fill='black')
for i in xrange(3):
    for j in xrange(3):
        panel.canvas.create_polygon(*make_poly_pts((i+offs,j+offs,0), (i+ooffs,j+offs,0), (i+ooffs,j+ooffs,0), (i+offs,j+ooffs,0)), outline='black', fill='yellow')

... then the other two faces can be created similarly by swapping axes.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • Thank you! Although this is much more complicated than I can completely understand I still appreciate the help! – Aiko As Jul 18 '12 at 22:56