Offline Player Data Test 1

--[[    This is rough, testing..

GET PLAYER'S DATA (between scenes)
        * which scene?
        * player count
        * which zone?
        
        
        Make MAIN the hub where players decide where to travel to so Main
        can track where everyone is (for multiplayer)
        
        * Need to "keep alive" this Main (hub)
        * Limit the amount of time a player can hang around in here.
        
        
--]]

--full list: local _players = require( script:GetCustomProperty("ListPlayers") )
--local _players = {"BFM","togagames"}

local _players = {} -- create list as players join "Main"

local SHARED_KEY = script:GetCustomProperty("StorageKey") -- shared key..
--https://docs.coregames.com/api/storage/#getsharedofflineplayerdata
-- tutorial: 
-- https://docs.coregames.com/fr/tutorials/persistent_storage_tutorial/#writing-the-code

local _var = {}

local _rot = 145
local _speed = .22 -- how fast trap swings
local _wait = 2 -- agreed wait for synch
local _delay = 5 -- how long trap waits to go "back and forth"
local _num = _speed * _wait
local _counter = -1
local data

local _trapSwitch = {nil} -- switch forth/back
_trapSwitch[0] = nil
_trapSwitch[1] = nil

--math.randomseed(os.time())
-- Game.GetCurrentSceneName()

local _scene = {"Main","Lobby","Menu","Rivervale"}


-- Server Context (receive):
function _transfer(player,ww)
    -- Transfer the player to the scene, and set the spawn point.
    --player:TransferToScene(sceneName, { spawnKey = "TutorialStart" })
    --player:SetResource("scene", ww)
    Chat.BroadcastMessage(player.name.." ("..player.id..") ".." moved to Scene: ".._scene[ww].."." )
    
    local transferData = {
        name = player.name,
        scene = ww
    }
    Storage.SetSharedPlayerData(SHARED_KEY, player, transferData)    
    print("Transfer "..player.name.." ("..player.id..")  w/data: ".._scene[transferData.scene])
    player:TransferToScene(_scene[ww])
end

function _detect(player,nn)
    local _offlineID = "21c0b4284eff4bb091ce80a75c984fd4"--varglbargl
    data = Storage.GetSharedOfflinePlayerData(SHARED_KEY, _offlineID)
    local _savedName = data["name"]
    local _savedScene = data["scene"]
    --Chat.BroadcastMessage( _savedName.." (".._offlineID..") ".." in scene: ".._scene[_savedScene].."." )
    Chat.BroadcastMessage(_savedName.." is in scene: ".._savedScene..".")
    
end

Events.ConnectForPlayer("Transfer", _transfer)
Events.ConnectForPlayer("Detect",_detect)


function OnResourceChanged(player, resName, resValue)
    if (resName == "scene" or resName == "xp") then
        local data = Storage.GetPlayerData(player)
        data[resName] = resValue
        local resultCode,errorMessage = Storage.SetPlayerData(player, data)
    end
end

function _addPlayerId(player)
    -- add if not found
    if(2>1)then
        _players[#_players+1] = player.id
        player:SetResource("scene", 1) -- track this player's current "scene"/zone         
         -- Player is not here, use offline storage. This yields the thread
        if STORAGE_KEY and STORAGE_KEY.isAssigned then
            -- If there is a shared game key
            local transferData = {
                name = player.name,
                scene = 1
            }
            Storage.SetSharedPlayerData(SHARED_KEY, player, transferData)          
        else
            print("Data storage error")
        end
    end
end

function OnPlayerJoined(player)
    if(Game.GetCurrentSceneName() == "Main")then
        -- Store joined player id data
        --_addPlayerId(player)
    end
    --player.resourceChangedEvent:Connect(OnResourceChanged)
    data = Storage.GetSharedPlayerData(SHARED_KEY, player) -- method 1
    local _name = data["name"]
    local _scene = data["scene"]
    Chat.BroadcastMessage( _name.." ("..player.id..") ".." connected, in scene: ".._scene.."." )
    --Chat.BroadcastMessage( player.name..": ("..player.id..") joined! There are now "..tostring( #Game.GetPlayers().." players in the game." ) )

end

Game.playerJoinedEvent:Connect(OnPlayerJoined)













function _timing(pid)-- switch between: forth() and back()
    _counter = _counter + 1
    _trapSwitch[_counter%2]() -- 0 or 1 (switch)
end

function _startTask(tid)
    _var[tid] = Task.Spawn(function() _timing(tid) end)
    _var[tid].repeatCount = -1 -- forever
    _var[tid].repeatInterval = _delay -- every x seconds
end

_trapSwitch[0] = function()--forth
    Chat.BroadcastMessage( tostring( " in Scene: ".._scene[1].."." ) )
    print( Game.GetPlayers()[1]:GetResource("scene") )
    Chat.BroadcastMessage( tostring( #Game.GetPlayers().." players in the game. [First in list]:"..Game.GetPlayers()[1].name.." in Scene: ".._scene[Game.GetPlayers()[1]:GetResource("scene")].."." ) )    
end

_trapSwitch[1] = function()--back
    Chat.BroadcastMessage( tostring( #Game.GetPlayers().." players in the game." ) )    
end

Task.Wait(_delay)-- trap will call ( back() and forth() always )
--_startTask("scenes")














------------------------ BELOW IS THE CLIENT CODE:

-- keys are being pressed!
function OnBindingPressed(player, binding)
     -- '1-4' key
    if(binding == "ability_extra_1")then
        Events.BroadcastToServer("Transfer", 1)
    end    
    if(binding == "ability_extra_2")then
        Events.BroadcastToServer("Transfer", 2)
    end    
    if(binding == "ability_extra_3")then
        Events.BroadcastToServer("Transfer", 3)
    end    
    if(binding == "ability_extra_4")then
        Events.BroadcastToServer("Transfer", 4)
    end
    if(binding == "ability_extra_5")then
        Events.BroadcastToServer("Detect", 5)
    end    
end

-- on player joined/left functions need to be defined before calling event:Connect()
Game.playerJoinedEvent:Connect(function(player)
    --_player = player
    player.bindingPressedEvent:Connect(OnBindingPressed)
end)

Latest Posts