Roblox · Пигги

10 ключей и 10 дверей

Как в Piggy: на карте 10 ключей разных цветов и 10 дверей с замками таких же цветов. Подбираешь ключ в руки и открываешь дверь его цвета. В руках только один ключ, чужой замок не откроется. Погиб — ключ лежит там, где ты упал.

Структура

Синим — что нужно создать.

Workspace
├─ Keys (Folder) — ключи на карте
│  └─ KeyRed…KeyBlack (Part) — атрибут KeyColor; Anchored вкл., CanCollide выкл.
└─ LockedDoors (Folder) — двери с замками
   └─ DoorRed…DoorBlack (Model) — атрибут KeyColor
      ├─ Door (Part) — полотно двери
      └─ Lock (Part) — замок
ServerScriptService
├─ KeysServer (Script)
└─ ResetKeys (BindableEvent) — новый раунд

Шаги

  1. Пара — это один и тот же атрибут KeyColor у ключа и у двери. Коды: Red, Blue, Green, Yellow, Orange, Purple, Pink, Cyan, White, Black. Выдели деталь → Properties → Attributes → «+» → имя KeyColor, тип string.
  2. Ключ — одна деталь или MeshPart в папке Keys, Anchored вкл. Разложи ключи по карте, прячь как хочешь. Цвет и кнопку «Взять» поставит скрипт.
  3. Дверь — модель в папке LockedDoors с деталями «Door» и «Lock» (обе Anchored). Цвет замка и кнопку «Открыть» поставит скрипт. Петли — сторона Left детали Door: поверни деталь, если дверь открывается не в ту сторону.
  4. В руках один ключ: возьмёшь новый — старый ляжет на его место. Выбросить ключ клавишей Backspace нельзя.
  5. Ключ чужого цвета дверь не откроет: над замком появится «Нужен красный ключ».
  6. Подошёл — ключ тратится, замок снимается, дверь открывается и остаётся открытой.
  7. Погиб — ключ лежит на этом месте, его может поднять другой игрок. Вышел из игры — ключ возвращается на своё место.
  8. Новый раунд: из своего скрипта вызови game.ServerScriptService.ResetKeys:Fire() — ключи вернутся на места, двери закроются.
  9. Цвета и названия — таблица COLORS вверху скрипта. Новая пара: добавь строку и поставь её код в KeyColor.

Скрипты

KeysServer

Где: ServerScriptService · Script
Зачем: Подбор ключей, замки, двери, сброс раунда.

-- игроки
local Players = game:GetService("Players")
-- плавное открытие
local TS = game:GetService("TweenService")
-- убирает подсказку
local Debris = game:GetService("Debris")
-- ключи на карте
local keysFolder = workspace:WaitForChild("Keys")
-- двери с замками
local doorsFolder = workspace:WaitForChild("LockedDoors")
-- BindableEvent: новый раунд
local resetEvent = script.Parent:WaitForChild("ResetKeys")
-- на сколько градусов открывается дверь
local OPEN_ANGLE = 100
-- сколько секунд открывается
local OPEN_TIME = 1
-- пары: код цвета, название, цвет
local COLORS = {
    -- пара 1
    Red = {"красный", Color3.fromRGB(230, 40, 40)},
    -- пара 2
    Blue = {"синий", Color3.fromRGB(40, 80, 230)},
    -- пара 3
    Green = {"зелёный", Color3.fromRGB(40, 180, 70)},
    -- пара 4
    Yellow = {"жёлтый", Color3.fromRGB(250, 220, 40)},
    -- пара 5
    Orange = {"оранжевый", Color3.fromRGB(245, 130, 30)},
    -- пара 6
    Purple = {"фиолетовый", Color3.fromRGB(140, 50, 210)},
    -- пара 7
    Pink = {"розовый", Color3.fromRGB(250, 120, 190)},
    -- пара 8
    Cyan = {"голубой", Color3.fromRGB(70, 210, 240)},
    -- пара 9
    White = {"белый", Color3.fromRGB(240, 240, 240)},
    -- пара 10
    Black = {"чёрный", Color3.fromRGB(25, 25, 25)},
-- конец таблицы
}
-- цвет → деталь ключа, её место и кнопка
local keys = {}
-- все двери: для сброса
local doors = {}
-- игрок → какой ключ несёт и его Tool
local carrying = {}

-- кнопка «E» на детали
local function Prompt(part, action, object)
    -- подсказка
    local prompt = Instance.new("ProximityPrompt")
    -- действие
    prompt.ActionText = action
    -- что это
    prompt.ObjectText = object
    -- подойти близко
    prompt.MaxActivationDistance = 10
    -- деталь рядом не мешает
    prompt.RequiresLineOfSight = false
    -- на деталь
    prompt.Parent = part
    -- отдаём
    return prompt
-- конец функции
end

-- положить ключ на карту
local function ShowKey(color, cf)
    -- ключ
    local key = keys[color]
    -- на место
    key.part.CFrame = cf
    -- виден
    key.part.Transparency = 0
    -- можно взять
    key.prompt.Enabled = true
-- конец функции
end
-- убрать ключ с карты
local function HideKey(color)
    -- не виден
    keys[color].part.Transparency = 1
    -- взять нельзя
    keys[color].prompt.Enabled = false
-- конец функции
end

-- дать ключ в руки
local function Give(player, color)
    -- предмет
    local tool = Instance.new("Tool")
    -- название в инвентаре
    tool.Name = COLORS[color][1] .. " ключ"
    -- Backspace не выбрасывает
    tool.CanBeDropped = false
    -- выглядит как ключ на карте
    local handle = keys[color].part:Clone()
    -- без кнопки
    handle:ClearAllChildren()
    -- за это игрок держит
    handle.Name = "Handle"
    -- двигается с рукой
    handle.Anchored = false
    -- не толкается
    handle.CanCollide = false
    -- ничего не весит
    handle.Massless = true
    -- виден
    handle.Transparency = 0
    -- в предмет
    handle.Parent = tool
    -- в инвентарь
    tool.Parent = player.Backpack
    -- запоминаем
    carrying[player] = {color = color, tool = tool}
    -- Humanoid
    local humanoid = player.Character and player.Character:FindFirstChildOfClass("Humanoid")
    -- сразу в руки
    if humanoid then humanoid:EquipTool(tool) end
-- конец функции
end
-- забрать ключ у игрока; вернуть его цвет
local function Take(player)
    -- что несёт
    local item = carrying[player]
    -- ничего
    if not item then return nil end
    -- руки пусты
    carrying[player] = nil
    -- предмета больше нет
    item.tool:Destroy()
    -- цвет
    return item.color
-- конец функции
end

-- каждый ключ
for _, part in ipairs(keysFolder:GetChildren()) do
    -- его цвет
    local color = part:GetAttribute("KeyColor")
    -- такой цвет есть
    if COLORS[color] then
        -- цвет из таблицы
        part.Color = COLORS[color][2]
        -- кнопка
        local prompt = Prompt(part, "Взять", COLORS[color][1] .. " ключ")
        -- запоминаем
        keys[color] = {part = part, home = part.CFrame, prompt = prompt}
        -- нажали «Взять»
        prompt.Triggered:Connect(function(player)
            -- Humanoid
            local humanoid = player.Character and player.Character:FindFirstChildOfClass("Humanoid")
            -- не живой
            if not humanoid or humanoid.Health <= 0 then return end
            -- ключ в руках? Несём только один
            local old = Take(player)
            -- старый ложится на место нового
            if old then ShowKey(old, part.CFrame) end
            -- новый исчезает с карты
            HideKey(color)
            -- и оказывается в руках
            Give(player, color)
        -- конец функции
        end)
    -- опечатка в атрибуте
    else
        -- подсказка в Output
        warn("Ключ " .. part.Name .. ": неизвестный KeyColor")
    -- конец проверки
    end
-- конец перебора
end

-- подсказка над замком на 2 секунды
local function Hint(lock, text)
    -- старая
    local old = lock:FindFirstChild("Hint")
    -- убираем
    if old then old:Destroy() end
    -- надпись в мире
    local gui = Instance.new("BillboardGui")
    -- имя
    gui.Name = "Hint"
    -- размер
    gui.Size = UDim2.fromOffset(220, 40)
    -- над замком
    gui.StudsOffset = Vector3.new(0, 2, 0)
    -- видно всегда
    gui.AlwaysOnTop = true
    -- текст
    local label = Instance.new("TextLabel")
    -- во весь размер
    label.Size = UDim2.fromScale(1, 1)
    -- без фона
    label.BackgroundTransparency = 1
    -- что написать
    label.Text = text
    -- белый
    label.TextColor3 = Color3.new(1, 1, 1)
    -- обводка
    label.TextStrokeTransparency = 0.3
    -- по размеру
    label.TextScaled = true
    -- жирный
    label.Font = Enum.Font.GothamBold
    -- в надпись
    label.Parent = gui
    -- над замком
    gui.Parent = lock
    -- исчезнет
    Debris:AddItem(gui, 2)
-- конец функции
end

-- каждая дверь
for _, model in ipairs(doorsFolder:GetChildren()) do
    -- какой ключ подходит
    local color = model:GetAttribute("KeyColor")
    -- полотно двери
    local part = model:WaitForChild("Door")
    -- замок
    local lock = model:WaitForChild("Lock")
    -- такой цвет есть
    if COLORS[color] then
        -- замок цвета ключа
        lock.Color = COLORS[color][2]
        -- снятый замок не должен мешать пройти
        lock.CanCollide = false
        -- кнопка
        local prompt = Prompt(lock, "Открыть", COLORS[color][1] .. " замок")
        -- закрытое положение
        local closed = part.CFrame
        -- петли — сторона Left детали Door
        local hinge = closed * CFrame.new(-part.Size.X / 2, 0, 0)
        -- открытое положение: поворот вокруг петель
        local open = hinge * CFrame.Angles(0, math.rad(OPEN_ANGLE), 0) * CFrame.new(part.Size.X / 2, 0, 0)
        -- для сброса
        table.insert(doors, {part = part, lock = lock, prompt = prompt, closed = closed})
        -- нажали «Открыть»
        prompt.Triggered:Connect(function(player)
            -- что в руках
            local item = carrying[player]
            -- нет ключа или он другой
            if not item or item.color ~= color then
                -- подсказка
                Hint(lock, "Нужен " .. COLORS[color][1] .. " ключ")
                -- не открываем
                return
            -- конец проверки
            end
            -- ключ тратится и не возвращается до нового раунда
            Take(player)
            -- кнопки больше нет
            prompt.Enabled = false
            -- замок снят
            lock.Transparency = 1
            -- дверь открывается
            TS:Create(part, TweenInfo.new(OPEN_TIME), {CFrame = open}):Play()
        -- конец функции
        end)
    -- опечатка в атрибуте
    else
        -- подсказка в Output
        warn("Дверь " .. model.Name .. ": неизвестный KeyColor")
    -- конец проверки
    end
-- конец перебора
end

-- игрок зашёл
local function Setup(player)
    -- новый персонаж
    player.CharacterAdded:Connect(function(character)
        -- Humanoid
        local humanoid = character:WaitForChild("Humanoid")
        -- погиб
        humanoid.Died:Connect(function()
            -- где он стоял
            local root = character:FindFirstChild("HumanoidRootPart")
            -- ключ выпадает из рук
            local color = Take(player)
            -- и лежит там, где игрок погиб
            if color and root then ShowKey(color, CFrame.new(root.Position - Vector3.new(0, 2, 0))) end
            -- упал в пропасть — ключ на своём месте
            if color and not root then ShowKey(color, keys[color].home) end
        -- конец функции
        end)
    -- конец функции
    end)
-- конец функции
end
-- новые игроки
Players.PlayerAdded:Connect(Setup)
-- кто зашёл раньше скрипта
for _, player in ipairs(Players:GetPlayers()) do Setup(player) end
-- вышел из игры
Players.PlayerRemoving:Connect(function(player)
    -- ключ у него?
    local color = Take(player)
    -- возвращается на своё место
    if color then ShowKey(color, keys[color].home) end
-- конец функции
end)

-- новый раунд: всё как в начале
resetEvent.Event:Connect(function()
    -- ключи из рук убираем
    for _, player in ipairs(Players:GetPlayers()) do Take(player) end
    -- все ключи на местах
    for color, key in pairs(keys) do ShowKey(color, key.home) end
    -- каждая дверь
    for _, door in ipairs(doors) do
        -- закрыта
        door.part.CFrame = door.closed
        -- замок на месте
        door.lock.Transparency = 0
        -- кнопка снова есть
        door.prompt.Enabled = true
    -- конец перебора
    end
-- конец функции
end)

Проверка

Запусти Play (или Run) и убедись:

Собрать 10 ключей и 10 дверей одной командой

Roblox · Piggy

10 keys and 10 doors

Like in Piggy: the map has 10 keys of different colors and 10 doors with locks of the same colors. You pick up a key and open the door of its color. You hold only one key, and a lock of another color won't open. If you die, the key stays where you fell.

Structure

Blue — what you need to create.

Workspace
├─ Keys (Folder) — keys on the map
│  └─ KeyRed…KeyBlack (Part) — KeyColor attribute; Anchored on, CanCollide off
└─ LockedDoors (Folder) — doors with locks
   └─ DoorRed…DoorBlack (Model) — KeyColor attribute
      ├─ Door (Part) — the door panel
      └─ Lock (Part) — the lock
ServerScriptService
├─ KeysServer (Script)
└─ ResetKeys (BindableEvent) — new round

Steps

  1. A pair is the same KeyColor attribute on a key and a door. Codes: Red, Blue, Green, Yellow, Orange, Purple, Pink, Cyan, White, Black. Select a part → Properties → Attributes → "+" → name KeyColor, type string.
  2. A key is one part or MeshPart in the Keys folder, Anchored on. Spread the keys around the map and hide them as you like. The script sets the color and the Take button.
  3. A door is a model in the LockedDoors folder with parts "Door" and "Lock" (both Anchored). The script sets the lock color and the Open button. The hinges are on the Left side of the Door part: rotate the part if the door opens the wrong way.
  4. You hold one key: take a new one and the old one goes into its place. You can't drop a key with Backspace.
  5. A key of another color won't open the door: "Need the red key" appears above the lock.
  6. With the right key, the key is used up, the lock comes off, and the door opens and stays open.
  7. If you die, the key stays at that spot and another player can pick it up. If you leave the game, the key returns to its place.
  8. New round: from your own script call game.ServerScriptService.ResetKeys:Fire() — the keys return to their places and the doors close.
  9. Colors and names are in the COLORS table at the top of the script. New pair: add a line and put its code into KeyColor.

Scripts

KeysServer

Where: ServerScriptService · Script
Why: Picking up keys, locks, doors, resetting the round.

-- players
local Players = game:GetService("Players")
-- smooth opening
local TS = game:GetService("TweenService")
-- removes the hint
local Debris = game:GetService("Debris")
-- keys on the map
local keysFolder = workspace:WaitForChild("Keys")
-- doors with locks
local doorsFolder = workspace:WaitForChild("LockedDoors")
-- BindableEvent: new round
local resetEvent = script.Parent:WaitForChild("ResetKeys")
-- how many degrees the door opens
local OPEN_ANGLE = 100
-- how many seconds it takes to open
local OPEN_TIME = 1
-- pairs: color code, name, color
local COLORS = {
    -- pair 1
    Red = {"красный", Color3.fromRGB(230, 40, 40)},
    -- pair 2
    Blue = {"синий", Color3.fromRGB(40, 80, 230)},
    -- pair 3
    Green = {"зелёный", Color3.fromRGB(40, 180, 70)},
    -- pair 4
    Yellow = {"жёлтый", Color3.fromRGB(250, 220, 40)},
    -- pair 5
    Orange = {"оранжевый", Color3.fromRGB(245, 130, 30)},
    -- pair 6
    Purple = {"фиолетовый", Color3.fromRGB(140, 50, 210)},
    -- pair 7
    Pink = {"розовый", Color3.fromRGB(250, 120, 190)},
    -- pair 8
    Cyan = {"голубой", Color3.fromRGB(70, 210, 240)},
    -- pair 9
    White = {"белый", Color3.fromRGB(240, 240, 240)},
    -- pair 10
    Black = {"чёрный", Color3.fromRGB(25, 25, 25)},
-- end of table
}
-- color → the key part, its place and button
local keys = {}
-- all doors: for the reset
local doors = {}
-- player → which key they carry and its Tool
local carrying = {}

-- an "E" button on the part
local function Prompt(part, action, object)
    -- a hint
    local prompt = Instance.new("ProximityPrompt")
    -- the action
    prompt.ActionText = action
    -- what it is
    prompt.ObjectText = object
    -- come close
    prompt.MaxActivationDistance = 10
    -- a nearby part doesn't block it
    prompt.RequiresLineOfSight = false
    -- onto the part
    prompt.Parent = part
    -- return it
    return prompt
-- end of function
end

-- put the key on the map
local function ShowKey(color, cf)
    -- the key
    local key = keys[color]
    -- into place
    key.part.CFrame = cf
    -- visible
    key.part.Transparency = 0
    -- can be taken
    key.prompt.Enabled = true
-- end of function
end
-- remove the key from the map
local function HideKey(color)
    -- invisible
    keys[color].part.Transparency = 1
    -- can't be taken
    keys[color].prompt.Enabled = false
-- end of function
end

-- put the key in the hands
local function Give(player, color)
    -- the item
    local tool = Instance.new("Tool")
    -- the name in the inventory
    tool.Name = COLORS[color][1] .. " ключ"
    -- Backspace doesn't drop it
    tool.CanBeDropped = false
    -- looks like the key on the map
    local handle = keys[color].part:Clone()
    -- without a button
    handle:ClearAllChildren()
    -- the player holds it by this
    handle.Name = "Handle"
    -- moves with the hand
    handle.Anchored = false
    -- doesn't push
    handle.CanCollide = false
    -- weighs nothing
    handle.Massless = true
    -- visible
    handle.Transparency = 0
    -- into the item
    handle.Parent = tool
    -- into the inventory
    tool.Parent = player.Backpack
    -- remember
    carrying[player] = {color = color, tool = tool}
    -- Humanoid
    local humanoid = player.Character and player.Character:FindFirstChildOfClass("Humanoid")
    -- straight into the hands
    if humanoid then humanoid:EquipTool(tool) end
-- end of function
end
-- take the key from the player; return its color
local function Take(player)
    -- what they carry
    local item = carrying[player]
    -- nothing
    if not item then return nil end
    -- hands are empty
    carrying[player] = nil
    -- the item is gone
    item.tool:Destroy()
    -- color
    return item.color
-- end of function
end

-- each key
for _, part in ipairs(keysFolder:GetChildren()) do
    -- its color
    local color = part:GetAttribute("KeyColor")
    -- this color exists
    if COLORS[color] then
        -- the color from the table
        part.Color = COLORS[color][2]
        -- a button
        local prompt = Prompt(part, "Взять", COLORS[color][1] .. " ключ")
        -- remember
        keys[color] = {part = part, home = part.CFrame, prompt = prompt}
        -- Take was pressed
        prompt.Triggered:Connect(function(player)
            -- Humanoid
            local humanoid = player.Character and player.Character:FindFirstChildOfClass("Humanoid")
            -- not alive
            if not humanoid or humanoid.Health <= 0 then return end
            -- a key in hand? We carry only one
            local old = Take(player)
            -- the old one goes to the new one's place
            if old then ShowKey(old, part.CFrame) end
            -- the new one disappears from the map
            HideKey(color)
            -- and ends up in the hands
            Give(player, color)
        -- end of function
        end)
    -- a typo in the attribute
    else
        -- a hint in the Output
        warn("Ключ " .. part.Name .. ": неизвестный KeyColor")
    -- end of check
    end
-- end of loop
end

-- a hint above the lock for 2 seconds
local function Hint(lock, text)
    -- the old one
    local old = lock:FindFirstChild("Hint")
    -- remove it
    if old then old:Destroy() end
    -- a label in the world
    local gui = Instance.new("BillboardGui")
    -- name
    gui.Name = "Hint"
    -- size
    gui.Size = UDim2.fromOffset(220, 40)
    -- above the lock
    gui.StudsOffset = Vector3.new(0, 2, 0)
    -- always visible
    gui.AlwaysOnTop = true
    -- text
    local label = Instance.new("TextLabel")
    -- full size
    label.Size = UDim2.fromScale(1, 1)
    -- no background
    label.BackgroundTransparency = 1
    -- what to write
    label.Text = text
    -- white
    label.TextColor3 = Color3.new(1, 1, 1)
    -- outline
    label.TextStrokeTransparency = 0.3
    -- scaled to fit
    label.TextScaled = true
    -- bold
    label.Font = Enum.Font.GothamBold
    -- into the label
    label.Parent = gui
    -- above the lock
    gui.Parent = lock
    -- will disappear
    Debris:AddItem(gui, 2)
-- end of function
end

-- each door
for _, model in ipairs(doorsFolder:GetChildren()) do
    -- which key fits
    local color = model:GetAttribute("KeyColor")
    -- the door panel
    local part = model:WaitForChild("Door")
    -- the lock
    local lock = model:WaitForChild("Lock")
    -- this color exists
    if COLORS[color] then
        -- a lock the key's color
        lock.Color = COLORS[color][2]
        -- a removed lock mustn't block the way
        lock.CanCollide = false
        -- a button
        local prompt = Prompt(lock, "Открыть", COLORS[color][1] .. " замок")
        -- the closed position
        local closed = part.CFrame
        -- the hinges are on the Left side of the Door part
        local hinge = closed * CFrame.new(-part.Size.X / 2, 0, 0)
        -- the open position: a turn around the hinges
        local open = hinge * CFrame.Angles(0, math.rad(OPEN_ANGLE), 0) * CFrame.new(part.Size.X / 2, 0, 0)
        -- for the reset
        table.insert(doors, {part = part, lock = lock, prompt = prompt, closed = closed})
        -- Open was pressed
        prompt.Triggered:Connect(function(player)
            -- what's in hand
            local item = carrying[player]
            -- no key or a different one
            if not item or item.color ~= color then
                -- a hint
                Hint(lock, "Нужен " .. COLORS[color][1] .. " ключ")
                -- don't open
                return
            -- end of check
            end
            -- the key is used up and doesn't come back until a new round
            Take(player)
            -- the button is gone
            prompt.Enabled = false
            -- the lock is removed
            lock.Transparency = 1
            -- the door opens
            TS:Create(part, TweenInfo.new(OPEN_TIME), {CFrame = open}):Play()
        -- end of function
        end)
    -- a typo in the attribute
    else
        -- a hint in the Output
        warn("Дверь " .. model.Name .. ": неизвестный KeyColor")
    -- end of check
    end
-- end of loop
end

-- a player joined
local function Setup(player)
    -- a new character
    player.CharacterAdded:Connect(function(character)
        -- Humanoid
        local humanoid = character:WaitForChild("Humanoid")
        -- died
        humanoid.Died:Connect(function()
            -- where it stood
            local root = character:FindFirstChild("HumanoidRootPart")
            -- the key drops from the hands
            local color = Take(player)
            -- and lies where the player died
            if color and root then ShowKey(color, CFrame.new(root.Position - Vector3.new(0, 2, 0))) end
            -- fell into the void — the key goes back to its place
            if color and not root then ShowKey(color, keys[color].home) end
        -- end of function
        end)
    -- end of function
    end)
-- end of function
end
-- new players
Players.PlayerAdded:Connect(Setup)
-- those who joined before the script ran
for _, player in ipairs(Players:GetPlayers()) do Setup(player) end
-- left the game
Players.PlayerRemoving:Connect(function(player)
    -- do they have a key?
    local color = Take(player)
    -- returns to its place
    if color then ShowKey(color, keys[color].home) end
-- end of function
end)

-- new round: everything as at the start
resetEvent.Event:Connect(function()
    -- remove keys from hands
    for _, player in ipairs(Players:GetPlayers()) do Take(player) end
    -- all keys in place
    for color, key in pairs(keys) do ShowKey(color, key.home) end
    -- each door
    for _, door in ipairs(doors) do
        -- closed
        door.part.CFrame = door.closed
        -- the lock is back
        door.lock.Transparency = 0
        -- the button is back
        door.prompt.Enabled = true
    -- end of loop
    end
-- end of function
end)

Testing

Press Play (or Run) and make sure:

Build 10 keys and 10 doors with one command