Skip to content

Instantly share code, notes, and snippets.

@tnlogy
Created May 30, 2023 21:43
Show Gist options
  • Select an option

  • Save tnlogy/54d422394e215e19201da48b2ffb42a9 to your computer and use it in GitHub Desktop.

Select an option

Save tnlogy/54d422394e215e19201da48b2ffb42a9 to your computer and use it in GitHub Desktop.
Network game in Codea using socket.udp and msgpack.lua with entity component system
--# Main
-- Rymdskepp
function setup()
viewer.mode = FULLSCREEN
setupMenu()
end
function setupMenu()
noStroke()
rectMode(CENTER)
textMode(CENTER)
fontSize(40)
local menu = ecs.System("label")
function menu:update(e)
if e.touched then
fill(233, 207, 80)
else
fill(130)
end
rect(e.pos.x, e.pos.y, 250,60)
fill(224)
text(e.label, e.pos.x, e.pos.y)
end
function menu:touched(e, touch)
if e .pos:dist(touch.pos) < 40 then
if touch.state ~= ENDED then
e.touched = true
else
setupGame(e.isHost)
end
else
e.touched = false
end
end
world = ecs.World(menu)
world:add(
{label="Host game", pos=vec2(WIDTH/2, HEIGHT/2+80), isHost=true},
{label="Connect", pos=vec2(WIDTH/2, HEIGHT/2), isHost=false}
)
end
function setupGame(isHost)
local bounce = ecs.System("pos and vel")
function bounce:update(e, dt)
e.pos = e.pos + e.vel * dt
if e.pos.x < 0 or e.pos.x > WIDTH then
e.vel.x = -e.vel.x
end
if e.pos.y < 100 or e.pos.y > (HEIGHT-100) then
e.vel.y = -e.vel.y
end
end
local drawPixels = ecs.System("pos and fill")
function drawPixels:update(e, dt)
fill(255, 20, 0)
rect(e.pos.x, e.pos.y, 8, 8)
end
local drawSprites = ecs.System("pos and (not fill)")
function drawSprites:update(e, dt)
sprite(asset.builtin.Space_Art.Green_Ship, e.pos.x, e.pos.y, 40, 40)
end
local fadeSystem = ecs.System("fill")
function fadeSystem:update(e, dt)
e.fill = e.fill:mix(color(0, 0), 1-dt*.5)
if e.fill.a <= 150 then
-- delete entity when faded
return ecs.DELETE
end
end
local score = {player1=0, player2=0}
local explode = ecs.System("pos and (not fill)")
function explode:touched(e, touch)
if touch.state == BEGAN and e.pos:dist(touch.pos) < 19 then
createExplosion(e.pos, 20)
if touch.isHost then
score.player1 = score.player1+1
else
score.player2 = score.player2+1
end
return ecs.DELETE
end
end
local scoreSys = ecs.System("player1")
function scoreSys:update(e)
fill(151, 80, 233)
fontSize(30)
text("P1:"..e.player1.." P2:"..e.player2, WIDTH/2,HEIGHT-60)
end
world = ecs.World(bounce, fadeSystem, drawPixels, drawSprites, explode, scoreSys)
if isHost then
world:add(score)
-- add 10 random sprites
for i = 1, 10 do
world:add({
pos=vec2(WIDTH/2, HEIGHT/2),
vel=vec2(math.random(150,300),0):rotate(i*10),
})
end
end
world:enableNetwork(isHost)
end
function draw()
background(40, 40, 50)
world:update(DeltaTime)
end
function touched(touch)
world:touched(touch)
end
function createExplosion(pos, n)
for i = 1,n do
world:add({
pos=pos,
vel=vec2(math.random(-100,100),math.random(-150,150)),
fill=color(255, 176, 0)
})
end
end
--# Ecs
local DEBUG = false
local BOOLS = {}
BOOLS["and"] = true
BOOLS["or"] = true
BOOLS["not"] = true
-- compile a boolean expression to check if
-- keys exists in a table
-- filter("a not b")({a=1}) => true
local function filter(expr)
local code = string.gsub(expr,
"(%w+)", function (n)
if BOOLS[n] then
return n
end
return "(e['" .. n .. "'] ~= nil)"
end)
code = "return function(e) return (" .. code .. ") end"
local fn, err = load(code)
return fn()
end
local World = class()
function World:init(...)
self.systems = {...}
self.entities = {}
self.newEntities = {}
self.touches = {}
end
function World:add(...)
for i, e in ipairs({...}) do
table.insert(self.newEntities, e)
end
end
function World:dispatch(action, ...)
local returnvalue = nil
for i,system in ipairs(self.systems) do
local preaction = "pre_"..action
if system[preaction] then
system[preaction](system)
end
for j,e in ipairs(self.entities) do
if system[action] ~= nil and system.filter(e) then
local res = system[action](system, e, ...)
if res ~= nil then
returnvalue = res
end
if res == ecs.DELETE then
table.remove(self.entities, j)
end
end
end
end
return returnvalue
end
function World:update(...)
if DEBUG then
fill(233, 80, 219)
text("entities:" .. #self.entities, 50, HEIGHT-50)
end
if #self.newEntities > 0 then
for i, e in ipairs(self.newEntities) do
table.insert(self.entities, e)
end
self.newEntities = {}
end
self:updateNetwork()
if #self.touches > 0 then
for i, touch in ipairs(self.touches) do
self:dispatch("touched", touch)
end
self.touches = {}
end
return self:dispatch("update", ...)
end
function World:updateNetwork()
if self.net ~= nil then
if self.isHost then
local data, remoteIp = self.net:receive()
if data ~= nil then
if data.action == "subscribe" then
self.clients[remoteIp] = true
elseif data.action == "touches" then
for i,t in ipairs(data[1]) do
table.insert(self.touches, t)
end
end
end
for clientIp,_ in pairs(self.clients) do
print("send "..clientIp)
self.net:send(clientIp, {action="updateentities", entities=self.entities})
end
else
if self.serverIp ~= nil then
if #self.touches > 0 then
self.net:send(self.serverIp, {
action="touches",
self.touches
})
self.touches = {}
end
else
print("sub")
self.net:broadcast({action="subscribe"})
end
local data, serverIp = self.net:receive()
if data ~= nil then
if data.action == "updateentities" then
self.entities = data.entities
self.serverIp = serverIp
end
end
end
end
end
function World:touched(touch)
table.insert(self.touches, {
pos=touch.pos, state=touch.state,
isHost=self.isHost
})
end
function World:enableNetwork(isHost)
self.net = Net(5099)
self.isHost = isHost
self.broadcasttime = ElapsedTime
self.clients = {}
self.updatenettimer = everynth(.5)
end
local System = class()
function System:init(expr)
self.filter = filter(expr)
end
local function tests()
m = filter("a and b")
assert(m({a=1,b=3}) == true)
end
tests()
ecs = {
World=World,
System=System,
filter=filter,
DELETE={}
}
--# Msgpack
-- copied from https://github.com/kieselsteini/msgpack and modified to handle some userdata in Codea
--[[----------------------------------------------------------------------------
MessagePack encoder / decoder written in pure Lua 5.3 / Lua 5.4
written by Sebastian Steinhauer <[email protected]>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
--]]
local pack, unpack = string.pack, string.unpack
local mtype, utf8len = math.type, utf8.len
local tconcat, tunpack = table.concat, table.unpack
local ssub = string.sub
local type, pcall, pairs, select = type, pcall, pairs, select
local encode_value -- forward declaration
local function is_an_array(value)
local expected = 1
for k in pairs(value) do
if k ~= expected then
return false
end
expected = expected + 1
end
return true
end
local encoder_functions = {
['nil'] = function()
return pack('B', 0xc0)
end,
['boolean'] = function(value)
if value then
return pack('B', 0xc3)
else
return pack('B', 0xc2)
end
end,
['number'] = function(value)
if mtype(value) == 'integer' then
if value >= 0 then
if value < 128 then
return pack('B', value)
elseif value <= 0xff then
return pack('BB', 0xcc, value)
elseif value <= 0xffff then
return pack('>BI2', 0xcd, value)
elseif value <= 0xffffffff then
return pack('>BI4', 0xce, value)
else
return pack('>BI8', 0xcf, value)
end
else
if value >= -32 then
return pack('B', 0xe0 + (value + 32))
elseif value >= -128 then
return pack('Bb', 0xd0, value)
elseif value >= -32768 then
return pack('>Bi2', 0xd1, value)
elseif value >= -2147483648 then
return pack('>Bi4', 0xd2, value)
else
return pack('>Bi8', 0xd3, value)
end
end
else
local test = unpack('f', pack('f', value))
if test == value then -- check if we can use float
return pack('>Bf', 0xca, value)
else
return pack('>Bd', 0xcb, value)
end
end
end,
['string'] = function(value)
local len = #value
if utf8len(value) then -- check if it is a real utf8 string or just byte junk
if len < 32 then
return pack('B', 0xa0 + len) .. value
elseif len < 256 then
return pack('>Bs1', 0xd9, value)
elseif len < 65536 then
return pack('>Bs2', 0xda, value)
else
return pack('>Bs4', 0xdb, value)
end
else -- encode it as byte-junk :)
if len < 256 then
return pack('>Bs1', 0xc4, value)
elseif len < 65536 then
return pack('>Bs2', 0xc5, value)
else
return pack('>Bs4', 0xc6, value)
end
end
end,
['table'] = function(value)
if is_an_array(value) then -- it seems to be a proper Lua array
local elements = {}
for i, v in pairs(value) do
elements[i] = encode_value(v)
end
local length = #elements
if length < 16 then
return pack('>B', 0x90 + length) .. tconcat(elements)
elseif length < 65536 then
return pack('>BI2', 0xdc, length) .. tconcat(elements)
else
return pack('>BI4', 0xdd, length) .. tconcat(elements)
end
else -- encode as a map
local elements = {}
for k, v in pairs(value) do
elements[#elements + 1] = encode_value(k)
elements[#elements + 1] = encode_value(v)
end
local length = #elements // 2
if length < 16 then
return pack('>B', 0x80 + length) .. tconcat(elements)
elseif length < 65536 then
return pack('>BI2', 0xde, length) .. tconcat(elements)
else
return pack('>BI4', 0xdf, length) .. tconcat(elements)
end
end
end,
}
encode_value = function(value)
if type(value) == "userdata" then
for k,v in pairs(userdata_encoders) do
if value[k] ~= nil then
value = userdata_encoders[k](value)
break
end
end
end
return encoder_functions[type(value)](value)
end
local function encode(...)
local data = {}
for i = 1, select('#', ...) do
data[#data + 1] = encode_value(select(i, ...))
end
return tconcat(data)
end
local decode_value -- forward declaration
local function decode_array(data, position, length)
local elements, value = {}
for i = 1, length do
value, position = decode_value(data, position)
elements[i] = value
end
return elements, position
end
local function decode_map(data, position, length)
local elements, key, value = {}
for i = 1, length do
key, position = decode_value(data, position)
value, position = decode_value(data, position)
elements[key] = value
end
return elements, position
end
local decoder_functions = {
[0xc0] = function(data, position)
return nil, position
end,
[0xc2] = function(data, position)
return false, position
end,
[0xc3] = function(data, position)
return true, position
end,
[0xc4] = function(data, position)
return unpack('>s1', data, position)
end,
[0xc5] = function(data, position)
return unpack('>s2', data, position)
end,
[0xc6] = function(data, position)
return unpack('>s4', data, position)
end,
[0xca] = function(data, position)
return unpack('>f', data, position)
end,
[0xcb] = function(data, position)
return unpack('>d', data, position)
end,
[0xcc] = function(data, position)
return unpack('>B', data, position)
end,
[0xcd] = function(data, position)
return unpack('>I2', data, position)
end,
[0xce] = function(data, position)
return unpack('>I4', data, position)
end,
[0xcf] = function(data, position)
return unpack('>I8', data, position)
end,
[0xd0] = function(data, position)
return unpack('>b', data, position)
end,
[0xd1] = function(data, position)
return unpack('>i2', data, position)
end,
[0xd2] = function(data, position)
return unpack('>i4', data, position)
end,
[0xd3] = function(data, position)
return unpack('>i8', data, position)
end,
[0xd9] = function(data, position)
return unpack('>s1', data, position)
end,
[0xda] = function(data, position)
return unpack('>s2', data, position)
end,
[0xdb] = function(data, position)
return unpack('>s4', data, position)
end,
[0xdc] = function(data, position)
local length
length, position = unpack('>I2', data, position)
return decode_array(data, position, length)
end,
[0xdd] = function(data, position)
local length
length, position = unpack('>I4', data, position)
return decode_array(data, position, length)
end,
[0xde] = function(data, position)
local length
length, position = unpack('>I2', data, position)
return decode_map(data, position, length)
end,
[0xdf] = function(data, position)
local length
length, position = unpack('>I4', data, position)
return decode_map(data, position, length)
end,
}
-- add fix-array, fix-map, fix-string, fix-int stuff
for i = 0x00, 0x7f do
decoder_functions[i] = function(data, position)
return i, position
end
end
for i = 0x80, 0x8f do
decoder_functions[i] = function(data, position)
return decode_map(data, position, i - 0x80)
end
end
for i = 0x90, 0x9f do
decoder_functions[i] = function(data, position)
return decode_array(data, position, i - 0x90)
end
end
for i = 0xa0, 0xbf do
decoder_functions[i] = function(data, position)
local length = i - 0xa0
return ssub(data, position, position + length - 1), position + length
end
end
for i = 0xe0, 0xff do
decoder_functions[i] = function(data, position)
return -32 + (i - 0xe0), position
end
end
decode_value = function(data, position)
local byte, value
byte, position = unpack('B', data, position)
value, position = decoder_functions[byte](data, position)
if type(value) == "table" and value.UDT ~= nil then
value = userdata_decoders[value.UDT](value)
end
return value, position
end
userdata_encoders = {
angleBetween = function (v)
return {x=v.x, y=v.y,UDT="vec2"}
end,
blend = function (v)
return {r=v.r, g=v.g, b=v.b, a=v.a, UDT="color"}
end
}
userdata_decoders = {
vec2=function (v)
return vec2(v.x, v.y)
end,
color=function (v)
return color(v.r, v.g, v.b, v.a)
end
}
msgpack = {
_AUTHOR = 'Sebastian Steinhauer <[email protected]>',
_VERSION = '0.6.1',
-- primary encode function
encode = function(...)
local data, ok = {}
for i = 1, select('#', ...) do
ok, data[i] = pcall(encode_value, select(i, ...))
if not ok then
return nil, 'cannot encode MessagePack'
end
end
return tconcat(data)
end,
-- encode just one value
encode_one = function(value)
local ok, data = pcall(encode_value, value)
if ok then
return data
else
return nil, 'cannot encode MessagePack'
end
end,
-- primary decode function
decode = function(data, position)
local values, value, ok = {}
position = position or 1
while position <= #data do
ok, value, position = pcall(decode_value, data, position)
if ok then
values[#values + 1] = value
else
return nil, 'cannot decode MessagePack'
end
end
return tunpack(values)
end,
-- decode just one value
decode_one = function(data, position)
local value, ok
ok, value, position = pcall(decode_value, data, position or 1)
if ok then
return value, position
else
return nil, 'cannot decode MessagePack'
end
end,
userdata_encoders = userdata_encoders,
userdata_decoders = userdata_decoders
}
--# Net
-- UDP network class
socket=require("socket")
Net = class()
function Net:init(port)
self.port = port
self:get_ip()
self.server=socket.udp()
self.server:setsockname(self.ip, port)
self.hostname = socket.dns.gethostname()
print("ip: " .. self.ip)
print("hostname: " .. self.hostname)
self.server:settimeout(0)
self.client=socket.udp()
self.client:settimeout(0)
self.listeners = {}
end
function Net:update(isHost, ...)
local data, remote_ip = self:receive()
if data ~= nil then
if data.action == "connect" then
table.insert(self.listeners, remote_ip)
data = nil
end
end
for msg in ipairs(...) do
local data = msgpack.encode(msg)
for ip in ipairs(self.listeners) do
self.client:setpeername(ip, self.port)
self.client:send(data)
end
end
return data
end
function Net:get_ip()
local server=socket.udp()
server:setpeername("1.1.1.1",self.port)
self.ip,_=server:getsockname()
self.networkid, self.hostid=string.match(self.ip,"(%d+.%d+.%d+.)(%d+)")
end
function Net:broadcast(data)
data = msgpack.encode(data)
for hostid=1,254 do
if hostid~=tonumber(self.hostid) then
self.client:setpeername(self.networkid..hostid,self.port)
self.client:send(data)
end
end
end
function Net:send(ip, data)
data = msgpack.encode(data)
self.client:setpeername(ip, self.port)
self.client:send(data)
end
function Net:receive()
local data, remoteIp, port=self.server:receivefrom()
if data~=nil then
data = msgpack.decode(data)
return data, remoteIp
else
return nil, nil
end
end
--# Utils
function everynth(seconds)
local t = ElapsedTime
return function ()
if ElapsedTime - t >= seconds then
t = ElapsedTime
return true
end
return false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment