hex

package module
v0.0.0-...-980f4c9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2017 License: MIT Imports: 9 Imported by: 0

README

What's this?

This is a Go library for 2D hex grids.

It should be especially suitable for implementing games played on hex grids.

It contains:

  • Basic types and operations on them: * Hex coordinates * Hex directions * Hex coordinate sets
  • A shadowcasting algorithm (for field-of-view)
  • Protobuf equivalents of the above types
  • A couple of searching algorithms:
    • BFS
    • DFS
    • A*

I (@steinarvk) hold the copyright on this code. It is not associated with any employer of mine, past or present.

The code is made available for use under the MIT license; see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	North     HexDir = iota
	Northwest        = iota
	Southwest        = iota
	South            = iota
	Southeast        = iota
	Northeast        = iota
)

Variables

View Source
var (
	// FullAngularInterval is the AngularInterval that contains all angles.
	FullAngularInterval = AngularInterval{Full: true}

	// EmptyAngularInterval is the AngularInterval that contains no angles.
	EmptyAngularInterval = AngularInterval{Empty: true}
)
View Source
var (
	OrderedDirections = []HexDir{
		North, Northwest, Southwest, South, Southeast, Northeast,
	}

	OrthogonalCCW = map[HexDir]HexDir{
		North:     Southwest,
		Northwest: South,
		Southwest: Southeast,
		South:     Northeast,
		Southeast: North,
		Northeast: Northwest,
	}

	Directions = map[HexDir]HexCoord{
		North:     HexCoord{0, 2},
		Northwest: HexCoord{-1, 1},
		Southwest: HexCoord{-1, -1},
		South:     HexCoord{0, -2},
		Southeast: HexCoord{1, -1},
		Northeast: HexCoord{1, 1},
	}

	Origin = HexCoord{0, 0}
)

Functions

func DirectionToProto

func DirectionToProto(d HexDir) pb.Direction

DirectionToProto converts a HexDir to a pb.Direction.

func HexCircumference

func HexCircumference(r int) int

HexCircumference computes the circumference (in number of cells) of a hex "circle" of radius r, where with the degenerate case of r=0 representing a single cell.

func IsFullyConnected

func IsFullyConnected(s *HexSet) bool

IsFullyConnected checks whether a HexSet is fully connected.

Types

type AStarParams

type AStarParams struct {
	Start     *HexSet
	IsGoal    func(HexCoord) bool
	Cost      func(HexCoord, HexCoord) (float64, bool)
	Heuristic func(HexCoord) float64
	MaxCost   float64
}

AStarParams provides parameters for an A* search.

type AStarResult

type AStarResult struct {
	Path []HexCoord
	Cost float64
}

AStarResult represents the result of an A* search.

func AStar

func AStar(params *AStarParams) (*AStarResult, error)

AStar performs an A* search.

type AngularInterval

type AngularInterval struct {
	Empty, Full bool
	Rad0, Rad1  float64
}

AngularInterval is a connected interval of angles.

func NewAngularInterval

func NewAngularInterval(a0, a1 float64) AngularInterval

NewAngularInterval constructs a new angular interval -- neither empty nor full.

func NewAngularSextant

func NewAngularSextant(section HexDir) AngularInterval

NewAngularSextant computes an AngularInterval corresponding to a given sextant (i.e. 60-degree section of the plane corresponding to the hex directions outwards from the origin).

func (AngularInterval) Contains

func (n AngularInterval) Contains(a float64) bool

Contains tests whether another AngularInterval is contained in this one.

func (AngularInterval) Intersection

Intersection computes the intersection of two AngularIntervals.

func (AngularInterval) Size

func (n AngularInterval) Size() float64

Size returns the size (in radians) of an angular interval.

func (AngularInterval) String

func (n AngularInterval) String() string

String returns a human-readable string form of an AngularInterval.

type GeoCoord

type GeoCoord struct {
	X, Y float64
}

GeoCoord is a geometric coordinate (a general coordinate on the 2D plane, not restricted to the hex grid).

func NewGeoPolar

func NewGeoPolar(r float64, a float64) GeoCoord

NewGeoPolar creates a GeoCoord, specified with polar coordinates.

func (GeoCoord) Add

func (g GeoCoord) Add(g2 GeoCoord) GeoCoord

Add adds two GeoCoords.

func (GeoCoord) Angle

func (g GeoCoord) Angle() float64

Angle converts a GeoCoord to an angle (from the origin).

func (GeoCoord) Cross

func (c GeoCoord) Cross(v GeoCoord) float64

GeoCoord computes the cross product of this GeoCoord with another.

func (GeoCoord) DistanceTo

func (g GeoCoord) DistanceTo(g2 GeoCoord) float64

DistanceTo computes the distance between two GeoCoords.

func (GeoCoord) Length

func (g GeoCoord) Length() float64

Length computes the distance of a GeoCoord from the origin.

func (GeoCoord) Normalized

func (c GeoCoord) Normalized() GeoCoord

Normalized produces a new GeoCoord that is a normalized version of the old one.

func (GeoCoord) Scaled

func (c GeoCoord) Scaled(s float64) GeoCoord

Scaled produces a new GeoCoord that is a scaled version of the old one.

func (GeoCoord) SquareLength

func (g GeoCoord) SquareLength() float64

SquareLength computes the squared length of a GeoCoord (the squared distance from the origin).

func (GeoCoord) String

func (p GeoCoord) String() string

String returns a human-readable string form of a GeoCoord.

func (GeoCoord) Sub

func (g GeoCoord) Sub(g2 GeoCoord) GeoCoord

Sub subtracts two GeoCoords.

type HexCoord

type HexCoord struct {
	X, Y int
}

HexCoord is a coordinate on a hex grid. (X,Y) is a valid hex coordinate if and only if X and Y are of equal parity.

func BreadthFirstSearch

func BreadthFirstSearch(start HexCoord, isSteppable func(HexCoord, HexCoord) bool, isGoal func(HexCoord) bool) ([]HexCoord, error)

BreadthFirstSearch runs a breadth-first search through a hex grid. The hex grid is specified through the two functions "isSteppable" (which determines whether a step from one coordinate to another is legal) and "isGoal" (which determines whether the goal has been reached).

func BreadthFirstSearchFromMultiple

func BreadthFirstSearchFromMultiple(frontierSet *HexSet, isSteppable func(HexCoord, HexCoord) bool, isGoal func(HexCoord) bool) ([]HexCoord, error)

BreadthFirstSearchFromMultiple performs a breadth-first search (like BreadthFirstSearch), except starting from multiple coordinates at once.

func DepthFirstSearch

func DepthFirstSearch(start HexCoord, isSteppable func(HexCoord, HexCoord) bool, isGoal func(HexCoord) bool) ([]HexCoord, error)

DepthFirstSearch performs a depth-first search on a hex grid. Like BreadthFirstSearch, the hex grid is specified through callback functions "isSteppable" and "isGoal".

func HexCircle

func HexCircle(r int) []HexCoord

HexCircle computes a slice of all the HexCoords at a certain radius.

func HexDisk

func HexDisk(r int) []HexCoord

HexDisk computes a slice of all the HexCoords at or below a certain radius.

func HexFromProto

func HexFromProto(p *pb.HexCoord) (HexCoord, error)

HexFromProto converts a proto to a HexCoord.

func NewHex

func NewHex(x, y int) HexCoord

NewHex creates a new HexCoord, without checking that it is valid.

func NewHexPolar

func NewHexPolar(r, step int) HexCoord

NewHexPolar computes a HexCoord using integral polar coordinates.

func RandomHexOnCircle

func RandomHexOnCircle(r *rand.Rand, radius int) HexCoord

RandomHexOnCircle returns a random hex on a "hex circle".

func RayIntersection

func RayIntersection(start, delta HexCoord, set *HexSet) (HexCoord, error)

RayIntersection finds the first intersection of a ray (where the direction is cell-aligned) with a HexSet. An error is returned if no intersection exists.

func TryNewHex

func TryNewHex(x, y int) (HexCoord, error)

TryNewHex creates a new HexCoord, returning an error if the two integers do not specify a valid coordinate (i.e. are not of equal parity).

func (*HexCoord) AbsX

func (c *HexCoord) AbsX() int

AbsX returns the absolute value of the HexCoord's X coordinate.

func (*HexCoord) AbsY

func (c *HexCoord) AbsY() int

AbsY returns the absolute value of the HexCoord's Y coordinate.

func (*HexCoord) AddDelta

func (c *HexCoord) AddDelta(d HexCoord) HexCoord

AddDelta adds two HexCoords.

func (*HexCoord) AddMultDelta

func (c *HexCoord) AddMultDelta(m int, d HexCoord) HexCoord

AddMultDelta adds a multiple of a HexCoord; i.e. c + m * d.

func (HexCoord) CalculateFov

func (c HexCoord) CalculateFov(cone AngularInterval, maxR int, obstruct func(HexCoord) bool, addLight func(HexCoord, AngularInterval))

CalculateFov calculates shadowcasting field-of-view from the origin. FOV may be restricted by angle or by radius (use -1) to not restrict by radius. Obstructions are specified through the "obstruct" callback. Output happens with the "addLight" callback which adds light to a certain HexCoord. Note that addLight can be called multiple times for one HexCoord.

func (HexCoord) ContainsRay

func (c HexCoord) ContainsRay(dx, dy float64) bool

ContainsRay tests whether the hex would intersect a given ray from the origin.

func (HexCoord) ExtremeAngles

func (c HexCoord) ExtremeAngles() AngularInterval

ExtremeAngles computes the AngularInterval of this hexagon seen from the origin.

func (HexCoord) Geo

func (c HexCoord) Geo() GeoCoord

Geo finds the GeoCoord representing the center of the given HexCoord.

func (HexCoord) IsZero

func (c HexCoord) IsZero() bool

IsZero tests whether a HexCoord is the origin.

func (HexCoord) Less

func (a HexCoord) Less(b HexCoord) bool

Less computes a lexicographic ordering of HexCoords.

func (HexCoord) Minus

func (c HexCoord) Minus(p HexCoord) HexCoord

Minus subtracts two HexCoords.

func (*HexCoord) Move

func (c *HexCoord) Move(ds ...HexDir) HexCoord

Move computes a HexCoord that results after taking an number of steps from an initial HexCoord.

func (HexCoord) Negation

func (c HexCoord) Negation() HexCoord

Negation computes the negation of the HexCoord (i.e. scaled by -1).

func (*HexCoord) Neighbours

func (c *HexCoord) Neighbours() []HexCoord

Neighbours computes a slice of the HexCoord's immediate neighbours.

func (*HexCoord) NeighboursSet

func (c *HexCoord) NeighboursSet() *HexSet

NeighboursSet computes the HexSet of a HexCoord's immediate neighbours.

func (*HexCoord) Radius

func (c *HexCoord) Radius() int

Radius computes the radius of the HexCoord.

func (HexCoord) String

func (c HexCoord) String() string

String computes a human-readable string form of a HexCoord.

func (HexCoord) ToProto

func (c HexCoord) ToProto() *pb.HexCoord

ToProto converts a HexCoord to a proto.

func (HexCoord) Vertex

func (c HexCoord) Vertex(i int) GeoCoord

Vertex finds the GeoCoord at the i'th corner vertex of the hexagon. i=0 is the east vertex (k,0) from the center, and the vertices proceed counterclockwise around the hexagon.

type HexDir

type HexDir int32

HexDir represents one of the six directions on a hex grid.

func DirectionFromProto

func DirectionFromProto(d pb.Direction) HexDir

DirectionFromProto converts a pb.Direction to a HexDir.

type HexSet

type HexSet struct {
	// contains filtered or unexported fields
}

HexSet is a set of HexCoords.

func FindConnectedComponent

func FindConnectedComponent(start HexCoord, isContained func(HexCoord) bool) (*HexSet, error)

FindConnectedComponent determines, given a representative coordinate and a membership-test function, the connected component of the representative.

func HexSetFromProto

func HexSetFromProto(p *pb.HexSet) (*HexSet, error)

HexSetFromProto converts a pb.HexSet proto to a HexSet.

func HexSetWithHolesFilled

func HexSetWithHolesFilled(s *HexSet) *HexSet

HexSetWithHolesFilled returns a HexSet with any internal holes filled.

func NewHexSet

func NewHexSet() *HexSet

NewHexSet creates a new (empty and unfrozen) HexSet.

func NewHexSetAround

func NewHexSetAround(p HexCoord, r int) *HexSet

NewHexSetAround creates a new HexSet containing one HexCoord and all HexCoords within a certain radius of it.

func NewHexSetSingleton

func NewHexSetSingleton(p HexCoord) *HexSet

NewHexSetSingleton creates a new HexSet containing a single HexCoord.

func (*HexSet) Add

func (h *HexSet) Add(x HexCoord)

Add adds a HexCoord to the HexSet.

func (*HexSet) AddHex

func (h *HexSet) AddHex(i, j int)

RemoveHex adds a certain HexCoord (specified explicitly with integers) to the HexSet.

func (*HexSet) Clone

func (h *HexSet) Clone() *HexSet

Clone makes a clone of a HexSet.

func (*HexSet) Contains

func (h *HexSet) Contains(x HexCoord) bool

Contains checks whether a HexSet contains a certain HexCoord.

func (*HexSet) ContainsHex

func (h *HexSet) ContainsHex(i, j int) bool

ContainsHex checks whether a certain HexCoord (specified explicitly with integers) is in the HexSet.

func (*HexSet) ContainsSet

func (h *HexSet) ContainsSet(xs *HexSet) bool

ContainsSet checks whether a HexSet contains an entire other set.

func (*HexSet) Difference

func (h *HexSet) Difference(x *HexSet) *HexSet

Difference removes all elements in another HexSet from this HexSet.

func (*HexSet) Each

func (h *HexSet) Each(f func(HexCoord))

Each runs a callback on each of the HexCoords in a HexSet.

func (*HexSet) Enumerate

func (h *HexSet) Enumerate() []HexCoord

Enumerate converts a HexSet to a slice of HexCoords.

func (*HexSet) Except

func (h *HexSet) Except(p HexCoord) *HexSet

Except computes a new HexSet that is like this one, except not containing a certain HexCoord.

func (*HexSet) Expand

func (h *HexSet) Expand(n int)

Expand expands the HexSet n steps outward from each coordinate.

func (*HexSet) ExpandFiltered

func (h *HexSet) ExpandFiltered(n int, f func(HexCoord) bool)

ExpandFiltered expands the HexSet n steps outwards; except not proceeding into any hex p where f(p) return false.

func (*HexSet) Expanded

func (h *HexSet) Expanded(n int) *HexSet

Expanded computes a new HexSet that is like the old one, except expanded by n steps.

func (*HexSet) Filter

func (h *HexSet) Filter(f func(HexCoord) bool)

Filter removes any point p from the HexSet where f(p) returns false.

func (*HexSet) Filtered

func (h *HexSet) Filtered(f func(HexCoord) bool) *HexSet

Filtered computes a new HexSet that is like the old one, except only containing HexCoords p where f(p) returns true.

func (*HexSet) Freeze

func (s *HexSet) Freeze()

Freeze marks the HexSet as immutable.

func (*HexSet) GeoDistanceHeuristic

func (c *HexSet) GeoDistanceHeuristic() func(HexCoord) float64

GeoDistanceHeuristic returns a function f(x) that, given a HexCoord x, computes the minimum geometric distance to any point p in the HexSet.

func (*HexSet) GoRepr

func (s *HexSet) GoRepr() string

GoRepr returns an explicit Go representation of the HexSet (code that would produce it).

func (*HexSet) InPlaceUnion

func (h *HexSet) InPlaceUnion(x *HexSet)

InPlaceUnion mutates the HexSet to take the union with another.

func (*HexSet) Intersection

func (h *HexSet) Intersection(x *HexSet) *HexSet

Intersection computes the intersection of two HexSets.

func (*HexSet) Intersects

func (h *HexSet) Intersects(x *HexSet) bool

Intersects checks whether two HexSets intersect.

func (*HexSet) IntersectsWithOffset

func (h *HexSet) IntersectsWithOffset(x *HexSet, offset HexCoord) bool

IntersectsWithOffset checks whether a HexSet intersects with the result of mapping over another by (+offset), i.e. adding a certain HexCoord delta to each element.

func (*HexSet) MaxRadius

func (h *HexSet) MaxRadius() int

MaxRadius returns an upper bound on the radius of the HexCoords in the set.

func (*HexSet) OuterBorder

func (s *HexSet) OuterBorder() *HexSet

OuterBorder computes the outer border of the HexSet.

func (*HexSet) PickArbitrary

func (h *HexSet) PickArbitrary() (HexCoord, error)

PickArbitrary picks an arbitrary HexCoord from a HexSet.

func (*HexSet) Predicate

func (c *HexSet) Predicate() func(HexCoord) bool

Predicate converts the HexSet to a callback that checks for HexCoord membership in the set.

func (*HexSet) Random

func (h *HexSet) Random() (HexCoord, error)

Random selects a random HexCoord from a HexSet.

func (*HexSet) RandomFrom

func (h *HexSet) RandomFrom(r *rand.Rand) (HexCoord, error)

RandomFrom selects a random HexCoord from a HexSet, using a specified rand.Rand.

func (*HexSet) Remove

func (h *HexSet) Remove(x HexCoord)

Remove removes a HexCoord from the HexSet.

func (*HexSet) RemoveHex

func (h *HexSet) RemoveHex(i, j int)

RemoveHex removes a certain HexCoord (specified explicitly with integers) from the HexSet.

func (*HexSet) Size

func (h *HexSet) Size() int

Size returns the number of elements in the HexSet.

func (*HexSet) ToList

func (h *HexSet) ToList() []HexCoord

ToList converts a HexSet to a list of HexCoords.

func (*HexSet) ToOrderedList

func (h *HexSet) ToOrderedList() []HexCoord

ToOrderedList converts a HexSet to an ordered list of HexCoords.

func (*HexSet) ToProto

func (c *HexSet) ToProto() *pb.HexSet

ToProto converts a HexSet to a pb.HexSet proto.

func (*HexSet) Union

func (h *HexSet) Union(x *HexSet) *HexSet

Union computes a new HexSet that is like this one union'd with another.

Directories

Path Synopsis
Package hexpb is a generated protocol buffer package.
Package hexpb is a generated protocol buffer package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL