密码锁
Coddy Roblox 游戏:逃离黑暗 课程的第 19 课,共 25 课。
Vault 房间的门没有钥匙,而是需要输入一个四位数密码。密码写在房间墙上的一张纸条上。创建房间时,服务器会选定密码,并按门存入一个表中,客户端无法读取这个表。
玩家在键盘上输入密码(下一课会介绍),键盘会通过 RemoteFunction 向服务器发起请求。与 RemoteEvent 不同,它会返回答案:
remotes.TryCode.OnServerInvoke = function(player, door, code)
return code == codes[door]
end四位数密码有 9,000 种猜测方式,利用漏洞的人可能会在一秒内全部尝试一遍。因此,服务器只允许每隔 Settings.CodeWait 尝试一次,而且玩家必须站在真实的金库旁。
挑战
困难保险库只能用密码打开。
- 在
addRoom中,将保险库门的tostring(math.random(1000, 9999))存入codes;它的Note会显示Code 4821。 setupDoor会忽略上锁的保险库。remotes.TryCode.OnServerInvoke:如果门不是保险库门、玩家距离门超过 12 studs、在Settings.CodeWait时间内再次尝试,或密码错误,则返回 false;否则解锁、添加下一间房、打开门,并返回 true。
按“开始”并到达第 6 间房:纸条上会显示密码。然后按“检查”。
亲手试试
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
-- 怪物的行动逻辑:每隔四分之一秒追踪玩家
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
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)
-- 第 19 课:密码锁的代码写在这里
-- 每位玩家:排行榜上显示 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)
Roblox 游戏:逃离黑暗中的所有课
自己练习: Roblox 在线编辑器