Menu
CoddyTech

Lưu khi rời đi

Bài học 19 trên 20 trong khóa học Trò chơi Roblox: mô phỏng thú cưng của Coddy.

Xu, sa mạc và mọi thú cưng vẫn nên còn đó vào lần tiếp theo người chơi tham gia. DataStore lưu một bảng cho mỗi người chơi, theo UserId của họ. Thú cưng là các instance mà DataStore không thể lưu, vì vậy hãy lưu một bảng thông thường gồm tên của mỗi thú cưng và thông tin liệu nó có đang được trang bị hay không:

{ Coins = 340, Desert = false, Pets = { { Name = "Bunny", Equipped = true } } }

Hãy lưu dữ liệu khi người chơi rời đi (PlayerRemoving) và, phòng trường hợp máy chủ tắt khi vẫn còn người chơi bên trong, trong game:BindToClose. Quá trình lưu có thể thất bại ở phía Roblox, vì vậy hãy bọc nó trong pcall:

pcall(function()
	saveStore:SetAsync(player.UserId, data)
end)

Trong Roblox Studio, DataStore hoạt động sau khi địa điểm được xuất bản và bật Enable Studio Access to API Services.

challenge icon

Thử thách

Khó

Lưu trò chơi của từng người chơi khi họ rời đi.

  1. Lấy DataStoreService và local saveStore = DataStoreService:GetDataStore("Pets").
  2. Viết save(player): trong một lệnh pcall, gọi saveStore:SetAsync(player.UserId, data) với Coins, Desert và Pets, một danh sách gồm { Name = pet.Value, Equipped = ... }.
  3. Gọi hàm này khi có sự kiện Players.PlayerRemoving và với mọi người chơi trong game:BindToClose.

Nhấn Chơi, kiếm xu rồi nhấn Dừng: dữ liệu sẽ được lưu khi bạn rời đi. Sau đó nhấn Kiểm tra.

Tự làm thử

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 = {} -- mỗi đống xu tương ứng với vị trí của nó
local lastHit = {} -- mỗi người chơi tương ứng với thời điểm đánh gần nhất

print("A Meadow pile gives " .. Settings.PileValue .. " coins")

-- Settings.Pets theo tên
local petInfo = {}
for _, info in Settings.Pets do
	petInfo[info.Name] = info
end

-- Một thú cưng: StringValue trong thư mục Pets của người chơi, lưu tên của nó cùng
-- độ hiếm và sức mạnh dưới dạng thuộc tính
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

-- số thú cưng mà người chơi đang cho ra ngoài
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

-- sức mạnh thú cưng cộng thêm vào mỗi lần đánh của người chơi
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

-- Mỗi người chơi có Coins trên bảng xếp hạng
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

	-- những thú cưng họ sở hữu
	local pets = Instance.new("Folder")
	pets.Name = "Pets"
	pets.Parent = player
end)

-- Đống xu tại một vị trí: bản sao của ServerStorage.CoinPile, có lượng máu
-- và giá trị dưới dạng thuộc tính
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

-- Mỗi lần đánh trừ 1 cộng với sức mạnh thú cưng của người chơi khỏi lượng máu của đống xu;
-- Khi còn 0 máu, đống xu vỡ ra và trả số xu tương ứng với giá trị của nó
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()
	-- Vài giây sau, một đống xu mới xuất hiện ở cùng vị trí
	task.delay(Settings.RespawnTime, spawnPile, spot)
end

-- Mỗi vị trí trong mỗi khu vực đều có một đống xu
for _, zone in workspace.Zones:GetChildren() do
	for _, spot in zone.Spawns:GetChildren() do
		spawnPile(spot)
	end
end

-- Client yêu cầu đánh một đống xu. Đừng bao giờ tin client: bất kỳ ai cũng có thể kích hoạt
-- remote này với bất kỳ dữ liệu nào, từ bất kỳ đâu, nhanh tùy ý.
remotes.Hit.OnServerEvent:Connect(function(player, pile)
	-- đúng là đống xu trong trò chơi
	if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
		return
	end
	-- trong tầm đánh
	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
	-- không đánh quá nhanh
	local now = time()
	if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
		return
	end
	lastHit[player] = now
	-- trong khu vực người chơi đã mở khóa
	if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
		return
	end
	hitPile(player, pile)
end)

-- Chọn ngẫu nhiên có trọng số: Chance của mỗi pet (trên 100) quyết định phần cơ hội của pet đó
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

-- Ấp trứng: tương tác với quả trứng và trả bằng xu
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()
	-- cho pet ra ngay nếu còn chỗ
	local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
	print(player.Name .. " hatched a " .. name)
	-- Mọi người đều biết khi có thú cưng hiếm nhất
	if pet:GetAttribute("Rarity") == "Legendary" then
		remotes.Announce:FireAllClients(player.Name, name)
	end
end)

-- Thú cưng được mang theo sẽ đi theo chủ: mỗi con có một bộ phận trong thế giới, nằm
-- thành hàng sau người chơi ở mỗi khung hình
local petModels = {} -- mỗi thú cưng -> bộ phận của nó trong thế giới
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
				-- Cất đi: bộ phận của nó biến mất
				model:Destroy()
				petModels[pet] = nil
			end
		end
	end
end)

-- Client yêu cầu mang thú cưng ra hoặc cất đi. Máy chủ kiểm tra: thú cưng đó
-- thuộc về người chơi và số thú cưng được mang theo không vượt quá 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)

-- Cổng Desert: trả tiền một lần để mở cổng, chỉ dành cho người chơi đó
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)

-- Bài học 19: phần lưu khi rời trò chơi nằm ở đây

Tất cả bài học trong Trò chơi Roblox: mô phỏng thú cưng

Tự luyện tập: Playground Roblox