residentsleeper/scripts/residentsleeper.lua

98 lines
1.9 KiB
Lua

local event = require('event')
local regexp = require('regexp')
zzzRe = regexp.MustCompile('^z{3,}$')
ratio = 0.30
votes = {}
onlinePlayers = 0
expireTime = 0
event.on('init', function()
-- This is called when the server is started or the script is initialized (late load)
online, max, names, err = rcon:OnlinePlayers()
onlinePlayers = online
end)
event.on('message', function(user, message)
if not zzzRe:MatchString(message) then
return
end
t = rcon:GetTime()
if t < 12000 then
rcon:SendColorfulMessage(user, 'red', "It's not night time, go mine some more.")
return
end
-- Reset votes if we got this far and the previous vote expired
if os.time() > expireTime then
votes = {}
end
local difference = 24000 - t
-- 20 ticks per second (50ms per tick)
expireTime = os.time() + ((difference * 50) / 1000)
votes[user] = true
local currentVotes = tablelength(votes)
local requiredVotes = math.ceil(onlinePlayers * ratio)
if currentVotes >= requiredVotes then
mimicSleeping(t)
else
rcon:SendColorfulMessage('@a', 'blue', string.format('%s wants to sleep (%d of %d votes)', user, currentVotes, requiredVotes))
end
end)
event.on('logged_in', function(user)
onlinePlayers = onlinePlayers + 1
end)
event.on('leave', function(user)
onlinePlayers = onlinePlayers - 1
if votes[user] then
votes[user] = nil
if os.time() > expireTime then
votes = {}
return
end
end
local requiredVotes = math.ceil(onlinePlayers * ratio)
if tablelength(votes) > requiredVotes then
mimicSleeping(-1)
end
end)
function mimicSleeping(t)
if t == -1 then
t = rcon:GetTime()
end
local difference = 24000 - t
votes = {}
local newTime = rcon:AddTime(difference)
if newTime < 0 or newTime > 12000 then
rcon:ServerMessage('Unable to set time!')
return
end
rcon:SendColorfulMessage('@a', 'green', 'Good morning, rise and shine!')
end
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end