summaryrefslogtreecommitdiff
path: root/common/coords.lua
diff options
context:
space:
mode:
Diffstat (limited to 'common/coords.lua')
-rw-r--r--common/coords.lua34
1 files changed, 17 insertions, 17 deletions
diff --git a/common/coords.lua b/common/coords.lua
index 2399e43..351aa53 100644
--- a/common/coords.lua
+++ b/common/coords.lua
@@ -1,3 +1,5 @@
+local class = require"common.class"
+
-- Hex: q,r,s. invariant that q+r+s=0
-- add, subtract
-- constructor takes 3 positions and rounds to closest hex centre.
@@ -15,12 +17,11 @@ local Pos, Hex
local SR3 = math.sqrt(3)
-Hex={}
-Hex.__index = Hex
-function Hex.make(q,r,s)
+local Hex = class()
+function Hex.make(cls,q,r,s)
s=s or -q-r
assert(q+r+s==0,"hex coord doesn't meet invariant")
- return setmetatable({q=q,r=r,s=s},Hex)
+ return setmetatable({q=q,r=r,s=s},cls)
end
function Hex.round(self)
-- return a new Hex rounded to integer coordinates
@@ -40,32 +41,31 @@ function Hex.round(self)
rs = -rq-rr
end
- return Hex.make(rq,rr,rs)
+ return Hex:make(rq,rr,rs)
end
function Hex.to_pos(self)
local x = self.q*SR3 + self.r*(SR3/2)
local y = self.r*(3/2)
- return Pos.make(x,y)
+ return Pos:make(x,y)
end
-function Hex.__add(self,other) return Hex.make(self.q+other.q, self.r+other.r, self.s+other.s) end
-function Hex.__sub(self,other) return Hex.make(self.q-other.q, self.r-other.r, self.s-other.s) end
+function Hex.__add(self,other) return Hex:make(self.q+other.q, self.r+other.r, self.s+other.s) end
+function Hex.__sub(self,other) return Hex:make(self.q-other.q, self.r-other.r, self.s-other.s) end
function Hex.__tostring(self) return string.format("H(%.2f,%.2f)",self.q,self.r) end
-Pos = {}
-Pos.__index=Pos
-function Pos.make(x,y)
- return setmetatable({x=x,y=y},Pos)
+Pos = class()
+function Pos.make(cls,x,y)
+ return setmetatable({x=x,y=y},cls)
end
-function Pos.__add(self,other) return Pos.make(self.x+other.x,self.y+other.y) end
-function Pos.__sub(self,other) return Pos.make(self.x-other.x,self.y-other.y) end
+function Pos.__add(self,other) return Pos:make(self.x+other.x,self.y+other.y) end
+function Pos.__sub(self,other) return Pos:make(self.x-other.x,self.y-other.y) end
function Pos.__mul(a,b)
if type(a) == "number" then
- return Pos.make(a*b.x,a*b.y)
+ return Pos:make(a*b.x,a*b.y)
elseif type(b) == "number" then
- return Pos.make(a.x*b,a.y*b)
+ return Pos:make(a.x*b,a.y*b)
else
error("can only multiply Pos by scalar")
end
@@ -81,7 +81,7 @@ function Pos.dot(self,other) return self.x*other.x + self.y*other.y end
function Pos.to_hex(self)
local q = self.x*(SR3/3) - self.y*(1/3)
local r = (2/3)*self.y
- return Hex.make(q,r,-q-r)
+ return Hex:make(q,r,-q-r)
end
function Pos.__tostring(self) return string.format("(%.2f,%.2f)",self.x,self.y) end