Skip to content

Advanced Examples

Advanced usage patterns and complex implementations using PlayerState.

Multi-Player Plot System

lua
-- Server: Plot ownership and management
local PlotService = {}
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)

function PlotService.ClaimPlot(player: Player, plotId: string): boolean
    -- Check if player already owns a plot
    local currentPlot = PlayerState.GetPath(player, "Plot.Id")
    if currentPlot then
        return false -- Already owns a plot
    end
    
    -- Initialize plot data
    PlayerState.SetPath(player, "Plot", {
        Id = plotId,
        Likes = 0,
        Buildings = {},
        Theme = "Default",
        LastUpdated = os.time()
    })
    
    return true
end

function PlotService.AddBuilding(player: Player, building: any): boolean
    local buildings = PlayerState.GetPath(player, "Plot.Buildings") or {}
    
    if #buildings >= 10 then
        return false -- Building limit reached
    end
    
    building.PlacedAt = os.time()
    return PlayerState.AddToArray(player, "Plot.Buildings", building)
end

Leaderboard System

lua
-- Server: Real-time leaderboards
local LeaderboardService = {}
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)

function LeaderboardService.UpdatePlayerStats(player: Player, statType: string, value: number)
    PlayerState.SetPath(player, `Stats.{statType}`, value)
    
    -- Update global leaderboard (you'd use OrderedDataStore here)
    -- This is a simplified example
end

-- Client: Leaderboard display
local LeaderboardUI = {}
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateClient)

function LeaderboardUI.init()
    PlayerState.OnChanged("Stats", function()
        -- Update leaderboard display
        LeaderboardUI.refreshDisplay()
    end)
end

Achievement System

lua
-- Server: Achievement tracking
local AchievementService = {}
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)

local ACHIEVEMENTS = {
    first_kill = {name = "First Blood", coins = 100},
    level_10 = {name = "Veteran", coins = 500},
    -- Add more achievements
}

function AchievementService.CheckAchievement(player: Player, achievementId: string): boolean
    local achievements = PlayerState.GetPath(player, "Achievements") or {}
    
    -- Check if already earned
    for _, earned in ipairs(achievements) do
        if earned == achievementId then
            return false
        end
    end
    
    -- Award achievement
    local achievement = ACHIEVEMENTS[achievementId]
    if achievement then
        PlayerState.AddToArray(player, "Achievements", achievementId)
        PlayerState.Set(player, "Coins", PlayerState.Get(player, "Coins") + achievement.coins)
        
        -- Fire achievement event to client
        return true
    end
    
    return false
end

PlayerState - High-Performance Roblox Data Management