def test_at_distance(self): horizontally_aligned_tile = Tile(10, 3) vertically_aligned_tile = Tile(2, 10) diagonally_aligned_tile = Tile(3, 4) self.assertFalse(self.tile.at_distance(7, horizontally_aligned_tile)) self.assertTrue(self.tile.at_distance(8, horizontally_aligned_tile)) self.assertTrue(self.tile.at_distance(7, vertically_aligned_tile)) self.assertFalse(self.tile.at_distance(8, vertically_aligned_tile)) self.assertFalse(self.tile.at_distance(1, diagonally_aligned_tile))
def test_direction_from(self): south_east_tile = Tile(5, 5) west_tile = Tile(1, 3) north_east_tile = Tile(5, 2) self.assertEqual(south_east_tile.direction_from(self.tile), (1, 1)) self.assertEqual(west_tile.direction_from(self.tile), (-1, 0)) self.assertEqual(north_east_tile.direction_from(self.tile), (1, -1))
def test_odd(self): even_tile = Tile(2, 2) odd_tile = Tile(3, 3) mixed_tile = Tile(2, 3) self.assertFalse(even_tile.odd()) self.assertTrue(odd_tile.odd()) self.assertFalse(mixed_tile.odd())
def create_tiles(self, filename): map = self.read(filename) x, y = 0, 0 for row in map: x = 0 for tile in row: if tile == '673': self.tiles.append( Tile('assets/tiles/grass.png', False, x * self.tile_size, y * self.tile_size)) elif tile == '674': self.tiles.append( Tile('assets/tiles/grass.png', True, x * self.tile_size, y * self.tile_size)) elif tile == '721': self.tiles.append( Tile('assets/tiles/dirt.png', False, x * self.tile_size, y * self.tile_size)) elif tile == '722': self.tiles.append( Tile('assets/tiles/dirt.png', True, x * self.tile_size, y * self.tile_size)) elif tile == '702': self.enemies.append( Skeleton(self.game, x * self.tile_size, y * self.tile_size)) elif tile == '900': self.objects.append( Coin(self.game, x * self.tile_size, y * self.tile_size)) elif tile == '895': self.objects.append( Trap(self.game, False, x * self.tile_size, y * self.tile_size)) elif tile == '847': self.objects.append( Trap(self.game, True, x * self.tile_size, y * self.tile_size)) elif tile == '937': self.goal = x * self.tile_size self.objects.append( Goal(self.game, x * self.tile_size, y * self.tile_size)) elif tile == '558': self.objects.append( Save(self.game, x * self.tile_size, y * self.tile_size)) x += 1 y += 1 self.map_w = x * self.tile_size self.map_h = y * self.tile_size
def _gen_sample(self): for i in range(CONFIG['sample_map_x_size']): self.tiles.append([]) for j in range(CONFIG['sample_map_y_size']): if (j == (CONFIG['sample_map_y_size'] - 1)) or (j == 0) or ( i == (CONFIG['sample_map_x_size'] - 1)) or (i == 0): self.tiles[i].append(Tile(1)) else: if randint(0, 9) == 1: self.tiles[i].append(Tile(3)) else: self.tiles[i].append(Tile(2)) self.size_x = len(self.tiles) self.size_y = len(self.tiles[0])
def __init__(self): self.X_SIZE = 4 self.Y_SIZE = 4 self.cells = [[ Tile(random.randrange(MODULUS), x=x, y=y) for x in range(self.X_SIZE) ] for y in range(self.Y_SIZE)]
def loop(): #------------- Init ------------- #Display a window of 768x768 window = pygame.display.set_mode([832, 768]) #Window name pygame.display.set_caption("ShootGame") #Variables quit_flag = False clock = pygame.time.Clock() tileMap = Tile() #Options pygame.key.set_repeat(10, 200) #Characters #-------------------------------- while not quit_flag: time = clock.tick(30) # events for event in pygame.event.get(): if event.type == pygame.QUIT: quit_flag = True # detect events on_event(time, event) # update scene (stuff) on_update(time) # redraw the screen on_draw(window, tileMap) pygame.display.flip()
def initalize(self): for row in range(self.rows): for col in range(self.cols): tile = Tile(row, col, False, self.blockwidth, self.blockheight) self.board.append(tile) self.addneighbours(self.board, self.weights) self.initalizeStartAndEnd(self.board, static_locations=self.static_locations)
def _load_map(self): x, y = 0, 0 tile_data = [] with open(self.bg_file, 'r') as f: for line in f: # (0,0) , (0,1), (0,2), (0,3) ... x = 0 for cell in line.split(' '): if len(self.tiles) <= x: self.tiles.append([]) self.tiles[x].append(Tile(int(cell))) x += 1
def loadCurrentRoom(self, data): """ Sets up rendering of the room at the currentRoom position """ data.groups.walls = pygame.sprite.Group() # Empty wall tileset data.groups.terrain = pygame.sprite.Group() # Empty tileset data.groups.monsters = pygame.sprite.Group() # Remove all enemies data.groups.spawners = pygame.sprite.Group() # Remove old spawners data.groups.damagedWalls = pygame.sprite.Group( ) # Removed old broken walls. data.groups.items = pygame.sprite.Group() currRoom = self.rooms[data.currentRoomsPos[1]][data.currentRoomsPos[0]]\ .tileList for row in range(StaticDungeonLayout.DUNGEON_ROOM_HEIGHT): for col in range(StaticDungeonLayout.DUNGEON_ROOM_WIDTH): # Create a new GameObject based on the type of tile: newTile = Tile(row, col, data) data.groups.terrain.add(newTile) if currRoom[row][col] == StaticDungeonLayout.WALL_CHAR: newWall = Wall(row, col, data) data.groups.walls.add(newWall) elif currRoom[row][col] == StaticDungeonLayout.PLAYER_CHAR: if data.player != None: continue playerY = row * Value.CELL_SIZE + Value.CELL_SIZE / 2 playerX = col * Value.CELL_SIZE + Value.CELL_SIZE / 2 data.player = Player(playerX, playerY, Value.PLAYER_SIZE) data.groups.player.add(data.player) elif currRoom[row][col] == StaticDungeonLayout.MONSTER_CHAR: monsterY = row * Value.CELL_SIZE + Value.CELL_SIZE / 2 monsterX = col * Value.CELL_SIZE + Value.CELL_SIZE / 2 data.groups.monsters.add( Monster(monsterX, monsterY, Value.MONSTER_SIZE)) elif currRoom[row][col] == StaticDungeonLayout.SPAWNER_CHAR: spawnerY = row * Value.CELL_SIZE + Value.CELL_SIZE / 2 spawnerX = col * Value.CELL_SIZE + Value.CELL_SIZE / 2 data.groups.spawners.add( Spawner(spawnerX, spawnerY, Value.SPAWNER_SIZE)) elif currRoom[row][ col] == StaticDungeonLayout.DAMAGED_WALL_CHAR: wallX = col * Value.CELL_SIZE + Value.CELL_SIZE / 2 wallY = row * Value.CELL_SIZE + Value.CELL_SIZE / 2 data.groups.walls.add( DamagedWall(wallX, wallY, Value.TERRAIN_SIZE)) elif currRoom[row][col] == StaticDungeonLayout.GHOST_CHAR: ghostX = col * Value.CELL_SIZE + Value.CELL_SIZE / 2 ghostY = row * Value.CELL_SIZE + Value.CELL_SIZE / 2 data.groups.monsters.add( Ghost(ghostX, ghostY, Value.GHOST_SIZE)) elif currRoom[row][col] == StaticDungeonLayout.BOSS_CHAR: bossX = col * Value.CELL_SIZE + Value.CELL_SIZE / 2 bossY = row * Value.CELL_SIZE + Value.CELL_SIZE / 2 data.groups.monsters.add( Boss(bossX, bossY, Value.BOSS_SIZE))
def make_map(): global map map = [[Tile(True) for y in range(MAP_HEIGHT)] for x in range(MAP_WIDTH)] rooms = [] num_rooms = 0 for r in range(MAX_ROOMS): w = libtcod.random_get_int(0, ROOM_MIN_SIZE, ROOM_MAX_SIZE) h = libtcod.random_get_int(0, ROOM_MIN_SIZE, ROOM_MAX_SIZE) x = libtcod.random_get_int(0, 0, MAP_WIDTH - w - 1) y = libtcod.random_get_int(0, 0, MAP_HEIGHT - h - 1) new_room = Rect(x, y, w, h) intersected = False for room in rooms: if new_room.overlap(room): intersected = True break if not intersected: create_room(new_room) (newx, newy) = new_room.center() if num_rooms == 0: player.x = newx player.y = newy else: # Not player spawn! (prevx, prevy) = rooms[num_rooms - 1].center() if libtcod.random_get_int(0, 0, 1) == 1: create_horz_tunnel(prevx, newx, prevy) create_vert_tunnel(prevy, newy, newx) else: create_vert_tunnel(prevy, newy, prevx) create_horz_tunnel(prevx, newx, newy) rooms.append(new_room) num_rooms += 1 stairs_index = random.randint(1, num_rooms - 1) (stairsx, stairsy) = rooms[stairs_index].center() global stairs stairs.clear() del entities[0] stairs = Entity(stairsx, stairsy, '=', libtcod.blue, con, 'object', 'stairs', [], {}) entities.insert(0, stairs) #Generate monsters! for i in range(0, num_rooms): randy = random.randint(1, num_rooms - 1) randMonst = get_random_enemy() (centx, centy) = rooms[randy].center() randMonst.x = centx randMonst.y = centy entities.append(randMonst)
def test_get_empty_at_distance_two(self): empty_west = Tile(0, 3) empty_north = Tile(2, 1) floor_east = Tile(4, 3) floor_east.set_type("floor") tiles_to_check = [empty_west, empty_north, floor_east] self.assertEqual(self.tile.get_empty_at_distance_two(tiles_to_check), [empty_west, empty_north])
def gen_tileset_map(self, tileset_id): filename = CONFIG['tile_configs']['tilesets'][tileset_id]['filename'] rm.load_tileset_by_id(tileset_id) testmap = Map() testmap.empty_map() x = 0 y = 0 count = 0 for tileconfig in rm.tilesets[filename]: if y >= CONFIG['tool_tileviewer_max_col_size']: x += 1 y = 0 tile = Tile(0) tile.tileset_id = tileset_id tile.tile_id = count if x not in testmap.tiles: testmap.tiles.append([]) testmap.tiles[x].append(tile) y += 1 count += 1 return testmap
def generate( self, map_width: int, map_height: int) -> Tuple[List[List[Tile]], List[pygame.Rect]]: self.current_map = [[ Tile(True, self.wall_texture) for y in range(0, map_height) ] for x in range(0, map_width)] self.regions = np.zeros((map_width, map_height)) self.current_map_width = map_width self.current_map_height = map_height self.add_rooms() for y in range(1, self.current_map_height, 2): for x in range(1, self.current_map_width, 2): if self.current_map[x][y].block_path: self.grow_maze(x, y) self.connect_regions() self.remove_dead_ends() return self.current_map, self.rooms
def __init__(self, x, y, model): self.__x = x self.__y = y self.__tiles = [] self.__model = model rect[Constants.X] = rect[ Constants.X] + self.__x + Constants.SIDE_MENU_TEXT_LEFT_MARGIN rect[Constants.Y] = rect[Constants.Y] + self.__y for x in range(0, NUMBER_OF_TILES): tileStyle = dict(tileGenericStyle) if tilesTitles[x] in tilesProperties: tileStyle.update(tilesProperties[tilesTitles[x]]) tileStyle['rect'] = pygame.Rect(rect) self.__tiles.append(Tile(tileStyle, tilesTitles[x])) # We get the initial data to populate the screen self.getData()
def clip(self, tile: Tile): """ Clips this raster according to the size of original geometry of the tile provided :param tile: Tile element corresponding with this raster :return: None """ try: self.open() except Exception: return False clip_geom = tile.get_unbuffered_geometry() clip_height = clip_geom.bounds[3] - clip_geom.bounds[1] # maxy - miny clip_width = clip_geom.bounds[2] - clip_geom.bounds[0] # maxx - minx try: print(self._raster_name, clip_geom) out_image, out_transform = mask(dataset=self._raster, shapes=[clip_geom], crop=True) out_meta = self._raster.meta.copy() self.close() out_meta.update({ "driver": "GTiff", "height": clip_height / self._base_raster_cell_size, "width": clip_width / self._base_raster_cell_size, "transform": out_transform, }) with rasterio.Env(): with rasterio.open(self.filepath, "w", **out_meta) as dest: dest.write(out_image) except Exception as e: print(e) return False
def connect_tiles(tile1, tile2): dim = (tile1.img.shape[0]+tile2.img.shape[0], max(tile1.img.shape[1],tile2.img.shape[1]), 3) #TODO someting's wrong here -> find out! img = np.zeros((1000,1000,3)) img = overlay_image_alpha(img, tile1.img, (0,0), tile1.mask) x_offset = tile1.corners[1][0]-tile2.corners[0, 0] y_offset = 17 # TODO: currently manual tryout -> calculate img = overlay_image_alpha(img, tile2.img, (x_offset, y_offset), tile2.mask) img = cv2.circle(img, tuple(tile1.corners[1]), 8, green, thickness=6) img = cv2.circle(img, (tile2.corners[0][0]+x_offset, tile2.corners[0][1]+y_offset), 17, green, thickness=6) return img for tile_id in range(len(boxes)): box = boxes[tile_id] crop = img[int(box[0][1]):int(box[1][1]), int(box[0][0]):int(box[1][0])] tile = Tile(crop) box = boxes[tile_id+2] crop = img[int(box[0][1]):int(box[1][1]), int(box[0][0]):int(box[1][0])] tile1 = Tile(crop) #tile1.show() #input() test = overlay_image_alpha(np.zeros((1000,1000,3)), np.rot90(tile.img), (0,0), np.rot90(tile.mask)) test = overlay_image_alpha(test, tile.img, (tile.corners[1][0]-tile.corners[0, 0], 0), tile.mask) tile.rotate() tile1.rotate(2) test = connect_tiles(tile, tile1).astype(int) plt.subplot(121),plt.imshow(test ,cmap = 'gray') plt.title('original tile with corners'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(tile.img,cmap = 'gray') plt.title('perspective correction'), plt.xticks([]), plt.yticks([])
class TileTest(unittest.TestCase): def setUp(self): self.tile = Tile(2, 3) def test_init(self): self.assertEqual(2, self.tile.x) def test_set_type(self): self.tile.set_type("floor") self.assertEqual("floor", self.tile.type) def test_char(self): self.tile.type = "corridor" self.assertEqual("#", self.tile.char()) def test_empty(self): self.assertTrue(self.tile.empty()) self.tile.set_type("wall") self.assertFalse(self.tile.empty()) def test_walkable(self): self.tile.set_type("floor") self.assertTrue(self.tile.walkable()) self.tile.set_type("wall") self.assertFalse(self.tile.walkable()) def test_odd(self): even_tile = Tile(2, 2) odd_tile = Tile(3, 3) mixed_tile = Tile(2, 3) self.assertFalse(even_tile.odd()) self.assertTrue(odd_tile.odd()) self.assertFalse(mixed_tile.odd()) def test_get_empty_at_distance_two(self): empty_west = Tile(0, 3) empty_north = Tile(2, 1) floor_east = Tile(4, 3) floor_east.set_type("floor") tiles_to_check = [empty_west, empty_north, floor_east] self.assertEqual(self.tile.get_empty_at_distance_two(tiles_to_check), [empty_west, empty_north]) def test_at_distance(self): horizontally_aligned_tile = Tile(10, 3) vertically_aligned_tile = Tile(2, 10) diagonally_aligned_tile = Tile(3, 4) self.assertFalse(self.tile.at_distance(7, horizontally_aligned_tile)) self.assertTrue(self.tile.at_distance(8, horizontally_aligned_tile)) self.assertTrue(self.tile.at_distance(7, vertically_aligned_tile)) self.assertFalse(self.tile.at_distance(8, vertically_aligned_tile)) self.assertFalse(self.tile.at_distance(1, diagonally_aligned_tile)) def test_direction_from(self): south_east_tile = Tile(5, 5) west_tile = Tile(1, 3) north_east_tile = Tile(5, 2) self.assertEqual(south_east_tile.direction_from(self.tile), (1, 1)) self.assertEqual(west_tile.direction_from(self.tile), (-1, 0)) self.assertEqual(north_east_tile.direction_from(self.tile), (1, -1)) def test_dead_end(self): tile = Tile(2, 2) west = Tile(1, 2) east = Tile(3, 2) north = Tile(2, 1) south = Tile(2, 3) tile.set_type("corridor") south.set_type("corridor") adjacents = [west, east, north, south] self.assertTrue(tile.dead_end(adjacents)) def test_not_dead_end(self): tile = Tile(2, 2) west = Tile(1, 2) east = Tile(3, 2) north = Tile(2, 1) south = Tile(2, 3) tile.set_type("corridor") south.set_type("corridor") north.set_type("corridor") adjacents = [west, east, north, south] self.assertFalse(tile.dead_end(adjacents))
def get_tile_connectivity(): """ Uses data from AHN3 to transform all tiles into polygons, then doing intersection tests to determine if tiles are in some way connected (done by checking if exterior of 2 polygons intersects). If it intersects, then a few more tests are done te determine on which side the intersection is. When it is done, it assigns the neighboring tile in the correct place in the Tile class. Note: Possibly there is a more efficient way to do intersection tests and determining where a tile is in respect to another tile. :return: Dictionary containing tile id as key and Tile class as value """ print("Getting AHN3 tile connectivity before starting...") data = get_ahn_index() if data is None: raise Exception("Could not retrieve tile data from AHN3 server") tiles = {} for tile in data: polygon = Polygon(tile['geometry']['coordinates'][0][0]) tiles[tile['properties']['bladnr'].upper()] = polygon output_tiles = {} for tile_name_1 in tiles.keys(): tile_poly_1 = tiles[tile_name_1] output_tiles[tile_name_1] = Tile(tile_name=tile_name_1, geometry=tile_poly_1) for tile_name_2 in tiles.keys(): if tile_name_1 != tile_name_2: # Don't check against same tile tile_poly_2 = tiles[tile_name_2] if tile_name_2 not in output_tiles.keys(): output_tiles[tile_name_2] = Tile(tile_name=tile_name_2, geometry=tile_poly_2) if tile_poly_1.touches(tile_poly_2): # Are neighbors intersection = tile_poly_1.exterior.intersection( tile_poly_2.exterior) # Some polygons have non-straight edges (MultiLineString), simplify them if intersection.geom_type == "MultiLineString": # Round any points that may cause floating point issues points = [ round(coord) for coord in list(intersection.bounds) ] intersection = LineString([points[:2], points[2:]]) if intersection.geom_type == "Point": # Is a single point of intersection (corner) if intersection.x < tile_poly_1.centroid.x: # Intersection is left of tile if intersection.y < tile_poly_1.centroid.y: # Intersection is below tile output_tiles[ tile_name_1]._bottom_left = output_tiles[ tile_name_2] else: output_tiles[ tile_name_1]._top_left = output_tiles[ tile_name_2] else: if intersection.y < tile_poly_1.centroid.y: # Intersection is above tile output_tiles[ tile_name_1]._bottom_right = output_tiles[ tile_name_2] else: output_tiles[ tile_name_1]._top_right = output_tiles[ tile_name_2] elif intersection.geom_type == "LineString": # Is a line of intersection (sides) if intersection.coords[0][0] == intersection.coords[1][ 0]: # X axis is unchanged if intersection.coords[0][ 0] < tile_poly_1.centroid.x: # Intersection is left of tile output_tiles[tile_name_1]._left = output_tiles[ tile_name_2] else: output_tiles[ tile_name_1]._right = output_tiles[ tile_name_2] else: if intersection.coords[0][ 1] < tile_poly_1.centroid.y: # Intersection is below tile output_tiles[ tile_name_1]._bottom = output_tiles[ tile_name_2] else: output_tiles[tile_name_1]._top = output_tiles[ tile_name_2] return output_tiles
def test_not_dead_end(self): tile = Tile(2, 2) west = Tile(1, 2) east = Tile(3, 2) north = Tile(2, 1) south = Tile(2, 3) tile.set_type("corridor") south.set_type("corridor") north.set_type("corridor") adjacents = [west, east, north, south] self.assertFalse(tile.dead_end(adjacents))
def clip_tile_by_subtiles(self): """ Uses las2las from LAStools in a subprocess to clip the provided main tile (self._tile) into the determined subtile grid. Has checks to determine which other tiles should be included in the las2las command. This prevents the unnecessary merging of extra AHN3 tiles. Creates as many subprocesses as there are subtiles and waits for them all to complete before closing the function. :return: None """ for subtile_id in range(1, len(self._subtiles) + 1): save_name = self._parent_tile.get_save_path( stage=Stages.SUBTILING, subtile_id=str(subtile_id), extension="LAS") subtile = self._subtiles[subtile_id - 1] tile_name = self._parent_tile.get_tile_name() subtile_name = tile_name + "_" + str(subtile_id) buffered_geometry = box(minx=subtile["buffered"][0], miny=subtile["buffered"][1], maxx=subtile["buffered"][2], maxy=subtile["buffered"][3]) unbuffered_geometry = box(minx=subtile["unbuffered"][0], miny=subtile["unbuffered"][1], maxx=subtile["unbuffered"][2], maxy=subtile["unbuffered"][3]) if os.path.exists( save_name) and self._to_overwrite or not os.path.exists( save_name): command = ['las2las', '-i', self._parent_tile.filepath] if subtile_id == 1: # Bottom left command.extend( self._connectivity[tile_name].get_bottom_left()) elif subtile_id == self._num_rows: # Top left command.extend( self._connectivity[tile_name].get_top_left()) elif subtile_id == self._num_rows * self._num_cols: # Top right command.extend( self._connectivity[tile_name].get_top_right()) elif subtile_id == (self._num_rows * self._num_cols ) - self._num_rows + 1: # Bottom right command.extend( self._connectivity[tile_name].get_bottom_right()) elif self._num_rows > subtile_id > 1: # Left side command.extend(self._connectivity[tile_name].get_left()) elif self._num_rows * self._num_cols > subtile_id > ( self._num_rows * self._num_cols) - self._num_rows + 1: # Right side command.extend(self._connectivity[tile_name].get_right()) elif subtile_id % self._num_rows == 0: # Top command.extend(self._connectivity[tile_name].get_top()) elif subtile_id % self._num_rows == 1: # Bottom (works as long as grid is relatively square command.extend(self._connectivity[tile_name].get_bottom()) command.extend([ '-merged', '-o', save_name, '-keep_xy', str(subtile["buffered"][0]), str(subtile["buffered"][1]), str(subtile["buffered"][2]), str(subtile["buffered"][3]) ]) print(command) process = subprocess.Popen(args=command, ) start_time = time.time() process.communicate() process.wait() print('{0}: Split tile "{1}" in {2} seconds.'.format( multiprocessing.current_process().name, subtile_name, str(round(time.time() - start_time, 2)))) self._subtiles[subtile_id - 1] = Tile( tile_name=subtile_name, geometry=buffered_geometry, tile_type=TileTypes.SUBTILE, unbuffered_geometry=unbuffered_geometry, parent_tile=self._parent_tile)
def setUp(self): self.tile = Tile(2, 3)