Lưu khi rời đi
Bài học 24 trên 25 trong khóa học Trò chơi Roblox: thoát khỏi bóng tối của Coddy.
Phòng sâu nhất mà người chơi đã đến, giá trị Best trên bảng xếp hạng, nên được lưu lại giữa các lần chơi. DataStore lưu dữ liệu trên máy chủ Roblox theo khóa: ở đây là UserId của người chơi dưới dạng chuỗi.
Hãy lưu dữ liệu khi người chơi rời đi và khi máy chủ đóng (game:BindToClose), vì máy chủ đang đóng không kịp kích hoạt PlayerRemoving cho tất cả mọi người. Data store có thể gặp lỗi, nên hãy đặt lệnh gọi trong pcall:
pcall(function()
scoreStore:SetAsync(tostring(player.UserId), 7)
end)Trong Roblox Studio, DataStore hoạt động sau khi bạn xuất bản place và bật Enable Studio Access to API Services.
Thử thách
KhóLưu lại căn phòng xa nhất mà mỗi người chơi đã đến, rồi lưu dữ liệu khi họ rời đi.
- Thêm
local bestStore = DataStoreService:GetDataStore("BestRoom")và một IntValueBesttrong leaderstats. - Trong
setupEntry, tăng Best khi số phòng cao hơn. - Viết
saveBest(player): gọiSetAsync(tostring(player.UserId), Best)trong một pcall. Kết nối hàm này vớiPlayers.PlayerRemoving, rồi chạy hàm cho tất cả người chơi tronggame:BindToClose.
Nhấn Chơi rồi đi vào phòng 1: Best của bạn chuyển thành 1. Sau đó nhấn Kiểm tra.
Tự làm thử
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Lighting = game:GetService("Lighting")
local TweenService = game:GetService("TweenService")
local PathfindingService = game:GetService("PathfindingService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local rooms = workspace.Rooms
local lastRoom = rooms.Lobby -- Phòng mới nhất
local count = 0 -- Số phòng đã tạo đến lúc này
local monster = nil
local codes = {} -- Cửa hầm: mã của cửa đó
local lastTry = {} -- Người chơi: thời điểm họ thử nhập mã gần nhất
-- Đêm xuống: không có mặt trời, ánh sáng yếu khắp nơi và sương mù
Lighting.ClockTime = Settings.ClockTime
Lighting.Ambient = Settings.Ambient
Lighting.OutdoorAmbient = Settings.Ambient
Lighting.FogColor = Color3.new(0, 0, 0)
Lighting.FogEnd = Settings.FogEnd
print("Lights out")
-- Vật dụng người chơi mang theo: cầm trên tay hoặc để trong Backpack
local function findTool(player, name)
return (player.Character and player.Character:FindFirstChild(name)) or player.Backpack:FindFirstChild(name)
end
-- Đèn pin hao pin khi bật và tắt khi hết pin
task.spawn(function()
while true do
task.wait(0.25)
for _, player in Players:GetPlayers() do
local flashlight = player.Character and player.Character:FindFirstChild("Flashlight")
if flashlight and flashlight.Handle.Beam.Enabled then
local battery = math.max(0, flashlight:GetAttribute("Battery") - Settings.BatteryDrain * 0.25)
flashlight:SetAttribute("Battery", battery)
if battery == 0 then
flashlight.Handle.Beam.Enabled = false
end
end
end
end
end)
-- Mở cửa bằng cách xoay quanh bản lề
local function openDoor(door)
door:SetAttribute("Open", true)
door.Panel.Prompt.Enabled = false
local hinge, panel = door.Hinge, door.Panel
local goal = hinge.CFrame * CFrame.Angles(0, math.rad(90), 0) * hinge.CFrame:ToObjectSpace(panel.CFrame)
TweenService:Create(panel, TweenInfo.new(0.6), { CFrame = goal }):Play()
end
-- Thoát ra: lượt chơi kết thúc (và thời gian đã mất)
local function escape(player)
if player:GetAttribute("Escaped") then
return
end
player:SetAttribute("EscapeTime", workspace:GetServerTimeNow() - player:GetAttribute("StartedAt"))
player:SetAttribute("Escaped", true)
if monster then
monster:Destroy()
monster = nil
end
end
-- Người chơi còn sống gần nhất mà quái vật có thể bắt (không ẩn nấp), trong phạm vi MonsterSight, cùng khoảng cách đến họ
local function nearestCharacter(position)
local best, bestDistance = nil, Settings.MonsterSight
for _, player in Players:GetPlayers() do
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if root and character.Humanoid.Health > 0 and not character:GetAttribute("Hidden") then
local distance = (root.Position - position).Magnitude
if distance < bestDistance then
best, bestDistance = character, distance
end
end
end
return best, bestDistance
end
-- Quái vật có nhìn thấy nhân vật này không? Một tia từ đầu quái vật chiếu trúng nhân vật
local function canSee(shadow, character)
local from = shadow.Head.Position
local params = RaycastParams.new()
params.FilterDescendantsInstances = { shadow }
local hit = workspace:Raycast(from, character.HumanoidRootPart.Position - from, params)
return hit ~= nil and hit.Instance:IsDescendantOf(character)
end
-- Đi tới một điểm: đi thẳng nếu không bị cản, nếu không thì đi theo đường tìm được
local function walkToward(shadow, goal, path)
local root = shadow.HumanoidRootPart
local params = RaycastParams.new()
params.FilterDescendantsInstances = { shadow }
local hit = workspace:Raycast(root.Position, goal - root.Position, params)
if not hit or hit.Instance.Parent:FindFirstChildOfClass("Humanoid") then
shadow.Humanoid:MoveTo(goal)
return
end
path:ComputeAsync(root.Position, goal)
local points = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success and points[2] then
shadow.Humanoid:MoveTo(points[2].Position)
end
end
-- Giữa căn phòng cách phòng người chơi đang ở `back` phòng (phòng
-- ngay trước phòng mới nhất), nơi quái vật tuần tra
local function patrolPoint(back)
for _, room in rooms:GetChildren() do
if room:GetAttribute("Number") == count - 1 - back then
return (room.Entrance.CFrame * CFrame.new(0, 3.1, -12)).Position
end
end
return nil
end
-- Hành vi của quái vật: cứ mỗi phần tư giây lại đuổi theo ai đó
local function runMonster(shadow)
local humanoid = shadow.Humanoid
local root = shadow.HumanoidRootPart
local path = PathfindingService:CreatePath()
local lastSeen = nil -- nơi nó nhìn thấy ai đó lần cuối
local back = 0 -- Lộ trình tuần tra: 0 là phòng của người chơi, 2 là phòng cách đó hai phòng
while shadow.Parent do
local character = nearestCharacter(root.Position)
if character and canSee(shadow, character) then
lastSeen = character.HumanoidRootPart.Position
else
character = nil
end
if character and (character.HumanoidRootPart.Position - root.Position).Magnitude <= Settings.CatchDistance then
-- bắt được người chơi: người chơi thua, quái vật biến mất cho đến cánh cửa tiếp theo
character.Humanoid.Health = 0
shadow:Destroy()
monster = nil
return
end
local goal = character and character.HumanoidRootPart.Position or lastSeen
if goal then
walkToward(shadow, goal, path)
-- đến nơi nó nhìn thấy bạn lần cuối mà bạn không còn ở đó: nó bỏ cuộc
if not character and ((goal - root.Position) * Vector3.new(1, 0, 1)).Magnitude < 1.5 then
lastSeen = nil
end
else
-- không thấy ai: tuần tra qua lại
local point = patrolPoint(back) or patrolPoint(0)
if point then
walkToward(shadow, point, path)
if ((point - root.Position) * Vector3.new(1, 0, 1)).Magnitude < 2 then
back = back == 0 and 2 or 0
end
end
end
task.wait(0.25)
end
end
-- Quái vật xuất hiện phía sau bạn, ở lối vào căn phòng cách phòng mới nhất hai phòng
local function spawnMonster()
local behind = nil
for _, room in rooms:GetChildren() do
if room:GetAttribute("Number") == count - 2 then
behind = room
end
end
if not behind then
return
end
monster = ServerStorage.Shadow:Clone()
monster:PivotTo(behind.Entrance.CFrame + Vector3.new(0, 3.1, 0))
monster.Humanoid.WalkSpeed = Settings.MonsterSpeed
monster.Parent = workspace
task.spawn(runMonster, monster)
end
local addRoom -- viết bên dưới: mở cửa sẽ thêm một phòng, và mỗi phòng đều có cửa
-- Cửa hoạt động thế nào khi người chơi mở nó
local function setupDoor(door)
door.Panel.Prompt.Triggered:Connect(function(player)
if door:GetAttribute("Open") then
return
end
if door:GetAttribute("Vault") and door:GetAttribute("Locked") then
return -- cửa kho mở bằng mã nhập trên bàn phím
end
if door:GetAttribute("Locked") then
local key = findTool(player, "Key")
if not key then
return
end
key:Destroy()
door:SetAttribute("Locked", nil)
end
if door:GetAttribute("Exit") then
escape(player)
openDoor(door)
return
end
if door.Parent == lastRoom then
addRoom()
end
openDoor(door)
end)
end
setupDoor(workspace.Rooms.Lobby.Door)
-- Khi người chơi bước vào một phòng, phòng đó trở thành Room và điểm hồi sinh của họ
local function setupEntry(room)
room.Entry.Touched:Connect(function(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
local number = room:GetAttribute("Number")
player.leaderstats.Room.Value = number
player.RespawnLocation = room.Checkpoint
end
end)
end
setupEntry(workspace.Rooms.Lobby)
-- Tủ quần áo: nhấn E để trốn vào, nhấn E lần nữa để ra ngoài
local function setupCloset(closet)
closet.Front.Prompt.Triggered:Connect(function(player)
local character = player.Character
if character:GetAttribute("Hidden") then
character:PivotTo(closet.Front.CFrame * CFrame.new(-3, -1, 0) * CFrame.Angles(0, math.rad(90), 0))
character:SetAttribute("Hidden", nil)
else
character:PivotTo(closet.Inside.CFrame + Vector3.new(0, 2.5, 0))
character:SetAttribute("Hidden", true)
end
end)
end
-- Phòng mới nằm ở lối ra của phòng mới nhất
function addRoom()
count += 1
local name = Settings.Order[(count - 1) % #Settings.Order + 1]
if count >= Settings.RoomsToEscape then
name = "Exit"
end
local room = ServerStorage.Rooms[name]:Clone()
room:PivotTo(lastRoom.Exit.CFrame)
room:SetAttribute("Number", count)
room.Sign.SurfaceGui.Number.Text = "Room " .. count
room.Parent = rooms
lastRoom = room
setupDoor(room.Door)
setupEntry(room)
-- phòng bị khóa chứa chìa khóa bên trong
local keySpot = room:FindFirstChild("KeySpot")
if keySpot then
local key = ServerStorage.Key:Clone()
key.Handle.CFrame = keySpot.CFrame
key.Parent = room
key.Handle.Prompt.Triggered:Connect(function(player)
key.Handle.Prompt.Enabled = false
key.Parent = player.Backpack
end)
end
local closet = room:FindFirstChild("Closet")
if closet then
setupCloset(closet)
end
-- một số phòng có pin
local batterySpot = room:FindFirstChild("BatterySpot")
if batterySpot then
local battery = ServerStorage.Battery:Clone()
battery.CFrame = batterySpot.CFrame
battery.Parent = room
battery.Prompt.Triggered:Connect(function(player)
local flashlight = findTool(player, "Flashlight")
if flashlight and battery.Parent then
flashlight:SetAttribute("Battery", math.min(Settings.BatteryMax, flashlight:GetAttribute("Battery") + Settings.BatteryRefill))
battery:Destroy()
end
end)
end
-- mã két sắt nằm trên tờ giấy bên trong két
if room.Door:GetAttribute("Vault") then
local code = tostring(math.random(1000, 9999))
codes[room.Door] = code
room.Note.SurfaceGui.Code.Text = "Code " .. code
end
-- giữ lại phòng mới nhất và KeepRooms phòng phía sau
for _, old in rooms:GetChildren() do
local number = old:GetAttribute("Number")
if number < count - Settings.KeepRooms then
print("Room " .. number .. " is gone")
old:Destroy()
end
end
if count >= Settings.MonsterFrom and not monster then
spawnMonster()
end
return room
end
-- Ra khỏi tủ quần áo, bạn không còn ẩn nấp nữa
task.spawn(function()
while true do
task.wait(0.25)
for _, player in Players:GetPlayers() do
local character = player.Character
if character and character:GetAttribute("Hidden") then
local closest = math.huge
for _, inside in workspace.Rooms:GetDescendants() do
if inside.Name == "Inside" then
closest = math.min(closest, (inside.Position - character.HumanoidRootPart.Position).Magnitude)
end
end
if closest > 4 then
character:SetAttribute("Hidden", nil)
end
end
end
end
end)
-- Mã nhập trên bàn phím két sắt. Máy chủ kiểm tra: két sắt có thật ở gần
-- người chơi, mỗi CodeWait chỉ thử một lần và mã phải đúng
remotes.TryCode.OnServerInvoke = function(player, door, code)
if typeof(door) ~= "Instance" or not codes[door] or typeof(code) ~= "string" then
return false
end
local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
if not root or (root.Position - door.Panel.Position).Magnitude > 12 then
return false
end
local now = time()
if lastTry[player] and now - lastTry[player] < Settings.CodeWait then
return false
end
lastTry[player] = now
if code ~= codes[door] then
return false
end
codes[door] = nil
door:SetAttribute("Locked", nil)
if door.Parent == lastRoom then
addRoom()
end
openDoor(door)
return true
end
-- Mỗi người chơi: Room trên bảng xếp hạng và một đèn pin mỗi lần hồi sinh
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local room = Instance.new("IntValue")
room.Name = "Room"
room.Parent = leaderstats
player.CharacterAdded:Connect(function()
if not player:GetAttribute("StartedAt") then
player:SetAttribute("StartedAt", workspace:GetServerTimeNow())
end
local flashlight = ServerStorage.Flashlight:Clone()
flashlight:SetAttribute("Battery", Settings.BatteryMax)
flashlight.Parent = player.Backpack
local beam = flashlight.Handle.Beam
flashlight.Activated:Connect(function()
if beam.Enabled then
beam.Enabled = false
elseif flashlight:GetAttribute("Battery") > 0 then
beam.Enabled = true
end
end)
end)
end)
-- Bài học 24: thêm Save on Leave vào đây
Tất cả bài học trong Trò chơi Roblox: thoát khỏi bóng tối
4Thoát hiểm
PinTự luyện tập: Playground Roblox