Last active
April 18, 2022 10:27
-
-
Save caillef/85a5c306a40ad5f38096ce8ddea399c4 to your computer and use it in GitHub Desktop.
Persistence example Particubes - Storing values in the game Lumberjack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
Resources are stored in Player.resources on the client side. | |
There are 4 resources: logs, bLogs, mLogs and coins. | |
Ping Pong between client and server to load: | |
- start the game | |
- client sends loadResources to the server | |
- the server get the store and sends loadResources with the data | |
- client receives loadResources and use a custom resourceSystems to update the values | |
--]] | |
-- Server | |
serverSaveResources = function(p, event) | |
local store = KeyValueStore(p.UserID.."resources") | |
local logs, bLogs, mLogs, coins = event.logs, event.bLogs, event.mLogs, event.coins | |
store:Set( | |
"logs", logs, | |
"bLogs", bLogs, | |
"mLogs", mLogs, | |
"coins", coins | |
) | |
end | |
serverLoadResources = function(p, event) | |
local store = KeyValueStore(p.UserID.."resources") | |
store:Get("logs", "bLogs", "mLogs", "coins", function(success, results) | |
if not success then return end | |
local e = Event() | |
e.action = "loadResources" | |
local res = { "logs", "bLogs", "mLogs", "coins" } | |
for _,name in ipairs(res) do | |
e[name] = results[name] or 0 | |
end | |
e:SendTo(p) | |
end) | |
end | |
local SERVER_CMDS = { | |
saveResources = serverSaveResources, | |
loadResources = serverLoadResources | |
} | |
Server.DidReceiveEvent = function(event) | |
local p = event.Sender | |
local action = event.action | |
if not action then return end | |
local handler = SERVER_CMDS[action] | |
if not handler then print("Error: unknown action '"..action.."').") return end | |
handler(p, event) | |
end | |
-- CLIENT | |
-- Called when the player joins | |
initResources = function() | |
Player.resources = {} | |
local e = Event() | |
e.action = "loadResources" | |
e:SendTo(Server) | |
end | |
-- Called when I want to save the resources | |
saveProgress = function() | |
local e = Event() | |
e.action = "saveResources" | |
local res = { "logs", "bLogs", "mLogs", "coins" } | |
for _,name in ipairs(res) do | |
e[name] = Player.resources[name] | |
end | |
e:SendTo(Server) | |
end | |
Client.DidReceiveEvent = function(event) | |
local sender = event.Sender | |
if sender ~= Server then return end | |
if event.action == "loadResources" then | |
local res = { "logs", "bLogs", "mLogs", "coins" } | |
for _,name in ipairs(res) do | |
resourcesSystem_updateResource(name, event[name]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment