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
53
54
55
56
57
|
local G = love.graphics
local common = require 'common'
local Camera = require'r.camera'
local Pos = require'r.pos'
local class = require'r.class'
local enet = require'enet'
local pprint = require'pprint'
local json = require'dkjson'
local SPEED = 8 -- tiles per second
local colors = {[true]={141/255,128/255,22/255}, [false]={71/255,50/255,122/255}}
local host = enet.host_create()
local conn = host:connect('localhost:19683')
local players = {}
local chunks = common.ChunkMap()
local lp = { pos=Pos(0,0), movetimer=0, dir=nil } -- local player
local directions = {w=Pos(0,-1),a=Pos(-1,0),s=Pos(0,1),d=Pos(1,0)}
function love.keypressed(k,s,r) if directions[s] then lp.dir=s end end
function love.keyreleased(k,s) if s==lp.dir then lp.dir=nil end end
function lp.update(dt)
lp.movetimer = lp.movetimer - dt
if lp.movetimer <= 0 and lp.dir then
local d = directions[lp.dir] local newpos = lp.pos+d
if chunks:tile(newpos) == false then
lp.pos = newpos
conn:send(json.encode{type='move',x=newpos.x,y=newpos.y})
lp.movetimer = 1 / SPEED end end end
local function draw_player(p, c) G.setColor(c) G.circle('fill',p.x,p.y,0.3) end
function lp.draw() draw_player(lp.pos, {0,1,0}) end
local cam = Camera(nil, 64)
function love.update(dt)
lp.update(dt)
local ev = host:service() while ev do
-- pprint(ev)
if ev.type == 'receive' then local j = json.decode(ev.data)
if j.type == 'player' then players[j.name] = {name=j.name,pos=Pos(j.x,j.y)}
elseif j.type == 'unplayer' then players[j.from] = nil
elseif j.type == 'move' then players[j.from].pos = Pos(j.x,j.y)
elseif j.type == 'chunk' then chunks:add(Pos(j.x,j.y),j.d)
elseif j.type == 'unchunk' then chunks:remove(Pos(j.x,j.y))
end
end
ev = host:service()
end
end
function love.draw()
G.clear(1,1,1); G.origin()
cam.pos = lp.pos; cam:apply_trans()
-- if chunk then for x=0,63 do for y=0,63 do
-- G.setColor(colors[chunk[1+x*64+y]]) G.rectangle('fill',x-0.5,y-0.5,1,1) end end end
lp.draw()
for _,player in pairs(players) do draw_player(player.pos,{0,1,1}) end
end
|