/hexgrid

Hexagonal game grids for Elixir

Primary LanguageElixirMIT LicenseMIT

HexGrid

Build Status

Create hexagonal grids in Elixir. Provides basic computational and mapping support.

Work is based on this excellent article from redblobgames.

See hex package and docs for more details.

Installation

The package can be installed by listing it as a hex dependency:

def deps do
  [{:hexgrid, "~> 2.1"}]
end

Usage

alias HexGrid.Map, as: HexMap
alias HexGrid.Hex, as: Hex

API

Hex Tile

new(q, r, s)

Create a tile in a cube coordinate system.

Example:

Hex.new(0, 0, 0)

neighbour(hex, direction)

Gets the neighbuoring hex. Neighbours are just offsets on the given hex:

0 -> Hex.new(+1, -1, 0)
1 -> Hex.new(+1, 0, -1)
2 -> Hex.new(0, +1, -1)
3 -> Hex.new(-1, +1, 0)
4 -> Hex.new(-1, 0, +1)
5 -> Hex.new(0, -1, +1)

Example:

Hex.neighbours(Hex.new(0, 0, 0))

neighbours(hex)

For a given hex tile, get all adjacent tiles.

Example:

Hex.neighbours(Hex.new(0, 0, 0))

Map

Provides support for creating and maintaining tile structures, as well as containing tile data.

Note: Examples alias HexGrid.Map as Map

new()

Creates an empty map.

Example:

Map.new()

new_hex(radius)

Utility to create a hexagonal-shaped map with a given radius.

Example:

Map.new_hex(5)

insert(map, tile)

Adds tile to the map.

Example:

{:ok, map} = HexMap.new()
{result, map} = HexMap.insert(map, Hex.new(0, 0, 0))

set(map, tile, key, value)

Sets an arbitrary value on a map, for a given tile.

Example:

hex = Hex.new(0, 0, 0)
{_, map} = HexMap.new()
{_, map} = HexMap.insert(map, hex)

{_, map} = HexMap.set(map, hex, :hello, :world)

get(map, tile, key)

Gets the value from the map, for a given tile.

Example:

hex = Hex.new(0, 0, 0)
{_, map} = HexMap.new()
{_, map} = HexMap.insert(map, hex)
{_, map} = HexMap.set(map, hex, :hello, :world)

assert HexMap.get(map, hex, :hello) == {:ok, :world}