Roblox · Сбор-а-тон · урок 6
Нашёл всё — экран победы плавно проявляется: поздравление, счёт, кнопки «Выйти» и «Играть дальше».
Синим — что добавляем на этом уроке.
ReplicatedStorage └─ Events (Folder) └─ GameOverEvent (RemoteEvent) ServerScriptService └─ CollectServer (Script) — дополнили StarterGui └─ GameOverGui (ScreenGui) — ResetOnSpawn выкл., IgnoreGuiInset вкл. ├─ GameOverFrame (Frame) — на весь экран, Visible выкл. │ ├─ Congrats (TextLabel) │ ├─ Found (TextLabel) │ └─ ExitButton, ContinueButton (TextButton) └─ GameOverLocal (LocalScript)
Где: ServerScriptService · Script
Зачем: Находки и конец игры.
-- игроки
local Players = game:GetService("Players")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- сохранение
local DSS = game:GetService("DataStoreService")
-- нашивки (по желанию)
local BadgeService = game:GetService("BadgeService")
-- все предметы
local items = workspace:WaitForChild("Items")
-- события
local events = RS:WaitForChild("Events")
-- «нашёл предмет»
local collectEvent = events:WaitForChild("CollectEvent")
-- «нашёл всё»
local gameOverEvent = events:WaitForChild("GameOverEvent")
-- хранилище находок
local store = DSS:GetDataStore("CollectData")
-- у кого находки загрузились
local loaded = {}
-- сохранить находки
local function Save(player)
-- не загрузились — не затираем
if not loaded[player] then return end
-- имена найденных
local list = {}
-- каждая находка
for _, mark in ipairs(player.Found:GetChildren()) do
-- в список
table.insert(list, mark.Name)
-- конец перебора
end
-- сохраняем
pcall(function() store:SetAsync("found_" .. player.UserId, list) end)
-- конец функции
end
-- игрок нашёл предмет
local function Collect(player, item)
-- его находки
local found = player:FindFirstChild("Found")
-- уже нашёл
if not found or found:FindFirstChild(item.Name) then return end
-- отметка
local mark = Instance.new("BoolValue")
-- имя = предмет
mark.Name = item.Name
-- в папку игрока
mark.Parent = found
-- сообщение на экране
collectEvent:FireClient(player, item.Name)
-- ID нашивки
local badge = item:FindFirstChild("BadgeID")
-- нашивка настроена
if badge and badge.Value > 0 then
-- не задерживаем остальное
task.spawn(function()
-- выдаём; в Studio может не сработать
pcall(function() BadgeService:AwardBadge(player.UserId, badge.Value) end)
-- конец функции
end)
-- конец проверки
end
-- найдено всё
if #found:GetChildren() >= #items:GetChildren() then
-- через секунду — экран победы
task.delay(1, function() gameOverEvent:FireClient(player) end)
-- конец проверки
end
-- конец функции
end
-- игрок зашёл
local function Setup(player)
-- его находки
local found = Instance.new("Folder")
-- имя
found.Name = "Found"
-- загружаем
local ok, list = pcall(function() return store:GetAsync("found_" .. player.UserId) end)
-- загрузка удалась
if ok then
-- каждое сохранённое имя
for _, name in ipairs(list or {}) do
-- такой предмет ещё есть
if items:FindFirstChild(name) then
-- отметка
local mark = Instance.new("BoolValue")
-- имя
mark.Name = name
-- в папку
mark.Parent = found
-- конец проверки
end
-- конец перебора
end
-- можно сохранять
loaded[player] = true
-- конец проверки
end
-- в игрока — клиент видит
found.Parent = player
-- конец функции
end
-- новые игроки
Players.PlayerAdded:Connect(Setup)
-- кто зашёл раньше скрипта
for _, player in ipairs(Players:GetPlayers()) do task.spawn(Setup, player) end
-- игрок вышел
Players.PlayerRemoving:Connect(function(player)
-- сохраняем
Save(player)
-- забываем
loaded[player] = nil
-- конец функции
end)
-- сервер закрывается
game:BindToClose(function()
-- сохраняем всех
for _, player in ipairs(Players:GetPlayers()) do Save(player) end
-- конец функции
end)
-- каждый предмет — один раз
for _, item in ipairs(items:GetChildren()) do
-- клик
local clicker = item:FindFirstChildOfClass("ClickDetector") or Instance.new("ClickDetector")
-- кликнуть можно только рядом
clicker.MaxActivationDistance = 20
-- в предмет
clicker.Parent = item
-- кто-то кликнул
clicker.MouseClick:Connect(function(player)
-- засчитываем
Collect(player, item)
-- конец функции
end)
-- конец перебора
endГде: StarterGui → GameOverGui · LocalScript
Зачем: Экран победы.
-- плавные появления
local TS = game:GetService("TweenService")
-- игроки
local Players = game:GetService("Players")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- «нашёл всё»
local gameOverEvent = RS:WaitForChild("Events"):WaitForChild("GameOverEvent")
-- этот игрок
local player = Players.LocalPlayer
-- экран победы
local frame = script.Parent:WaitForChild("GameOverFrame")
-- «Поздравляем!»
local congrats = frame:WaitForChild("Congrats")
-- сколько найдено
local foundText = frame:WaitForChild("Found")
-- выйти
local exitButton = frame:WaitForChild("ExitButton")
-- играть дальше
local continueButton = frame:WaitForChild("ContinueButton")
-- полторы секунды, равномерно
local FADE = TweenInfo.new(1.5, Enum.EasingStyle.Linear)
-- плавно показать
local function Show(element)
-- виден (пока прозрачный)
element.Visible = true
-- проявляется
TS:Create(element, FADE, {BackgroundTransparency = 0, TextTransparency = 0}):Play()
-- конец функции
end
-- спрятать сразу
local function Hide(element)
-- не виден и не нажимается
element.Visible = false
-- прозрачный фон
element.BackgroundTransparency = 1
-- прозрачный текст
element.TextTransparency = 1
-- конец функции
end
-- кнопки подписываем один раз
exitButton.MouseButton1Click:Connect(function()
-- выход из игры
player:Kick("До встречи!")
-- конец функции
end)
-- играть дальше
continueButton.MouseButton1Click:Connect(function()
-- убираем экран
frame.Visible = false
-- конец функции
end)
-- сервер: найдено всё
gameOverEvent.OnClientEvent:Connect(function()
-- всё спрятано
for _, element in ipairs({congrats, foundText, exitButton, continueButton}) do Hide(element) end
-- текст
foundText.Text = "Ты нашёл все предметы: " .. #player.Found:GetChildren()
-- фон прозрачный
frame.BackgroundTransparency = 1
-- экран включён
frame.Visible = true
-- затемнение
TS:Create(frame, FADE, {BackgroundTransparency = 0.25}):Play()
-- ждём
task.wait(1.5)
-- поздравление
Show(congrats)
-- ждём
task.wait(1.5)
-- счёт
Show(foundText)
-- ждём
task.wait(1.5)
-- кнопки
Show(exitButton)
-- кнопки
Show(continueButton)
-- конец функции
end)Запусти Play (или Run) и убедись:
Roblox · Collect-a-thon · lesson 6
Find everything and a victory screen fades in: congratulations, the count, and "Выйти" (exit) and "Играть дальше" (keep playing) buttons.
Blue — what we add in this lesson.
ReplicatedStorage └─ Events (Folder) └─ GameOverEvent (RemoteEvent) ServerScriptService └─ CollectServer (Script) — extended StarterGui └─ GameOverGui (ScreenGui) — ResetOnSpawn off, IgnoreGuiInset on ├─ GameOverFrame (Frame) — full screen, Visible off │ ├─ Congrats (TextLabel) │ ├─ Found (TextLabel) │ └─ ExitButton, ContinueButton (TextButton) └─ GameOverLocal (LocalScript)
Where: ServerScriptService · Script
Why: Finds and game over.
-- players
local Players = game:GetService("Players")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- saving
local DSS = game:GetService("DataStoreService")
-- badges (optional)
local BadgeService = game:GetService("BadgeService")
-- all items
local items = workspace:WaitForChild("Items")
-- events
local events = RS:WaitForChild("Events")
-- "found an item"
local collectEvent = events:WaitForChild("CollectEvent")
-- "found everything"
local gameOverEvent = events:WaitForChild("GameOverEvent")
-- the finds store
local store = DSS:GetDataStore("CollectData")
-- whose finds have loaded
local loaded = {}
-- save the finds
local function Save(player)
-- not loaded — don't overwrite
if not loaded[player] then return end
-- names of found items
local list = {}
-- each find
for _, mark in ipairs(player.Found:GetChildren()) do
-- into the list
table.insert(list, mark.Name)
-- end of loop
end
-- save
pcall(function() store:SetAsync("found_" .. player.UserId, list) end)
-- end of function
end
-- the player found an item
local function Collect(player, item)
-- their finds
local found = player:FindFirstChild("Found")
-- already found
if not found or found:FindFirstChild(item.Name) then return end
-- a marker
local mark = Instance.new("BoolValue")
-- name = item
mark.Name = item.Name
-- into the player's folder
mark.Parent = found
-- an on-screen message
collectEvent:FireClient(player, item.Name)
-- the badge ID
local badge = item:FindFirstChild("BadgeID")
-- the badge is set up
if badge and badge.Value > 0 then
-- don't hold up the rest
task.spawn(function()
-- award it; may not work in Studio
pcall(function() BadgeService:AwardBadge(player.UserId, badge.Value) end)
-- end of function
end)
-- end of check
end
-- everything is found
if #found:GetChildren() >= #items:GetChildren() then
-- in a second — the victory screen
task.delay(1, function() gameOverEvent:FireClient(player) end)
-- end of check
end
-- end of function
end
-- a player joined
local function Setup(player)
-- their finds
local found = Instance.new("Folder")
-- name
found.Name = "Found"
-- load it
local ok, list = pcall(function() return store:GetAsync("found_" .. player.UserId) end)
-- loading succeeded
if ok then
-- each saved name
for _, name in ipairs(list or {}) do
-- this item still exists
if items:FindFirstChild(name) then
-- a marker
local mark = Instance.new("BoolValue")
-- name
mark.Name = name
-- into the folder
mark.Parent = found
-- end of check
end
-- end of loop
end
-- saving is allowed
loaded[player] = true
-- end of check
end
-- into the player — the client sees it
found.Parent = player
-- end of function
end
-- new players
Players.PlayerAdded:Connect(Setup)
-- those who joined before the script ran
for _, player in ipairs(Players:GetPlayers()) do task.spawn(Setup, player) end
-- the player left
Players.PlayerRemoving:Connect(function(player)
-- save
Save(player)
-- forget
loaded[player] = nil
-- end of function
end)
-- the server is closing
game:BindToClose(function()
-- save everyone
for _, player in ipairs(Players:GetPlayers()) do Save(player) end
-- end of function
end)
-- each item — once
for _, item in ipairs(items:GetChildren()) do
-- a click
local clicker = item:FindFirstChildOfClass("ClickDetector") or Instance.new("ClickDetector")
-- you can only click from nearby
clicker.MaxActivationDistance = 20
-- into the item
clicker.Parent = item
-- someone clicked
clicker.MouseClick:Connect(function(player)
-- count it
Collect(player, item)
-- end of function
end)
-- end of loop
endWhere: StarterGui → GameOverGui · LocalScript
Why: The victory screen.
-- smooth fade-ins
local TS = game:GetService("TweenService")
-- players
local Players = game:GetService("Players")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- "found everything"
local gameOverEvent = RS:WaitForChild("Events"):WaitForChild("GameOverEvent")
-- this player
local player = Players.LocalPlayer
-- the victory screen
local frame = script.Parent:WaitForChild("GameOverFrame")
-- "Поздравляем!" (congratulations)
local congrats = frame:WaitForChild("Congrats")
-- how many are found
local foundText = frame:WaitForChild("Found")
-- exit
local exitButton = frame:WaitForChild("ExitButton")
-- keep playing
local continueButton = frame:WaitForChild("ContinueButton")
-- one and a half seconds, evenly
local FADE = TweenInfo.new(1.5, Enum.EasingStyle.Linear)
-- fade in
local function Show(element)
-- visible (still transparent)
element.Visible = true
-- fades in
TS:Create(element, FADE, {BackgroundTransparency = 0, TextTransparency = 0}):Play()
-- end of function
end
-- hide at once
local function Hide(element)
-- invisible and not clickable
element.Visible = false
-- a transparent background
element.BackgroundTransparency = 1
-- transparent text
element.TextTransparency = 1
-- end of function
end
-- connect the buttons once
exitButton.MouseButton1Click:Connect(function()
-- leave the game
player:Kick("До встречи!")
-- end of function
end)
-- keep playing
continueButton.MouseButton1Click:Connect(function()
-- remove the screen
frame.Visible = false
-- end of function
end)
-- server: everything is found
gameOverEvent.OnClientEvent:Connect(function()
-- everything hidden
for _, element in ipairs({congrats, foundText, exitButton, continueButton}) do Hide(element) end
-- text
foundText.Text = "Ты нашёл все предметы: " .. #player.Found:GetChildren()
-- the background is transparent
frame.BackgroundTransparency = 1
-- the screen is on
frame.Visible = true
-- the fade
TS:Create(frame, FADE, {BackgroundTransparency = 0.25}):Play()
-- wait
task.wait(1.5)
-- the congratulations
Show(congrats)
-- wait
task.wait(1.5)
-- the count
Show(foundText)
-- wait
task.wait(1.5)
-- buttons
Show(exitButton)
-- buttons
Show(continueButton)
-- end of function
end)Press Play (or Run) and make sure: