Synchronize coins and candles

This commit is contained in:
slemonide 2017-12-19 21:34:21 -08:00
parent 00405f1659
commit 4bb533673d
3 changed files with 54 additions and 4 deletions

View File

@ -1,5 +1,4 @@
local logger = require("log")
local socket = require "socket"
client = {}
@ -46,6 +45,27 @@ function client:update(dt)
assert(x and y)
x, y = tonumber(x), tonumber(y)
nodes:addNode(x, y, ent)
elseif cmd == "addItem" then
local x, y = parms:match("^(%-?[%d.e]*) (%-?[%d.e]*)$")
assert(x and y)
x, y = tonumber(x), tonumber(y)
if (ent == "coin") then
coins:add(x, y)
elseif (ent == "candle") then
candles:add(x,y)
else
log("addItem: unknown item: " .. ent)
end
elseif cmd == "removeItem" then
local x, y = parms:match("^(%-?[%d.e]*) (%-?[%d.e]*)$")
assert(x and y)
x, y = tonumber(x), tonumber(y)
if (ent == "coin") then
coins:_remove(x, y)
else
log("removeItem: unknown item: " .. ent)
end
else
log("unrecognised command: " .. cmd)
end

View File

@ -1,3 +1,14 @@
require('xy_map')
require('client')
coins = newXYMap()
coins = newXYMap()
coins._remove = coins.remove
function coins:remove(x, y)
if (client.connected) then
client.udp:send(string.format("%s %s %f %f", client.id, 'removeCoin', x, y))
end
coins:_remove(x, y)
end

View File

@ -1,7 +1,6 @@
require("players")
require("nodes")
local logger = require("log")
local logger = require("log")
local socket = require "socket"
server = {}
@ -36,6 +35,16 @@ function server:update_nodes(client_id, msg_or_ip, port_or_nil)
end)
end
function server:update_items(client_id, msg_or_ip, port_or_nil)
coins:forEach(function(x, y)
server.udp:sendto(string.format("%s %s %d %d", "coin", 'addItem', x, y), msg_or_ip, port_or_nil)
end)
candles:forEach(function(x, y)
server.udp:sendto(string.format("%s %s %d %d", "candle", 'addItem', x, y), msg_or_ip, port_or_nil)
end)
end
function server:update()
if (server.started) then
local data, msg_or_ip, port_or_nil = server.udp:receivefrom()
@ -57,7 +66,17 @@ function server:update()
elseif cmd == "update" then
server:update_players(client_id, msg_or_ip, port_or_nil)
server:update_nodes(client_id, msg_or_ip, port_or_nil)
server:update_items(client_id, msg_or_ip, port_or_nil)
elseif cmd == "removeCoin" then
local x, y = parms:match("^(%-?[%d.e]*) (%-?[%d.e]*)$")
assert(x and y) -- validation is better, but asserts will serve.
x, y = tonumber(x), tonumber(y)
log(string.format("Player %s collects coin from %d %d", client_id, x, y))
coins:remove(x, y)
-- notify others
--server.udp:sendto(string.format("%s %s %d %d", "coin", 'removeItem', x, y), msg_or_ip, port_or_nil)
else
log("unrecognised command: " .. cmd)
end