summaryrefslogtreecommitdiff
path: root/common/chunk.lua
blob: e210387669e98592f73404c45237728894bcb8dc (plain)
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
local json = require"common.dkjson"

local CHUNK_SIZE = 128

-- 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 = {}
Chunk.__index = Chunk
function Chunk.make(tiles)
	return setmetatable({tiles=tiles},Chunk)
end
function Chunk.gen()
	-- todo actual worldgen
	local tiles = {}
	for i=0,CHUNK_SIZE-1 do
		for j=0,CHUNK_SIZE-1 do
			tiles[index(i,j)] = (math.random()<0.5)
		end
	end

	return Chunk.make(tiles)
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.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
}