Menu
CoddyTech

Lưu khi rời đi

Bài học 18 trên 22 trong khóa học Game Roblox: nhà máy tycoon của Coddy.

Không ai muốn chơi một trò chơi xây dựng đế chế rồi bị quên mất tiến trình. DataStore lưu một bảng cho mỗi người chơi theo UserId của họ, và thời điểm lưu là khi họ rời đi:

local scoreStore = DataStoreService:GetDataStore("Scores")
scoreStore:SetAsync(player.UserId, { Best = 12 })

Lệnh gọi DataStore đi qua mạng nên có thể thất bại, vì vậy nó được bọc trong pcall: khi lưu thất bại, lệnh gọi trả về false thay vì làm dừng tập lệnh. Việc lưu diễn ra khi có sự kiện Players.PlayerRemoving, và với mọi người chơi trong game:BindToClose, sự kiện này chạy khi máy chủ tắt trong lúc vẫn còn người chơi.

challenge icon

Thử thách

Khó

Lưu Cash và Rebirths của mỗi người chơi khi họ rời đi.

  1. Gần đầu đoạn code: local factoryStore = DataStoreService:GetDataStore("Factory").
  2. Viết saveFactory(player): tạo local data = { Cash = ..., Rebirths = ... } từ leaderstats của họ, rồi gọi factoryStore:SetAsync(player.UserId, data) trong pcall.
  3. Gọi hàm này khi sự kiện Players.PlayerRemoving xảy ra và cho mọi người chơi trong game:BindToClose.

Nhấn Chơi: trò chơi vẫn chạy như trước, còn bài học tiếp theo sẽ tải dữ liệu mà bài học này lưu. Sau đó nhấn Kiểm tra.

Tự làm thử

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local CollectionService = game:GetService("CollectionService")
local TweenService = game:GetService("TweenService")
local Debris = game:GetService("Debris")
local Settings = require(game.ReplicatedStorage.Settings)

local tycoon = workspace.Tycoon
local items = ServerStorage.TycoonItems
local rebirthPad = ServerStorage.RebirthPad
local owner = nil
local headline = "Step on the green pad to claim this factory"
local earned = 0

print("Ore is worth " .. Settings.OreValue .. " Cash")

-- Mỗi người chơi đều có Cash và Rebirths 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 cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Parent = leaderstats

	local rebirths = Instance.new("IntValue")
	rebirths.Name = "Rebirths"
	rebirths.Parent = leaderstats
end)

-- Biển hiệu phía trên nhà máy
local gui = Instance.new("SurfaceGui")
gui.Parent = tycoon.Sign

local signLabel = Instance.new("TextLabel")
signLabel.Name = "Status"
signLabel.Size = UDim2.fromScale(1, 1)
signLabel.BackgroundColor3 = Color3.fromRGB(25, 25, 35)
signLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
signLabel.TextScaled = true
signLabel.Text = "Step on the green pad to claim this factory"
signLabel.Parent = gui

local function setSign(text)
	signLabel.Text = text
end

-- Ore: một khối nhỏ có giá trị Cash, rơi ra bên dưới máy thả
local function dropOre(dropper)
	local ore = Instance.new("Part")
	ore.Name = "Ore"
	ore.Size = Vector3.new(1, 1, 1)
	ore.Color = Color3.fromRGB(150, 150, 160)
	ore.Position = dropper.Position - Vector3.new(0, 2.5, 0)
	ore:SetAttribute("Value", Settings.OreValue)
	if math.random() < Settings.GoldChance then
		ore.Color = Color3.fromRGB(255, 200, 40)
		ore.Material = Enum.Material.Neon
		ore:SetAttribute("Value", Settings.OreValue * 5)
	end
	ore.Parent = workspace
	Debris:AddItem(ore, 20)
end

local function startDropper(dropper)
	task.spawn(function()
		while dropper:IsDescendantOf(workspace) do
			dropOre(dropper)
			task.wait(Settings.DropInterval)
		end
	end)
end

-- Băng chuyền vận chuyển mọi thứ nằm trên đó
tycoon.Conveyor.AssemblyLinearVelocity = Vector3.new(Settings.BeltSpeed, 0, 0)

-- Máy thu gom chuyển Ore thành Cash
tycoon.Collector.Touched:Connect(function(hit)
	if hit.Name == "Ore" then
		local value = hit:GetAttribute("Value")
		hit:Destroy()
		if owner then
			value = math.floor(value * (1 + owner.leaderstats.Rebirths.Value * Settings.RebirthBonus))
			owner.leaderstats.Cash.Value += value
			earned += value
		end
	end
end)

-- Máy nâng cấp tăng gấp đôi giá trị của mỗi Ore đi qua, chỉ một lần
items.Upgrader.Touched:Connect(function(hit)
	if hit.Name == "Ore" and not hit:GetAttribute("Upgraded") then
		hit:SetAttribute("Upgraded", true)
		hit:SetAttribute("Value", hit:GetAttribute("Value") * 2)
		hit.Color = Color3.fromRGB(155, 89, 182)
	end
end)

-- Các bệ chờ một vật phẩm khác được xây trước
local waiting = Instance.new("Folder")
waiting.Name = "WaitingPads"
waiting.Parent = ServerStorage

-- Các bệ đã mua, được giữ lại cho lần tái sinh tiếp theo
local bought = Instance.new("Folder")
bought.Name = "BoughtPads"
bought.Parent = ServerStorage

-- Một khối mới trồi lên đúng vị trí
local function riseIn(part)
	local goal = part.Position
	local transparency = part.Transparency
	part.Position = goal - Vector3.new(0, 8, 0)
	part.Transparency = 1
	TweenService:Create(part, TweenInfo.new(1), { Position = goal, Transparency = transparency }):Play()
end

local function checkComplete()
	if #tycoon.Buttons:GetChildren() == 0 and #waiting:GetChildren() == 0 then
		headline = "Factory complete! Step on the purple pad to rebirth"
		setSign(headline)
		rebirthPad.Parent = tycoon
	end
end

-- Đưa vật phẩm đã mua vào nhà máy
local function build(item)
	item.Parent = tycoon.Built
	if item:IsA("BasePart") then
		riseIn(item)
	end
	for _, part in item:GetDescendants() do
		if part:IsA("BasePart") then
			riseIn(part)
		end
	end
	if item:HasTag("Dropper") then
		-- Bắt đầu thả Ore khi máy đã vào đúng vị trí
		task.delay(1, startDropper, item)
	end
	for _, pad in waiting:GetChildren() do
		if pad:GetAttribute("After") == item.Name then
			pad.Parent = tycoon.Buttons
		end
	end
	checkComplete()
end

-- Mua: bệ biến mất và vật phẩm tương ứng được xây
local function buy(pad, player)
	if player ~= owner or pad.Parent ~= tycoon.Buttons then
		return
	end
	local cash = player.leaderstats.Cash
	local price = pad:GetAttribute("Price")
	if cash.Value < price then
		return
	end
	cash.Value -= price
	pad.Parent = bought
	build(items:FindFirstChild(pad:GetAttribute("Item")))
end

for _, pad in tycoon.Buttons:GetChildren() do
	pad.Touched:Connect(function(hit)
		local player = Players:GetPlayerFromCharacter(hit.Parent)
		if player then
			buy(pad, player)
		end
	end)
end

-- Nhãn giá hiển thị phía trên mỗi bệ
for _, pad in tycoon.Buttons:GetChildren() do
	local tag = Instance.new("BillboardGui")
	tag.Name = "PriceTag"
	tag.Size = UDim2.fromOffset(160, 40)
	tag.StudsOffset = Vector3.new(0, 3, 0)
	tag.Parent = pad

	local label = Instance.new("TextLabel")
	label.Size = UDim2.fromScale(1, 1)
	label.BackgroundColor3 = Color3.fromRGB(25, 25, 35)
	label.BackgroundTransparency = 0.2
	label.TextColor3 = Color3.fromRGB(255, 255, 255)
	label.TextScaled = true
	label.Text = pad:GetAttribute("Label") .. ": $" .. pad:GetAttribute("Price")
	label.Parent = tag
end

-- Lúc bắt đầu, chỉ các bệ đầu tiên xuất hiện
for _, pad in tycoon.Buttons:GetChildren() do
	if pad:GetAttribute("After") then
		pad.Parent = waiting
	end
end

-- Đưa nhà máy về trạng thái trống: cất vật phẩm vào kho, đưa các bệ về vị trí ban đầu
local function resetFactory()
	rebirthPad.Parent = ServerStorage
	for _, item in tycoon.Built:GetChildren() do
		item.Parent = items
	end
	for _, pad in bought:GetChildren() do
		if pad:GetAttribute("After") then
			pad.Parent = waiting
		else
			pad.Parent = tycoon.Buttons
		end
	end
end

rebirthPad.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if player and player == owner and rebirthPad.Parent == tycoon then
		resetFactory()
		player.leaderstats.Rebirths.Value += 1
		player.leaderstats.Cash.Value = 0
		headline = player.Name .. "'s Factory"
		setSign(headline)
	end
end)

-- Bài học 18: thêm tính năng lưu khi rời trò chơi tại đây

-- Bảng hiệu hiển thị thu nhập của chủ nhà máy sau mỗi 5 giây
task.spawn(function()
	while true do
		task.wait(5)
		if owner then
			setSign(headline .. "\n$" .. math.floor(earned / 5) .. " a second")
		end
		earned = 0
	end
end)

-- Nhận nhà máy: người chơi đầu tiên bước lên bệ sẽ sở hữu nhà máy
local claimPad = tycoon.ClaimPad
claimPad.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if player and not owner then
		owner = player
		claimPad.Color = Color3.fromRGB(120, 120, 120)
		claimPad.Material = Enum.Material.SmoothPlastic
		headline = player.Name .. "'s Factory"
		setSign(headline)
		for _, dropper in CollectionService:GetTagged("Dropper") do
			if dropper:IsDescendantOf(workspace) then
				startDropper(dropper)
			end
		end
	end
end)

Tất cả bài học trong Game Roblox: nhà máy tycoon

Tự luyện tập: Playground Roblox