접속할 때 불러오기
Coddy의 Roblox 게임: 어둠 속 탈출 코스 레슨. 25개 중 25번째.
최고 점수는 저장되지만, 돌아온 플레이어는 여전히 0에서 시작합니다. 플레이어가 참가할 때 GetAsync로 값을 다시 읽어 오세요. 이때도 pcall을 사용합니다.
GetAsync는 저장소의 응답을 기다립니다. PlayerAdded 안에서 대기하는 함수는 아래 코드가 실행되기 전에 플레이어의 첫 캐릭터가 생성될 시간을 벌어 줍니다. 따라서 CharacterAdded 연결을 먼저 하고, 읽기는 마지막에 합니다.
local ok, saved = pcall(function()
return scoreStore:GetAsync(tostring(player.UserId))
end)
if ok and saved then
score.Value = saved
end이것이 게임의 전부입니다. 어두운 방, 괴물, 그리고 탈출구가 있습니다.
챌린지
어려움다시 접속한 플레이어에게 최고 기록을 돌려주세요.
PlayerAdded에서BestIntValue 다음에bestStore:GetAsync(tostring(player.UserId))를 pcall 안에서 호출하세요.- 호출에 성공하고 숫자를 찾았다면 Best를 해당 숫자로 설정하세요.
‘플레이’를 누르고 방 1로 걸어 들어간 다음, 중지하고 다시 ‘플레이’를 누르세요. Best가 여전히 1로 표시됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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 DataStoreService = game:GetService("DataStoreService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local rooms = workspace.Rooms
local lastRoom = rooms.Lobby -- 가장 최근에 생성된 방
local count = 0 -- 지금까지 생성된 방의 수
local monster = nil
local codes = {} -- 금고 문 -> 해당 문의 비밀번호
local lastTry = {} -- 플레이어 -> 마지막으로 비밀번호를 입력한 시각
local bestStore = DataStoreService:GetDataStore("BestRoom")
-- 밤이 찾아온다: 태양은 사라지고, 사방에 희미한 빛과 안개가 깔린다
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")
-- 플레이어가 가진 도구: 손에 들고 있거나 Backpack에 있음
local function findTool(player, name)
return (player.Character and player.Character:FindFirstChild(name)) or player.Backpack:FindFirstChild(name)
end
-- 손전등은 켜져 있는 동안 배터리가 줄어들고, 배터리가 다하면 꺼진다
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)
-- 경첩을 축으로 문을 회전시켜 연다
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
-- 탈출: 플레이가 끝난다 (걸린 시간도 기록)
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
-- MonsterSight 범위 안에서 잡을 수 있는 가장 가까운 살아 있는 플레이어(숨어 있지 않음)와 그 거리
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
-- 괴물이 이 캐릭터를 볼 수 있을까? 머리에서 쏜 광선이 캐릭터에 닿는지 확인
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
-- 목표 지점으로 이동: 길이 뚫려 있으면 직진하고, 아니면 경로를 따라 이동
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
-- 플레이어가 있는 방에서 `back`개 방만큼 앞선 방(가장 최신 방의
-- 바로 앞 방)의 중앙, 몬스터의 순찰 지점
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
-- 몬스터의 행동 방식: 0.25초마다 누군가를 쫓음
local function runMonster(shadow)
local humanoid = shadow.Humanoid
local root = shadow.HumanoidRootPart
local path = PathfindingService:CreatePath()
local lastSeen = nil -- 마지막으로 누군가를 본 위치
local back = 0 -- 순찰 위치: 0은 플레이어의 방, 2는 두 방 뒤
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
-- 붙잡힘: 플레이어는 쓰러지고, 몬스터는 다음 문이 열릴 때까지 사라짐
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)
-- 마지막으로 당신을 본 곳에 도착했는데 당신이 없으면 추적을 포기함
if not character and ((goal - root.Position) * Vector3.new(1, 0, 1)).Magnitude < 1.5 then
lastSeen = nil
end
else
-- 시야에 아무도 없으면 앞뒤로 순찰함
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
-- 몬스터가 뒤에서 나타남: 가장 최신 방에서 두 방 앞선 방의 입구
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 -- 아래에 정의됨: 문을 열면 방이 추가되고, 방에는 문이 있음
-- 플레이어가 문을 열 때 일어나는 일
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 -- 금고 문은 키패드에 코드를 입력하면 열림
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)
-- 방에 들어가면 그 방이 플레이어의 Room이자 체크포인트가 됩니다
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
if number > player.leaderstats.Best.Value then
player.leaderstats.Best.Value = number
end
end
end)
end
setupEntry(workspace.Rooms.Lobby)
-- 옷장: E를 누르면 안에 숨고, 다시 E를 누르면 나옵니다
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
-- 가장 최근 방의 출구에 새 방을 만듭니다
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)
-- 잠긴 방의 열쇠는 그 방 안에 있습니다
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
-- 일부 방에는 배터리가 있습니다
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
-- 금고의 코드는 그 안에 있는 쪽지에 적혀 있습니다
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
-- 가장 최근 방과 그 뒤의 KeepRooms개 방을 유지합니다
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
-- 옷장에서 나오면 더 이상 숨어 있지 않습니다
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)
-- 금고 키패드에 입력한 코드. 서버가 확인합니다: 플레이어 근처에 실제 금고가 있는지,
-- CodeWait마다 한 번만 시도했는지, 코드가 맞는지
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
-- 모든 플레이어: 리더보드에 Room과 Best를 표시하고, 부활할 때마다 손전등을 지급합니다
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)
-- 이 플레이어가 도달한 가장 깊은 방
local best = Instance.new("IntValue")
best.Name = "Best"
best.Parent = leaderstats
-- 레슨 25: Load on Join은 여기에 작성합니다
end)
-- 플레이어가 나가거나 서버가 종료될 때 가장 멀리 도달한 방을 저장합니다
local function saveBest(player)
pcall(function()
bestStore:SetAsync(tostring(player.UserId), player.leaderstats.Best.Value)
end)
end
Players.PlayerRemoving:Connect(saveBest)
game:BindToClose(function()
for _, player in Players:GetPlayers() do
saveBest(player)
end
end)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Roblox 게임: 어둠 속 탈출의 모든 레슨
직접 연습해 보세요: Roblox 플레이그라운드