Carica quando entri
Lezione 20 di 20 del corso Gioco Roblox: Simulatore di animali domestici di Coddy.
Ora rileggi il salvataggio quando il giocatore si unisce. GetAsync restituisce ciò che SetAsync ha memorizzato sotto la chiave, oppure nil per un giocatore che non ha mai salvato. Anche questa operazione può non riuscire, quindi chiamala in un pcall, che restituisce se è andata a buon fine e poi il valore:
local ok, saved = pcall(function()
return saveStore:GetAsync(player.UserId)
end)
if ok and saved then
print(saved.Coins)
endCarica i dati dopo aver creato le cartelle, così gli animali domestici avranno una cartella Pets in cui essere inseriti. Ignora qualsiasi nome salvato che non sia presente in petInfo: un animale domestico rimosso dal gioco non dovrebbe impedire a un giocatore di unirsi.
Sfida
DifficileRestituisci ai giocatori ciò che hanno salvato.
- In
PlayerAdded, dopo aver creato la cartella Pets:local ok, saved = pcall(function() return saveStore:GetAsync(player.UserId) end). - Se
ok and saved: imposta Coins susaved.Coinse l'attributoDesertsusaved.Desert. - Per ogni animale salvato in
petInfo,givePet(player, pet.Name, pet.Equipped == true).
Premi «Gioca», fai schiudere un uovo, premi Stop e poi di nuovo «Gioca»: le tue monete e i tuoi animali sono tornati. Poi premi «Verifica».
Provalo tu
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local RunService = game:GetService("RunService")
local DataStoreService = game:GetService("DataStoreService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local saveStore = DataStoreService:GetDataStore("Pets")
local pileSpot = {} -- ogni mucchio -> il punto in cui si trova
local lastHit = {} -- ogni giocatore -> quando ha colpito l'ultima volta
print("A Meadow pile gives " .. Settings.PileValue .. " coins")
-- Settings.Pets per nome
local petInfo = {}
for _, info in Settings.Pets do
petInfo[info.Name] = info
end
-- Un animale domestico: uno StringValue nella cartella Pets del giocatore che ne contiene il nome, con
-- la rarità e la potenza come attributi
local function givePet(player, name, equipped)
local info = petInfo[name]
local pet = Instance.new("StringValue")
pet.Name = "Pet"
pet.Value = name
pet:SetAttribute("Rarity", info.Rarity)
pet:SetAttribute("Power", info.Power)
pet:SetAttribute("Equipped", equipped)
pet.Parent = player.Pets
return pet
end
-- quanti animali domestici ha schierato un giocatore
local function equippedCount(player)
local count = 0
for _, pet in player.Pets:GetChildren() do
if pet:GetAttribute("Equipped") then
count += 1
end
end
return count
end
-- quanto aggiungono gli animali domestici di un giocatore a ogni colpo
local function petPower(player)
local power = 0
for _, pet in player.Pets:GetChildren() do
if pet:GetAttribute("Equipped") then
power += pet:GetAttribute("Power")
end
end
return power
end
-- Ogni giocatore ha Coins nella classifica
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
-- gli animali domestici che possiedono
local pets = Instance.new("Folder")
pets.Name = "Pets"
pets.Parent = player
-- Lezione 20: Load on Join va qui
end)
-- Un mucchio di monete in un punto: una copia di ServerStorage.CoinPile con la salute
-- e il valore come attributi
local function spawnPile(spot)
local desert = spot.Parent.Parent.Name == "Desert"
local health = desert and Settings.DesertHealth or Settings.PileHealth
local pile = ServerStorage.CoinPile:Clone()
pile.Position = spot.Position
pile:SetAttribute("MaxHealth", health)
pile:SetAttribute("Health", health)
pile:SetAttribute("Value", desert and Settings.DesertValue or Settings.PileValue)
pile:SetAttribute("Zone", spot.Parent.Parent.Name)
pile.HealthGui.Label.Text = pile:GetAttribute("Health") .. "/" .. pile:GetAttribute("MaxHealth")
pileSpot[pile] = spot
pile.Parent = piles
return pile
end
-- Un colpo sottrae 1, più la potenza dei pet del giocatore, alla salute di un mucchio;
-- quando arriva a 0, il mucchio si rompe e assegna il suo valore
local function hitPile(player, pile)
local health = pile:GetAttribute("Health") - (1 + petPower(player))
if health > 0 then
pile:SetAttribute("Health", health)
pile.HealthGui.Label.Text = health .. "/" .. pile:GetAttribute("MaxHealth")
return
end
player.leaderstats.Coins.Value += pile:GetAttribute("Value")
local spot = pileSpot[pile]
pileSpot[pile] = nil
pile:Destroy()
-- un nuovo mucchio nello stesso punto, pochi secondi dopo
task.delay(Settings.RespawnTime, spawnPile, spot)
end
-- Un mucchio in ogni punto, in ogni zona
for _, zone in workspace.Zones:GetChildren() do
for _, spot in zone.Spawns:GetChildren() do
spawnPile(spot)
end
end
-- Il client chiede di colpire un mucchio. Non fidarti mai del client: chiunque può attivare
-- questo remote con qualsiasi cosa, da qualsiasi luogo, con la frequenza che vuole.
remotes.Hit.OnServerEvent:Connect(function(player, pile)
-- un mucchio valido
if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
return
end
-- a portata
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if not root or (root.Position - pile.Position).Magnitude > Settings.Reach then
return
end
-- non troppo in fretta
local now = time()
if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
return
end
lastHit[player] = now
-- in una zona che il giocatore ha sbloccato
if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
return
end
hitPile(player, pile)
end)
-- Un'estrazione ponderata: Chance di ogni pet (su 100) è la sua quota dell'intervallo
local function rollPet()
local roll = math.random() * 100
for _, info in Settings.Pets do
roll -= info.Chance
if roll <= 0 then
return info.Name
end
end
return Settings.Pets[1].Name
end
-- Schiusa: il prompt dell'uovo, pagato in monete
workspace.Egg.ProximityPrompt.Triggered:Connect(function(player)
local coins = player.leaderstats.Coins
if coins.Value < Settings.EggPrice then
return
end
coins.Value -= Settings.EggPrice
local name = rollPet()
-- subito attivo, se c'è posto
local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
print(player.Name .. " hatched a " .. name)
-- tutti vengono a sapere degli animali più rari
if pet:GetAttribute("Rarity") == "Legendary" then
remotes.Announce:FireAllClients(player.Name, name)
end
end)
-- Gli animali attivi seguono il proprietario: ciascuno ha una parte nel mondo, disposta
-- in fila dietro al giocatore a ogni frame
local petModels = {} -- ogni animale -> la sua parte nel mondo
RunService.Heartbeat:Connect(function()
for _, player in Players:GetPlayers() do
local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
local pets = player:FindFirstChild("Pets")
local slot = 0
for _, pet in pets and pets:GetChildren() or {} do
local model = petModels[pet]
if pet:GetAttribute("Equipped") and root then
slot += 1
if not model then
model = ServerStorage.PetModels[pet.Value]:Clone()
model.Parent = petParts
petModels[pet] = model
end
model.CFrame = root.CFrame * CFrame.new((slot - 2) * 3, -1.5, 4)
elseif model then
-- messo via: la sua parte scompare
model:Destroy()
petModels[pet] = nil
end
end
end
end)
-- Il client chiede di attivare o mettere via un animale. Il server verifica che l'animale sia
-- del giocatore e che non ce ne siano più di MaxEquipped attivi.
remotes.Equip.OnServerEvent:Connect(function(player, pet)
if typeof(pet) ~= "Instance" or pet.Parent ~= player.Pets then
return
end
if pet:GetAttribute("Equipped") then
pet:SetAttribute("Equipped", false)
elseif equippedCount(player) < Settings.MaxEquipped then
pet:SetAttribute("Equipped", true)
end
end)
-- Il cancello di Desert: si paga una volta e si apre, solo per quel giocatore
workspace.Gate.ProximityPrompt.Triggered:Connect(function(player)
local coins = player.leaderstats.Coins
if player:GetAttribute("Desert") or coins.Value < Settings.GatePrice then
return
end
coins.Value -= Settings.GatePrice
player:SetAttribute("Desert", true)
end)
-- Salvataggio: Coins, Desert e ogni animale
local function save(player)
local pets = {}
for _, pet in player.Pets:GetChildren() do
table.insert(pets, { Name = pet.Value, Equipped = pet:GetAttribute("Equipped") == true })
end
local data = {
Coins = player.leaderstats.Coins.Value,
Desert = player:GetAttribute("Desert") == true,
Pets = pets,
}
pcall(function()
saveStore:SetAsync(player.UserId, data)
end)
end
Players.PlayerRemoving:Connect(save)
game:BindToClose(function()
for _, player in Players:GetPlayers() do
save(player)
end
end)
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Gioco Roblox: Simulatore di animali domestici
4Il mondo
La porta del desertoEsercitati da solo: Playground Roblox