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
|
local json = require"common.dkjson"
local class = require"common.class"
local CHUNK_SIZE = 64
-- for now tiles shall be booleans
local function index_ok(offq,offr)
return 0<=offq and 0<=offr and offq<CHUNK_SIZE and offr<CHUNK_SIZE
end
local function index(offq,offr)
-- indexes start at 0
-- and go up to (CHUNK_SIZE^2)-1
assert(index_ok(offq,offr), "chunk hex offset out of bounds")
return CHUNK_SIZE*offq + offr + 1
end
local Chunk = class()
function Chunk.make(cls,tiles)
return setmetatable({tiles=tiles},cls)
end
function Chunk.at(self,hoffs)
if not index_ok(hoffs.q,hoffs.r) then return nil end
return self.tiles[index(hoffs.q,hoffs.r)]
end
function Chunk.set_at(self,hoffs,tile)
if not index_ok(hoffs.q,hoffs.r) then return end
self.tiles[index(hoffs.q,hoffs.r)] = tile
end
function Chunk.data_packet(self)
return json.encode{t="chunk",tiles=self.tiles}
end
function Chunk.from_packet_data(packet)
-- assuming packet has already been json.decoded
-- since otherwise how would we know it's a chunk packet
return Chunk:make(packet.tiles)
end
return {
Chunk=Chunk,
SIZE=CHUNK_SIZE,
index=index,
index_ok=index_ok,
}
|