Спасите питомцев
Урок 18 из 18 курса Игра в Roblox: симулятор питомцев на Coddy.
Монеты, Пустыня и все питомцы должны оставаться на месте, когда игрок присоединится в следующий раз. DataStore хранит таблицу для каждого игрока под его UserId. Питомцы — это экземпляры, которые DataStore не может хранить, поэтому сохраняй простую таблицу с именем каждого питомца и указанием, находится ли он вне клетки, а при присоединении снова создавай питомцев на её основе:
{ Coins = 120, Desert = true, Pets = { { Name = "Fox", Equipped = true } } }Сохраняй данные, когда игрок выходит (PlayerRemoving) и когда сервер закрывается (game:BindToClose); загружай их в PlayerAdded. Оба вызова могут завершиться ошибкой на стороне Roblox, поэтому оберни их в pcall. В Roblox Studio DataStores работают после публикации места, если включён параметр Enable Studio Access to API Services.
Задание
Сложно- Получи
DataStoreServiceи хранилище данных с именемPets. - Напиши
save(player): сохраняйCoins,Desertи список{ Name, Equipped }для каждого питомца под UserId игрока с помощью pcall. Вызывай её приPlayerRemovingи для каждого игрока вgame:BindToClose. - В
PlayerAdded, после создания папок, загрузи сохранение (с помощью pcall) и восстанови монеты, атрибут Desert и питомцев (пропускай имена, которых нет вpetInfo).
Нажми Play, вылупи питомца, нажми Stop, а затем снова Play: твои питомцы вернулись. Затем нажми Check.
Попробуйте сами
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local RunService = game:GetService("RunService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local pileSpot = {} -- каждая куча -> место, на котором она стоит
local lastHit = {} -- каждый игрок -> время его последнего удара
print("A Meadow pile gives " .. Settings.PileValue .. " coins")
-- Settings.Pets по имени
local petInfo = {}
for _, info in Settings.Pets do
petInfo[info.Name] = info
end
-- Питомец: StringValue в папке Pets игрока, хранящий его имя, а также
-- редкость и силу в виде атрибутов
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
-- сколько питомцев игрока сейчас выпущено
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
-- сколько силы питомцы игрока добавляют к каждому удару
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
-- Каждый игрок получает Coins в таблице лидеров
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
-- питомцы, которыми они владеют
local pets = Instance.new("Folder")
pets.Name = "Pets"
pets.Parent = player
end)
-- Куча монет на месте появления: копия ServerStorage.CoinPile, у которой здоровье
-- и ценность заданы атрибутами
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
-- Удар уменьшает здоровье кучи на 1 плюс силу питомцев игрока;
-- при 0 куча разрушается, и игрок получает её стоимость
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()
-- через несколько секунд на том же месте появляется новая куча
task.delay(Settings.RespawnTime, spawnPile, spot)
end
-- По куче на каждом месте в каждой зоне
for _, zone in workspace.Zones:GetChildren() do
for _, spot in zone.Spawns:GetChildren() do
spawnPile(spot)
end
end
-- Клиент запрашивает удар по куче. Никогда не доверяйте клиенту: кто угодно может отправить
-- это удалённое событие с любыми данными, откуда угодно и сколь угодно часто.
remotes.Hit.OnServerEvent:Connect(function(player, pile)
-- настоящая куча
if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
return
end
-- в пределах досягаемости
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
-- не слишком часто
local now = time()
if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
return
end
lastHit[player] = now
-- в зоне, которую игрок открыл
if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
return
end
hitPile(player, pile)
end)
-- Случайный выбор с весами: Chance каждого питомца (из 100) определяет его долю
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
-- Вылупление: взаимодействие с яйцом за монеты
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()
-- сразу выпустить питомца, если есть место
local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
print(player.Name .. " hatched a " .. name)
-- Все узнают о самых редких питомцах
if pet:GetAttribute("Rarity") == "Legendary" then
remotes.Announce:FireAllClients(player.Name, name)
end
end)
-- Выпущенные питомцы следуют за владельцем: у каждого есть объект в игровом мире; они выстраиваются
-- в ряд позади игрока на каждом кадре
local petModels = {} -- каждый питомец -> его объект в игровом мире
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
model:Destroy()
petModels[pet] = nil
end
end
end
end)
-- Клиент запрашивает выпуск питомца или его отзыв. Сервер проверяет, что питомец
-- принадлежит игроку и что выпущено не более MaxEquipped питомцев.
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)
-- Ворота в Desert: заплатив один раз, игрок открывает их только для себя
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)
В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.