Beispiel #1
0
def test_constructor():
    """Test the constructor of the Tile class."""
    tile = Tile(150, 150, 100, 'white')
    assert tile.x == 150
    assert tile.y == 150
    assert tile.diameter == 100 * tile.COEFFICIENT
    assert tile.color == 'white'
Beispiel #2
0
	def new_game(self):
		self.board = Board(self.dimension)
		tile = Tile(None)
		tile.set_start_value()
		self.board.set_new_tile(tile)
		self.board.all_moves.append(self.board.board)
		self.update_board()
Beispiel #3
0
    def __init__(self, con, width, height, max_room_size, min_room_size, max_rooms,
            torch_radius, light_walls, algorithm):
        """Initialize the map to a width and height

        :width: width of the map
        :height: height of the map

        """
        self.dark_wall = tcod.Color(0, 0, 100)
        self.light_wall = tcod.Color(130, 110, 50)
        self.dark_ground = tcod.Color(50, 50, 150)
        self.light_ground = tcod.Color(200, 180, 50)

        self._torch_radius = torch_radius
        self._light_walls = light_walls
        self._algorithm = algorithm
        
        self._max_room_size = max_room_size
        self._min_room_size = min_room_size
        self._max_rooms = max_rooms

        self._width = width
        self._height = height
        self._map = [ [Tile(True) 
            for y in range(self._height) ]
                for x in range(self._width) ]

        self._fov_map = tcod.map_new(width, height)

        self._con = con
Beispiel #4
0
 def countTiles(self, tile):
     if self.interrupted or not self.extent.intersects(tile.toRectangle()):
         return
     if self.minZoom <= tile.z and tile.z <= self.maxZoom:
         if not self.renderOutsideTiles:
             for layer in self.layers:
                 t = QgsCoordinateTransform(
                     layer.crs(), QgsCoordinateReferenceSystem('EPSG:4326'))
                 if t.transform(layer.extent()).intersects(
                         tile.toRectangle()):
                     self.tiles.append(tile)
                     break
         else:
             self.tiles.append(tile)
     if tile.z < self.maxZoom:
         for x in xrange(2 * tile.x, 2 * tile.x + 2, 1):
             for y in xrange(2 * tile.y, 2 * tile.y + 2, 1):
                 self.mutex.lock()
                 s = self.stopMe
                 self.mutex.unlock()
                 if s == 1:
                     self.interrupted = True
                     return
                 subTile = Tile(x, y, tile.z + 1, tile.tms)
                 self.countTiles(subTile)
Beispiel #5
0
    def __init__(self):
        #  Screen setup
        self.width = 602
        self.height = 602
        self.win = pygame.display.set_mode((self.width, self.height))

        # CLock setup
        self.clock = pygame.time.Clock()

        # Tiles setup
        self.tile_width = 5
        self.tile_height = 5
        self.columns = self.width // self.tile_width
        self.rows = self.height // self.tile_height
        print(self.rows, self.columns)
        self.grid = []
        for j in range(self.rows):
            for i in range(self.columns):
                self.grid.append(Tile(i, j, self.tile_width, self.tile_height))
        self.grid[0].walls[0] = False
        self.grid[-1].walls[2] = False

        # Depth-first setup
        self.stack = []
        self.current = self.grid[0]

        # States setup
        self.generated = False
        self.solved = False
Beispiel #6
0
    def __init__(self, length, size, side, offset):
        self.length = length
        self.size = size
        self.side = side
        self.offset = offset

        self.tiles = list()
        self.highlighted_coords = list()
        self.tile_flip_lookup = dict()

        # ellipse width and height
        ellipse_len = self.side - self.offset
        center_offset = self.side // 2

        # initialize all tiles
        for i in range(self.size):
            initial_y = (i * self.side) + (i + 1) * self.offset
            temp_row = []
            for j in range(self.size):
                x_position = ((j + 1) * self.offset) + (j * self.side) + center_offset - self.offset // 2
                y_position = initial_y + center_offset - self.offset // 2

                ellipse_width = ellipse_height = ellipse_len - self.offset * 2
                temp_row.append(Tile(x_position, y_position, ellipse_width, ellipse_height, self.offset))

            self.tiles.append(temp_row)

        # set initial four tiles
        a, b = self.size // 2, self.size // 2 - 1
        self.tiles[b][b].set_color(COLOR_WHITE)
        self.tiles[a][a].set_color(COLOR_WHITE)
        self.tiles[b][a].set_color(COLOR_BLACK)
        self.tiles[a][b].set_color(COLOR_BLACK)
Beispiel #7
0
 def spawn_orb(self):
     ''' Places the Orb/Heart to the middle of the map '''
     x = self.map_size//2
     y = self.map_size//2
     self.heart_pos = (x, y)
     map_pos = x + y * self.map_size
     self.terrain_map[map_pos] = Tile(x, y, 'Orb', (244, 219, 168), self.tile_size, Sprite(textures['orb']), self.heart_hp, False, True)
Beispiel #8
0
 def create_tiles(self):
   for x in range(0,self.width):
     self.tiles.append([])
     for y in range(0,self.height):
       self.tiles[x].append(None)
       tile = Tile(x,y)
       self.tiles[x][y] = tile
Beispiel #9
0
    def generate_level(self):
        ''' Fills the map with sand tiles '''
        for y in range(self.map_size):
            for x in range(self.map_size):
                self.terrain_map[x + y * self.map_size] = Tile(x, y, 'Sand', (244, 219, 168), self.tile_size)

        self.spawn_orb()
Beispiel #10
0
 def __iter__(self):
     
     for x in self.longitudeRange.atZoom(self.zoom):
         for y in self.latitudeRange.atZoom(self.zoom):
             tile = Tile(self.mapType, config.STYLE_ID, config.RESOLUTION, self.zoom, x, y)
             yield tile
     raise StopIteration
Beispiel #11
0
 def generateEmptyTileset(self, x, y):
     colorSwitch = Toggle(False)
     
     for i in range(x):
         l = []
         
         for j in range(y):
             t = Tile()
             
             t.generate()
             
             #color switcher
             t.setTexture("misc/grass")
             
             #setting right coordinates
             t.setX(i-(x/2))
             t.setY(j-(y/2))
             #reparenting to grid node
             t.node.reparentTo(self.node)
             
             #appending to list
             l.append(t)
                 
                 
         self.tileset.append(l)
Beispiel #12
0
    def __init__(self, path_or_data: Union[Path, Dict]):

        # Create a new dictionary from the data
        if isinstance(path_or_data, Path):
            data = json.loads(path_or_data.read_text())
            data["name"] = path_or_data.name
        else:
            data = path_or_data.copy()  # avoid mutating the input data

        # Convert raw symbols and tiles (simple lists of integers) into appropriate objects
        d = {s[0]: Symbol(*s) for s in enumerate(data.pop("symbol_weights"))}
        data["symbols"] = frozenset(d.values())
        data["tiles"] = [Tile([d[i] for i in t]) for t in data.pop("tiles")]

        # Populate the other fields without touching the raw values
        self.name = data.get("name")
        self.height = data["height"]
        self.symbol_weight_bound = data["symbol_weight_bound"]
        self.symbol_count = data["symbol_count"]
        self.symbols = data["symbols"]
        self.tiles = data["tiles"]

        # Add some calculated attributes
        self.symbol_weight_sum = sum(symbol.weight for symbol in self.symbols)
        self.tile_count = len(self.tiles)
Beispiel #13
0
    def generate_random_tile(self, pos):
        num_weight = 50
        op_weight = 10
        eq_weight = 20
        total_weight = num_weight + op_weight + eq_weight

        rand = random.uniform(0, 1)

        if (self.none_counter <= 2) & (self.equals_counter < self.equals_min):
            tile = Tile("equals", "=")
            self.board[pos[0]][pos[1]] = tile
            self.equals_counter += 1

        elif (self.none_counter <= 3) & (self.op_counter < self.op_min):
            opdict = {"+": "add", "-": "minus"}

            tile_value = random.choice(["+", "-"])

            tile = Tile(opdict[tile_value], tile_value)
            self.board[pos[0]][pos[1]] = tile
            self.op_counter += 1

        elif (rand < eq_weight / total_weight) & (self.equals_counter <
                                                  self.equals_max):
            tile = Tile("equals", "=")
            self.board[pos[0]][pos[1]] = tile
            self.equals_counter += 1

        elif (rand < (eq_weight + op_weight) / total_weight) & (self.op_counter
                                                                < self.op_max):
            opdict = {"+": "add", "-": "minus"}

            tile_value = random.choice(["+", "-"])

            tile = Tile(opdict[tile_value], tile_value)
            self.board[pos[0]][pos[1]] = tile
            self.op_counter += 1

        else:
            numdict = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five"}

            tile_number = random.randint(1, 5)

            tile = Tile(numdict[tile_number], tile_number)
            self.board[pos[0]][pos[1]] = tile

        self.none_counter -= 1
Beispiel #14
0
def add_center_duchy(size_list, allowable_chunks, a_dist, b_dist, ranking):
    '''Given a list of necessary sizes (size_list), and a list of list of hexes (allowable_chunks), 
    attempt to create a center duchy, where counties are adjacent to both a and b (has a hex with 1 a_dist and 1 b_dist).
    Ranking is a dictionary of all (base) elements in allowable_chunks.
    Returns False if it doesn't find a solution in time.'''
    size = sum(size_list)
    while len(allowable_chunks) > 0:
        chunk = allowable_chunks.pop(0)
        if len(chunk) >= size:
            poss_centers = sort_hexlist([
                el for el in chunk
                if all([nel in chunk for nel in el.neighbors()])
            ], ranking)
            a_adj = sort_hexlist([el for el in chunk if a_dist[el] == 1],
                                 ranking)
            b_adj = sort_hexlist([el for el in chunk if b_dist[el] == 1],
                                 ranking)
            for center in poss_centers:
                duchy = Tile(hex_list=[],
                             tile_list=[
                                 make_capital_county(size_list[0],
                                                     origin=center,
                                                     coastal=False)
                             ],
                             rgb=d_col())
                c_nbrs = [
                    el for el in duchy.tile_list[0].neighbors() if el in chunk
                ]
                drhl = duchy.real_hex_list()
                a_county = add_center_county(
                    size_list[1], c_nbrs, a_adj,
                    [el for el in chunk if el not in drhl])
                if a_county:
                    duchy.add_tile(a_county)
                else:
                    continue
                drhl = duchy.real_hex_list()
                c_nbrs = [
                    el for el in duchy.tile_list[0].neighbors()
                    if el in chunk and el not in drhl
                ]
                b_county = add_center_county(size_list[2],
                                             duchy.tile_list[0].neighbors(),
                                             b_adj, chunk)
                if b_county:
                    duchy.add_tile(b_county)
                else:
                    continue
                for _ in range(20):
                    try:
                        duchy.add_bordering_tile(size_list[3],
                                                 rgb=c_col(),
                                                 only=chunk,
                                                 ranking=ranking)
                        break
                    except:
                        continue
                return duchy
    return False
Beispiel #15
0
    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()
        if self.mode == 'DIR':
            self.writer = DirectoryWriter(self.output, self.rootDir)
            if self.mapurl:
                self.writeMapurlFile()
            if self.viewer:
                self.writeLeafletViewer()
        elif self.mode == 'ZIP':
            self.writer = ZipWriter(self.output, self.rootDir)
        elif self.mode == 'NGM':
            self.writer = NGMArchiveWriter(self.output, self.rootDir)
        elif self.mode == 'MBTILES':
            self.writer = MBTilesWriter(self.output, self.rootDir, self.format,
                                        self.minZoom, self.maxZoom,
                                        self.extent, self.mbtilesCompression)
        if self.jsonFile:
            self.writeJsonFile()
        if self.overview:
            self.writeOverviewFile()
        self.rangeChanged.emit(self.tr('Searching tiles...'), 0)
        useTMS = 1
        if self.tmsConvention:
            useTMS = -1
        self.countTiles(Tile(0, 0, 0, useTMS))

        if self.interrupted:
            del self.tiles[:]
            self.tiles = None
            self.processInterrupted.emit()
        self.rangeChanged.emit(self.tr('Rendering: %v from %m (%p%)'),
                               len(self.tiles))

        if len(self.tiles) > self.warring_threshold_tiles_count:
            self.confirmMutex.lock()
            self.threshold.emit(self.warring_threshold_tiles_count)

        self.confirmMutex.lock()
        if self.interrupted:
            self.processInterrupted.emit()
            return

        for t in self.tiles:
            self.render(t)
            self.updateProgress.emit()
            self.mutex.lock()
            s = self.stopMe
            self.mutex.unlock()
            if s == 1:
                self.interrupted = True
                break

        self.writer.finalize()
        if not self.interrupted:
            self.processFinished.emit()
        else:
            self.processInterrupted.emit()
Beispiel #16
0
 def addTile(self, image, source=QString()):
     newTile = Tile(image, source, self.tileCount(), self)
     self.mTiles.append(newTile)
     if (self.mTileHeight < image.height()):
         self.mTileHeight = image.height()
     if (self.mTileWidth < image.width()):
         self.mTileWidth = image.width()
     return newTile
Beispiel #17
0
 def initTiles(self):
     print("Initializing Tiles...")
     for id in range(19):
         tile = Tile()
         self.tiles.append(tile)
         #TODO take care of the tile-vertex association with the getNeighbours funciton
         h.addTiles(self, id, tile)
     return
Beispiel #18
0
 def choose_tile(q):
     tiles = []
     for data in [
             tile.strip().split('-')
             for tile in q[q.index('[') + 1:q.index(']')].split(',')
     ]:
         tiles.append(Tile(data[0], data[1], data[2]))
     return tiles
Beispiel #19
0
    def test_same(self):
        grid1 = Grid()
        grid2 = grid1.clone()
        grid3 = grid2.clone()
        grid4 = grid3.clone()
        grid2.setCell(Tile({"x": 0, "y": 0}, 8))
        grid3.setCell(Tile({"x": 0, "y": 0}, 8))

        # grid1.gprint()
        # grid2.gprint()
        # grid3.gprint()
        # grid4.gprint()

        assert (grid1.same(grid2) == False)
        assert (grid2.same(grid3) == True)
        assert (grid3.same(grid4) == False)
        assert (grid4.same(grid1) == True)
    def test_initialize_board_padding(self):
        # Test successful initialize board with need for padding

        # Invalid json board representation
        valid_json = json.loads("[[1], [1, 2], [0, 2, 3]]")

        # Board obtained from the initialize_board function
        result_board = xboard.initialize_board(valid_json)

        # Test properties of the board
        self.assertTrue(isinstance(result_board, Board))
        self.assertEquals(result_board.rows, 3)
        self.assertEquals(result_board.cols, 3)
        self.assertEquals(result_board.tile_no, 9)

        # Expected tile dict
        expected_tiles = \
        {
            Position(0, 0): Tile(1),
            Position(0, 1): Hole(),
            Position(0, 2): Hole(),
            Position(1, 0): Tile(1),
            Position(1, 1): Tile(2),
            Position(1, 2): Hole(),
            Position(2, 0): Hole(),
            Position(2, 1): Tile(2),
            Position(2, 2): Tile(3)
        }

        # Verify all the positions in the board are the same as expected
        self.assertCountEqual(expected_tiles.keys(), result_board.tiles.keys())

        # Verify that all tiles have the correct number of fish
        for key in expected_tiles:
            tile = expected_tiles[key]

            # Tile on initialized board
            actual_tile = result_board.get_tile(key)

            # Assert both tiles are the same type
            self.assertEqual(tile.is_tile, actual_tile.is_tile)

            # If the tiles are both tiles, assert that the ones on the board
            # have the expected number of fish
            if tile.is_tile:
                self.assertEqual(tile.fish_no, actual_tile.fish_no)
Beispiel #21
0
def create_wall(x, y, tiles_data):
    tile = (Tile(x, y, 'Cave Wall', tiles_data['Cave Wall']['image'],
                 tiles_data['Cave Wall']['color_fg'],
                 tiles_data['Cave Wall']['color_bg'],
                 tiles_data['Cave Wall']['walkable'],
                 tiles_data['Cave Wall']['blocksLOS']))

    return tile
Beispiel #22
0
 def expand(self, tile):
     for outcome in Mover.possible_moves(tile):
         if (outcome.layout == Tile().layout):
             return outcome.history
         if (self.original.layout != outcome.layout and
             (tile.history == [] or outcome.layout != tile.history[-1])):
             self.queue.insert(outcome,
                               self.gofH(outcome) + len(tile.history))
Beispiel #23
0
    def __init__(self, game, w, h, group, height):
        self.tiles = []
        super().__init__(game, w, h)

        self.height = height
        self.col = (255, 255, 255)

        if height == -1:
            self.tiles.append(Tile(game, w, h, 0, group, 'water'))
        else:
            for z in range(height):
                self.tiles.append(
                    Tile(game, w, h, z * game.CELL_Z, group, 'dirt'))

            tile = 'dirt' if random.randint(0, 3) > height else 'grass'
            self.tiles.append(
                Tile(game, w, h, height * game.CELL_Z, group, tile))
Beispiel #24
0
def test_all_legal_moves():
    """Test all_legal_moves method.
    When the game is initialized, there are four legal moves
    for either black or white tile"""
    tile = Tile()
    computer = Computer(tile)
    legal_move = computer.all_legal_moves()
    assert legal_move == [(2, 3), (3, 2), (4, 5), (5, 4)]
Beispiel #25
0
 def initialize_board(self):
     randomBoard = []
     for row in range(self.YDIM):
         randomBoard.append([])
         for column in range(self.XDIM):
             randomFruit = random.choices(self.FRUITS, weights= self.WEIGHTS, k = 1)[0]
             randomBoard[row].append(Tile(self, row, column, randomFruit))
     return randomBoard
Beispiel #26
0
 def test_manhattan_distance_yields_two(self):
     results = Tile()
     results.layout = [
         [1, 3, 0],
         [8, 2, 4],
         [7, 6, 5],
     ]
     self.assertEqual(self.metrics.manhattan(results), 2)
Beispiel #27
0
 def test_manhattan_distance_yields_fourteen(self):
     results = Tile()
     results.layout = [
         [2, 4, 0],
         [8, 6, 7],
         [5, 1, 3],
     ]
     self.assertEqual(self.metrics.manhattan(results), 14)
Beispiel #28
0
 def transform(self, tile):
     result = [[], [], []]
     for i in range(len(tile.layout)):
         for j in range(len(tile.layout[0])):
             result[i].append(tile.layout[j][i])
     t = Tile()
     t.layout = result
     return t
Beispiel #29
0
def generate_random_node2():
    num = randrange(1, 17)
    board = Board()
    b = [[0 for i in range(4)] for j in range(4)]
    board.board = b
    for i in range(num):
        board.set_new_tile(Tile(2**randrange(12)))
    return board
Beispiel #30
0
 def displaced(self, tile):
     goal = Tile()
     total = 0
     for rowIndex, row in enumerate(tile.layout):
         for squareIndex, square in enumerate(row):
             if square != 0 and square != goal.layout[rowIndex][squareIndex]:
                 total += 1
     return total