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