def _generate_hexes(width: int, height: int, initial_x: float = 0, initial_y: float = 0, hex_size: float = 50) -> List[HexTile]: """Generate a hexmap of size (width x height) in hexes.""" # Create one tile to use its measurements later on. tile = HexTile(initial_x, initial_y, hex_size) tiles = [] for n_row, n_column in product(range(height), range(width)): # Offset hexes to the right in odd rows. offset = 0.5 * tile.width if n_row % 2 == 1 else 0 # Vertical space is smaller than tile's full height for hexes. vertical_space = tile.height * 0.75 tiles.append( HexTile( initial_x + n_column * tile.width + offset, initial_y + n_row * vertical_space, hex_size, # Set up even X-coordinates for even rows by doubling. # In odd rows, offset them by 1. n_column * 2 + (1 if offset else 0), n_row, HexType.Sea # if randint(0, 1) == 0 else HexType.Land )) return tiles
def test_corner_math(position, size, expected): # Prepare a hex tile for testing. x, y = position hex_tile = HexTile(_x_position=x, _y_position=y, _size=size) for corner in hex_tile.corners: (x, y) = corner assert (x, y) in expected
def pixel2hex(self, pixel_x: float, pixel_y: float) -> HexTile: """Find hex in this map by pixel location (i.e. a mouse click).""" # First find coordinates without the initial offset from top-left. base_x, base_y = self._first_hex x = pixel_x - base_x y = pixel_y - base_y # Find hex's position in (q, r) axis. # Math src: https://www.redblobgames.com/grids/hexagons/#pixel-to-hex q_axis = (sqrt(3) / 3 * x - 1 / 3 * y) / self._hex_size r_axis = (2 / 3 * y) / self._hex_size # Convert coords axial -> cube, round them to the closest hex, # convert from cube back to axial and then to doubled 0_0. coords = HexTile.axial2doubled( HexTile.cube2axial( HexTile.round_cube(HexTile.axial2cube((q_axis, r_axis))))) return self.get_hex(coords)
def _draw_hex(screen): """Draw one hex on the screen.""" # Initialize one hex and draw it on the screen. my_tile = HexTile(350, 350, 50) pygame.draw.polygon(screen, COLORS[HexType.Land], my_tile.corners)
def test_doubled_axial_counversion(doubled: DoubledCoords, axial: AxialCoords): assert HexTile.doubled2axial(doubled) == axial assert HexTile.axial2doubled(axial) == doubled
def hex_100_size() -> HexTile: return HexTile(_size=100)
def default_hex() -> HexTile: return HexTile()
def test_axial_cube_conversion(axial: AxialCoords, cube: CubeCoords): assert HexTile.axial2cube(axial) == cube assert HexTile.cube2axial(cube) == axial