+/HIP

hexagonal iso-path game

git clone https://git.julia.blue/+/HIP

Joseph RyanOptimize move computing64793d8

v1.0
2.4 KiB99 linesraw
1import sys
2import math
3import collections
4
5class Hex(collections.namedtuple("Hex", ["q", "r", "s"])):
6    __slots__ = ()
7    def __repr__(self):
8        return '(' + str(self.q) + ',' + str(self.r) + ',' + str(self.s) + ')'
9
10Point = collections.namedtuple("Point", ["x", "y"])
11
12Orientation = collections.namedtuple("Orientation", ["f0", "f1", "f2", "f3", "b0", "b1", "b2", "b3", "startAngle"])
13
14Layout = collections.namedtuple("Layout", ["orientation", "size", "origin"])
15
16
17def sign(x): return 1 if x > 0 else 0 if x == 0 else -1
18
19
20def addHex(a, b):
21    return Hex(a.q + b.q, a.r + b.r, a.s + b.s)
22
23
24def subHex(a, b):
25    return Hex(a.q + b.q, a.r + b.r, a.s + b.s)
26
27
28def hexDirection(direction):
29    return [Hex(1, 0, -1), Hex(1, -1, 0), Hex(0, -1, 1), Hex(-1, 0, 1), Hex(-1, 1, 0), Hex(0, 1, -1)][direction]
30
31
32def hexNeighbor(hex, direction):
33    return addHex(hex, hexDirection(direction))
34
35
36def hexLength(hex):
37    return (abs(hex.q) + abs(hex.r) + abs(hex.s)) // 2
38
39
40def hexDistance(a, b):
41    return hexLength(subHex(a, b))
42
43
44def hexNeighbors(hex):
45    return [hexNeighbor(hex, j) for j in range(6)]
46
47
48def hexRound(h):
49    q = int(round(h.q))
50    r = int(round(h.r))
51    s = int(round(h.s))
52    q_diff = abs(q - h.q)
53    r_diff = abs(r - h.r)
54    s_diff = abs(s - h.s)
55    if q_diff > r_diff and q_diff > s_diff:
56        q = -r - s
57    else:
58        if r_diff > s_diff:
59            r = -q - s
60        else:
61            s = -q - r
62    return Hex(q, r, s)
63
64
65def hexToPixel(layout, h):
66    M = layout.orientation
67    size = layout.size
68    origin = layout.origin
69    x = (M.f0 * h.q + M.f1 * h.r) * size.x
70    y = (M.f2 * h.q + M.f3 * h.r) * size.y
71    return Point(x + origin.x, y + origin.y)
72
73
74def pixelToHex(layout, p, round=True):
75    M = layout.orientation
76    size = layout.size
77    origin = layout.origin
78    pt = Point((p.x - origin.x) / size.x, (p.y - origin.y) / size.y)
79    q = M.b0 * pt.x + M.b1 * pt.y
80    r = M.b2 * pt.x + M.b3 * pt.y
81    if round:
82        return hexRound(Hex(q, r, -q - r))
83    return Hex(q, r, -q - r)
84
85
86def hexCornerOffset(layout, corner):
87    M = layout.orientation
88    size = layout.size
89    angle = 2.0 * math.pi * (M.startAngle - corner) / 6
90    return Point(size.x * math.cos(angle), size.y * math.sin(angle))
91
92
93def polygonCorners(layout, h):
94    corners = []
95    center = hexToPixel(layout, h)
96    for i in range(0, 6):
97        offset = hexCornerOffset(layout, i)
98        corners.append(Point(center.x + offset.x, center.y + offset.y))
99    return corners