def plot_grid_2_mc(): test_grids = TEST_GRIDS all_test_list = [(key, grid) for key, grid in test_grids.items()] sorted(all_test_list, key=lambda x: x[0]) agent = Agent() iters = ITERS total_normal_grid_score, total_grid1_score, total_grid2_score, total_grid3_score, total_grid4_score = [],[],[],[],[] repeats = REPEATS # for n in iters: # print("Running iteration {n}".format(n=n)) grid2_score, grid4_score = [], [] for ind, grid_init in all_test_list: normalized_score = 0 for j in range(repeats): grid_num = int(ind) #ind initially is a string. if (grid_num < 200) or (grid_num > 300): continue best_reward = grid_init['best_reward'] testgrid = Grid(5, random=False, init_pos=grid_init) if grid_num in {204, 208}: Q, policy = agent.mc_first_visit_control(testgrid.copy(), iters=500) _, _, mc_reward = agent.run_final_policy(testgrid.copy(), Q, display=True) else: continue normalized_score += mc_reward - best_reward if normalized_score != 0: print( "Grid num {0} did not achieve best score".format(grid_num))
def set_ui(self): """ Sets the elements in the UI. """ f = tk.Frame(self) f.pack(fill="both", expand=True) self.b_start = ttk.Button(f, text="Démarrer", command=self.btn_run_pause) self.b_start.pack(side="left", padx=5, pady=5) self.b_reset = ttk.Button(f, text="Recommencer", command=self.btn_reset) self.b_reset.pack(side="left", padx=5, pady=5) self.s_ms = tk.Scale(f, from_=10, to=1000, resolution=10, variable=self.var_ms, orient="horizontal") self.s_ms.pack(side="left", padx=5, pady=5) # self.l_ms = ttk.Label() self.canvas = tk.Canvas() self.canvas.pack() self.field = Grid(self.canvas)
def grid_creation(): from src.grid import Grid grid = Grid() yield grid print('\n') print(f'sum check: {grid.sum_check()}') grid.show_grid()
def __init__(self, particles_positions, params, wall): self.wall = wall self.params = params self.particles_positions = particles_positions self.handlers = [] self.grid = Grid(self.wall, self.params.rv)
def _init_widgets(self): """Initialize widgets""" self.widgets = Widgets(self) self.entry_line = Entryline(self) self.grid = Grid(self) self.macro_panel = MacroPanel(self, self.grid.model.code_array) self.main_splitter = QSplitter(Qt.Vertical, self) self.setCentralWidget(self.main_splitter) self.main_splitter.addWidget(self.entry_line) self.main_splitter.addWidget(self.grid) self.main_splitter.addWidget(self.grid.table_choice) self.main_splitter.setSizes( [self.entry_line.minimumHeight(), 9999, 20]) self.macro_dock = QDockWidget("Macros", self) self.macro_dock.setObjectName("Macro Panel") self.macro_dock.setWidget(self.macro_panel) self.addDockWidget(Qt.RightDockWidgetArea, self.macro_dock) self.macro_dock.installEventFilter(self) self.gui_update.connect(self.on_gui_update) self.refresh_timer.timeout.connect(self.on_refresh_timer)
def setUp(self): """Defines a 4x3 grid with the following layout: (0=walkable, X=not walkable, P=position, D=destination) 0 0 0 D 0 P X 0 X X X X """ self.grid = Grid(4, 3) pwalkdirs = WalkDirs(up_left=True, up=True, up_right=False, left=True, right=False, down_left=False, down=False, down_right=False) self.grid.set(1, 1, pwalkdirs) walkdirs_0_0 = WalkDirs(False, False, False, False, True, False, True, True) self.grid.set(0, 0, walkdirs_0_0) walkdirs_0_1 = WalkDirs(False, True, True, False, True, False, False, False) self.grid.set(0, 1, walkdirs_0_1) walkdirs_1_0 = WalkDirs(False, False, False, True, True, True, True, False) self.grid.set(1, 0, walkdirs_1_0) walkdirs_2_0 = WalkDirs(False, False, False, True, True, False, False, False) self.grid.set(2, 0, walkdirs_2_0) walkdirs_3_0 = WalkDirs(False, False, False, True, False, False, True, False) self.grid.set(3, 0, walkdirs_3_0) self.position = (1, 1)
def set_ui(self): """ Sets the structure of the ui """ self.canvas = tk.Canvas(self) self.canvas.pack() self.field = Grid(self.canvas)
def set_ui(self): """ Sets the elements in the UI. """ self.canvas = tk.Canvas(self) self.canvas.pack() self.entry = ttk.Entry(self.canvas, justify="center", font=("Calibri", 12)) self.grid = Grid(self.canvas)
def do(self, grid: Grid, robot: Robot): if robot.is_lost: raise Exception('Dead') orientation = robot.orientation current_pos = robot.position # Ignore instruction if known bad place. if MoveForward.__to_dropoff(grid, current_pos, orientation): return next_position = orientation.next_forward_position(current_pos) if grid.is_within_grid(next_position): robot.set_position(next_position) else: robot.is_now_lost() label = Label(orientation) grid.add_scent(current_pos, label)
def __init__(self): super().__init__() self.game_over = False self.grid = Grid(num_tiles=9) self.add(self.grid) self.objects = {} self.create_game_over_text((Window.width, Window.height)) # Add the character to the game self.character = Character(self) self.add(self.character)
def graph_dual_model_performance(): test_grids = TEST_GRIDS all_test_list = [(key, grid) for key, grid in test_grids.items()] sorted(all_test_list, key=lambda x: x[0]) agent = Agent() iters = ITERS total_normal_grid_score, total_grid1_score, total_grid2_score, total_grid3_score, total_grid4_score = [],[],[],[],[] repeats = REPEATS for n in iters: print("Running iteration {n}".format(n=n)) normal_grid_score, grid1_score, grid2_score, grid3_score, grid4_score = [],[],[],[],[] for ind, grid_init in all_test_list: normalized_score = 0 for j in range(repeats): grid_num = int(ind) #ind initially is a string. best_reward = grid_init['best_reward'] testgrid = Grid(5, random=False, init_pos=grid_init) Q, policy = agent.mc_first_visit_control(testgrid.copy(), iters=n, nn_init=True) _, _, dual_model_reward = agent.run_final_policy( testgrid.copy(), Q, nn_init=True, display=False) normalized_score += dual_model_reward - best_reward if grid_num < 100: normal_grid_score.append(normalized_score / repeats) elif grid_num < 200: #grid type 1 grid1_score.append(normalized_score / repeats) elif grid_num < 300: #grid type 2 grid2_score.append(normalized_score / repeats) elif grid_num < 400: #grid type 3 grid3_score.append(normalized_score / repeats) else: #grid type 4 grid4_score.append(normalized_score / repeats) total_normal_grid_score.append(np.mean(normal_grid_score)) total_grid1_score.append(np.mean(grid1_score)) total_grid2_score.append(np.mean(grid2_score)) total_grid3_score.append(np.mean(grid3_score)) total_grid4_score.append(np.mean(grid4_score)) # plt.plot(iters, total_normal_grid_score, label="normal grids", color="red") plt.plot(iters, total_grid1_score, label='push dilemma', color="blue") plt.plot(iters, total_grid2_score, label='switch dilemma', color="green") plt.plot(iters, total_grid3_score, label='switch save', color="orange") plt.plot(iters, total_grid4_score, label='push get', color="brown") plt.legend() plt.xlabel("Number of MC Iterations") plt.ylabel("Normalized Score") plt.title("Dual model performance on all test grids") plt.show()
def test_grid(self): rover1 = Rover("Rover-001", "N", 0, 0) grid1 = Grid([[0, 0], [0, 0], ["Rover2", 0]]) grid2 = Grid([[0, "Rock"], [0, 0], ["Rover2", 0]]) # TODO ejecucion por Grid2 -> No se mueve a [0, 1] Rover.commands(rover1, grid2, "rf") self.assertEqual(rover1.y, 0) self.assertEqual(rover1.x, 0) # TODO Ejecucion por Grid 1 -> Si se mueve a [0, 1] Rover.commands(rover1, grid1, "rf") self.assertEqual(rover1.y, 1) self.assertEqual(rover1.x, 0)
def test_read_instructions_three_robots_oneloss_oneavoidance(self): dir_name = self._create_dir() filepath = f'{dir_name}/allgood' afile = ( f'{filepath}_2', '''5 3\n\n1 1 E\nRFRFRFRF\n\n3 2 N\nFRRFLLFFRRFLL\n\n0 3 W\nLLFFFLFLFL\n''' ) expectations = ( ('::Start[1,1,E] ::TurnRight ::MoveForward ::TurnRight ::MoveForward ::TurnRight ::MoveForward ::TurnRight ::MoveForward', '1 1 E'), ('::Start[3,2,N] ::MoveForward ::TurnRight ::TurnRight ::MoveForward ::TurnLeft ::TurnLeft ::MoveForward ::MoveForward ::TurnRight ::TurnRight ::MoveForward ::TurnLeft ::TurnLeft', '3 3 N LOST'), ('::Start[0,3,W] ::TurnLeft ::TurnLeft ::MoveForward ::MoveForward ::MoveForward ::TurnLeft ::MoveForward ::TurnLeft ::MoveForward ::TurnLeft', '2 3 S'), ) with open(afile[0], 'a') as fl: fl.write(afile[1]) inst_file_processor = InstructionsFile(afile[0]) inst_file_processor.initialise_instructions() grid_extents = inst_file_processor.grid_extents self.assertEqual(grid_extents.coord_x, 5) self.assertEqual(grid_extents.coord_y, 3) grid = Grid(grid_extents) count = 0 for robot_instruction in inst_file_processor.next_instructions(): self.assertEqual(str(robot_instruction), expectations[count][0]) robot = Robot() for inst in robot_instruction.instruction_list: inst.do(grid, robot) if robot.is_lost: break self.assertEqual(str(robot), expectations[count][1]) count += 1 self.assertEqual(count, 3)
def __init__(self): """! @pre None @post GameState is initialized with default values for the beginning of the game """ self.numShipsPerPlayer = 0 self.playerType = 1 # Whether P2 is a human (1) or AI (2-4 for difficulty) self.grid = Grid() self.shipDir = 0 # Direction of the ship currently being placed (index of c.DIRS) self.lenShip = 1 # Length of the ship to place next self.p1Ships = [] self.p2Ships = [] # Number of special shots each player has (gain one every 10 rounds) self.round = 0 self.p1_special_shots = 0 self.p2_special_shots = 0 self.is_P1_turn = False self.is_placing = False self.is_shooting = False self.in_transition = False self.msg = "" # Message to display below game board
def __init__(self, row_sz: int, col_sz: int): self.grid = Grid(row_sz, col_sz) self.policy = Policy(env.ACTIONS, env.ETA, env.GAMMA, env.EPSILON) self.robby = Agent(self.grid, np.random.randint(0, row_sz), np.random.randint(0, col_sz), self.policy) self.epoch = 1 self.rewards_per_episode = []
class Simulator: ORIGIN = Point(0, 0) def __init__(self): self.robot = Robot(Simulator.ORIGIN, WindRose.NORTH_INDEX) self.grid = Grid() def run(self, steps): step = 0 if steps < 0: raise Exception('number of steps must be positive(%d)' % steps) while step < steps: print('Step %d' % step) original_cell = self.robot.position cell = self.grid.add_cell(original_cell) if cell.color == Color.WHITE: self.robot.clockwise_rotate() elif cell.color == Color.BLACK: self.robot.anti_clockwise_rotate() cell.flip() self.robot.move() step = step + 1 def export_grid(self, filename): print('export_grid') print(self.grid.x_range) print(self.grid.y_range) for cell in self.grid.cells: print('cell: %s - color:%s' % (cell, self.grid.cells[cell].color)) x_min = self.grid.x_range[0] - 2 x_max = self.grid.x_range[1] + 2 y_min = self.grid.y_range[0] - 2 y_max = self.grid.y_range[1] + 2 with open(filename, "w") as simulation_file: simulation_file.write('x range: [%d,%d]\n' % (x_min, x_max)) simulation_file.write('y range: [%d,%d]\n' % (y_min, y_max)) simulation_file.write('\n') y = y_max while y >= y_min: simulation_file.write('|') x = x_min while x <= x_max: cell = self.grid.cells.get(Point(x, y)) if cell is None or cell.color == Color.WHITE: simulation_file.write('W|') elif cell.color == Color.BLACK: simulation_file.write('B|') x = x + 1 y = y - 1 simulation_file.write('\n')
def test_moveBackward(self): rover1 = Rover("Rover-001", "N", 5, 0) grid1 = Grid([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0], [0]]) Rover.moveBackward(rover1, grid1) self.assertEqual(rover1.y, 6) grid1.noPrivadoGrid[rover1.y][rover1.x] = 0
def test_error_message(self): rover4 = Rover("Rover-004", "E", 2, 4) grid2 = Grid([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, "rock", 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0], [0]]) result = Rover.moveForward(rover4, grid2) self.assertEqual(result, "There is a rock on y = 2 , x = 5") grid2.noPrivadoGrid[rover4.y][rover4.x] = 0
def test_grid_left(self): rover1 = Rover("Rover-001", "N", 0, 0) grid1 = Grid([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0], [0]]) Rover.commands(rover1, grid1, "lfff") self.assertEqual(rover1.y, 0) self.assertEqual(rover1.x, 0) grid1.noPrivadoGrid[rover1.y][rover1.x] = 0
def test_obstacle(self): rover1 = Rover("Rover-001", "N", 0, 0) grid1 = Grid([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, "rock", 0, 0, 0, 0, 0], [0, 0], [0]]) Rover.commands(rover1, grid1, "bbbbrf") self.assertEqual(rover1.y, 4) self.assertEqual(rover1.x, 0) grid1.noPrivadoGrid[rover1.y][rover1.x] = 0
class ParticleHandlers: def __init__(self, particles_positions, params, wall): self.wall = wall self.params = params self.particles_positions = particles_positions self.handlers = [] self.grid = Grid(self.wall, self.params.rv) def create_handlers(self): for k, position in enumerate(self.particles_positions): self.add_handler( ParticleHandler(k, self.particles_positions, self.wall, self.grid, self.params)) self.create_grid() self.calc_verlet_lists() def add_handler(self, handler): self.handlers.append(handler) def create_grid(self): ctime = time.time() self.grid.clear() ctime = time.time() - ctime asstime = time.time() for handler in self.handlers: idx = handler.get_idx() position = self.particles_positions[idx] self.grid.add_to_grid(idx, position) asstime = time.time() - asstime return ctime, asstime def get_handler(self, idx): return self.handlers[idx] def calc_verlet_lists(self): start_time = time.time() for handler in self.handlers: handler.create_verlet_list() total_time = time.time() - start_time return total_time
def grid_creation(): from src.grid import Grid import copy grid = Grid() copied_grid = copy.deepcopy(grid) for i in range(9, 18): grid.cells[i].remove(9) copied_grid.cells[i].remove(3) grid.cells[12].add(9) copied_grid.cells[16].add(3) for i in range(9, 18): if i != 12: assert grid.cells[i].candidates == 0b011111111 else: assert grid.cells[i].candidates == 0b111111111 yield grid, copied_grid print() grid.show_grid() copied_grid.show_grid()
def randomSolver(nbErreurs, choixExercice): """ Fonction permettant de remplir la matrice "city plan" de façon aléatoire. :param nbErreurs: (int) nombre d'erreurs maximale autorisée :param choixExercice: (int) choisir parmi les "inputs" fournis par Google. 0->a_*, 5->f_* """ nbErreursCourant = 0 print("Random Solver lancé !") print("Création de grille lancée à : " + time.strftime('%H:%M:%S')) print("chargement des projets du fichier " + Const.FILE_NAMES[choixExercice] + ".in ...") inputs = InManager(Const.FILE_NAMES[choixExercice]) maximumDistance = inputs.walkDist # ici on charge dans projectList les projets présents dans le fichier projectList, trueNum = projectListBuilder(inputs) print("fichiers chargés\n\nconstructions des batiments ...") city = Grid(inputs.rows, inputs.columns) while nbErreursCourant < nbErreurs: # Condition d'arrêt : après un certains nombre d'érreurs consecutives # sélection aléatoire de coordonnées et de type de batiment numProjectRand = random.randint(0, len(projectList) - 1) numColsRand = random.randint(0, inputs.columns) numRowsRand = random.randint(0, inputs.rows) if city.isBuildable(projectList[numProjectRand], (numRowsRand, numColsRand)): # Si le projet peut-être placé alors nous le plaçons aux coordonnées définie aléatoirement. city.buildProject(projectList[numProjectRand], (numRowsRand, numColsRand)) else: nbErreursCourant += 1 inputs.close() print("limite de {} erreurs atteinte".format(nbErreursCourant) + " : grille construite") out = OutManager("{} {}".format(Const.FILE_NAMES[choixExercice], time.strftime('%d-%m-%Y %H-%M-%S'))) # city.showNumProject() # Prend beaucoup de ressources. print("nombre de batiments résidentiels : ", len(city.buildedR), " / utilitaires : ", len(city.buildedU), "\n") # on calcule le score et on l'écrit dans un fichier et dans le terminal score = getGridScore(projectList, maximumDistance, city.buildedR, city.buildedU, True) out.writeScore(score) out.writeProjects(getBuildedNums(city.buildedR + city.buildedU, trueNum)) print("score = ", score) # printGrid(city, projectList) # Affichage avec TKinter Grid.show(city) # Affiche la grille dans la console
def rules(self): grid = Grid(10, 10) steps = [ 'Each player get a total of 5 ships of varying lengths', \ ' Carrier: 5', \ ' Battleship: 4', \ ' Cruiser: 3', \ ' Submarine: 3', \ ' Destroyer: 3', \ 'And a grid to place them on, it looks like this:', \ grid.display(), \ 'I will ask you for the direction, x and y start for each of your ships', \ 'Once you have placed your ships the real fun begins', \ 'I will ask you for a set of coordinates that you would like to attack', \ 'if one of your opponent\'s ships is occupying that square, you will score a hit', \ 'Each ship can take as many hits as it is long', \ 'once a ship it reaches that maximum, it sinks', \ 'The first player to sink all of his/her opponents ships is the winner', \ 'Let\'s get started' ] return wrap_in_box('\n'.join(steps), self.width)
def test_create(tp=0): # grid_creation): # from src.pysimplegui import show_on_gui from src.grid import Grid print('\n') for _ in range(20): grid = Grid(np_type=tp, min_gr_size=2, max_gr_size=5) assert grid.create() is True # show_on_gui([*map(str, grid.group)], grid.lines, False) assert grid.sum_check() is True grid.create_problem(0) # sums = grid.sum_symbol if tp == 2 else [0] * 81 # show_on_gui( # [' ' if s == '0' else s for s in grid.answer], # grid.lines, # False, # sums, # ) # show_on_gui( # [' ' if s == '0' else s for s in grid.sequence], # grid.lines, # False, # sums, # ) print(f'Answer: {grid.answer}') print(f'Problem: {grid.problem}') print(f'Lines: {grid.lines}') print(f'Hints: {grid.count_digits()}') for key, value in grid.techniques.items(): print(f'{value*1}: {key}')
def duplicate(city, nbDupliX, nbDupliY, projectList): """ Fonction permettant de dupliquer une grille le nombre de fois demandé :param city: (Grid) grille à dupliquer :param nbDupliX: (int) nombre de duplications en X :param nbDupliY: (int) nombre de duplications en Y :param projectList: (list[Project]) list des projets de l'input :return grid: (Grid) grille finale dupliquée """ grid = Grid(city.grows * nbDupliX, city.gcolumns * nbDupliY) for i in range(nbDupliX): for j in range(nbDupliY): for k in range(len(city.buildedR)): proj = projectList[city.buildedR[k][Const.NUM_PROJ]] newBuildedR = copy.deepcopy(city.buildedR[k]) newBuildedR[Const.COORD_PROJ] = ( newBuildedR[Const.COORD_PROJ][0] + city.grows * i, newBuildedR[Const.COORD_PROJ][1] + city.gcolumns * j) grid.buildProject(proj, newBuildedR[Const.COORD_PROJ]) for k in range(len(city.buildedU)): proj = projectList[city.buildedU[k][Const.NUM_PROJ]] newBuildedU = copy.deepcopy(city.buildedU[k]) newBuildedU[Const.COORD_PROJ] = ( newBuildedU[Const.COORD_PROJ][0] + city.grows * i, newBuildedU[Const.COORD_PROJ][1] + city.gcolumns * j) grid.buildProject(proj, newBuildedU[Const.COORD_PROJ]) return grid
def executeJPSOnCSVInstance(url): instance = InstanceUtilities.readCSVInstance(url) grid = Grid(instance.matrixWidth, instance.matrixHeight, instance.matrix) grid.buildNodes() print('Computing ...') startTime = time.time() method = PathPlanning(grid) use_method = 'w_jps' # 这里可以选择jps 或者 A* 或者w_jps path = method.findPath(instance.startX, instance.startY, instance.endX, instance.endY, use_method) endTime = time.time() - startTime rmRepeatedPoint(path) InstanceUtilities.displayInstanceWithPath(path) curve_show(path) print('Done. ' + use_method + ' Result computed in ' + str(endTime) + ' ms.') print("Expand node number is: " + str(method.expendCount) + '.') print("path length is: " + str(pathLength(path)))
def __init__(self): self.right = False self.left = False self.down = False self.rotate_right = False self.rotate_left = False self.drop = False self.grid = Grid(10, 20, 20) self.shape = Shape(self.grid) self.shape_list = [] for x in range(3): self.shape_list.insert(0, Shape(self.grid))
def __init__(self): """! @pre None @post GameState is initialized with default values for the beginning of the game """ self.grid = Grid() self.shipDir = 0 # Direction of the ship currently being placed (index of c.DIRS) self.lenShip = 1 # Length of the ship to place next self.numShipsPerPlayer = 0 self.playerType = 1 self.p1Ships = [] self.p2Ships = [] self.is_P1_turn = False self.is_placing = False self.is_shooting = False self.msg = "" # Message to display below game board
def __init__(self, id=""): self.id = id # Drawing stuff self.sprite = sf.Sprite(res.ship) self.sprite_offset = sf.Vector2(-71, -40) self.room_offset = sf.Vector2(63, 32) # Offset of room origin self.position = sf.Vector2(0, 0) # Shield renering self.shields_offset = sf.Vector2(-30, -50) self.shields_sprite = sf.Sprite(res.shields) #self.shields_sprite.origin - self.shields_sprite.local_bounds.size/2 # Stats n stuff self.alive = True self.hull_points = 10 # Explosion stuff self.exploding = False # Playing the explosion animation self.explosion_timer = 0 self.hull_pieces = [\ HullPiece(res.ship_piece1, sf.Vector2(205, 60), 10, 20, 0, 360, -30, 30),\ HullPiece(res.ship_piece2, sf.Vector2(70, 108), 20, 40, 160, 200, -40, 40),\ HullPiece(res.ship_piece3, sf.Vector2(130, 127), 40, 60, 220, 260, -60, -20),\ HullPiece(res.ship_piece4, sf.Vector2(17, 0), 30, 50, 20, 70, -30, 30),\ HullPiece(res.ship_piece5, sf.Vector2(0, 61), 40, 80, 110, 160, -30, 30),\ HullPiece(res.ship_piece6, sf.Vector2(72, 0), 20, 50, 330, 350, -30, 30),\ ] # Path grid for pathfinding self.path_grid = Grid(10, 10) # Things on the ship self.rooms = [] self.weapon_slots = [] self.weapon_system = None self.engine_system = EngineSystem() self.shield_system = None