예제 #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 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)
예제 #3
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)
예제 #4
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()
예제 #5
0
파일: 3.1-revised.py 프로젝트: n41r0j/Zelle
def main():
    r = float(input("What is the radius: "))
    sphere = GeoSphere(r)

    print("The volume is {0:0.0f} m3 and the area is {1:0.0f} m2.".format(sphere.volume(),sphere.surfaceArea()))

    l = float(input("What is the length of a side?"))
    cube = Cube(l)

    print("The volume is {0:0.0f} m3 and the area is {1:0.0f} m2.".format(cube.volumeCube(),cube.surfaceArea()))
예제 #6
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")
예제 #7
0
 def display(self):
     y = 0
     for row in self.number:
         x = 0
         for cube in row:
             if cube:
                 theCube = Cube(0.35, self.color)
                 glPushMatrix()
                 glTranslated(2.55, 10.5, 0)
                 glTranslated(-x * 1.1 * theCube.size, -y * 1.1 * theCube.size, 16)
                 theCube.display()
                 glPopMatrix()
             x += 1
         y += 1
예제 #8
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")
예제 #9
0
def myprior(cube, ndim, nparams):
    """ MultiNest callback function. Sets the model parameters
    from the unit hypercube.
    Arguments:
    cube -- Unit hypercube from which model parameters are mapped.
    ndim -- Number of model paramers.
    nparams -- Total number of parameters in the cube .

    Returns:

    """
    # Set-up the paramters - CMSSM model.
    Model = CMSSMModelTracker()

    # Set the model parameters from the cube.
    Model.SetParams(cube)

    # Copy them to the cube so that they are printed, in alphabetical order.
    for name in sorted(Model.param.keys(), key=str.lower):
        Cube.AddCube(cube, Model.param[name].value, Cube.label, name)

    # Print-out cube model parameters for debugging.
    print '*****************************************************'
    print 'Parameters:'
    for i in range(Cube.AddCube.count() + 1):  # Count begins at 0 - need +1.
        print Cube.label[i], cube[i]
예제 #10
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()
예제 #11
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)
예제 #12
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__())
예제 #13
0
def main_repo(repo):
    c = Cube()
    randomize(c, 100)
    print c
    solver = AidedEntropicSolver(c, BasicEntropyEstimator(), repo)
    solver.solve()
    print c    
예제 #14
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
예제 #15
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()
예제 #16
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
예제 #17
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
예제 #18
0
def main():
    c = Cube()
    randomize(c, 3)
    print c
    solver = EntropicSolver(c, BasicEntropyEstimator())
    solver.solve()
    print c
예제 #19
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)
예제 #20
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
예제 #21
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())
예제 #22
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
예제 #23
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
예제 #24
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])]
예제 #25
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
예제 #26
0
    def checkValidityOfLinks(self, cubeNetFile):
        """
        Checks the validity of each of the transit links against the given cubeNetFile.
        That is, each link in a .lin should either be in the roadway network, or in a .link file.
        """
        import Cube
    
        (nodes_dict, links_dict) = Cube.import_cube_nodes_links_from_csvs(cubeNetFile,
                                        extra_link_vars=['LANE_AM', 'LANE_OP','LANE_PM',
                                                         'BUSLANE_AM', 'BUSLANE_OP', 'BUSLANE_PM'],
                                        extra_node_vars=[],
                                        links_csv=os.path.join(os.getcwd(),"cubenet_validate_links.csv"),
                                        nodes_csv=os.path.join(os.getcwd(),"cubenet_validate_nodes.csv"),
                                        exportIfExists=True)
        for line in self:
            
            # todo fix this
            line_is_oneway = True
            
            last_node = None
            for node in line:

                # this is the first node - nothing to do                
                if not last_node:
                    last_node = node
                    continue
                
                # we need to check this link but possibly also the reverse
                link_list = [(abs(last_node), abs(node))]
                if not line_is_oneway:
                    link_list.append((abs(node), abs(last_node)))
                
                # check the link(s)
                for (a,b) in link_list:
                    
                    # it's a road link
                    if (a,b) in links_dict: continue
                    
                    found_link = False
                    for link in self.links:
                        if not isinstance(link,TransitLink): continue
                        
                        if link.Anode == a and link.Bnode == b:
                            found_link = True
                            break
                        
                        if not link.isOneway() and link.Anode == b and link.Bnode == a:
                            found_link = True
                            break
                    
                    if found_link: continue

                    WranglerLogger.debug("TransitNetwork.checkValidityOfLinks: (%d, %d) not in the roadway network nor in the off-road links (line %s)" % (a, b, line.name))
                
                last_node = node
예제 #27
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)
예제 #28
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
예제 #29
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)
예제 #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")
예제 #31
0
파일: tests.py 프로젝트: BenSDuggan/CubeAI
def IDA_star_Test(n, scramble_length, tests, outputs, output_name, time_out, heuristic):
	print('Testing IDA*: n=' + str(n) + ', scramble_length: ' + str(scramble_length) + ', tests: ' + str(tests))

	results = [['Trial', 'scrambleLength', 'scramblePattern', 'scrambleHash', 'obviousSolution', 'correct', 'solvedTime(sec)', 'aiPath']]

	for i in range(tests):
		c = Cube(n)
		scramble_pattern = c.trueScramble(scramble_length)
		scramble_hash = c.__hash__()
		obvious_solution = Cube.obviousSolution(scramble_pattern)
		ai = IDA_Star(c, heuristic)
		start_time = time.time()
		try:
			ai_path = ai.solve(time_out)

			print(ai_path)

			# Run didn't time out!
			run_time = time.time() - start_time
			correct = ai_path[-1][1].isSolved()
			better_ai_path = []
			for j in ai_path:
				better_ai_path.append((j[0], j[1].state, j[1].__hash__()))
		except Exception as e:
			run_time = 'timed out (>' + str(time_out) + ' secs)'
			better_ai_path = []
			correct = False
			print('Timed out')
		
		print('\tTrial ' + str(i+1) + ': scramble_length: ' + str(scramble_length) + '; scramble_pattern: ' + str(scramble_pattern) + '; correct: ' + str(correct) + '; solved time: ' + str(run_time) + ' sec; ai_length: ' + str(len(better_ai_path)) + '; ai_path: ' + str(better_ai_path))

		results.append([i+1, scramble_length, scramble_pattern, scramble_hash, obvious_solution, correct, run_time, better_ai_path])

	if 'csv' in outputs:
		file = open(output_name+'.csv', 'w', newline='')  
		with file:  
		   writer = csv.writer(file)
		   writer.writerows(results)
예제 #32
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
예제 #33
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()
예제 #34
0
파일: main.py 프로젝트: Behsan05/Misc
# main.py

from pygame import *
from random import *
from Object import *
from Cube import *
import os

os.environ['SDL_VIDEO_WINDOW_POS'] = '100,50'
screen = display.set_mode((1000, 900))

display.set_caption("3D")

clock = time.Clock()
cube = Cube(500, 50, 2000, 50)

running = True
while running:
	screen.fill((0, 0, 0))
	for e in event.get():
		if e.type == QUIT:
			running = False

	pressed = key.get_pressed()

	cube.updateVar(pressed)
	cube.render(screen)

	display.flip()

quit()
예제 #35
0
class TestCubeSimple(unittest.TestCase):
    """Test de Cube() -- part 1"""

    def setUp(self):
        self.cube = Cube()  # un cube résolu

    def tearDown(self):
        self.cube = None

    def testCubes(self):
        """Un Cube() doit posséder tous les petits cubes"""

        keysExpected = [
            # 1ère couronne
            "FU",
            "FRU",
            "RU",
            "RBU",
            "BU",
            "BLU",
            "LU",
            "LFU",
            # 2ème couronne
            "FR",
            "BR",
            "BL",
            "FL",
            # 3ème couronne
            "FD",
            "FRD",
            "RD",
            "RBD",
            "BD",
            "BLD",
            "LD",
            "LFD",
        ]

        self.assertListEqual(sorted(keysExpected), sorted(list(self.cube.cubes.keys())))

    def testCubesValues(self):
        """Un cube doit être résolu par défault"""

        cubes = [
            # 1ère couronne
            ("FU", [1, 5]),
            ("FRU", [1, 2, 5]),
            ("RU", [2, 5]),
            ("RBU", [2, 3, 5]),
            ("BU", [3, 5]),
            ("BLU", [3, 4, 5]),
            ("LU", [4, 5]),
            ("LFU", [4, 1, 5]),
            # 2ème couronne
            ("FR", [1, 2]),
            ("BR", [3, 2]),
            ("BL", [3, 4]),
            ("FL", [1, 4]),
            # 3ème couronne
            ("FD", [1, 0]),
            ("FRD", [1, 2, 0]),
            ("RD", [2, 0]),
            ("RBD", [2, 3, 0]),
            ("BD", [3, 0]),
            ("BLD", [3, 4, 0]),
            ("LD", [4, 0]),
            ("LFD", [4, 1, 0]),
        ]

        for cube, facettes in cubes:
            self.assertTrue(numpy.array_equal(self.cube.cubes[cube], facettes))

    def testGetFacettes(self):
        """Cube.get_facettes() doit retourner la bonne facette"""

        cubes = [
            # 1ère couronne
            ("FU", Array([1, 5])),
            ("FRU", Array([1, 2, 5])),
            ("RU", Array([2, 5])),
            ("RBU", Array([2, 3, 5])),
            ("BU", Array([3, 5])),
            ("BLU", Array([3, 4, 5])),
            ("LU", Array([4, 5])),
            ("LFU", Array([4, 1, 5])),
            # 2ème couronne
            ("FR", Array([1, 2])),
            ("BR", Array([3, 2])),
            ("BL", Array([3, 4])),
            ("FL", Array([1, 4])),
            # 3ème couronne
            ("FD", Array([1, 0])),
            ("FRD", Array([1, 2, 0])),
            ("RD", Array([2, 0])),
            ("RBD", Array([2, 3, 0])),
            ("BD", Array([3, 0])),
            ("BLD", Array([3, 4, 0])),
            ("LD", Array([4, 0])),
            ("LFD", Array([4, 1, 0])),
        ]

        for cube, facettes in cubes:
            for index, facette in enumerate(facettes):
                self.assertEqual(self.cube.get_facette(cube, index), facette)

    def testEditCubeException(self):
        """Cube.edit_cube() doit accepter uniquement des cubes"""

        with self.assertRaises(ValueError):
            self.cube.edit_cube("abc", [0, 1])
        with self.assertRaises(ValueError):
            self.cube.edit_cube(0, [0, 1])
        with self.assertRaises(ValueError):
            self.cube.edit_cube(None, [0, 1])

    def testEditCubeGroup(self):
        """
        Cube.edit_cube() doit s'assurer qu'un même groupe de couleurs
        n'est pas présent plus d'une fois
        """
        with self.assertRaises(ValueError):
            self.cube.edit_cube("FRU", [0, 1, 0])
        with self.assertRaises(ValueError):
            self.cube.edit_cube("FRU", [2, 2, 2])
        with self.assertRaises(ValueError):
            self.cube.edit_cube("FRU", [0, 5, 5])

    def testEditCubeGroup(self):
        """Cube.edit_cube() doit planter si problème de taille de cube"""
        with self.assertRaises(ValueError):
            self.cube.edit_cube("FRU", [0, 1])
        with self.assertRaises(ValueError):
            self.cube.edit_cube("FU", [0, 1, 2])

    def testEditCubeCouleur(self):
        """Cube.edit_cube() ne doit accèpter que des couleurs"""
        with self.assertRaises(ValueError):
            self.cube.edit_cube("FRU", [0, 1, 8])

    def testEditCubeEdit(self):
        """Cube.edit_cube() doit faire son job"""
        self.cube.edit_cube("FRU", [0, 1, 2])
        self.assertTrue(numpy.array_equal(self.cube.cubes["FRU"], [0, 1, 2]))

    def testCubeContientCouleur(self):
        """Cube.cube_contient_couleur() doit faire son job"""
        self.assertTrue(self.cube.cube_contient_couleur("FRU", 1, 2, 5))
        self.assertFalse(self.cube.cube_contient_couleur("FRU", 0, 2, 5))
        self.assertTrue(self.cube.cube_contient_couleur("FR", 1, 2))
        self.assertFalse(self.cube.cube_contient_couleur("FR", 19, 2))

    def testFaceResolueError(self):
        """Cube.face_resolue() ne doit accèpter que des faces"""
        with self.assertRaises(ValueError):
            self.cube.face_resolue("W")

    def testFaceResolue(self):
        """
        Cube.face_resolue() doit fonctionner sur toutes les faces d'un cube résolu
        """
        for f in ["U", "L", "F", "R", "B", "D"]:
            self.assertTrue(self.cube.face_resolue(f))

    def testCubeResolu(self):
        """Cube.resolu() doit faire son job"""
        c = Cube()
        self.assertTrue(c.resolu())
        c.rot_R()
        self.assertFalse(c.resolu())
예제 #36
0
 def testCubeResolu(self):
     """Cube.resolu() doit faire son job"""
     c = Cube()
     self.assertTrue(c.resolu())
     c.rot_R()
     self.assertFalse(c.resolu())
예제 #37
0
 def validateTurnPens(self, CubeNetFile, turnPenReportFile=None, suggestCorrectLink=True):
     import Cube
     turnpens_files = ['turnsam.pen','turnsop.pen','turnspm.pen']
     pen_regex = r'^\s*(?P<frnode>\d+)\s+(?P<thnode>\d+)\s+(?P<tonode>\d+)\s+\d+\s+(?P<pen>-[\d+])'
     if turnPenReportFile:
         outfile = open(turnPenReportFile,'w')
         outfile.write('file,old_from,old_through,old_to,on_street,at_street,new_from,new_through,new_to,note\n')
         
     (nodes_dict, links_dict) = Cube.import_cube_nodes_links_from_csvs(CubeNetFile,
                                                                       extra_link_vars=['LANE_AM', 'LANE_OP','LANE_PM',
                                                                                        'BUSLANE_AM', 'BUSLANE_OP', 'BUSLANE_PM'],
                                                                       extra_node_vars=[],
                                                                       links_csv=os.path.join(os.getcwd(),"cubenet_validate_links.csv"),
                                                                       nodes_csv=os.path.join(os.getcwd(),"cubenet_validate_nodes.csv"),
                                                                       exportIfExists=True)
     found_matches = {}
     
     for file_name in turnpens_files:
         f = open(file_name,'r')
         for line in f:
             text = line.split(';')[0]
             m = re.match(pen_regex, text)
             if m:
                 new_fr = None
                 new_th = None
                 new_to = None
                 from_street = 'missing'
                 to_street = 'missing'
                 fr_node = int(m.groupdict()['frnode'])
                 th_node = int(m.groupdict()['thnode'])
                 to_node = int(m.groupdict()['tonode'])
                 pen     = int(m.groupdict()['pen'])
                 if not (fr_node,th_node) in links_dict:
                     WranglerLogger.debug("HighwayNetwork.validateTurnPens: (%d, %d) not in the roadway network for %s (%d, %d, %d)" % (fr_node,th_node,file_name,fr_node,th_node,to_node))
                     
                     if suggestCorrectLink:
                         new_fr = -1
                         new_th = th_node
                         match_links_fr = []
                         match_links_th = []
                         # if we already found a match for this, don't keep looking.
                         if (fr_node,th_node) in found_matches.keys():
                             match = found_matches[(fr_node,th_node)]
                             new_fr = match[0][1]
                         else:
                             #catch the links matching fr_node on the from end
                             for (a,b) in links_dict.keys():
                                 if a == fr_node:
                                     match_links_fr.append((a,b))
                                 # and links matching th_node on the to end
                                 if b == th_node:
                                     match_links_th.append((a,b))
                             # now take matched links and look for match_links_fr node b to match match_links_th node a
                             for (a1,b1) in match_links_fr:
                                 for (a2,b2) in match_links_th:
                                     if b1 == a2:
                                         #WranglerLogger.info("For link1 (%d, %d) and link2 (%d, %d): %d == %d" % (a1,b1,a2,b2,b1,a2))
                                         found_matches[(fr_node,th_node)] = [(a1,b1),(a2,b2)]
                                         new_fr = a2
                                         # index 1 is streetname
                                         from_street = links_dict[(a2,b2)][1]
                                         break
                 else:
                     new_fr = fr_node
                     from_street = links_dict[(fr_node,th_node)][1]
     
                         
                 if not (th_node,to_node) in links_dict:
                     WranglerLogger.debug("HighwayNetwork.validateTurnPens: (%d, %d) not in the roadway network for %s (%d, %d, %d)" % (th_node,to_node,file_name,fr_node,th_node,to_node))
                     #if turnPenReportFile: outfile.write("%s,%d,%d,outbound link missing from, %d, %d, %d\n" %(file_name,th_node,to_node,fr_node,th_node,to_node))
                     if suggestCorrectLink:
                         new_th = th_node
                         new_to = -1
                         match_links_th = []
                         match_links_to = []
                         # if we already found a match for this, don't keep looking.
                         if (th_node,to_node) in found_matches.keys():
                             match = found_matches[(th_node,to_node)]
                             new_to = match[0][1]
                         else:
                             #catch the links matching fr_node on the from end
                             for (a,b) in links_dict.keys():
                                 if a == th_node:
                                     match_links_th.append((a,b))
                                 # and links matching th_node on the to end
                                 if b == to_node:
                                     match_links_to.append((a,b))
                             # now take matched links and look for match_links_fr node b to match match_links_th node a
                             for (a1,b1) in match_links_th:
                                 for (a2,b2) in match_links_to:
                                     if b1 == a2:
                                         #WranglerLogger.info("For link1 (%d, %d) and link2 (%d, %d): %d == %d" % (a1,b1,a2,b2,b1,a2))
                                         found_matches[(th_node,to_node)] = [(a1,b1),(a2,b2)]
                                         new_to = a2
                                         to_street = links_dict[(a2,b2)][1]
                                         break
                 else:
                     new_to = to_node
                     to_street = links_dict[(th_node,to_node)][1]
                 
                 if new_th != None:
                     #outfile.write('file,old_from,old_through,old_to,on_street,at_street,new_from,new_through,new_to,note\n')
                     print file_name,fr_node,th_node,to_node,from_street,to_street,new_fr,new_th,new_to
                     outfile.write('%s,%d,%d,%d,%s,%s,%d,%d,%d,note\n' % (file_name,fr_node,th_node,to_node,from_street,to_street,new_fr if new_fr else -1,new_th,new_to if new_to else -1))
예제 #38
0
 def setUp(self):
     self.cube = Cube()  # un cube résolu