-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhexgrid.go
134 lines (111 loc) · 2.32 KB
/
hexgrid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package hexgrid
import (
"fmt"
)
type Coord struct {
X int `json:"x"`
Y int `json:"y"`
}
func (c Coord) String() string {
return fmt.Sprintf("C(%d, %d)", c.X, c.Y)
}
type ByXY []Coord
func (a ByXY) Len() int { return len(a) }
func (a ByXY) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByXY) Less(i, j int) bool {
return a[i].Y < a[j].Y || (a[i].Y == a[j].Y && a[i].X < a[j].X)
}
type HexGrid[T any] struct {
xdim int
ydim int
hexes []T
}
func (g HexGrid[T]) Dims() (int, int) {
return g.xdim, g.ydim
}
func Generate[T any](xdim int, ydim int, initFn func(coord Coord) T) HexGrid[T] {
hexes := make([]T, 0, xdim*ydim)
for y := 0; y < ydim; y++ {
for x := 0; x < xdim; x++ {
val := initFn(Coord{x, y})
hexes = append(hexes, val)
}
}
return HexGrid[T]{
xdim,
ydim,
hexes,
}
}
func (g HexGrid[T]) MapHexes(hexFn func(coord Coord, hexData *T)) {
for y := 0; y < g.ydim; y++ {
for x := 0; x < g.xdim; x++ {
hexFn(Coord{x, y}, &g.hexes[g.xyToIndex(x, y)])
}
}
}
func (g HexGrid[T]) xyToIndex(x int, y int) int {
return y*g.xdim + x
}
func (g HexGrid[T]) coordToIndex(coord Coord) int {
return g.xyToIndex(coord.X, coord.Y)
}
func (g HexGrid[T]) indexToCoord(i int) Coord {
return Coord{i % g.xdim, i / g.xdim}
}
func (g HexGrid[T]) isInBounds(coord Coord) bool {
if coord.X < 0 || coord.X >= g.xdim {
return false
}
if coord.Y < 0 || coord.Y >= g.ydim {
return false
}
return true
}
func (g HexGrid[T]) GetAt(coord Coord) *T {
return g.GetAtXY(coord.X, coord.Y)
}
func (g HexGrid[T]) GetAtXY(x int, y int) *T {
if x < 0 || x >= g.xdim || y < 0 || y >= g.ydim {
return nil
}
index := g.xyToIndex(x, y)
return &g.hexes[index]
}
func (g HexGrid[T]) GetNeighbors(coord Coord) []Coord {
return g.GetNeighborsXY(coord.X, coord.Y)
}
type offset struct {
x int
y int
}
func (g HexGrid[T]) GetNeighborsXY(x int, y int) []Coord {
var offsets []offset
if y%2 == 1 {
offsets = []offset{
{+0, -1},
{+1, -1},
{+1, +0},
{+1, +1},
{+0, +1},
{-1, +0},
}
} else {
offsets = []offset{
{-1, -1},
{+0, -1},
{+1, +0},
{+0, +1},
{-1, +1},
{-1, +0},
}
}
result := make([]Coord, 0, len(offsets))
for _, offset := range offsets {
coord := Coord{x + offset.x, y + offset.y}
if g.isInBounds(coord) {
result = append(result, coord)
}
}
return result
}