예제 #1
0
 def __init__(self, s, d):
     #Attributes
     self.NumX = s
     self.SizeOfSquare = d
     #Once we have the size of the cube we need to make the individual
     #Cubes so we need a triple for loop around NumX
     self.Cubes = []
     #Position of cube is (idx*SizeOfSquare - sizeOfSquare
     for idx in range(0, self.NumX):
         x = idx * self.SizeOfSquare - (
             (self.NumX - 1) / 2.0) * self.SizeOfSquare
         #Reset the layers
         self.layer = []
         for jdx in range(0, self.NumX):
             y = jdx * self.SizeOfSquare - (
                 (self.NumX - 1) / 2.0) * self.SizeOfSquare
             #Reset the columns
             self.col = []
             for kdx in range(0, self.NumX):
                 z = kdx * self.SizeOfSquare - (
                     (self.NumX - 1) / 2.0) * self.SizeOfSquare
                 newCube = Cube(x, y, z, self.SizeOfSquare)
                 #Append each Cube to a Column
                 self.col.append(newCube)
                 #print x,y,z
             #Append Each Column to a Layer
             #print self.col
             self.layer.append(self.col)
         #Append each layer to the array of Cubes
         self.Cubes.append(self.layer)
     if self.NumX == 1:
         self.Cubes = [[[Cube(0, 0, 0, self.SizeOfSquare)]]]
예제 #2
0
def main():
    randy = Renderer()

    polyCube = Cube()
    polyCube.build_polygon_mesh()
    randy.render(polyCube.mesh, 512, "polyCube.jpg")

    triangleCube = Cube()
    triangleCube.build_triangle_mesh(4000)
    randy.render(triangleCube.mesh, 1080, "HDcube.jpg")

    polyCylinder = Cylinder()
    polyCylinder.build_polygon_mesh()
    randy.render(polyCylinder.mesh, 512, "polyCylinder.jpg")

    triangleCylinder = Cylinder()
    triangleCylinder.build_triangle_mesh(4000)
    randy.render(triangleCylinder.mesh, 1080, "HDcylinder.jpg")

    polySphere = Sphere()
    polySphere.build_polygon_mesh()
    randy.render(polySphere.mesh, 512, "polySphere")

    triangleSphere = Sphere()
    triangleSphere.build_triangle_mesh(4000)
    randy.render(triangleSphere.mesh, 1080, "HDSphere")
예제 #3
0
def CubingOnUp():
    cube_1_obj = Cube.Cube(cube_1)
    cube_2_obj = Cube.Cube(cube_2)
    cube_3_obj = Cube.Cube(cube_3)
    cube_4_obj = Cube.Cube(cube_4)

    cube_list = [cube_1_obj, cube_2_obj, cube_3_obj, cube_4_obj]
    cube_stack = CubeStack.CubeStack(cube_list)

    print(cube_stack.validate_stack())
    print(cube_stack)
    '''
    Randomly pick a Cube from the CubeStack
    Either rotate it left or clockwise
    Check if it is a valid stack
    '''
    counter = 0
    #while( not cube_stack.validate_stack() and counter < 1000000 ):
    while (counter < 10000000):
        counter = counter + 1
        if counter % 100000 == 0:
            print(counter)

        idx = random.randint(0, len(cube_stack.stack) - 1)

        if random.getrandbits(1):
            cube_stack.stack[idx].rotate_left()
        else:
            cube_stack.stack[idx].rotate_clockwise()

        if cube_stack.validate_stack():
            print(cube_stack.validate_stack())
            print(cube_stack)
예제 #4
0
 def __init__(self, pos):
     self.body = []
     self.head = Cube.Cube(pos)
     self.body.append(self.head)
     body1 = Cube.Cube((self.head.pos[0]+1, self.head.pos[1]))
     self.body.append(body1)
     body2 = Cube.Cube((self.head.pos[0] + 2, self.head.pos[1]))
     self.body.append(body2)
     self.direction = (-1, 0)
예제 #5
0
def scrambler(n):
    algor_list = []
    algor = alg(algor_list, n)
    cube = Cube.Cube()

    for x in algor_list:
        if x[1] == " ":
            repeat = 1
        elif x[1] == "2":
            repeat = 2
        elif x[1] == "'":
            repeat = 3

        for i in range(repeat):
            if x[0] == "R":
                cube.r()

            elif x[0] == "L":
                cube.l()

            elif x[0] == "U":
                cube.u()

            elif x[0] == "D":
                cube.d()

            elif x[0] == "F":
                cube.f()

            else:
                cube.b()

    #print (str(cube))
    image_output.image(str(cube), algor)
예제 #6
0
def parseState(message_array):
    system_time = message_array[0]
    if system_time == lasttime: return
    message = np.delete(message_array.flatten(), 0)
    length = message.shape[0]
    nrows = int(length / 8)
    if length % nrows != 0:
        print "Error cant reshape"
        return

    message = message.reshape(nrows, 8)
    for row_id in nrows:
        row = message[row_id]
        cube_id = row[0]
        if cube_id not in cubes.keys():
            cubes[cube_id] = Cube(cube_id)
        faceup = row[1] - 1  #1-6 or 0-5
        sensors = row[2:]
        # is this the truth table i want or sensors>
        sensors = sensors < ambient_threshold
        cube = cubes[cube_id]
        cube.setMostRecentFaceUp(faceup)
        cube.setMostRecentLightSensorState(sensors)

    lasttime = system_time
예제 #7
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((800,600), DOUBLEBUF|OPENGL)
    pygame.display.set_caption('OpenGL Cube Exemple')

    gluPerspective(45, (800/600), 0.1, 50.0)

    glTranslatef(0.0, 0.0, -10)

    glRotatef(25, 1, -1, 0)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    glTranslatef(-0.5, 0, 0)
                if event.key == pygame.K_RIGHT:
                    glTranslatef(0.5, 0, 0)
                if event.key == pygame.K_UP:
                    glTranslatef(0, 0.5, 0)
                if event.key == pygame.K_DOWN:
                    glTranslatef(0, -0.5, 0)
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 4:
                    glTranslatef(0, 0, 1.0)
                if event.button == 5:
                    glTranslatef(0, 0, -1.0)

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube.Cube()
        pygame.display.flip()
예제 #8
0
    def solve(self, timeout=float('inf')):
        start_time = time.time()
        start_state = State(self.cube, None, 0, 0, None)
        goal_state = State(Cube(self.cube.size), None, 0, 0, None)
        explored = set()
        fringe = [start_state]
        heapq.heapify(fringe)

        #print("starting solve")
        while len(fringe) > 0:
            # Check to see if AI is timed out
            if time.time() - start_time >= timeout:
                print('time: ' + str(time.time()))
                raise Exception('Code timed out')

            current_state = heapq.heappop(fringe)
            #print(current_state)
            if current_state.current_state.isSolved():
                return self.find_path(start_state, current_state)
            if current_state.__hash__() in explored:
                continue
            for i in current_state.current_state.children('2x'):
                if i.__hash__() not in explored:
                    new_addition = State(i[1], current_state, current_state.depth+1+self.heuristic(i[1]), current_state.depth+1, i[0])
                    heapq.heappush(fringe, new_addition)
                    explored.add(current_state.__hash__())
예제 #9
0
def main_repo(repo):
    c = Cube()
    randomize(c, 100)
    print c
    solver = AidedEntropicSolver(c, BasicEntropyEstimator(), repo)
    solver.solve()
    print c    
예제 #10
0
class Debug:
    cube = Cube(2)
    move_list = []

    def __init__(self):
        pass

    @staticmethod
    def view(hash):
        if hash == None:
            return
        m = Cube(2)
        m.state = Cube.decode(hash)
        g = GUI(cube=m, player=True, width=800, height=600)

        while True:
            g.update()

    @staticmethod
    def reset(cube=Cube(2)):
        Debug.cube = cube
        Debug.move_list = [((None, None), cube.__hash__())]

    @staticmethod
    def addMove(move):
        Debug.move_list.append(move)

    @staticmethod
    def viewMoves():
        g = GUI(cube=Debug.cube, width=800, height=600)
        g.moveList(Debug.move_list)

        while True:
            g.update()
예제 #11
0
def scrambler(n):
    algor_list = alg(n)
    cube = Cube.Cube()

    for x in algor_list:
        if x[1] == " ":
            repeat = 1
        elif x[1] == "2":
            repeat = 2
        elif x[1] == "'":
            repeat = 3

        for i in range(repeat):
            if x[0] == "R":
                cube.r()

            elif x[0] == "L":
                cube.l()

            elif x[0] == "U":
                cube.u()

            elif x[0] == "D":
                cube.d()

            elif x[0] == "F":
                cube.f()

            else:
                cube.b()

    print cube
예제 #12
0
def main():
    c = Cube()
    randomize(c, 3)
    print c
    solver = EntropicSolver(c, BasicEntropyEstimator())
    solver.solve()
    print c
예제 #13
0
def chargerEnv(nomfichier):
    """Fonction de chargement, ouverture du fichier en mode lecture"""
    with open(nomfichier, 'r') as f:
        liste_cube = list()
        liste_robot = list()
        """deux listes vides pour contenir les objets charges"""
        for line in f:
            ligne = line.split(";")
            if ligne[0] == 'Arene':
                """On cree une nouvelle arene avec les parametres trouves sur la ligne, separes par des ';' """
                arene = Arene(int(ligne[1]), int(ligne[2]), int(ligne[3]),
                              liste_cube)
                arene.liste_robot = liste_robot
            elif ligne[0] == 'Cube':
                """On ajoute le cube a la liste de cube de l'arene, avec parametres trouves sur la ligne"""
                arene.liste_cube.append(
                    Cube(int(ligne[1]), int(ligne[2]), int(ligne[3]),
                         int(ligne[4]), int(ligne[5]), int(ligne[6])))
            elif ligne[0] == 'Mur':
                arene.liste_cube.append(
                    Mur(int(ligne[1]), int(ligne[2]), int(ligne[3]),
                        int(ligne[4]), int(ligne[5]), int(ligne[6])))
            elif ligne[0] == 'Sol':
                arene.liste_cube.append(
                    Sol(int(ligne[1]), int(ligne[2]), int(ligne[3]),
                        int(ligne[4]), int(ligne[5])))
            elif ligne[0] == 'Robot':
                (x, y, z) = literal_eval(ligne[1])
                (a, b, c) = literal_eval(ligne[2])
                (lo, la, ha) = literal_eval(ligne[3])
                arene.liste_robot.append(
                    Robot((x, y, z), (a, b, c), (lo, la, ha)))
        print("Arene chargée.")
        return arene
예제 #14
0
class CubicalComplex(Complex):
    __init__(self, signatures):
        dim=len(signatures[0])
        cubes=[{} for i in range(dim+1)]
        for sig in signatures:
            if not sig in cubes[get_sig_dim(sig)]:
                cubes[get_sig_dim(sig)][sig]=Cube(sig,cubes)
        Complex.__init__(self,cubes.values())
예제 #15
0
 def hammingDistance(cube):
     current_state = cube.state
     goal_state = Cube(cube.size).state
     score = 6
     for i in range(6):
         if current_state[i] == goal_state[i]:
             score -= 1
     return score
예제 #16
0
def game_loop(game):
    # TODO - create cubes
    matrix = game.get_matrix()
    game_cubes = []
    for row in matrix:
        for letter in row:
            cube = Cube(letter)
        game_cubes.append(cube)
예제 #17
0
    def view(hash):
        if hash == None:
            return
        m = Cube(2)
        m.state = Cube.decode(hash)
        g = GUI(cube=m, player=True, width=800, height=600)

        while True:
            g.update()
예제 #18
0
    def __init__(self):
        #initial cube object created upon initialization of CuBot object (54mm width, 3x3)
        self.cube = Cube.Cube(54, 3)

        #initialize self.arms object with all 3 self.arms (9 servos)
        self.arms = Arms2.AllArms(self.cube)

        self.leftArm = self.arms.leftArm
        self.rightArm = self.arms.rightArm
        self.centerArm = self.arms.centerArm
예제 #19
0
def getBox(w,h,d,x,y,z,string):
    glPushMatrix()
    glColor3f(1, 1, 1)
    glTranslatef(x, y, z)
    glActiveTexture(GL_TEXTURE0)
    LoadTextures(string)
    Cube(w, h, d)
    glPopMatrix()
    glDisable(GL_TEXTURE_2D)
    return x-w,x+w,z-d,z+d
예제 #20
0
 def __init__(self):
     cubeface = CubeFaces(Cube_1)
     cubeface.init_all_faces()
     self.cube = Cube.Cube(cubeface.faces)
     self.grids = [Grid("UP", cubeface.faces[UP], self.pos_grid[UP]),
                   Grid("FRONT", cubeface.faces[FRONT], self.pos_grid[FRONT]),
                   Grid("RIGHT", cubeface.faces[RIGHT], self.pos_grid[RIGHT]),
                   Grid("BACK", cubeface.faces[BACK], self.pos_grid[BACK]),
                   Grid("LEFT", cubeface.faces[LEFT], self.pos_grid[LEFT]),
                   Grid("DOWN", cubeface.faces[DOWN], self.pos_grid[DOWN])]
예제 #21
0
 def __init__(self, r, c, w, h, window):
     self.rows = r
     self.cols = c
     self.cubes = [[Cube(self.board[i][j], i, j, w, h) for j in range(c)]
                   for i in range(r)]
     self.width = w
     self.height = h
     self.model = None
     self.update_model()
     self.selected = None
     self.win = window
예제 #22
0
파일: Play.py 프로젝트: thomasg8/ZoomGames
def Cube():
    window.destroy()
    import Cube
    print("""\n\n\n\nGavin presents Cube!\nClick on the pile to update the card.
            Press a to see how many cards are in the piles.""")
    for i in range(1,4):
        pygame.init()
        #pygame.font.init()
        cards = Cube.CubeCards(r=i)
        Cube.Cube(cards)
        print("\n\n\n\n\n")
예제 #23
0
def main():

    print "Rubik's Cube scrambler by Ching, input the length of random algorithm you want and the resulting cube will be shown\nThis scrambler assume the use of Western color sheme with white face to the top and blue to the player"
    cube2 = Cube.Cube()
    print "Basic orientation:"
    print cube2

    moves = input(
        "Please input the number of steps you want the crambler to have: ")
    print "For the meaning of algorithm, please refer to: \nhttp://w.astro.berkeley.edu/~converse/rubiks.php?id1=basics&id2=notation"
    scrambler(moves)
예제 #24
0
def main():
    pygame.init()
    windowScale = 1
    display = (int(1920 * windowScale), int(1080 * windowScale))
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

    gluPerspective(25, (display[0] / display[1]), 0.0, 50.0)
    # glTranslatef(0, 0.0, -5)
    cam = Camera()
    cam.setPosition(0, 0, 10)
    glRotatef(0, 0, 0, 0)

    myStream = VisStream.VisStream(rate=48000 * 2, chunkSize=2**11)
    cube = Cube.Cube()
    # sheet = Sheet.Sheet()

    while True:
        glRotatef(myStream.getDynamicRotation(.0001, 50, 150), 3, 1, 1)
        # glRotatef(1, 1, 0, 0)
        # cam.setPosition(0, 0, -1*myStream.getDynamicRotation(5, 15, 150))
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        cube.setSideColors(myStream.getSideColors())

        cube.draw()
        # sheet.draw()
        cs = myStream.getDynamicRotation(1, 1.5, 100)
        cube.scaleCorner(scalars=[cs, cs, cs, cs, cs, cs, cs, cs])

        pygame.display.flip()
        pygame.time.wait(10)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                myStream.endStream()
                quit()
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_f:
                    myStream.plotStream()
                if event.key == pygame.K_r:
                    myStream.reset()
                if event.key == pygame.K_p:
                    gluPerspective(myStream.getDynamicRotation(45, 90, 150),
                                   (display[0] / display[1]), 0.0, 50.0)
                if event.key == pygame.K_DOWN:
                    cam.move(0, -1, 0)
                if event.key == pygame.K_UP:
                    cam.move(0, 1, 0)
                if event.key == pygame.K_LEFT:
                    cam.move(-1, 0, 0)
                if event.key == pygame.K_RIGHT:
                    cam.move(1, 0, 0)
예제 #25
0
    def solve(self, timeout=float('inf')):
        start_time = time.time()
        goal_state = Cube(self.cube.size).__hash__()
        depth = 0
        if self.cube.__hash__() == goal_state:
            print('Found goal at depth ' + str(depth))
            return [(None, self.cube)]

        seen = {}
        seen[self.cube.__hash__()] = (
            self.cube, None, None, -1
        )  #Current cube, parent cube, move from parent to current, move from parent of parent to parent
        fringe = {}
        fringe[self.cube.__hash__()] = (self.cube, None, None, -1)

        while True:
            if time.time() - start_time >= timeout:
                print('time: ' + str(time.time()))
                raise Exception('Code timed out')

            depth += 1
            print('Depth: ' + str(depth) + ', length of fringe: ' +
                  str(len(fringe)) + '; len seen: ' + str(len(seen)))
            print('time: ' + str(time.time()) + '; overlaped time: ' +
                  str(time.time() - start_time))

            new_fringe = {}
            for i in fringe:
                if time.time() - start_time >= timeout:
                    print('time: ' + str(time.time()))
                    raise Exception('Code timed out')

                for j in fringe[i][0].children('2x'):
                    if j[1].__hash__() == goal_state:
                        print('Found goal at depth ' + str(depth))
                        return self.find_path(seen,
                                              (j[1], fringe[i][0], j[0], -1))
                    if j[0][0] == fringe[i][3]:
                        continue
                    if j[1].__hash__() not in fringe and j[1].__hash__(
                    ) not in seen:
                        new_fringe[j[1].__hash__()] = (j[1], fringe[i][0],
                                                       j[0], j[0][0])
                        seen[j[1].__hash__()] = (j[1], fringe[i][0], j[0],
                                                 j[0][0])
            fringe = new_fringe
예제 #26
0
def main():
    display = (800, 600) 
    window = init(display)

    cube_length = 10

    #inicia instancias de Física e esferas
    physics = Physics(cube_length)
    list_spheres = create_spheres(physics, 25, 1, 20, 10)

    timeA = glfw.get_time()

    print_timer = 0.0

    while not glfw.window_should_close(window):
        timeB = glfw.get_time()
        dt = timeB - timeA
        timeA = timeB

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        Cube(cube_length)

        physics.update()
        for sphere in list_spheres:
            sphere.update(dt)
        for sphere in list_spheres:
            sphere.rend()

        #imprime informações sobre conservação
        print_timer += dt
        if print_timer > 1.0:
            kinetic_energy = 0.0
            for sphere in list_spheres:
                kinetic_energy += float(sphere.velocity.norm() ** 2)#assumimos a massa como sendo uma unidade e nao dividimos por 2 para economizar processamento
            print("Total kinetic energy: {}\n".format(kinetic_energy), end = '\r')
            print_timer = 0.0

        glfw.swap_buffers(window)
        glfw.poll_events()
        glfw.swap_interval(1);

    end(window)
    quit()
예제 #27
0
def create_repo(filename, depth=4):
    repository = {}
    depth = 5
    basic_moves = []
    for f in xrange(6):
        for n in xrange(1, 4):
            basic_moves.append((f, n))
    for i, moves in enumerate(product(basic_moves, repeat=depth)):
        c = Cube()
        for move in moves:
            c.rotate(*move)
        t = c.get_current_tuple_representation()
        repository.setdefault(t, moves)
        print i

    f = open('repo.dat', 'w')
    cPickle.dump(repository, f)
    f.close()
    return repository
예제 #28
0
    def solve(self, timeout=float('inf')):
        start_time = time.time()
        goal_state = Cube(self.cube.size).__hash__()
        depth = 0
        if self.cube.__hash__() == goal_state:
            #print('Found goal at depth ' + str(depth))
            return [(None, self.cube)]

        # Remembers every state seen and allows us to find the parent state of a cube so we can output the path
        seen = {}
        seen[self.cube.__hash__()] = (self.cube, None, None, -1) #Current cube, parent cube, move from parent to current, move from parent of parent to parent
        # The nodes that need to be expanded (the deepest lay)
        fringe = {}
        fringe[self.cube.__hash__()] = (self.cube, None, None, -1) 

        while True:
            # Check to see if AI is timed out
            if time.time() - start_time >= timeout:
                print('time: ' + str(time.time()))
                raise Exception('Code timed out')

            depth += 1
            #print('Depth: ' + str(depth) + ', length of fringe: ' + str(len(fringe)) + '; len seen: ' + str(len(seen)))
            #print('time: ' + str(time.time()) + '; overlaped time: ' + str(time.time()-start_time))

            new_fringe = {}
            for i in fringe:
                # Check to see if AI is timed out
                if time.time() - start_time >= timeout:
                    print('time: ' + str(time.time()))
                    raise Exception('Code timed out')

                for j in fringe[i][0].children('2x'):
                    if j[1].__hash__() == goal_state:
                        #print('Found goal at depth ' + str(depth))
                        return self.find_path(seen, (j[1], fringe[i][0], j[0], -1))
                    if j[0][0] == fringe[i][3]:
                        continue
                    if j[1].__hash__() not in fringe and j[1].__hash__() not in seen:
                        new_fringe[j[1].__hash__()] = (j[1], fringe[i][0], j[0], j[0][0])
                        seen[j[1].__hash__()] = (j[1], fringe[i][0], j[0], j[0][0])
            fringe = new_fringe
예제 #29
0
 def fillRubiks(self):
     top = (self.size - 2)
     id = 0
     for x in range(self.size):
         for y in range(self.size):
             for z in range(self.size):
                 self.rubiks[x][y][z] = Cube.Cube(True, id)
                 self.rubiks[x][y][z].setCords(x, y, z)
                 if x <= top:
                     self.rubiks[x][y][z].removeSide(0)
                 if x >= 1:
                     self.rubiks[x][y][z].removeSide(1)
                 if y <= top:
                     self.rubiks[x][y][z].removeSide(2)
                 if y >= 1:
                     self.rubiks[x][y][z].removeSide(3)
                 if z <= top:
                     self.rubiks[x][y][z].removeSide(4)
                 if z >= 1:
                     self.rubiks[x][y][z].removeSide(5)
                 id += 1
예제 #30
0
def test():
    # set up tests
    cubeFactory = Cube()
    sphereFactory = Sphere()
    cylinderFactory = Cylinder()

    cube = cubeFactory.build_triangle_mesh(256)
    sphere = sphereFactory.build_triangle_mesh(256)
    cylinder = cylinderFactory.build_triangle_mesh(256)

    # do tests
    print("#### CUBE ####")
    cube.test_integrity()
    print("\n")

    print("#### CYLINDER ####")
    cylinder.test_integrity()
    print("\n")

    print("#### SPHERE ####")
    sphere.test_integrity()
    print("\n")