def __init__(self): self.current_vessel = 0 #Creating attack and defend grid. self.defend_grid = grid.Grid() self.attack_grid = grid.Grid() self.root = Tk() #Labels for the GUI, explain the grid. Label(text='Attack', font=myfont).grid(row=0, column=0) Label(text='Defend', font=myfont).grid(row=2, column=0) #Attack frame and buttons being set to buttons and a 10x10 grid. self.attack_frame, self.attack_grid_buttons = self.create_grid( grid.GRID_HEIGHT, grid.GRID_WIDTH, self.attack_button_clicked) self.attack_frame.grid(row=1, column=0) #Same as above, except with the defend grid. self.defend_frame, self.defend_grid_buttons = self.create_grid( grid.GRID_HEIGHT, grid.GRID_WIDTH, self.defend_button_clicked) self.defend_frame.grid(row=3, column=0) #Disables the attack buttons on the attack grid. self.set_grid('disabled', self.attack_grid_buttons) #Updates the buttons on the defend and attack grid. self.update_GUI(self.defend_grid.grid, self.defend_grid_buttons) self.update_GUI(self.attack_grid.grid, self.attack_grid_buttons) self.root.mainloop()
def setUp(self): #linear SAMPLE objects ct = 4 lim_t = 31 lbpar_t = cd.LbFixParams([ct], [lim_t]) shf_t = 5.0 band_t = 40.0 dt = band_t / ct diff = [dt] shf = [shf_t] band = [band_t] ptpar = cd.PtFixParams(diff, shf, band) lb_t = cd.LbGen(lbpar_t) pt_t = cd.PtGen(ptpar) dim_lb = (0, 0) obj_lb = [lb_t] dims_lb = [dim_lb] mst_lb = mst.MdimStruct(obj_lb, dims_lb) dims_pt = [(0, 0)] obj_pt = [pt_t] mst_pt = mst.MdimStruct(obj_pt, dims_pt) genS = gn.Generator(mst_lb, mst_pt) self.gdS = gd.Grid(genS) #BOUNDS diff = [dt] shf = [shf_t - 5.0] band = [band_t] ptpar = cd.PtFixParams(diff, shf, band) pt_t = cd.PtGen(ptpar) dims_pt = [(0, 0)] obj_pt = [pt_t] mst_pt = mst.MdimStruct(obj_pt, dims_pt) genB = gn.Generator(mst_lb, mst_pt) self.gdB = gd.Grid(genB) return
def buildCoarseGrid(self, type, L, n, X0, hf): # buildCoarseGrid constructs an indentical coarse grid on each processor # it then builds a local mesh for each subdomain - including overlap # Identical Coarse Grid is built on each processor self.macroGrid = fem.Grid() self.macroGrid.buildStructuredMesh2D(L, n, X0, 1, 0) # Type: element or node centric # Node centric - Overlapping, each domain support of node (assumming linear macro finite element) allNeighbours, allN2E = self.macroGrid.findNeighbours() self.NN = allNeighbours[self.rank] self.N2E = allN2E[self.rank] self.numNeighbours = len(self.NN) # Find boundary box for local grid bottomLeft = self.macroGrid.coords[self.rank][:] topRight = self.macroGrid.coords[self.rank][:] l1 = np.zeros(self.numNeighbours + 1) l1[0] = np.sum(np.abs(self.macroGrid.coords[self.rank][:])) for i in range(0, self.numNeighbours): l1[i + 1] = np.sum(np.abs(self.macroGrid.coords[self.NN[i]][:])) tmp_id_min = np.argmin(l1) tmp_id_max = np.argmax(l1) if (tmp_id_min == 0): bottomLeft = self.macroGrid.coords[self.rank][:] else: bottomLeft = self.macroGrid.coords[self.NN[tmp_id_min - 1]][:] if (tmp_id_max == 0): topRight = self.macroGrid.coords[self.rank][:] else: topRight = self.macroGrid.coords[self.NN[tmp_id_max - 1]][:] # Build local finite element grid L_local = topRight - bottomLeft nf = [] for i in range(0, self.dim): nf.append(int(np.floor(L_local[i] / hf[i]))) self.fineGrid = fem.Grid() self.fineGrid.buildStructuredMesh2D(L_local, nf, bottomLeft, 1, 0)
def __init__(self, choice: str = "default"): if choice == "easy": self.grid = grid.Grid(8, 11, 10) elif choice == "medium": self.grid = grid.Grid(14, 20, 39) elif choice == "hard": self.grid = grid.Grid(20, 29, 102) elif choice == "insane": self.grid = grid.Grid(26, 38, 194) else: self.grid = grid.Grid(14, 20, 39)
def test_single_cell(self): """Tests removing each individual cell.""" for i in range(81): values = list(TEST_VALUES) p = [None] * 81 p[i] = set([values[i]]) values[i] = None g = grid.Grid(values) self.assertEqual(grid.GridStorage(p), solver.possibilities(g)) self.assertEqual(grid.Grid(TEST_VALUES), solver.set_trivial(g))
def problem(self): """ Show problem on screen """ self._clear_screen() letters_grid = grid.Grid(self.screen, 200, 5, 350, 50) letters_grid.draw() letters_grid.draw_letters(self.letters) start_grid = grid.Grid(self.screen, 200, 5, 650, 50) start_grid.draw() start_grid.draw_letters(self.start_pattern) pygame.display.flip()
def main(argv) : if len(argv) < 0 or len(argv) > 4 : print "Inadequate number of parameters, view README" return b = g.get_bot() sensor_grid = grid.Grid(size, size) # Grid for displaying noisy readings ml_grid = grid.Grid(size, size) # Grid for displaying most likely pos accuracy = [] # At each step, how far away is the most likely state steps = 15 # How many steps the robot should take print_info = False # Flag for info print_grid = False # Flag for grid printing time_per_step = 0.0 if len(argv) >= 1 : steps = int(argv[0]) if len(argv) >= 2 : print_info = (int(argv[1]) != 0) if len(argv) >= 3 : print_grid = (int(argv[2]) != 0) if len(argv) >= 4 : time_per_step = float(argv[3]) count = 0 for i in xrange(steps) : obs = g.next() # Latest observation update(obs) if not obs[0] is "nothing" : # Nothing handling sensor_grid.set_bot(obs[0][0], obs[0][1]) ml_state = most_likely() if print_grid : # This prints three parallell grids ml_grid.set_bot(ml_state.get_x(), ml_state.get_y()) grid_string = g.to_string().split("\n") sensor_string = sensor_grid.to_string().split("\n") ml_string = ml_grid.to_string().split("\n") for j in xrange(len(grid_string)) : print (grid_string[j] + sensor_string[j] + ml_string[j]) bstate = b.to_state() diff = bstate.diff(ml_state) accuracy.append(diff) if print_info : info = "Actual" + str(bstate.to_string()) info += "\tSensor" info += str((obs[0], bot.h_to_string(obs[1]))) info += "\tMost likely" + str(ml_state.to_string()) print info + "\n" print "Off by " + str(diff) if print_grid : time.sleep(time_per_step) s = str(len(accuracy)) + ": " for x in accuracy : s += str(abs(x[0]) + abs(x[1])) + " " print "\nAccuracy as a function of time: " print s
def test_clear_rows(self): g = grid.Grid(8, 10) for i in range(4, 8): for j in range(10): g.cells[i][j] = 1 g.cells[5][6] = 0 cleared_lines = g.clear_rows() self.assertEqual(cleared_lines, 3) current_grid = grid.Grid(8, 10) for i in range(10): current_grid.cells[7][i] = 1 current_grid.cells[7][6] = 0 self.assertEqual(g.cells, current_grid.cells)
def test_row(self): """Tests removing a whole row of values. The column of each should still fix the value.""" values = list(TEST_VALUES) p = [None] * 81 for i in range(9, 18): p[i] = set([values[i]]) values[i] = None g = grid.Grid(values) self.assertEqual(grid.GridStorage(p), solver.possibilities(g)) self.assertEqual(grid.Grid(TEST_VALUES), solver.set_trivial(g))
def __init__(self, samps = None, bounds = None, volume = None, measure = None, is_eq = True, bandlims = None): #TODO: remove this member self.is_eq = is_eq if samps is None: self.samps = gd.Grid() self.bounds = gd.Grid() else: self.samps = samps self.bounds = bounds self.ns = self.samps.get_curr_cards() if volume is None: self.volume = vol.Volume() else: self.volume = volume if measure is None: self.measure = ms.Measure() else: self.measure = measure if bandlims is None: bounds = deep(self.bounds) self.bandlims = deep(bounds.get_lims() ) else: self.bandlims = deep(bandlims) return
def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((840, 480), pygame.HWSURFACE) self._grid = grid.Grid(10, 10) self._status_window = status_window.StatusWindow() self._running = True
def __init__(self): """Constructor. Class/member variables for playing board and current player's turn.""" self.grid = grid.Grid() self.player1 = player.ManualPlayer(1) self.player2 = player.ManualPlayer(2) self.players = [self.player1, self.player2] self.pid_turn = 1
def expand_nodes(self, starting_grid, search_method): """Take a grid state, add all possible 'next moves' to the frontier""" node_order = ['up', 'down', 'left', 'right'] if search_method == 'dfs': node_order = reversed(node_order) for node in node_order: # the program is imagining the future!! (maybe change this name...) imagined_grid = grid.Grid(starting_grid.state) # pass path history from previous grid to the next grid # using copy to avoid python's reference bindings imagined_grid.path_history = copy.copy(starting_grid.path_history) if imagined_grid.move(node): # returns false if move not possible imagined_grid.path_history.append(node) if imagined_grid not in self.frontier and imagined_grid not in self.explored: if search_method == 'ast': imagined_grid.score = imagined_grid.manhattan_score( self.goal_state) self.ast_frontier.queue.put( (imagined_grid.score, imagined_grid)) else: self.frontier.queue.append(imagined_grid) self.metrics.update_max_fringe() self.metrics.nodes_expanded += 1
def a_star_search(self): """Explore search space using A*-search, using Manhattan Priority Function as a heuristic.""" self.metrics.start_timer() initial_grid = grid.Grid(self.initial_state) initial_grid.score = initial_grid.manhattan_score(self.goal_state) # TODO: ridiculous parameters self.ast_frontier.queue.put((initial_grid.score, initial_grid)) # while queue is not empty.. while self.ast_frontier.queue: # TODO: better name for state. It's a grid. state.state is the state! lowest_scored = self.ast_frontier.queue.get() state = lowest_scored[1] self.metrics.search_depth = len(state.path_history) self.metrics.update_max_depth() self.explored.set.add(state) if self.goal_test(state): self.metrics.path_to_goal = state.path_history self.metrics.stop_timer() self.metrics.measure_ram_useage() return self.metrics self.expand_nodes(state, 'ast') # if we get to here it's gone t**s up raise ValueError('Shouldn\'t have got to here - gone t**s')
def uninformed_search(self, search_method): """Explore search space using either breadth-first or depth-first search""" self.metrics.start_timer() initial_grid = grid.Grid(self.initial_state) self.frontier.queue.append(initial_grid) # while queue is not empty.. while self.frontier.queue: # TODO: better name for state. It's a grid. state.state is the state! if search_method == 'bfs': state = self.frontier.queue.popleft() elif search_method == 'dfs': state = self.frontier.queue.pop() self.metrics.search_depth = len(state.path_history) self.metrics.update_max_depth() self.explored.set.add(state) if self.goal_test(state): self.metrics.path_to_goal = state.path_history self.metrics.stop_timer() self.metrics.measure_ram_useage() return self.metrics self.expand_nodes(state, search_method) # if we get to here it's gone t**s up # TODO: this doesn't feel like good design! raise ValueError('Shouldn\'t have got to here - gone t**s')
def regrid(self, newgrid, newmask=None, interp='nearest'): ''' Regrids a field to a grid defined in newgrid interp is interpolation method. ''' X = newgrid['lon'] Y = newgrid['lat'] newshape = self.time.shape + self.grid['lev'].shape + newgrid[ 'lat'].shape nt, km, jm, im = newshape x = self.data.reshape(-1, self.grid['lat'].shape[0], self.grid['lon'].shape[1]) xnew = sp.ma.masked_array(sp.zeros((nt * km, jm, im))) for ii, xx in enumerate(x): mm = ~sp.ma.getmaskarray(xx) xnew[ii] = interpolate.griddata(zip(self.grid['lon'][mm], self.grid['lat'][mm]), xx[mm], (X, Y), method=interp) xnew = xnew.reshape(newshape) if newmask is not None: xnew.mask = newmask xnew[sp.isnan(xnew)] = sp.ma.masked self.data = xnew self.grid = grid.Grid(newgrid['lon'], newgrid['lat'], self.grid['lev'])
def test_square(self): g = grid.Grid(TEST_VALUES) self.assertEqual(g.square(0), (1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertEqual(g.square(1), (4, 5, 6, 7, 8, 9, 1, 2, 3)) self.assertEqual(g.square(3), (2, 3, 4, 5, 6, 7, 8, 9, 1)) self.assertEqual(g.square(8), (9, 1, 2, 3, 4, 5, 6, 7, 8)) self.assertEqual(g.square(7), (6, 7, 8, 9, 1, 2, 3, 4, 5))
def test_init_with_initial_grid(self): g = grid.Grid(3, 2, initial_grid=[["RED", "RED"], ["RED", "RED"], ["RED", "RED"]]) self.assertEqual([["RED", "RED"], ["RED", "RED"], ["RED", "RED"]], g.grid)
def simulate_player(self, possibilities, sunk_ships): sunk_ships_copy = copy.deepcopy(sunk_ships) ship_sizes = [5, 4, 3, 3, 2] random.shuffle(ship_sizes) temp_grid = grid.Grid() for size in ship_sizes: if size in sunk_ships_copy: possible_locations = [sunk_ships_copy[size]] sunk_ships_copy.pop(size) else: possible_locations = list(possibilities[size]) random.shuffle(possible_locations) ship_added = False for location in possible_locations: square, direction = location col, row = square ship_str = ' '.join([str(size), col, row, direction]) new_ship = ship.Ship(ship_str) if temp_grid.add_ship(new_ship): ship_added = True break if not ship_added: # ran out of locations return [] if self.shots_hit <= temp_grid.occupied_squares(): return list(temp_grid.occupied_squares()) return []
def setUp(self): self.tmp_list = files.ListFile('tests/list_tmp.life') self.tmp_life = files.LifeFile('tests/life_tmp.life') self.glider = [(1, 1), (1, 2), (1, 3), (2, 1), (3, 2)] self.game = game.Game(grid.Grid()) for coords in self.glider: self.game.grid.live(coords)
def get_visits(self): # Initialize a board for the same state board = grid.Grid(int(len(self.state)**0.5)) board.set_from_state(self.state) # Empty list that we are going to fill up visits = [] # Get all the nodes b_states = board.get_state(False) # Match is with legal actions for b in b_states: found = False i = None for ai in range(len(self.actions)): # If there is such an ai that if b == self.actions[ai].action: found = True i = ai # Set to 0 if the action is not legal if found: visits.append(self.actions[i].visits) else: visits.append(0) # Return the complete list return visits
def __init__(self, pacman_agent): self.pacman_agent = pacman_agent self.grid = grid.Grid() self.pacman = pacman.Pacman(grid.PACMAN_STARTPOS, 0, 0) self.blinky = ghost.Blinky(grid.GHOST_STARTPOS, 0, 0) self.inky = ghost.Inky(grid.GHOST_STARTPOS, 0, 0) self.pinky = ghost.Pinky(grid.GHOST_STARTPOS, 0, 0) self.clyde = ghost.Clyde(grid.GHOST_STARTPOS, 0, 0) self.ghosts = pygame.sprite.Group() self.ghost_house = pygame.sprite.Group() self.ghosts.add(self.blinky) self.ghost_house.add(self.inky) self.ghost_house.add(self.pinky) self.ghost_house.add(self.clyde) pygame.time.set_timer(CHANGESTATEEVENT, int(self.ghosts_state * 1000)) pygame.time.set_timer(GHOSTHOUSEEVENT, int(GHOSTHOUSETIME * 1000)) self._font = pygame.font.Font(globals.FONT, globals.FONT_SIZE)
def __init__(self, width, height): super().__init__(width, height, SCREEN_TITLE) arcade.set_background_color(arcade.color.WHITE) self.grid = grid.Grid(width, height, GRID_COLUMNS, GRID_ROWS) self.player = player.Player(self.grid.column_width, self.grid.row_height) self.playerPosition = Position(0, 0)
def __init__(self, img, xml, side, w, h, b, classes): self.array = numpy.asarray(Image.open(img)) self.array = numpy.asarray([ self.array[:, :, 0] / 255, self.array[:, :, 1] / 255, self.array[:, :, 2] / 255 ], dtype='float32') self.side = side self.w = w self.h = h self.b = b self.classes = classes self.grid = grid.Grid(self.side, self.w, self.h) tree = ET.parse(xml) root = tree.getroot() for obj in root.iter('object'): geometry = obj.find('geometry') box = geometry.find('bndbox') xmin, ymin = float(box.find('xmin').text), float( box.find('ymin').text) xmax, ymax = float(box.find('xmax').text), float( box.find('ymax').text) class_num = self.classes.index(obj.find('name').text) self.grid.insert(box=grid.Box(xmin, ymin, xmax, ymax, class_num))
def test_is_valid(self): self.assertTrue(grid.Grid(TEST_VALUES).is_valid()) values = list(TEST_VALUES) values[5] = 9 self.assertFalse(grid.Grid(values).is_valid()) values = list(TEST_VALUES) values[5] = None self.assertTrue(grid.Grid(values).is_valid()) self.assertTrue(grid.Grid([None] * len(TEST_VALUES)).is_valid()) values = [None] * len(TEST_VALUES) values[6] = 3 self.assertTrue(grid.Grid(values).is_valid())
def play(self, M, N, G, board_size): for anet1 in self.anets: for anet2 in [a for a in self.anets if a != anet1]: for i in range(G): play = grid.Grid(board_size) # Playing until the board is in terminal state. Anet1 is always the first player # This ensures that all networks will have a chance to play as first player while not play.is_terminal()[0]: # Let the player whose turn it currently is to make the move an = anet1 if play.get_player() == 1 else anet2 # Get the probability distribution from ANET pd = an.policy( str(play.get_player()) + play.get_state() ) # Make the best move play.make_move(play.get_coor( pd.index(h.argmax( pd ))) ) # Save the results of the game key = "an" + str(self.anets.index(anet1)) + " vs an" + str(self.anets.index(anet2)) # Add the results into the dictionary if play.is_terminal()[1] == 1: if key in self.results: self.results[key][0] += 1 else: self.results[key] = [1,0] else: if key in self.results: self.results[key][1] += 1 else: self.results[key] = [0, 1]
def vinterp(self, newgrid, revert_axis=False, newmask=None): ''' Performs vertical interpolation from self.grid['lev'] to newgrid['lev']. Levels should be monotonicaly increasing. If levels are decreasing, i.g. pressure levels, use revert_axis=True. ''' if revert_axis: ind = slice(None, None, -1) else: ind = slice(None) lev = self.grid['lev'][ind] newlev = newgrid['lev'][ind] nt, km, jm, im = self.dims kmout = newlev.size data = self.data[:, ind, :, :] mm = data.mean() data[data.mask] = mm f = interpolate.interp1d(lev, data, axis=1) self.data = sp.ma.masked_values(f(newlev)[:, ind, :, :], mm) if newmask is not None: self.data.mask = newmask self.grid = grid.Grid(self.grid['lon'], self.grid['lat'], newgrid['lev'])
def process_text(self, text, lang): if len(text) == 1: if self.is_grid_running == True: if '0' <= text[:1] <= '9': #send command to grid self.grid.select_cell(text) reporter.report_success(text) return True else: self.insert_text(text, lang) return True if text == "grid" or text == "griglia": if self.grid != None and self.is_grid_running == True: self.grid.stop() if (self.grid == None): self.grid = grid.Grid() self.grid.start() self.is_grid_running = True reporter.report_success(text) return True # Ignore some token in initial position if text.startswith('open ') or text.startswith( 'run ') or text.startswith('apri '): startpos = text.find(" ") + 1 t = text[startpos:] return self.open_program(t, lang, text.split(" ")[0].strip()) # Keyword in order to go to a web page elif text.startswith('vai su ') or text.startswith('go to '): startpos = text.find(" ") + 1 t = text[startpos:] startpos = t.find(" ") + 1 t = t[startpos:] self.google_search(t) return True # Keyword in order to write with vocal keyboard elif text.startswith('scrivi ') or text.startswith('write '): startpos = text.find(" ") + 1 t = text[startpos:] self.insert_text(t, lang) return True else: status = self.open_program(text, lang, "") if self.is_grid_running == True and status == True: self.grid.stop() if (status == False): t = text if text.startswith('chi è ') or text.startswith('cosa è '): startpos = text.find("è ") + 1 t = text[startpos:] if text.startswith('who is') or text.startswith('what is'): startpos = text.find("is ") + 1 t = text[startpos:] status = self.sparql.run(t, lang[:2]) if (status == True): reporter.report_success(text) return status reporter.report_failure(text)
def staticGridSimulation(): wMap = grid.Grid(tile_num_height, tile_num_width, tile_size) # Generates random enviroment on the grid generator = RandomObjects(wMap) # You can change the number of every type of object you want generator.create_env(20, 0, 0, 20, 7) generator.bloatTiles(robot_radius, bloat_factor) # Starting location topLeftX = 2.0 topLeftY = 2.0 # Ending Location botRightX = tile_size * tile_num_width - 2.0 botRightY = tile_size * tile_num_height - 2.0 # Run algorithm to get path try: dists, path = search.a_star_search(wMap, (topLeftX, topLeftY), (botRightX, botRightY), search.euclidean) root = Tk() # start GUI and run animation simulation = MapPathGUI(root, wMap, path) simulation.runSimulation(True) except: print("C1C0: \"There is no path to the desired location. Beep Boop\"") if __name__ == "__main__": staticGridSimulation()
def playgame(): grid = g.Grid() x = 0 score = 0 while grid.reward(score) == 0: grid.printGrid() x, y = raw_input("Enter row, column: ").split() if x == 'x': break x = int(x) y = int(y) if x < 0 or x >= grid.getNumRows(): print "Invalid row entry" continue if y < 0 or y >= grid.getNumCols(): print "Invalid column entry" continue round = grid.noisyThrow(x, y) score += round print "You got ",round," Current score:", score if grid.reward(score) == -1: print "You lose." return if grid.reward(score) == 1: print "You win!" return