def move(self, next_dir): # import ipdb; ipdb.set_trace() new_coor = self.snake.coords + next_dir self.__validate_point(new_coor.y, new_coor.x) new_cell = self.matrix[new_coor.y][new_coor.x] if not new_cell.is_empty(): if isinstance(new_cell.content, BlackHole): raise DeathError elif isinstance(new_cell.content, Wall): raise DeathError elif isinstance(new_cell.content, PythonPart): raise DeathError elif isinstance(new_cell.content, Food): # import ipdb; ipdb.set_trace() self.snake.score += new_cell.content.energy self.foods -= 1 if self.foods == 0: raise WinError self.snake.tail.append(PythonPart()) self.snake_coords.append("Dummy") freed_cell = self.snake_coords.pop() if type(freed_cell) is Vec2D: self.matrix[freed_cell.y][freed_cell.x] = Cell() self.matrix[new_coor.y][new_coor.x] = Cell(PythonHead()) self.matrix[self.snake_coords[0].y][self.snake_coords[0].x] = Cell( PythonPart()) self.snake_coords = [new_coor] + self.snake_coords self.snake.coords = new_coor self.snake.direction = next_dir
def cells_lists(self): """ Creating Cell objects from the structure of the maze """ # A dataFrame is created to facilitate the browsing of the data. df = self.create_dataframe() y = 0 # We run through the DataFrame and create each cell with the recovered coordinates. for y in df.index: x = 0 while x < len(df): if df[x][y] == WALL_CELL: self.wall.add(Cell(x, y, WALL_CELL, 'wall.png')) elif df[x][y] == LANE_CELL: self.lane.add(Cell(x, y, LANE_CELL, 'lane.png')) elif df[x][y] == START_CELL: self.start.add(Cell(x, y, START_CELL, 'lane.png')) elif df[x][y] == EXIT_CELL: self.exit.add(Cell(x, y, EXIT_CELL, 'lane.png')) else: pass x += 1 y += 1 # We place the objects created in the all_cells attribute self.all_cells = self.all_cells.union(self.wall, self.lane, self.start, self.exit)
class TestCell(unittest.TestCase): def setUp(self): self.cell = Cell(Food()) def test_is_empty_cell_on_full_one(self): self.assertFalse(self.cell.is_empty()) def test_emptying_the_cell(self): self.cell.empty_cell() self.assertEqual(self.cell.symbol, symbols.EMPTY)
def update_data(): result = request.get_json() newid = result["newid"] oldid = result["oldid"] newstatus = result["newstatus"] oldstatus = result["oldstatus"] if (newid != oldid): query = Cell.update(order=newid, status=newstatus).where( Cell.order == oldid and Cell.status == oldstatus) query.execute() query = Cell.update(order=oldid, status=newid).where(Cell.order == newid and Cell.status == newstatus) query.execute()
def create_new_cell(): cell_name = request.form['cell_title'] boardid = request.form['boardid'] if cell_name != "": query = Cell.select().join(Status).where((Status.status == 'new') & (Cell.board == boardid)) new_cell = Cell.create(name=cell_name, status=1, board=boardid, order=(len(query) + 1)) return jsonify({ 'id': new_cell.id, 'name': new_cell.name, 'order': new_cell.order })
def next_gen(self) -> None: """ Using either cells to check or full grid, kill/revive cells. """ if self.cells_to_check: print( f"Checking {len(self.cells_to_check)} cells from previous generation." ) new_cells_to_check = set() # can optimize by only looking at cells or neighbors that have changed for coords in self.cells_to_check: try: cell = self.get_cell(coords[0], coords[1]) except (IndexError, KeyError, TypeError): print(f"Invalid coordinates in set {coords}") raise # returns true if modified if cell.live_or_die(self): new_cells_to_check |= cell.get_coords_of_cell_and_neighbors( self) self.cells_to_check = new_cells_to_check else: # in case we haven't yet decided, check all cells self.cells_to_check = set() for col, column in enumerate(self.cell_grid): for row, cell in enumerate(column): cell = cell if cell else Cell(col, row) if cell.live_or_die(self): self.cells_to_check |= cell.get_coords_of_cell_and_neighbors( self) # swap old grid for new self.set_grid()
def move_left(self, map): ''' Changing the hero's position when moving to the left :param map: the map object (the maze), to access its attributes ''' # The new position new_pos = (self.position[0] - CELL_SIZE, self.position[1]) # The virtual new cell with the new position, which must be a lane new_cell = Cell(int(new_pos[0] / CELL_SIZE), int(new_pos[1] / CELL_SIZE), LANE_CELL, 'lane.png') # List of all cells of the game cells = list(map.all_cells) # The hero is not allowed to leave the frame of the game. if self.position[0] > 0: # The new position must be a lane if new_cell in cells: for cell in cells: # If we find a lane cell with the same position as the virtual cell, we check that there is not an item to pick up. if cell.position == new_cell.position: interface.collect_item(self, map.items_list) # The hero meets the guard if cell.position == new_cell.position and cell.type_of_cell == EXIT_CELL: interface.display_text_zone3(map.items_list) # We update the position of the hero self.position = new_pos return self.position else: # If it's not a lane, the hero doesn't move. return self.position
def test_eating_food_is_done_correctly(self): self.python.set_head() self.python.set_body() size = len(self.python.get_body_coords()) self.game_world.set_cell(Cell(Food(), Vector2D(5, 6))) self.python.move('d') size_n = len(self.python.get_body_coords()) self.assertEqual(size_n - size, 1)
def __init_next_gen(self, col: int, row: int) -> None: try: if not self.next_cell_grid[col][row]: self.next_cell_grid[col][row] = Cell(col, row) except IndexError: print( f"Tried to update cell {col} {row} outside of grid size {self.size}" ) raise
def delete_board(): boardid = request.form['boardid'] q = Cell.delete().where(Cell.board_id == boardid) q.execute() q = Boardstable.delete().where(Boardstable.board == boardid) q.execute() q = Board.delete().where(Board.id == boardid) q.execute() return "ok"
def __set_snake_in_matrix(self, snake): # import ipdb; ipdb.set_trace() temp_point = snake.coords for snake_part in [snake.head] + snake.tail: self.__validate_point(temp_point.y, temp_point.x) if not self.matrix[temp_point.y][temp_point.x].is_empty(): self.__rearange_cells(temp_point.y, temp_point.x) self.matrix[temp_point.y][temp_point.x] = Cell(snake_part) self.snake_coords.append(temp_point) temp_point = gen_next_coords(temp_point, snake.direction)
def rearrange_same_statused_cells(newid, oldid, id_in_db): moved_cell = Cell.get(Cell.id == id_in_db) if newid > oldid: cells = Cell.select().where((Cell.order > oldid) & (Cell.order <= newid) & (Cell.board == moved_cell.board)) for cell in cells: cell.order -= 1 cell.save() else: cells = Cell.select().where((Cell.order < oldid) & (Cell.order >= newid) & (Cell.status == moved_cell.status) & (Cell.board == moved_cell.board)) for cell in cells: cell.order += 1 cell.save() moved_cell.order = newid moved_cell.save()
def get_cell(self, col: int, row: int) -> None: """ Get cell """ try: return self.cell_grid[col][row] if self.cell_grid[col][ row] else Cell(col, row) except IndexError: print( f"Tried to update {col} {row} outside of grid size {self.size}" ) raise
def rearrange_different_statused_cells(newid, oldid, oldstatus, newstatus, id_in_db): moved_cell = Cell.get(Cell.id == id_in_db) # newStatused rearrange cells = Cell.select().where((Cell.status == Status.get( Status.status == newstatus)) & (Cell.board == moved_cell.board) & (Cell.order >= newid)) for cell in cells: cell.order += 1 cell.save() # oldStatus rearrange cells = Cell.select().where((Cell.status == Status.get( Status.status == oldstatus)) & (Cell.board == moved_cell.board) & (Cell.order > oldid)) for cell in cells: cell.order -= 1 cell.save() moved_cell.order = newid moved_cell.status = Status.get(Status.status == newstatus) moved_cell.save()
def copy(self, deep: bool = True) -> 'Snake': """ Copy a snake object :param deep: True if it has to be a deep copy, False otherwise :return: copied snake object """ if deep: new_body = [Cell(cell.x, cell.y) for cell in self.body] else: new_body = self.body return Snake(new_body)
def __init__(self, width: int, height: int): """ The challenge states that the board should be an array of integers, but having it as an object that you can compare will be easier and make the code more readable. :param width: Number of columns :param height: Number of rows """ self.cells = [ [Cell(x, y) for x in range(width)] for y in range(height) ]
def move_down(self, map): ''' Changing the hero's position when moving downwards ''' new_pos = (self.position[0], self.position[1] + CELL_SIZE) new_cell = Cell(int(new_pos[0] / CELL_SIZE), int(new_pos[1] / CELL_SIZE), LANE_CELL, 'lane.png') cells = list(map.all_cells) if self.position[1] < MAP_SIZE[1] - CELL_SIZE: if new_cell in cells: for cell in cells: if cell.position == new_cell.position: interface.collect_item(self, map.items_list) if cell.position == new_cell.position and cell.type_of_cell == EXIT_CELL: interface.display_text_zone3(map.items_list) self.position = new_pos return self.position else: return self.position
def __init__(self, layers, nodes, in_dim, feature_dim, num_classes, criterion, data_type='gc', readout='mean', dropout=0.0): super(Network, self).__init__() self._layers = layers self._in_dim = in_dim self._feature_dim = feature_dim self._num_classes = num_classes self._criterion = criterion self._nb_first_nodes = nodes self._nb_last_nodes = nodes self._data_type = data_type self._readout = readout self._dropout = dropout self._nb_first_edges = sum(1 + i for i in range(self._nb_first_nodes)) self._nb_middle_edges = self._nb_first_nodes self._nb_last_edges = sum(self._nb_first_nodes + i for i in range(self._nb_last_nodes)) if data_type in ['nc', 'rg']: self.embedding_h = nn.Embedding( self._in_dim, self._feature_dim) # node feat is an integer else: self.embedding_h = nn.Linear(self._in_dim, self._feature_dim) self.cells = nn.ModuleList([ Cell(self._nb_first_nodes, self._nb_last_nodes, self._feature_dim, self._dropout) for i in range(self._layers) ]) self._initialize_alphas() outdim = self._feature_dim if self._data_type not in [ 'ec' ] else 2 * self._feature_dim self.classifier = MLPReadout(outdim, self._num_classes)
def items_random_position(self): """ Random positions are generated for the items to be collected by the hero. """ # List of item image file names items_img = ['item1.png', 'item2.png', 'item3.png'] # As an item can only be found in a lane, 3 lane cells are chosen at random. items_positions = random.sample(self.lane, k=3) for it in items_positions: # Each cell is assigned an image from the tems_img list. select_img = random.choice(items_img) # We create item objects and place them in the items_list attribute self.items_list.add( Cell(int(it.position[0] / CELL_SIZE), int(it.position[1] / CELL_SIZE), ITEM_CELL, select_img)) # The assigned image is removed from the list to prevent it from being reassigned. items_img.remove(select_img) # We place the objects created in the all_cells attribute self.all_cells = self.all_cells.union(self.items_list)
def main(): game = GameWorld(15) p = Python(game, Vec2D(10, 10), 3, Python.LEFT) wall1 = Cell(Wall(), 2, 7) wall2 = Cell(Wall(), 3, 7) wall3 = Cell(Wall(), 4, 7) game.add_content([wall1, wall2, wall3]) cell1 = Cell(Food('banana', energy=3), 4, 0) cell2 = Cell(Food('mouse', energy=3), 0, 0) cell3 = Cell(Food('chick', energy=3), 1, 1) cell4 = Cell(Food('rabbit', energy=3), 4, 3) game.add_content(cell1) game.add_content(cell2) game.add_content(cell3) game.add_content(cell4) print(game) game.run()
def create_example_data(): if not Cell.select(): user = User(name='Example User', login_name='user', password='******') batman = User(name='Batman', login_name='batman', password='******') user.save() batman.save() board1 = Board(name='First') board2 = Board(name='Second') board3 = Board(name='Third') batman1 = Board(name='Batmobil') batman2 = Board(name='BatBarlang') batman3 = Board(name='BatRobin') board1.save() board2.save() board3.save() batman1.save() batman2.save() batman3.save() Boardstable.create(board=board1, user=user) Boardstable.create(board=board2, user=user) Boardstable.create(board=board3, user=user) Boardstable.create(board=batman1, user=batman) Boardstable.create(board=batman2, user=batman) Boardstable.create(board=batman3, user=batman) Cell.create(text="Rocket", name="Weapon", order=1, board=board1, status=Status.get(Status.status == "new")) Cell.create(text="Pistol", name="Weapon", order=2, board=board1, status=Status.get(Status.status == "new")) Cell.create(text="Sword", name="Weapon", order=3, board=board1, status=Status.get(Status.status == "new")) Cell.create(text="Kalasnyikov", name="Weapon", order=1, board=board1, status=Status.get(Status.status == "progress")) Cell.create(text="Grenade", name="Weapon", order=1, board=board1, status=Status.get(Status.status == "done"))
def print_paths(paths: List[List[Move]]): # Print the list of possible paths for path in paths: print("".join([move.value for move in path])) if __name__ == '__main__': # Read test configuration test_configuration = json.loads( (Path(__file__).parent / "test_config.json").read_text()) successful_tests = 0 for test in test_configuration.keys(): # Build state and look for paths board = Board(*test_configuration[test]["board"]) snake = Snake( [Cell(*cell) for cell in test_configuration[test]["snake"]]) paths = PathController.get_available_different_paths( board, snake, test_configuration[test]["depth"]) expected_number_of_paths = test_configuration[test]["expected_result"] # Print results success = len(paths) == expected_number_of_paths if success: successful_tests += 1 print( f"Test 1: {'SUCCESS!' if success else 'FAILED'}, {len(paths)}/{expected_number_of_paths} paths found" ) print_board_state(board, snake) print("\nList of moves:") print_paths(paths)
def initialize_field(self): print('\n') for i in range(0, self.size_x): for j in range(0, self.size_y): self.cells.append(Cell(i, j))
def test_no_food_board_on_set_food_cell(self): self.game_world.set_cell(Cell(Food(), Vector2D(3, 4))) self.assertFalse(self.game_world.no_food_board())
def setUp(self): self.cell = Cell(Food())
def main(): game = GameWorld(20) cell1 = Cell(Food(), Vector2D(4, 4)) cell2 = Cell(Food(), Vector2D(6, 7)) cell3 = Cell(Food(), Vector2D(6, 8)) cell4 = Cell(Food(), Vector2D(2, 1)) cell5 = Cell(Food(), Vector2D(0, 17)) cell6 = Cell(Food(), Vector2D(13, 15)) cell7 = Cell(Food(), Vector2D(14, 2)) cell8 = Cell(Wall(), Vector2D(5, 5)) cell9 = Cell(Wall(), Vector2D(7, 6)) cell10 = Cell(Wall(), Vector2D(8, 9)) cell11 = Cell(Wall(), Vector2D(11, 15)) cell12 = Cell(Wall(), Vector2D(18, 12)) cell13 = Cell(Wall(), Vector2D(19, 1)) cell14 = Cell(BlackHole(), Vector2D(2, 2)) game.add_content([cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9, cell10, cell11, cell12, cell13, cell14]) p = Python(game, (5, 2), 5, Python.DOWN) p.set_head() p.set_body() game.print_world() direction = getch.getch() with start_log('game_start.txt', 'a') as s: pass while direction: os.system('clear') p.move(direction) with move_log('move_log.txt', 'a', p.direction_by_ascii_code(direction)) as f: pass flag = p.is_dead() try: if not flag: game.print_world() direction = getch.getch() else: raise DeathError except DeathError: print("GAME OVER") break if game.no_food_board(): print("GAME WON!") break with end_log('game_end.txt', 'a') as e: pass
def empty_last(self): c = Cell(vector=self.body_coords[-1]) self.world.set_cell(c)
def __init_cells__(self): for i in range(self.rows): column = [] for j in range(self.columns): column.append(Cell(i, j)) self.cells.append(column)
def update_cell_text(): id = request.form["id_in_db"] text = request.form["cell_text"] query = Cell.update(text=text).where(Cell.id == id) query.execute() return "ok"
def __init__(self, run_config: RunConfig, arch_search_config: ArchSearchConfig, conv_candidates): super(AutoDeepLab, self).__init__() self._redundant_modules = None self._unused_modules = None self.cells = nn.ModuleList() self.run_config = run_config self.arch_search_config = arch_search_config self.conv_candidates = conv_candidates self.nb_layers = self.run_config.nb_layers self.nb_classes = self.run_config.nb_classes # TODO: criterion has calculated in run_manager # init arch_network_parameters self.arch_network_parameters = nn.Parameter( torch.Tensor(self.nb_layers, 4, 3)) # TODO: architecture params init in nas_manager # three init stems self.stem0 = nn.Sequential( nn.Conv2d(3, 64, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.stem1 = nn.Sequential( nn.Conv2d(64, 64, 3, stride=1, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.stem2 = nn.Sequential( nn.Conv2d(64, 128, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True)) prev_prev_c = 64 prev_c = 128 for i in range(self.nb_layers): if i == 0: cell1 = Cell( self.run_config, self.conv_candidates, 4, prev_c=prev_c, prev_prev_c=None, types=['same'], ) cell2 = Cell(self.run_config, self.conv_candidates, 8, prev_c=prev_c, prev_prev_c=None, types=['reduction']) self.cells += [cell1] self.cells += [cell2] elif i == 1: cell1 = Cell(self.run_config, self.conv_candidates, 4, prev_c=-1, prev_prev_c=128, types=['up', 'same']) cell2 = Cell(self.run_config, self.conv_candidates, 8, prev_c=-1, prev_prev_c=None, types=['reduction', 'same']) cell3 = Cell(self.run_config, self.conv_candidates, 16, prev_c=-1, prev_prev_c=None, types=['reduction']) self.cells += [cell1] self.cells += [cell2] self.cells += [cell3] elif i == 2: cell1 = Cell(self.run_config, self.conv_candidates, 4, prev_c=-1, prev_prev_c=-1, types=['same', 'up']) cell2 = Cell(self.run_config, self.conv_candidates, 8, prev_c=-1, prev_prev_c=-1, types=['reduction', 'same', 'up']) cell3 = Cell(self.run_config, self.conv_candidates, 16, prev_c=-1, prev_prev_c=None, types=['reduction', 'same']) cell4 = Cell(self.run_config, self.conv_candidates, 32, prev_c=-1, prev_prev_c=None, types=['reduction']) self.cells += [cell1] self.cells += [cell2] self.cells += [cell3] self.cells += [cell4] elif i == 3: cell1 = Cell(self.run_config, self.conv_candidates, 4, prev_c=-1, prev_prev_c=-1, types=['same', 'up']) cell2 = Cell(self.run_config, self.conv_candidates, 8, prev_c=-1, prev_prev_c=-1, types=['reduction', 'same', 'up']) cell3 = Cell(self.run_config, self.conv_candidates, 16, prev_c=-1, prev_prev_c=-1, types=['reduction', 'same', 'up']) cell4 = Cell(self.run_config, self.conv_candidates, 32, prev_c=-1, prev_prev_c=None, types=['reduction', 'same']) self.cells += [cell1] self.cells += [cell2] self.cells += [cell3] self.cells += [cell4] else: cell1 = Cell(self.run_config, self.conv_candidates, 4, prev_c=-1, prev_prev_c=-1, types=['same', 'up']) cell2 = Cell(self.run_config, self.conv_candidates, 8, prev_c=-1, prev_prev_c=-1, types=['reduction', 'same', 'up']) cell3 = Cell(self.run_config, self.conv_candidates, 16, prev_c=-1, prev_prev_c=-1, types=['reduction', 'same', 'up']) cell4 = Cell(self.run_config, self.conv_candidates, 32, prev_c=-1, prev_prev_c=-1, types=['reduction', 'same']) self.cells += [cell1] self.cells += [cell2] self.cells += [cell3] self.cells += [cell4] scale4_outc = int(self.run_config.filter_multiplier * self.run_config.block_multiplier * 4 / 4) scale8_outc = int(self.run_config.filter_multiplier * self.run_config.block_multiplier * 8 / 4) scale16_outc = int(self.run_config.filter_multiplier * self.run_config.block_multiplier * 16 / 4) scale32_outc = int(self.run_config.filter_multiplier * self.run_config.block_multiplier * 32 / 4) # dilation as 96/scale self.aspp4 = ASPP(scale4_outc, self.nb_classes, 24, self.run_config.nb_classes) self.aspp8 = ASPP(scale8_outc, self.nb_classes, 12, self.run_config.nb_classes) self.aspp16 = ASPP(scale16_outc, self.nb_classes, 6, self.run_config.nb_classes) self.aspp32 = ASPP(scale32_outc, self.nb_classes, 3, self.run_config.nb_classes) self.set_bn_param(momentum=self.run_config.bn_momentum, eps=self.run_config.bn_eps)