def runTest(self): """ftl_valide() doit faire son job""" c = Cube() self.assertTrue(ftl_valide(c)) c.rot_F() self.assertFalse(ftl_valide(c))
def main(): global width, rows, snake, snack width = Cube.width rows = Cube.rows win = pygame.display.set_mode((width, width)) snake = Snake(SNAKE_COlOR, (10, 10)) snack = Cube(randomSnack(rows, snake), color=SNACK_COLOR) clock = pygame.time.Clock() while True: pygame.time.delay(50) clock.tick(10) snake.move() if snake.body[0].position == snack.position: snake.addCube() snack = Cube(randomSnack(rows, snake), color=SNACK_COLOR) for x in range(len(snake.body)): if snake.body[x].position in list( map(lambda z: z.position, snake.body[x + 1:])): message_box('You Lost!', 'Score: {}. Play again!'.format(len(snake.body))) snake.reset((10, 10)) break redrawWindow(win)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_minimum_size(400, 300) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) self.cube = Cube()
def main(w, rows): global snake, food flag = True window = pygame.display.set_mode((w, w)) snake = Snake((10, 10), (255, 0, 0), rows) clock = pygame.time.Clock() food = Cube(randomFood(rows, snake), color=(0, 255, 0)) while flag: pygame.time.delay(10) clock.tick(10) snake.move() if snake.body[0].pos == food.pos: snake.addCube() food = Cube(randomFood(rows, snake), color=(0, 255, 0)) for x in range(len(snake.body)): if snake.body[x].pos in list( map(lambda z: z.pos, snake.body[x + 1:])): print('Score: ', len(snake.body)) snake.reset((10, 10)) break redrawWindow(window, w // rows)
def main(input_dir=None): # Input the faces of the Cube if input_dir is None: captured_faces, captured_imgs = capture_faces() else: input_imgs = load_imgs_from_dir(input_dir) captured_faces, captured_imgs = capture_faces_from_images(input_imgs) # Get the color classifier clf_yuv = get_classifier() # Predict the face colors from the input images faces = np.array(captured_faces) pred_colors_yuv, pred_proba_yuv = label_images(clf_yuv, [faces]) colors_cube = np.array(pred_colors_yuv).reshape((6, 3, 3)) # Inspect / adjust results if necessary. This step can modify pred_colors_yuv2. check_images(captured_imgs, captured_faces, colors_cube, clf_yuv) plt.show() # Define the cube using the updated colors c = Cube(colors_cube) # Solve and retain moves initial_state = c.export_state() s = Solver(c) s.solve() solve_moves = c.recorded_moves # Display the solution sg = SolutionGallery(initial_state, solve_moves) plt.show()
def _set_data(self): # assign follower value num_of_follower = 0 if self.main_table.follower is None else len( self.main_table.follower) for i in range(3): for f in range(num_of_follower): header_name = attach_column_type[i] person_name = self.main_table.follower[f].name self.container[attach_column_type[i]].container[f].set_value( self._get_ref_value(header_name, person_name)) # set total formula total_coordinate = coordinate_transfer(self.origin[0] + 1, self.origin[1] + 1 + i) + ':' + \ coordinate_transfer(self.origin[0] + 1 + num_of_follower - 1, self.origin[1] + 1 + i) total_formula = "=SUM(" + total_coordinate + ")" self.container[attach_column_type[i]].container[-1].set_formula( total_formula) # assign if table has owner if self.main_table.owner is not None: self.container[attach_column_type[i]].container.append( Cube(bg_color=bg_color[4])) # add total and owner for Target Volume KL # assign total formula total_coordinate = coordinate_transfer(self.origin[0] + 1, self.origin[1] + 4) + ':' + \ coordinate_transfer(self.origin[0] + num_of_follower, self.origin[1] + 4) total_formula = "=SUM(" + total_coordinate + ")" self.container[attach_column_type[3]].container[-1].set_formula( total_formula) # assign if table has owner if self.main_table.owner is not None: self.container[attach_column_type[3]].container.append( Cube(bg_color=bg_color[3]))
def readCube(self): cube = Cube() for i in range(6): cube.face[i] = self._readFace(i) #cube.face[0] = self._readFace(0) return cube
def constructBins(self): '''Populate the transmission spectrum bins with light curves.''' self.speak("constructing the bins of {0}".format(self)) # what files exist? possibleTLCs = glob.glob(self.rawlightcurvedirectory + '*.lightcurve') self.speak('there are {0} .lightcurve files in {1}'.format( len(possibleTLCs), self.rawlightcurvedirectory)) # do we have to make the light curve files from the spectroscopic cube? if len(possibleTLCs) == 0: self.speak("creating .lightcurve(s) from the spectroscopic cube") # initialize a cube object for this observation cube = Cube(self.obs) # bin and save the light curves for this binsize cube.makeLCs(binsize=self.binsize) # return the list of light curve filenames now possibleTLCs = glob.glob(self.rawlightcurvedirectory + '*.lightcurve') # make sure at least one TLC exists assert (len(possibleTLCs) > 0) # pull out the ????to???? strings from the .lightcurve filenames chunks = [] for file in possibleTLCs: chunks.append( (file.split('/')[-1].split('.lightcurve')[0]).split('_')[-1]) # populate bins (and their central wavelengths) bins = [] wavelengths = [] for trimmed in chunks: # figure out the boundaries of this bin left = np.int(trimmed.split('to')[0]) right = np.int(trimmed.split('to')[-1]) # create a wavelength bin (but don't load its lightcurve yet) bins.append(WavelengthBin(self, left=left, right=right)) wavelengths.append(bins[-1].wavelength) # assign the bins to this spectrum, sorted by wavelength self.bins = np.array(bins)[np.argsort(wavelengths)] self.wavelengths = np.array(wavelengths)[np.argsort(wavelengths)] # loop over the bins, and load the light curve for each self.loadLCs() # read the first bin (necessary for setting up initial conditions for fits) self.speak( "spectrum contains {0} bins covering {1} to {2}{3} at {4}{3} resolution" .format(len(self.bins), self.bins[0].left / self.unit, self.bins[-1].right / self.unit, self.unitstring, self.binsize / self.unit))
def __init__(self, surface): """ Initialization method for the snake :param surface: Surface for cubes to be drawn on """ self.surface = surface self.head = Cube(self.surface, NEON_YELLOW, 10, 10, 28) self.body = [self.head] self.d_vector = (0, 0) # direction vector self.impedance = IMPEDANCE # Impedance before moving the object
def _sprites(self): sprites = pygame.sprite.Group() if (self.player.alive): color = (255, 255, 0) else: color = (255, 0, 0) for position in self.player.body: cube = Cube(position, color) sprites.add(cube) sprites.add(Cube(self.snack, (0, 255, 0))) return sprites
def _set_style(self): if self.col_type == column_type[1] and self.col_role == role[ 1] and self.formula_type is None: return Cube(bg_color[3]) elif self.col_type == column_type[1] and self.col_role == role[ 2] and self.formula_type is None: return Cube(bg_color[4]) elif self.col_type == column_type[2] and self.formula_type is None: return Cube(bg_color[2]) elif self.formula_type is not None: return Cube(bg_color[1]) else: return Cube(bg_color[4])
def addCube(self): tail = self.body[-1] dx, dy = tail.dirnx, tail.dirny if dx == 1 and dy == 0: self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]))) elif dx == -1 and dy == 0: self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]))) elif dx == 0 and dy == 1: self.body.append(Cube((tail.pos[0], tail.pos[1] - 1))) elif dx == 0 and dy == -1: self.body.append(Cube((tail.pos[0], tail.pos[1] + 1))) self.body[-1].dirnx = dx self.body[-1].dirny = dy
def addCube(self): tail = self.body[-1] dx, dy = tail.xDir, tail.yDir if dx == 1 and dy == 0: self.body.append(Cube((tail.pos[0] - 1, tail.pos[1]))) if dx == -1 and dy == 0: self.body.append(Cube((tail.pos[0] + 1, tail.pos[1]))) if dx == 0 and dy == 1: self.body.append(Cube((tail.pos[0], tail.pos[1] - 1))) if dx == 1 and dy == -1: self.body.append(Cube((tail.pos[0], tail.pos[1] + 1))) self.body[-1].xDir = dx self.body[-1].yDir = dy
def __init__(self): load_prc_file_data("", "textures-power-2 none") load_prc_file_data("", "win-size 1600 900") # load_prc_file_data("", "fullscreen #t") load_prc_file_data("", "window-title cuboid") load_prc_file_data("", "icon-filename res/icon.ico") # I found openal works better for me load_prc_file_data("", "audio-library-name p3openal_audio") # ------ Begin of render pipeline code ------ # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes pipeline_path = "../../" # Just a special case for my development setup, so I don't accidentally # commit a wrong path. You can remove this in your own programs. if not os.path.isfile(os.path.join(pipeline_path, "setup.py")): pipeline_path = "../../RenderPipeline/" sys.path.insert(0, pipeline_path) # Use the utility script to import the render pipeline classes from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.mount_mgr.mount() self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml") self.render_pipeline.settings["pipeline.display_debugger"] = False self.render_pipeline.set_empty_loading_screen() self.render_pipeline.create(self) # [Optional] use the default skybox, you can use your own skybox as well # self.render_pipeline.create_default_skybox() # ------ End of render pipeline code, thats it! ------ # Set time of day self.render_pipeline.daytime_mgr.time = 0.812 self.menu = Menu(self) self.level = Level(self) self.cube = Cube(self.level) self.camControl = CamControl(self.cube) self.gui = GUI(self) self.menu.showMenu() base.accept("i", self.camControl.zoomIn) base.accept("o", self.camControl.zoomOut)
def _render_table_header(self): col_num = sheet_type[self.table_type]['header']['a_column'] self.main_table.write_cube_to_book( self.origin[0], self.origin[1], Cube(value='Name', style=Style(bg_color[4], font=font_style[2], al=alignment[1]))) for i in range(1, col_num): self.main_table.write_cube_to_book( self.origin[0], self.origin[1] + i, Cube(value=attach_column_type[i - 1], style=Style(bg_color[4], font=font_style[2], al=alignment[1])))
def _get_last_row(self): if self.last_row == column_last_row[1]: return Cube(bg_color[4]) elif self.last_row == column_last_row[2]: column_sum_style = Style(bg_color=bg_color[4], border=side_style[3]) return Cube(bg_color[4], value='N/A', style=column_sum_style) elif self.last_row == column_last_row[3]: column_sum_style = Style(bg_color=bg_color[1], border=side_style[3]) return Cube(bg_color[1], formula=formula_type[1], style=column_sum_style) else: pass
def addCube(self): tail = self.body[-1] if tail.moving_right(): newTail = Cube((tail.position[0]-1, tail.position[1]), self.color) elif tail.moving_left(): newTail = Cube((tail.position[0]+1, tail.position[1]), self.color) elif tail.moving_down(): newTail = Cube((tail.position[0], tail.position[1]-1), self.color) elif tail.moving_up(): newTail = Cube((tail.position[0], tail.position[1]+1), self.color) newTail.dirnx = tail.dirnx newTail.dirny = tail.dirny self.body.append(newTail)
def innit_snack(self, is_random=True): ''' Re-innitialize the snack to a new position ''' positions = self.snake.body while True: if is_random: x = random.randrange(1, self.rows-1) y = random.randrange(1, self.rows-1) if len(list(filter(lambda z: z.pos == (x, y), positions))) > 0: continue else: break else: return Cube((15,15), cube_type='snack') return Cube((x, y), cube_type='snack')
def reset(self, pos): self.head = Cube(pos) self.body = [] self.body.append(self.head) self.turns = {} self.dirnx = 0 self.dirny = 1
def __init__(self, pos, color, rows): self.color = color self.head = Cube(pos) self.body.append(self.head) self.dirX = 1 self.dirY = 0 self.rows = rows
def _cal_Target_Proceed(self): main_table_body = self.main_table.table_body num_of_follower = 0 if self.main_table.follower is None else len( self.main_table.follower) num_of_row = len( self.main_table.follower[0].target[target_mapper[0]].container) for i in range(num_of_follower): # get base volume coordinate base_coordinate = coordinate_transfer(self.origin[0] + 1 + i, self.origin[1] + 4) first_column = coordinate_transfer(main_table_body[0] + 2, main_table_body[1] + 3 + i * 6 + 4) + \ ':' + coordinate_transfer(main_table_body[0] + 2 + num_of_row - 1, main_table_body[1] + 3 + i * 6 + 4) second_column = coordinate_transfer(main_table_body[0] + 2, main_table_body[1] + 3 + i * 6 + 5) + \ ':' + coordinate_transfer(main_table_body[0] + 2 + num_of_row - 1, main_table_body[1] + 3 + i * 6 + 5) formula = '=' + base_coordinate + '*' + 'SUMPRODUCT(' + first_column + ',' + second_column + ')' self.container[attach_column_type[5]].container[i].set_formula( formula) # assign total formula total_coordinate = coordinate_transfer(self.origin[0] + 1, self.origin[1] + 6) + ':' + \ coordinate_transfer(self.origin[0] + num_of_follower, self.origin[1] + 6) total_formula = "=SUM(" + total_coordinate + ")" self.container[attach_column_type[5]].container[-1].set_formula( total_formula) # assign if table has owner if self.main_table.owner is not None: self.container[attach_column_type[5]].container.append( Cube(bg_color=bg_color[3]))
def cube(self): print 'Type in the variable you already know.' try: self.a = float(raw_input('a = ')) except (ValueError): self.a = 0 try: self.V = float(raw_input('V = ')) except (ValueError): self.V = 0 try: self.O = float(raw_input('O = ')) except (ValueError): self.O = 0 variables = {} if self.a != 0: variables['a'] = self.a if self.V != 0: variables['V'] = self.V if self.O != 0: variables['O'] = self.O return Cube(variables)
def main(): pygame.init() Display = (800, 600) pygame.display.set_mode(Display, DOUBLEBUF | OPENGL) glEnable(GL_DEPTH_TEST) obj = Cube() #glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ) x, y = 0, 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(x) rot_y = pyrr.Matrix44.from_y_rotation(y) transformLoc = glGetUniformLocation(obj.shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) DrawTriangle() pygame.display.flip() clock.tick(FPS) x += 0.05 y += 0.05
def extend(self): """ Method, which extends snake by 1 cube :return: """ self.body.insert(1, Cube(self.surface, NEON_YELLOW, self.head.x / 2, self.head.y / 2, 28)) self.head.move(*self.d_vector)
def f2(): steps = read_input('input.txt') steps = [(type, Cube(min_x, max_x, min_y, max_y, min_z, max_z)) for (type, (min_x, max_x, min_y, max_y, min_z, max_z)) in steps] cubes = [] for (type, cube) in steps: tmp_cubes = [] # switch off all cubes in cube with substraction for c in cubes: tmp_cubes.extend(c.substract(cube)) # if the step is to switch on then switch on by adding cube to the list if type == 1: tmp_cubes.append(cube) cubes = tmp_cubes count = 0 for cube in cubes: count += cube.get_volume() print(len(cubes)) print('[f2]: Result = %d' % (count)) return
def animateNotes(): curFrame = 50 tempo = 2.227 song = getDataFromFile('Users/cmgeorge/Documents/crush.txt') normalizer = 4.0 colorScaler = 255 / (max(song) / 1.0) blocks = [] ogColor = rgb(255, 255, 255) for i in range(8): newC = Cube(i*2, 0, 0) blocks.append(newC) maxNum = max(song) for i in range(len(song)): curBlock = blocks[i%8] frameDensity = song[i] newFill = rgb(255 - frameDensity*colorScaler, 255 - frameDensity*colorScaler, 255) OldRange = (OldMax - OldMin) NewRange = (NewMax - NewMin) NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin # Change color and deformer curBlock.fill = newFill curBlock.squashDeformer = squashDeformer(lowBound=-10, highBound=1, factor=10, expand=1, maxExpandPos=.01) curBlock.setKeyFrame(curFrame) # Change color and deformer to og set curBlock.fill = ogColor curBlock.squashDeformer = squashDeformer(lowBound=-10, highBound=1, factor=-10, expand=1, maxExpandPos=.01) curBlock.setKeyFrame(curFrame + 16) curFrame += tempo if i == 100: break
def testConsecutiveMoves(): cube = Cube(jManager.jsonReading("../json/check/x3cube.json")) state = State(cube) print(state.md5) letters = ["B", "b", "D", "d", "L", "l"] moves = [] for element in letters: for number in range(cube.size): moves.append(element + str(number)) while True: key = 0 print("\nOption's movements: ") print(",".join([item for item in moves])) key = input("Selection:") try: method = getattr(cube, key[0]) method(int(key[1])) state = State(cube) print(state.md5) except: print("ERROR. Not valid movement") jManager.jsonWriting('/testing', state.current) pprint(state.current.faces) print("Results have been saved in testing.json") time.sleep(1)
def animateNotes(): depthMap = getDataFromFile( '/Volumes/Users/cmgeorge/documents/depthData.txt') imageData = getDataFromFile('/Volumes/Users/cmgeorge/documents/garage.txt') imageRows = len(imageData) imageCols = len(imageData[0]) depthRows = len(depthMap) depthCols = len(depthMap[0]) rowScaling = depthRows / float(imageRows) colScaling = depthCols / float(imageCols) top = imageRows * .25 for r in range(imageRows): for c in range(imageCols): pix = imageData[r][c] col = rgb(pix[0], pix[1], pix[2]) depthRow = int(math.floor(r * rowScaling)) depthCol = int(math.floor(c * colScaling)) z = float(depthMap[depthRow][depthCol]) Cube(c * .25, top - (r * .25), z, width=.25, height=.25, depth=.25, fill=col)
def __init__(self, width, height): self.width = width self.height = height self.eye_x = self.eye_y = self.eye_z = 0 self.radius = 100 self.phi = 0.0 self.theta = 90.0 self.up_x = 0 self.up_y = 1 self.up_z = 0 self.scale = 1 self.surface = Surface(lambda x, y: 50 * (sin(x * pi / 180) + cos(y * pi / 180))) self.light = Light() self.cube = Cube(10) self.sphere = Sphere(20) self.enable_light_source = True
def game_loop(self): clock = pygame.time.Clock() font = pygame.font.Font('freesansbold.ttf', 32) food = Cube(self.random_food(self.snake), color=(0, 255, 0)) while self.is_running: pygame.time.delay(50) clock.tick(self.clocktick) self.snake.move() if self.check_food(food): food = Cube(self.random_food(self.snake), color=(0, 255, 0)) if self.check_collision(): self.end_menu(self.score) break self.draw_window(self.win, self.snake, food) self.display_score(font) self.display_speed(font) pygame.display.update()
def __init__(self): load_prc_file_data("", "textures-power-2 none") load_prc_file_data("", "win-size 1600 900") # load_prc_file_data("", "fullscreen #t") load_prc_file_data("", "window-title cuboid") load_prc_file_data("", "icon-filename res/icon.ico") # I found openal works better for me load_prc_file_data("", "audio-library-name p3openal_audio") # ------ Begin of render pipeline code ------ # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes pipeline_path = "../../" # Just a special case for my development setup, so I don't accidentally # commit a wrong path. You can remove this in your own programs. if not os.path.isfile(os.path.join(pipeline_path, "setup.py")): pipeline_path = "../../RenderPipeline/" sys.path.insert(0, pipeline_path) # Use the utility script to import the render pipeline classes from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.mount_mgr.mount() self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml") self.render_pipeline.settings["pipeline.display_debugger"] = False self.render_pipeline.set_empty_loading_screen() self.render_pipeline.create(self) # [Optional] use the default skybox, you can use your own skybox as well # self.render_pipeline.create_default_skybox() # ------ End of render pipeline code, thats it! ------ # Set time of day self.render_pipeline.daytime_mgr.time = 0.812 self.menu = Menu(self) self.level = Level(self) self.cube = Cube(self.level) self.camControl = CamControl(self.cube) self.gui = GUI(self) self.menu.showMenu() base.accept("i",self.camControl.zoomIn) base.accept("o",self.camControl.zoomOut)
:Args: q {int} max {int} """ return int((1 - q**(max+1)) / (1 - q) - 1) if __name__ == '__main__': args = readArgs() maximum = int(args['--max']) if '--max' in args else MAX_LENGTH shortcutsFile = args['--output-file'] if '--output-file' in args else SHORTCUTS_FILE ratio = float(args['--ratio']) if '--ratio' in args else RATIO cube = Cube() #un cube résolu with mp.Manager() as manager: """ states Stocke la liste des état, et le plus court jeu de mouvements qui mènent à l'état { <state> : <list de mouvements>, YYYY......WWWW: ('U R ... ', <longueur mouvement>) .... } """
def main(screen): import ThreeD.Graphics2D as g2d # Fix later from ThreeD.Canvas3D import Canvas3D try: curses.curs_set(0) except: pass curses.start_color() bkgd = g2d.white screen.bkgd(' ', bkgd) cube = Cube() cube.rotate(RotationMatrix.RotationMatrix().setRotation(1, -45)) cube.rotate(RotationMatrix.RotationMatrix().setRotation(0, 37)) canvas = Canvas3D() canvas.add_polys(cube.polygons()) canvas.offset_z += 8 canvas.scale += 7 screen.refresh() screen.timeout(0) read_thread = MyThread() read_thread.start() while 1: ch = screen.getch() MOVE_AWAY = '<' MOVE_CLOSER = '>' ZOOM_OUT = ',' ZOOM_IN = '.' RESET_VIEW = '1' FLIP_COLORS = '2' QUIT = '`' if ch == ord(QUIT): break elif ch == curses.KEY_LEFT: cube.rotate(RotationMatrix.RotationMatrix().setRotation(1, -30./10)) elif ch == curses.KEY_RIGHT: cube.rotate(RotationMatrix.RotationMatrix().setRotation(1, 30./10)) elif ch == curses.KEY_UP: cube.rotate(RotationMatrix.RotationMatrix().setRotation(0, -30./10)) elif ch == curses.KEY_DOWN: cube.rotate(RotationMatrix.RotationMatrix().setRotation(0, 30./10)) elif ch == ord(RESET_VIEW): cube.rotate(None) cube.rotate(RotationMatrix.RotationMatrix().setRotation(1, -45)) cube.rotate(RotationMatrix.RotationMatrix().setRotation(0, 37)) elif ch == ord(MOVE_AWAY): canvas.offset_z += .5 elif ch == ord(MOVE_CLOSER): canvas.offset_z -= .5 elif ch == ord(ZOOM_IN): canvas.scale += .1 elif ch == ord(ZOOM_OUT): canvas.scale -= .1 elif ch == ord(FLIP_COLORS): bkgd = g2d.black if bkgd == g2d.white else g2d.white screen.bkgd(' ', bkgd) elif 0 < ch < 256: cube.char_pressed(chr(ch)) screen.erase() cube.tick() canvas.draw(screen) screen.addstr(15, 15, "zoom in " + ZOOM_IN) screen.addstr(16, 15, "zoom out " + ZOOM_OUT) screen.addstr(17, 15, "move away " + MOVE_AWAY) screen.addstr(18, 15, "move closer " + MOVE_CLOSER) screen.addstr(19, 15, "reset view " + RESET_VIEW) screen.addstr(20, 15, "flip colors " + FLIP_COLORS) screen.addstr(21, 15, "quit " + QUIT) screen.addstr(23, 15, "is solved? " + str(cube.is_solved())) if len(read_thread.turns) != 0: cube.do_turn(read_thread.turns.popleft()) read_thread.running = False
# Grab the cube implementation from the Cube.py file from Cube import Cube # Variables data = [] instruction = [] inputFile = "../input/input_9.txt" # Open up the input file and read in the cube values with open(inputFile) as textFile: for line in textFile: for face in line.split(): # Add the values to the cube data data.append(face) # Create a cube object from the input data cube = Cube(data, instruction) # Move on to solve and print the cube ... if the input was valid if cube.check_inputs(): # Input was determined to be valid if cube.solve_cube(): cube.print_val() cube.print_turns() else: print("Error: correct input, but unable to solve.") else: # Input was determined to be invalid print("Input was determined to be invalid")
def loop4(arg): return partial(loopn, 4, arg) def loop5(arg): return partial(loopn, 5, arg) def loop6(arg): return partial(loopn, 6, arg) #def if_then_else(condition, out1, out2): # out1() if condition() else out2() # #def if_0_red_gt4(testcube, out1, out2): # return partial(if_then_else, sum([testcube.self.faces[0][y].tolist().count('r') for y in range(0,4)]) > 4, out1, out2) testcube = Cube() testcube.setFitFunc(sys.argv[4]) pset = gp.PrimitiveSet("MAIN", 0) pset.addPrimitive(prog2, 2) pset.addPrimitive(prog3, 3) pset.addPrimitive(prog4, 4) pset.addPrimitive(prog5, 5) pset.addPrimitive(prog6, 6) pset.addPrimitive(prog7, 7) pset.addPrimitive(prog8, 8) pset.addPrimitive(prog9, 9) pset.addPrimitive(prog10, 10) pset.addPrimitive(prog11, 11) pset.addPrimitive(prog12, 12) pset.addPrimitive(loop2, 1)
def lecture_cube(str_cube): ''' lecture_cube Fonction qui permet de lire l'entrée de l'utilisateur. Prend une chaîne de 54 caractères et renvoie un objet cube initialisé, avec les nombres se rapportant aux couleurs. :Args: str {String} chaîne de 54 facettes :Returns: {Boolean|String}, {Cube} (error, cube) Un objet cube initialisé avec les numéros correspondant à la chaîne de caractères entrée en paramètre ''' #1. Découpage des faces de la chaîne en entrée c = Cube() try: faces = decomposition_faces(str_cube) #on découpe en faces except ValueError as e: return str(e), None #2. Vérification des faces error = check_faces(faces) #on check que les faces sont ok if error: return error, None #3. Remplir le rubik's cube #Chaque petit cube est codé dans l'objet cube #Ils correspondent à toutes les arêtes/coins en commun des différentes faces #Exemple : FU = Cube reliant les faces Front et Up #Comme nous avons les couleurs et la position de chaque face, #nous pouvons attribuer à tous ces cubes leurs couleurs respectives insertions = [ ('FU', [faces[2][1], faces[0][7]]), ('FRU', [faces[2][2], faces[3][0], faces[0][8]]), ('FR', [faces[2][5], faces[3][3]]), ('FRD', [faces[2][8], faces[3][6], faces[5][2]]), ('FD', [faces[2][7], faces[5][1]]), ('LFD', [faces[1][8], faces[2][6], faces[5][0]]), ('FL', [faces[2][3], faces[1][5]]), ('LFU', [faces[1][2], faces[2][0], faces[0][6]]), ('LU', [faces[1][1], faces[0][3]]), ('LD', [faces[1][7], faces[5][3]]), ('BU', [faces[4][1], faces[0][1]]), ('RBU', [faces[3][2], faces[4][0], faces[0][2]]), ('BR', [faces[4][3], faces[3][5]]), ('RBD', [faces[3][8], faces[4][6], faces[5][8]]), ('BD', [faces[4][7], faces[5][7]]), ('BLD', [faces[4][8], faces[1][6], faces[5][6]]), ('BL', [faces[4][5], faces[1][3]]), ('BLU', [faces[4][2], faces[1][0], faces[0][0]]), ('RD', [faces[3][7], faces[5][5]]), ('RU', [faces[3][1], faces[0][5]]), ] #on insert ces petits cubes tant qu'on ne détecte pas de petit #cube défaillant i = 0 l = len(insertions) while i < l: try: c.edit_cube(insertions[i][0], insertions[i][1]) except ValueError as e: return "Petits cubes invalides", None i += 1 #4. Mettre le cube dans la bonne position #(face blanche en bas, bleue en front) #les couleurs de chaque faces couleurs_faces = [face[4] for face in faces] v = (couleurs_faces.index(0), couleurs_faces.index(1)) if v[0] == 0: #si la face blanche est sur U # alors la face bleue est sur L, F, R ou B c.rot_UF() c.rot_UF() if not v[1] == 4: #on place la face bleue, sauf si elle est déjà sur F for _ in range(v[1]): c.rot_FR() elif v[0] == 5: #la face blanche est placée #on place la face bleue, sauf si elle est déjà sur F if v[1] == 1: c.rot_FR() #on tourne for j in [3, 4]: if v[1] == j or v[1] == j: for x in range(6 - j): c.rot_FR() #on tourne else: #la face blanche est sur L, F, R ou B #on place la face blanche sur F if v[0] == 1: c.rot_FR() #on tourne else: for j in [3, 4]: if v[0] == j or v[0] == j: for x in range(6 - j): c.rot_FR() #on tourne c.rot_UF() #on descend la face blanche sur D #on place la face bleue #si elle était sur U, elle est à la bonne place maintenant if v[1] == 5: #si elle était sur D, elle est sur B maintenant c.rot_FR() c.rot_FR() #on s'intéresse aux cas pù la face bleue est sur L ou R #cas où on est sur R maintenant elif v[1] == v[0] + 1 or (v[0], v[1]) == (4, 1): for x in range(3): c.rot_FR() #cas où on est sur L maintenant elif v[1] == v[0] - 1 or (v[0], v[1]) == (1, 4): c.rot_FR() return (False, c)
print(" " * 4, "------------------------", " " * 12, "-----------") # Open up the input file and read in the cube values for file in inputFiles: numTest = numTest + 1 data = [] instruction = [] print(" " * 4, '{:25s}'.format(file), " " * 15, end="") with open(file) as textFile: for line in textFile: for face in line.split(): # Add the values to the cube data data.append(face) # Create a cube object from the input data cube = Cube(data, instruction) # Move on to solve and print the cube ... if the input was valid if cube.check_inputs(): # Input was determined to be valid returnValue = cube.solve_cube() if returnValue == 1: print("PASS") numPass = numPass + 1 elif returnValue == 2: print("FAIL - can't solve white side") elif returnValue == 3: print("FAIL - can't solve middle layer")
class GameControl(ShowBase): """ controlling the game itself, menu, editors level selection... it's sorta a fake-fsm. did i mention i dont like fsm's and prefer totaly whicked logic instead? """ def __init__(self): load_prc_file_data("", "textures-power-2 none") load_prc_file_data("", "win-size 1600 900") # load_prc_file_data("", "fullscreen #t") load_prc_file_data("", "window-title cuboid") load_prc_file_data("", "icon-filename res/icon.ico") # I found openal works better for me load_prc_file_data("", "audio-library-name p3openal_audio") # ------ Begin of render pipeline code ------ # Insert the pipeline path to the system path, this is required to be # able to import the pipeline classes pipeline_path = "../../" # Just a special case for my development setup, so I don't accidentally # commit a wrong path. You can remove this in your own programs. if not os.path.isfile(os.path.join(pipeline_path, "setup.py")): pipeline_path = "../../RenderPipeline/" sys.path.insert(0, pipeline_path) # Use the utility script to import the render pipeline classes from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.mount_mgr.mount() self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml") self.render_pipeline.settings["pipeline.display_debugger"] = False self.render_pipeline.set_empty_loading_screen() self.render_pipeline.create(self) # [Optional] use the default skybox, you can use your own skybox as well # self.render_pipeline.create_default_skybox() # ------ End of render pipeline code, thats it! ------ # Set time of day self.render_pipeline.daytime_mgr.time = 0.812 self.menu = Menu(self) self.level = Level(self) self.cube = Cube(self.level) self.camControl = CamControl(self.cube) self.gui = GUI(self) self.menu.showMenu() base.accept("i",self.camControl.zoomIn) base.accept("o",self.camControl.zoomOut) def startGame(self,level=0): #debug purpose only: to directly play a certian lvl number from sys import argv if len(argv) >1: level = int(argv[1]) self.menu.hideMenu() self.level.loadLevel(level) self.cube.resetCube() self.cube.resetStats() self.cube.enableGameControl() base.accept("escape", self.pauseGame) def pauseGame(self): self.cube.disableGameControl() self.menu.showMenu() self.menu.showResume() #base.accept("escape", self.resumeGame ) def resumeGame(self): self.menu.hideMenu() self.menu.hideResume() self.cube.enableGameControl() base.accept("escape", self.pauseGame) def levelEnd(self): self.cube.disableGameControl() self.menu.showMenu()