World > HexWorld

Contents

World > HexWorld#

API Reference#

class miniworlds.worlds.hex_world.hex_world.HexWorld(x=20, y=16, tile_size=40, empty=False)[source]#

A world that consists of hexagonal tiles.

Hexes are addressed with offset coordinates (column, row), like tiles in a TiledWorld. Odd rows are shifted half a hex to the right (pointy-top layout). Actors can also be placed on corners (shared by up to three hexes) or edges (shared by two hexes).

The six neighbors of a hex are reached with the directions “o”, “so”, “sw”, “w”, “nw”, “no”. Because odd rows are shifted, the diagonal neighbors depend on the row parity:

  • Odd rows: “no” and “so” point to (column + 1, row - 1) and (column + 1, row + 1), while “nw” and “sw” point to (column, row - 1) and (column, row + 1).

  • Even rows: “no” and “so” point to (column, row - 1) and (column, row + 1), while “nw” and “sw” point to (column - 1, row - 1) and (column - 1, row + 1).

“o” and “w” always point to (column + 1, row) and (column - 1, row).

Examples

from miniworlds import HexWorld, Actor

world = HexWorld(7, 7, tile_size=40)
actor = Actor((3, 3))
actor.fill_color = (255, 0, 0)

world.run()
__init__(x=20, y=16, tile_size=40, empty=False)[source]#

Create a hex world.

Parameters:
  • x – Number of columns.

  • y – Number of rows.

  • tile_size – The hex size in pixels (circumradius of the hex).

  • empty – If True, tiles, edges, and corners are not created automatically.

clear_highlights(tiles=None)[source]#

Remove highlights.

Return type:

None

Parameters:

tiles – Tiles or hex positions to clear. Without it, all highlights are removed.

Examples

world.clear_highlights()
dialog#
find_nearest(start, is_target, blocked=None, cost=None, max_cost=None, include_start=False)[source]#

Return the path to the nearest hex that satisfies is_target.

The nearest hex is the cheapest one to reach, not the one with the smallest hex distance. A target may be blocked (for example an enemy that blocks its hex): the path ends on it.

Return type:

List[HexTile]

Parameters:
  • start – Start hex as position, tile, or actor.

  • is_target – Function is_target(tile) -> bool.

  • blocked – Optional blocked(tile) -> bool, see find_path.

  • cost – Optional cost(tile) -> float, see find_path.

  • max_cost – Optional budget; more expensive targets are ignored.

  • include_start – If True, the start hex can be the target.

Returns:

The tiles from start to the nearest target, both included, or an empty list if no target is reachable.

Examples

path = world.find_nearest(robot, lambda tile: tile.terrain == "forest")
if path:
    robot.position = path[1].position
find_path(start, goal, blocked=None, cost=None, max_cost=None, min_cost=None)[source]#

Return the cheapest path between two hexes.

Entering a tile costs tile.cost (default 1). A tile is impassable if tile.is_blocking is set or an actor with is_blocking = True stands on it. The goal must be passable.

Return type:

List[HexTile]

Parameters:
  • start – Start hex as position, tile, or actor.

  • goal – Goal hex as position, tile, or actor.

  • blocked – Optional function blocked(tile) -> bool that replaces the default blocking rule.

  • cost – Optional function cost(tile) -> float that replaces tile.cost. Costs must not be negative.

  • max_cost – Optional budget; more expensive paths are not returned.

  • min_cost – Cheapest step cost of a custom cost function; speeds up the search. Too large values can return non-optimal paths.

Returns:

The tiles from start to goal, both included, or an empty list if there is no path.

Raises:

TileNotFoundError – If start or goal is not a tile of the world.

Examples

world.get_tile((2, 2)).is_blocking = True   # water
path = world.find_path((0, 0), (5, 4))
for tile in path:
    tile.highlight()
get_actors_from_pixel(position)[source]#

Return all actors under a screen pixel.

Actors on the hex tile under the pixel are returned, plus actors on corners or edges whose center lies within the detection radius (tile_size / 3, same as actor.detect_pixel) of the pixel.

The pixel is translated to world pixels first, so the query also works while the camera is scrolled or the world is docked next to other worlds. Corner and edge actors are detected without a tile under the pixel, so roads and settlements on the border of the world remain clickable.

Parameters:

position – Pixel position as (x, y).

Returns:

Actors located under the pixel. An empty list if no actor is under the pixel.

Examples

actors = world.get_actors_from_pixel(mouse_pos)
get_center_points()[source]#

Return a mapping of hex positions to their center pixels.

Return type:

Dict[Tuple[int, int], Tuple[float, float]]

get_corner(position, direction=None)[source]#

Return a corner by corner position or hex position plus direction.

Parameters:
  • position – Corner position, or hex position when direction is set.

  • direction – Optional corner direction, e.g. “no”.

Returns:

The matching corner.

Raises:

CornerNotFoundError – If no corner exists at the resolved position.

Examples

corner = world.get_corner((3, 3), "no")
get_corner_from_pixel(position)[source]#

Return the corner nearest to a screen pixel.

The pixel is translated to world pixels first, so the query also works while the camera is scrolled or the world is docked next to other worlds. Pixels near the border of the world pick from the border hexes, so corners on the border (settlement positions on a Catan board) remain clickable.

Parameters:

position – Pixel position as (x, y).

Returns:

The nearest corner, or None if the pixel is outside the camera view or outside the world.

Examples

corner = world.get_corner_from_pixel(mouse_pos)
get_distance(first, second)[source]#

Return the hex distance (number of steps) between two hexes.

The distance does not depend on the row parity and ignores blocked tiles; use find_path to count steps around obstacles.

Return type:

int

Parameters:
  • first – Hex position, tile, or actor.

  • second – Hex position, tile, or actor.

Returns:

The number of hexes you have to step from first to second.

Examples

if world.get_distance(robot, goal) <= 2:
    print("Goal in reach")
get_edge(position, direction=None)[source]#

Return an edge by edge position or hex position plus direction.

Parameters:
  • position – Edge position, or hex position when direction is set.

  • direction – Optional edge direction, e.g. “o”.

Returns:

The matching edge.

Raises:

EdgeNotFoundError – If no edge exists at the resolved position.

Examples

edge = world.get_edge((3, 3), "o")
get_edge_from_pixel(position)[source]#

Return the edge nearest to a screen pixel.

The pixel is translated to world pixels first, so the query also works while the camera is scrolled or the world is docked next to other worlds. Pixels near the border of the world pick from the border hexes, so edges on the border (road positions on a Catan board) remain clickable.

Parameters:

position – Pixel position as (x, y).

Returns:

The nearest edge, or None if the pixel is outside the camera view or outside the world.

Examples

edge = world.get_edge_from_pixel(mouse_pos)
get_from_pixel(position)[source]#

Return the hex position for a screen pixel.

The pixel is translated to world pixels first, so the query also works while the camera is scrolled or the world is docked next to other worlds.

Parameters:

position – Pixel position as (x, y).

Returns:

Hex position as (column, row), or None if the pixel lies outside the camera view or outside the world.

Examples

hex_position = world.get_from_pixel((80, 120))
get_path_cost(path, cost=None)[source]#

Return the cost of a path (the first hex is not counted).

Return type:

float

Parameters:
  • path – A list of tiles, for example the result of find_path.

  • cost – Optional cost(tile) -> float, see find_path.

Examples

path = world.find_path((0, 0), (5, 3))
print(world.get_path_cost(path))
get_reachable_tiles(start, max_cost, blocked=None, cost=None)[source]#

Return all hexes reachable within a movement budget.

With default costs max_cost is the number of steps; blocked tiles are walked around, so the result can be smaller than get_tiles_in_radius.

Return type:

List[HexTile]

Parameters:
  • start – Start hex as position, tile, or actor.

  • max_cost – Movement budget.

  • blocked – Optional blocked(tile) -> bool, see find_path.

  • cost – Optional cost(tile) -> float, see find_path.

Returns:

The reachable tiles including the start tile, ordered from the cheapest to the most expensive.

Examples

for tile in world.get_reachable_tiles(robot.position, 3):
    tile.highlight((0, 200, 0, 80))
get_tile_from_pixel(position)[source]#

Return the hex tile under a screen pixel.

The pixel is translated to world pixels first, so the query also works while the camera is scrolled or the world is docked next to other worlds.

Parameters:

position – Pixel position as (x, y).

Returns:

The registered hex tile under the pixel (the same object as world.get_tile(…)), or None if the pixel lies outside the world (no tile exists at the rounded hex position).

Examples

tile = world.get_tile_from_pixel((80, 120))
if tile is not None:
    tile.fill_color = (255, 0, 0)
get_tiles_in_line(start, end)[source]#

Return the tiles on the straight line between two hexes.

Both ends are included. Positions of the line outside the world are skipped. Together with tile.is_blocking this answers line-of-sight questions.

Return type:

List[HexTile]

Parameters:
  • start – Hex position, tile, or actor.

  • end – Hex position, tile, or actor.

Returns:

The tiles from start to end.

Examples

visible = all(
    not tile.is_blocking
    for tile in world.get_tiles_in_line(archer, target)
)
get_tiles_in_radius(position, radius, include_center=True)[source]#

Return all tiles within a hex distance of radius.

The result is independent of the row parity described in the HexWorld docstring. Offsets of a ring are computed once per row parity and radius, so repeated queries are cheap.

Return type:

List[HexTile]

Parameters:
  • position – Hex position (column, row), a tile, or an actor.

  • radius – Maximum hex distance (0 includes only the tile itself).

  • include_center – If False, the tile at position is left out.

Returns:

List of tiles within the radius, ordered from the center outwards in ring traversal order. Positions outside the world are skipped.

Raises:

TypeError – If radius or position has the wrong type.

Examples

neighbours = world.get_tiles_in_radius((3, 3), 1)
around = world.get_tiles_in_radius((3, 3), 2, include_center=False)
get_tiles_in_ring(position, radius)[source]#

Return all tiles at exactly radius hex distance.

The result is independent of the row parity described in the HexWorld docstring.

Return type:

List[HexTile]

Parameters:
  • position – Hex position (column, row), a tile, or an actor.

  • radius – Hex distance.

Returns:

List of tiles at the given distance, in ring traversal order starting at the westernmost hex of the ring. Positions outside the world are skipped.

Raises:

TypeError – If radius or position has the wrong type.

Examples

ring = world.get_tiles_in_ring((3, 3), 2)
has_line_of_sight(start, goal, blocked=None)[source]#

Return whether no blocked hex lies on the line between two hexes.

The line is the one of get_tiles_in_line. Only the hexes strictly between start and goal count; a blocked goal can still be seen.

Return type:

bool

Parameters:
  • start – Start hex as position, tile, or actor.

  • goal – Goal hex as position, tile, or actor.

  • blocked – Optional blocked(tile) -> bool, see find_path.

Examples

if world.has_line_of_sight(guard, player):
    print("spotted")
highlight_tiles(tiles, color=(255, 255, 0, 90))[source]#

Highlight hexes with a translucent color.

The highlights are drawn on the background below the actors and stay until clear_highlights is called.

Return type:

None

Parameters:
  • tiles – Tiles or hex positions.

  • color – RGB or RGBA color; with RGB a default transparency is used.

Examples

world.highlight_tiles(world.get_tiles_in_radius((3, 3), 1))
property hovered_tile#

The hex under the mouse, or None.

The value is kept up to date while the world has an on_tile_enter or on_tile_leave handler (or on_mouse_motion).

Examples

@world.register
def on_mouse_left(self, mouse_pos):
    if world.hovered_tile is not None:
        print(world.hovered_tile.position)
is_hex = True#
to_pixel(position, size=(0, 0), origin=(0, 0))[source]#

Convert a hex position to the pixel position of its center.

Parameters:
  • position – Hex position as (column, row).

  • size – Reserved for compatibility.

  • origin – Pixel offset added to the converted position.

Returns:

Pixel position as (x, y).

Examples

pixel = world.to_pixel((2, 3))
view_position_ranges(camera_rect)[source]#

Return position ranges covering camera_rect for index queries.

Positions on a hex world live in three different coordinate spaces: tiles in offset coordinates (column, row), corners in tripled cube coordinates, and edges in doubled cube coordinates. The chunk key of the tiled spatial index is derived from the raw position, so one range per space is returned. Every actor whose pixel rect may intersect the camera rect is covered by one of the ranges, while each range stays bounded by the visible window.

Parameters:

camera_rect – Camera rectangle in world pixels.

Returns:

A list of ((min_x, min_y), (max_x, max_y)) position pair ranges, covering tile, corner, and edge positions.

Examples

ranges = world.view_position_ranges(world.camera.rect)
class miniworlds.worlds.hex_world.hex_tile.HexTile(position, world=None)[source]#

A hexagonal tile in a HexWorld.

Tiles are addressed with offset coordinates (column, row), like tiles in a TiledWorld. Odd rows are shifted half a hex to the right; because of this shift, the diagonal neighbors of a hex depend on the row parity (see the HexWorld docstring for the full convention).

clear_highlight()[source]#

Remove the highlight of this hex.

Return type:

None

corner_vectors: OrderedDict[str, Tuple[float, float]] = {'n': (1, -2, 1), 'no': (2, -1, -1), 'nw': (-1, -1, 2), 's': (-1, 2, -1), 'so': (1, 1, -2), 'sw': (-2, 1, 1)}#
distance_to(other)[source]#

Return the hex distance to another tile (same as get_distance_to).

The rectangular Tile.distance_to measures the euclidean distance of the offset coordinates, which is wrong on a hex grid because of the shifted rows.

Return type:

int

edge_vectors: dict[str, Tuple[float, float]] = {'no': (1, -1, 0), 'nw': (0, -1, 1), 'o': (1, 0, -1), 'so': (0, 1, -1), 'sw': (-1, 1, 0), 'w': (-1, 0, 1)}#
classmethod from_pixel(pixel_position, world=None)[source]#

Return the hex tile containing a pixel position.

The conversion is exact: the pixel is converted to fractional cube coordinates and rounded to the nearest hex center. The position is not checked against the world bounds; use world.get_tile_from_pixel for a bounds-checked lookup that returns None outside the world.

Return type:

HexTile

classmethod from_position(position, world)[source]#

Create a tile from a world-relative position.

Return type:

HexTile

get_corner(direction)[source]#

Return the corner of this hex in the given direction.

Return type:

HexCorner

Parameters:

direction – Corner direction, e.g. “no”.

Examples

corner = world.get_tile((2, 2)).get_corner("no")
get_distance_to(other)[source]#

Return the hex distance (number of steps) to a tile, position, or actor.

Return type:

int

Examples

steps = tile.get_distance_to(goal_tile)
get_edge(direction)[source]#

Return the edge of this hex in the given direction.

Return type:

HexEdge

Parameters:

direction – Edge direction, e.g. “o”.

Examples

edge = world.get_tile((2, 2)).get_edge("o")
static get_local_center_coordinate(world)[source]#

Returns the center point offset for a tile, in local pixel coordinates.

Return type:

Tuple[float, float]

get_local_corner_points()[source]#

Return the six corner pixels relative to the hex bounding box topleft.

Return type:

List[Tuple[float, float]]

get_neighbour(direction)[source]#

Return the neighboring hex in one direction, or None at the border.

Return type:

Optional[HexTile]

Parameters:

direction – One of “o”, “so”, “sw”, “w”, “nw”, “no”.

Raises:

DirectionNotFoundError – If direction is not a hex direction.

Examples

east = world.get_tile((3, 3)).get_neighbour("o")
if east is not None:
    east.highlight()
get_neighbour_corners()[source]#

Return the six corners of this hex, clockwise from the top tip.

Return type:

List[HexCorner]

Examples

for corner in world.get_tile((2, 2)).get_neighbour_corners():
    print(corner.position)
get_neighbour_edges()[source]#

Return the six edges of this hex, clockwise from the north-east edge.

Return type:

List[HexEdge]

Examples

for edge in world.get_tile((2, 2)).get_neighbour_edges():
    print(edge.position)
get_neighbour_tiles()[source]#

Return the up to six neighboring hex tiles.

The list is a copy; changing it does not affect the world.

Return type:

List[HexTile]

static get_position_pixel_dict(world)[source]#

Returns a mapping of tile positions to pixel coordinates.

Return type:

dict

get_tiles_in_radius(radius, include_center=False)[source]#

Return the tiles within radius steps of this hex.

Unlike world.get_tiles_in_radius, the tile itself is not included by default, so get_tiles_in_radius(1) returns the same tiles as get_neighbour_tiles() (in ring order instead of direction order).

Return type:

List[HexTile]

Parameters:
  • radius – Maximum hex distance.

  • include_center – If True, this tile is the first result.

Examples

for tile in world.get_tile((3, 3)).get_tiles_in_radius(2):
    tile.highlight()
get_tiles_in_ring(radius)[source]#

Return the tiles at exactly radius steps from this hex.

Return type:

List[HexTile]

Examples

ring = world.get_tile((3, 3)).get_tiles_in_ring(2)
highlight(color=(255, 255, 0, 90))[source]#

Highlight this hex with a translucent color.

The highlight is drawn on the world background below the actors and stays until clear_highlight is called.

Return type:

None

Parameters:

color – RGB or RGBA color; with RGB a default transparency is used.

Examples

@world.register
def on_tile_enter(self, tile):
    tile.highlight((255, 255, 255, 80))

@world.register
def on_tile_leave(self, tile):
    tile.clear_highlight()
property is_highlighted: bool#

Whether this hex is currently highlighted.

Type:

bool

tile_vectors: dict[str, Tuple[int, int]] = {'no': (1, -1, 0), 'nw': (0, -1, 1), 'o': (1, 0, -1), 'so': (0, 1, -1), 'sw': (-1, 1, 0), 'w': (-1, 0, 1)}#
to_center()[source]#

Return the center pixel of the hex.

Return type:

Tuple[float, float]

to_pixel()[source]#

Return the topleft pixel of the hex bounding box.

Return type:

Tuple[float, float]

class miniworlds.worlds.hex_world.hex_corner.HexCorner(position, direction, world=None)[source]#

A corner of a hex, shared by up to three hexes.

The corner position is a unique key in tripled cube coordinates: all hexes that share the corner compute the same key, so corners are merged when the world is built.

angles: Dict[str, int] = {'n': 0, 'no': 1, 'nw': 5, 's': 3, 'so': 2, 'sw': 4}#
direction_angles: Dict[str, int] = {'n': 0, 'no': 0, 'nw': 0, 's': 0, 'so': 0, 'sw': 0}#
static direction_vectors()[source]#

Returns the available directions.

classmethod from_position(position, world)[source]#

Create a tile delimiter (override expected).

Return type:

HexCorner

get_neighbour_corners()[source]#

Return the corners one hex side away (up to three).

This is the “distance rule” of Catan: a settlement may only be built if no neighbouring corner holds one. Corners outside the world are skipped.

Return type:

List[HexCorner]

Examples

for corner in world.get_corner((3, 3), "n").get_neighbour_corners():
    print(corner.position)
get_neighbour_edges()[source]#

Return the edges that meet at this corner (up to three).

Edges outside the world are skipped.

Return type:

List[HexEdge]

Examples

roads = corner.get_neighbour_edges()
get_neighbour_tiles()[source]#

Return the up to three hexes that share this corner.

The hexes are derived from the merged corner references, so no tile has to exist for every reference: references to positions outside the world are skipped.

Return type:

List[HexTile]

start_angle()[source]#

Override: starting angle offset for layouting (e.g. hex rotation).

Return type:

int

to_pixel()[source]#

Return the pixel position of the corner.

Return type:

Tuple[float, float]

class miniworlds.worlds.hex_world.hex_edge.HexEdge(position, direction, world=None)[source]#

An edge of a hex, shared by exactly two hexes.

The edge position is a unique key in doubled cube coordinates: both hexes that share the edge compute the same key, so edges are merged when the world is built.

angles: Dict[str, int] = {'no': 5, 'nw': 4, 'o': 0, 'so': 1, 'sw': 2, 'w': 3}#
direction_angles: Dict[str, int] = {'no': 300, 'nw': 240, 'o': 0, 'so': 60, 'sw': 120, 'w': 180}#
static direction_vectors()[source]#

Returns the available directions.

classmethod from_position(position, world)[source]#

Create a tile delimiter (override expected).

Return type:

HexEdge

get_neighbour_corners()[source]#

Return the two corners at the ends of this edge.

Return type:

List[HexCorner]

Examples

first, second = edge.get_neighbour_corners()
get_neighbour_edges()[source]#

Return the edges that touch this edge at a corner (up to four).

This is the connection rule of Catan roads: a road must connect to a settlement or another road.

Return type:

List[HexEdge]

Examples

connected_roads = edge.get_neighbour_edges()
get_neighbour_tiles()[source]#

Return the up to two hexes that share this edge.

The hexes are derived from the merged edge references, so no tile has to exist for every reference: references to positions outside the world are skipped.

Return type:

List[HexTile]

start_angle()[source]#

Override: starting angle offset for layouting (e.g. hex rotation).

Return type:

int

to_pixel()[source]#

Return the pixel position of the edge center.

Return type:

Tuple[float, float]

class miniworlds.worlds.hex_world.hex_world_sensor_manager.HexWorldSensorManager(actor, world)[source]#

Sensor manager for hex worlds.

Click and pixel detection for actors on hexes uses the exact hex picking inherited from the tiled sensor manager. Actors on corners or edges are detected when the pixel is close to the corner or edge center, so settlements and roads can be clicked.

Distances between actors on hexes are hex distances (number of hexes between the positions), not euclidean offset distances.

Movement along the six hex axes (the directions “no”, “o”, “so”, “sw”, “w”, “nw” and their scratch-style degrees) moves from hex to hex in cube coordinates, so every step is exactly one hex, independent of the row parity. Angles that are not hex axes are snapped to the nearest axis (hex_coords.nearest_axis_degrees), so a single step never jumps more than one hex.

DETECTION_RADIUS_FACTOR = 0.3333333333333333#
detect_pixel(position)[source]#
Return type:

bool

static get_destination(start, direction, distance)[source]#

Computes a new (x, y) position starting from start, moving distance units in the direction (degrees).

Return type:

Tuple[float, float]

Parameters:
  • start (Tuple[float, float]) – Starting position (x, y).

  • direction (float) – Direction in degrees (0° = north/up, 90° = east/right).

  • distance (float) – Distance to move.

Returns:

New position (x, y).

Return type:

Tuple[float, float]

get_distance_to(obj)[source]#

Return the distance to another actor or position.

For actors and positions on hex tiles, the hex distance (the number of hexes between the positions) is returned. If a corner or edge is involved, the pixel distance between the corner, edge, or hex centers is returned.

Return type:

float

class miniworlds.worlds.hex_world.hex_world_position_manager.HexWorldPositionManager(actor, world, position)[source]#

Position manager for actors on hex worlds.

Actor sizes are derived from the hex bounding box instead of the square tile size. The six hex directions (“no”, “o”, “so”, “sw”, “w”, “nw”) are accepted as directions and mapped to their scratch-style degrees.

get_size()[source]#
Return type:

Tuple[int, int]

validate_direction(value)[source]#

Transforms a string value (“top”, “left”, “right”, “bottom) into a position

Parameters:

value – The String value (“top”, “left”, “right”, or “bottom)

Returns:

The position as scratch-style degrees

class miniworlds.worlds.hex_world.hex_camera_manager.HexCameraManager(view_x, view_y, world)[source]#

CameraManager for hex worlds.

View and world sizes are measured in hexes (columns, rows); pixel sizes are derived from the pointy-top hex geometry.

get_world_rect()[source]#

Returns the full world rectangle from the camera’s current origin.

Return type:

Rect

Returns:

A pygame.Rect representing the visible and scrolled world area.

Examples

>>> world.camera.get_world_rect()
property height: int#

Camera view height in pixels.

property topleft: tuple[int, int]#

Top-left corner of the camera view in pixels.

property width: int#

Camera view width in pixels.

class miniworlds.worlds.hex_world.hex_costume.HexCostume(*args, **kwargs)[source]#

Costume for actors on hex worlds.

Actors placed on a hex tile are drawn as hexagons instead of rectangles. Actors on corners or edges keep the rectangular shape.

animation_length#
draw_images#
draw_shapes#
font_manager#
id#
image_manager: image_manager.ImageManager#
initialized#
last_image#
loop#
parent#

the parent of a costume is the associated actor.

surface_loaded#
transformations_manager#

Coordinate mathematics for hexagonal worlds.

HexWorld uses a pointy-top layout with odd-r offset coordinates: Students address hexes with (column, row) tuples, exactly like tiles in a TiledWorld. Odd rows are shifted half a hex to the right.

Internally, cube coordinates (q, r, s) with q + r + s = 0 are used for neighbor and distance calculations, because they are uniform across rows.

All functions are pure and free of pygame or world dependencies.

miniworlds.worlds.hex_world.hex_coords.corner_edge_keys(corner_key)[source]#

Return the keys of the three edges that meet at a corner.

Return type:

List[Tuple[int, int, int]]

miniworlds.worlds.hex_world.hex_coords.corner_neighbour_corner_keys(corner_key)[source]#

Return the keys of the three corners one hex side away from a corner.

The keys are computed without a world, so they may lie outside the board; callers filter by the corners that exist.

Return type:

List[Tuple[int, int, int]]

miniworlds.worlds.hex_world.hex_coords.corner_pixel_offset(direction, tile_size)[source]#

Return the pixel offset of a hex corner, relative to the hex center.

Return type:

Tuple[float, float]

miniworlds.worlds.hex_world.hex_coords.corner_pixel_offsets(tile_size)[source]#

Return the pixel offsets of the six hex corners (relative to center).

Return type:

Dict[str, Tuple[float, float]]

miniworlds.worlds.hex_world.hex_coords.corner_pixel_points(position, tile_size)[source]#

Return the six corner pixels of a hex, clockwise from the top tip.

Return type:

List[Tuple[float, float]]

miniworlds.worlds.hex_world.hex_coords.corner_position(tile_position, direction)[source]#

Return the unique position key of a corner.

The key is expressed in tripled cube coordinates so that all hexes sharing the corner produce the same integer key.

Return type:

Tuple[int, int, int]

miniworlds.worlds.hex_world.hex_coords.corner_tile_references(corner_key)[source]#

Return (tile cube, corner direction) for every hex sharing a corner.

A corner key is 3 * cube + vector. Subtracting each corner vector and testing divisibility by three finds the (up to) three hexes that reach the corner, independent of the world bounds.

Return type:

List[Tuple[Tuple[int, int, int], str]]

miniworlds.worlds.hex_world.hex_coords.cube_destination(start, direction, distance)[source]#

Return the hex position reached from start moving along a hex axis.

Return type:

Tuple[int, int]

Parameters:
  • start – Hex position as (column, row).

  • direction – Neighbor direction, e.g. “no”.

  • distance – Number of hexes to move.

Returns:

The destination hex position. The destination is not checked against the world bounds.

miniworlds.worlds.hex_world.hex_coords.cube_distance(a, b)[source]#

Return the hex distance (number of hexes) between two cube positions.

Return type:

int

miniworlds.worlds.hex_world.hex_coords.cube_line(start, end)[source]#

Return the cubes of the straight line from start to end.

Both ends are included; the line has distance + 1 hexes. A tiny nudge makes the result deterministic when the line runs exactly along the border of two hexes.

Return type:

List[Tuple[int, int, int]]

miniworlds.worlds.hex_world.hex_coords.cube_ring(center, radius)[source]#

Return all cube positions at exactly radius hex distance.

The positions are returned in ring traversal order, starting at the westernmost hex of the ring and walking clockwise. For radius 0, only the center is returned; for negative radius, nothing is returned.

Return type:

List[Tuple[int, int, int]]

miniworlds.worlds.hex_world.hex_coords.cube_round(cube)[source]#

Round fractional cube coordinates to the nearest hex center.

Return type:

Tuple[int, int, int]

miniworlds.worlds.hex_world.hex_coords.cube_to_offset(cube)[source]#

Convert cube coordinates (q, r, s) to odd-r offset coordinates.

Return type:

Tuple[int, int]

miniworlds.worlds.hex_world.hex_coords.direction_vector(direction, vectors)[source]#

Return the vector for a direction name, with a helpful error.

Return type:

Tuple[int, int, int]

miniworlds.worlds.hex_world.hex_coords.disc_offset_deltas(row_parity, radius)[source]#

Return the offset deltas of all hexes within radius distance.

The center comes first, followed by the rings from the inside out, each in cube_ring order.

Return type:

Tuple[Tuple[int, int], ...]

miniworlds.worlds.hex_world.hex_coords.edge_corner_keys(edge_key)[source]#

Return the keys of the two corners at the ends of an edge.

Return type:

List[Tuple[int, int, int]]

miniworlds.worlds.hex_world.hex_coords.edge_neighbour_edge_keys(edge_key)[source]#

Return the keys of the (up to four) edges that touch an edge at a corner.

Return type:

List[Tuple[int, int, int]]

miniworlds.worlds.hex_world.hex_coords.edge_pixel_offset(direction, tile_size)[source]#

Return the pixel offset of an edge center, relative to the hex center.

Return type:

Tuple[float, float]

miniworlds.worlds.hex_world.hex_coords.edge_pixel_offsets(tile_size)[source]#

Return the pixel offsets of the six edge centers (relative to center).

Return type:

Dict[str, Tuple[float, float]]

miniworlds.worlds.hex_world.hex_coords.edge_position(tile_position, direction)[source]#

Return the unique position key of an edge.

The key is expressed in doubled cube coordinates so that both hexes sharing the edge produce the same integer key.

Return type:

Tuple[int, int, int]

miniworlds.worlds.hex_world.hex_coords.edge_tile_references(edge_key)[source]#

Return (tile cube, edge direction) for both hexes sharing an edge.

An edge key is 2 * cube + vector; see corner_tile_references.

Return type:

List[Tuple[Tuple[int, int, int], str]]

miniworlds.worlds.hex_world.hex_coords.hex_center(position, tile_size)[source]#

Return the pixel center of the hex at offset position (column, row).

The layout leaves half a hex margin at the top and left so that the top tip of the first row and the left edge of the first column are fully visible.

Return type:

Tuple[float, float]

miniworlds.worlds.hex_world.hex_coords.hex_distance(first, second)[source]#

Return the hex distance between two offset positions (column, row).

The distance is the number of hex steps between the positions; it does not depend on the row parity.

Return type:

int

miniworlds.worlds.hex_world.hex_coords.hex_height(tile_size)[source]#

Return the pixel height of a hex (bounding box height).

Return type:

float

miniworlds.worlds.hex_world.hex_coords.hex_width(tile_size)[source]#

Return the pixel width of a hex (bounding box width).

Return type:

float

miniworlds.worlds.hex_world.hex_coords.nearest_axis_degrees(direction)[source]#

Return the hex axis degree nearest to direction (scratch-style degrees).

The six hex axes are 30, 90, 150, 210, 270 and 330 degrees (0 = up, clockwise). Any other angle is snapped to the nearest axis, so one movement step is always exactly one hex. Ties round towards the next higher axis.

Return type:

int

miniworlds.worlds.hex_world.hex_coords.neighbour_offset_deltas(row_parity)[source]#

Return the offset deltas of the six neighbours for a row parity.

The deltas follow the order of CUBE_DIRECTIONS: “o”, “so”, “sw”, “w”, “nw”, “no”. Any integer row can be passed; only its parity counts.

Return type:

Tuple[Tuple[int, int], ...]

miniworlds.worlds.hex_world.hex_coords.offset_to_cube(position)[source]#

Convert odd-r offset coordinates (column, row) to cube coordinates.

Return type:

Tuple[int, int, int]

miniworlds.worlds.hex_world.hex_coords.pixel_to_cube(pixel, tile_size)[source]#

Return the cube coordinates of the hex containing a pixel position.

Return type:

Tuple[int, int, int]

miniworlds.worlds.hex_world.hex_coords.ring_offset_deltas(row_parity, radius)[source]#

Return the offset deltas of all hexes at exactly radius distance.

The order is the ring traversal order of cube_ring. For radius 0 the only delta is (0, 0); for negative radius it is empty. Any integer row can be passed; only its parity counts.

Return type:

Tuple[Tuple[int, int], ...]

miniworlds.worlds.hex_world.hex_coords.to_offset(value)[source]#

Return the offset position of a position tuple, tile, or actor.

Return type:

Tuple[int, int]

miniworlds.worlds.hex_world.hex_coords.world_pixel_size(columns, rows, tile_size)[source]#

Return the pixel size of a hex world with columns x rows hexes.

Return type:

Tuple[float, float]

Path finding on hexagonal worlds.

The functions work on the tiles of a HexWorld. Stepping onto a tile costs tile.cost (default 1); tiles are impassable if their is_blocking flag is set or a blocking actor (actor.is_blocking) stands on them. Both rules can be replaced with the blocked and cost callbacks.

Path finding runs in plain Python on the neighbour cache of the tiles, so it is meant for on-demand queries (a click, a turn), not for being called for hundreds of actors in every frame.

miniworlds.worlds.hex_world.hex_pathfinding.find_nearest(world, start, is_target, blocked=None, cost=None, max_cost=None, include_start=False)[source]#

Return the cheapest path to the nearest hex that satisfies is_target.

A target may be blocked, for example an enemy that blocks its own hex: the path ends on the target. Only the hexes on the way must be passable.

Return type:

List[HexTile]

Parameters:
  • world – The hex world.

  • start – Start hex (position, tile, or actor).

  • is_target – Function is_target(tile) -> bool.

  • blocked – Optional blocked(tile) -> bool, see find_path.

  • cost – Optional cost(tile) -> float, see find_path.

  • max_cost – Optional budget; targets that cost more are ignored.

  • include_start – If True, the start hex itself can be the target.

Returns:

The tiles from start to the nearest target, both included, or an empty list if no target is reachable.

miniworlds.worlds.hex_world.hex_pathfinding.find_path(world, start, goal, blocked=None, cost=None, max_cost=None, min_cost=None)[source]#

Return the cheapest path between two hexes (A*).

Return type:

List[HexTile]

Parameters:
  • world – The hex world.

  • start – Start hex (position, tile, or actor).

  • goal – Goal hex (position, tile, or actor).

  • blocked – Optional blocked(tile) -> bool; replaces the default rule (tile flag or blocking actor).

  • cost – Optional cost(tile) -> float for entering a tile; replaces tile.cost. Costs must not be negative.

  • max_cost – Optional budget; paths that cost more are not returned.

  • min_cost – Cheapest step cost, used to speed up the search. Only needed together with a custom cost; a too large value can return a path that is not the cheapest.

Returns:

The tiles from start to goal, both included, or an empty list if the goal is blocked, unreachable, or too expensive.

miniworlds.worlds.hex_world.hex_pathfinding.get_path_cost(path, cost=None)[source]#

Return the cost of a path: the sum of the costs of all hexes but the first.

Return type:

float

Parameters:
  • path – A list of tiles, for example the result of find_path.

  • cost – Optional cost(tile) -> float, see find_path.

miniworlds.worlds.hex_world.hex_pathfinding.get_reachable_tiles(world, start, max_cost, blocked=None, cost=None)[source]#

Return all hexes reachable within a movement budget (Dijkstra).

Return type:

List[HexTile]

Parameters:
  • world – The hex world.

  • start – Start hex (position, tile, or actor).

  • max_cost – Movement budget; with default costs this is the number of steps.

  • blocked – Optional blocked(tile) -> bool, see find_path.

  • cost – Optional cost(tile) -> float, see find_path.

Returns:

The reachable tiles including the start tile, ordered from the cheapest to the most expensive.

miniworlds.worlds.hex_world.hex_pathfinding.has_line_of_sight(world, start, goal, blocked=None)[source]#

Return whether no blocked hex lies between two hexes.

Only the hexes strictly between start and goal count, so a blocked goal (for example an enemy that blocks its own hex) can be seen.

Return type:

bool