코드 자물쇠
Coddy의 Roblox 게임: 어둠에서 탈출하기 코스 레슨. 20개 중 16번째.
Vault 방의 문에는 열쇠가 없습니다. 대신 네 자리 코드가 있으며, 방 벽에 붙은 쪽지에 적혀 있습니다. 서버는 방이 생성될 때 코드를 정하고 문별로 테이블에 보관합니다.
프롬프트를 열면 클라이언트에서 HUD의 Keypad가 표시되고, 여기서 숫자를 입력합니다. Enter를 누르면 서버에 RemoteFunction을 통해 요청합니다. RemoteEvent와 달리 RemoteFunction은 응답을 반환합니다.
-- 클라이언트
local ok = remotes.TryCode:InvokeServer(door, typed)
-- 서버
remotes.TryCode.OnServerInvoke = function(player, door, code)
return code == codes[door]
endSettings.CodeWait마다 한 번만 시도할 수 있게 하고, 실제 볼트 앞에 서 있는 플레이어에게만 허용합니다.
챌린지
어려움local remotes,local codes = {},local lastTry = {}를 추가하세요.addRoom에서 금고 문에tostring(math.random(1000, 9999))로 만든 값을codes에 넣고, 쪽지에도 표시합니다(Code 4821).setupDoor에서 잠긴 금고 문은 아무 동작도 하지 않습니다. 키패드로 열 수 있습니다.remotes.TryCode.OnServerInvoke를 작성하세요. 금고 문이codes에 없거나 코드가 문자열이 아닌 경우, 플레이어가 금고 문 패널에서 12 studs보다 멀리 있는 경우, 마지막 시도 후 CodeWait가 지나지 않은 경우, 또는 코드가 틀린 경우에는 false를 반환합니다. 그렇지 않으면 코드를 지우고, 잠금을 해제하고, 필요한 경우 다음 방을 추가하고, 문을 열고, true를 반환합니다.DarkClient에서 잠긴 금고 문에 대해ProximityPromptService.PromptTriggered가 실행되면 키패드를 표시합니다. 숫자 버튼을 누르면typed에 숫자를 추가하며(최대 4자리), Clear는 입력을 지우고, Enter는 TryCode를 호출합니다. 문이 열리면 키패드를 닫고, 그렇지 않으면Wrong을 표시합니다.
이 레슨의 첫 번째 방은 금고입니다. Play를 누른 다음 Check를 누르세요.
직접 해보기
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 rooms = workspace.Rooms
local lastRoom = rooms.Lobby -- 가장 최근에 생성된 방
local count = 0 -- 지금까지 생성된 방의 수
local monster = nil
-- 밤이 찾아온다: 태양은 사라지고 곳곳에 희미한 빛과 안개가 깔린다
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
-- 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("Locked") then
local key = findTool(player, "Key")
if not key then
return
end
key:Destroy()
door:SetAttribute("Locked", nil)
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
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
-- 가장 최근 방과 그 뒤의 KeepRooms개 방을 유지한다
for _, old in rooms:GetChildren() do
if old:GetAttribute("Number") < count - Settings.KeepRooms then
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)
-- 모든 플레이어: 리더보드에 Room을 표시하고, 부활할 때마다 손전등을 지급한다
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()
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)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.