Roblox · Захват флага · урок 6
В конце раунда сервер считает флаги каждой команды и показывает всем победителя.
Синим — что добавляем на этом уроке.
ReplicatedStorage └─ WinEvent (RemoteEvent) ServerScriptService └─ TimerServer (Script) — добавили подсчёт StarterGui └─ WinnerGui (ScreenGui) — Enabled выкл., ResetOnSpawn выкл. ├─ WinLabel (TextLabel) — крупно по центру └─ WinLocal (LocalScript)
Где: ServerScriptService · Script
Зачем: Раунды и подсчёт победителя.
-- игроки
local Players = game:GetService("Players")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- идёт лобби?
local lobby = RS:WaitForChild("Lobby")
-- сколько секунд осталось
local timeLeft = RS:WaitForChild("TimeLeft")
-- команды
local Teams = game:GetService("Teams")
-- объявить победителя
local winEvent = RS:WaitForChild("WinEvent")
-- секунд в лобби
local LOBBY_TIME = 30
-- секунд игры (5 минут)
local GAME_TIME = 300
-- всех игроков с командой — на точки своей команды
local function SendAll(folder)
-- каждый игрок
for _, player in ipairs(Players:GetPlayers()) do
-- команда выбрана
if player.Team then
-- точка команды в этой папке
player.RespawnLocation = folder:FindFirstChild(player.Team.Name)
-- возрождаем там (флаг сам вернётся)
player:LoadCharacter()
-- конец проверки
end
-- конец перебора
end
-- конец функции
end
-- обратный отсчёт
local function Countdown(seconds)
-- от seconds до 0
for t = seconds, 0, -1 do
-- игроки видят время
timeLeft.Value = t
-- секунда
task.wait(1)
-- конец цикла
end
-- конец функции
end
-- какая команда принесла больше флагов
local function Winner()
-- лучшая, её счёт, ничья ли
local bestTeam, bestScore, draw = nil, -1, false
-- каждая команда
for _, team in ipairs(Teams:GetTeams()) do
-- сумма флагов
local score = 0
-- игроки команды
for _, player in ipairs(team:GetPlayers()) do
-- таблица
local stats = player:FindFirstChild("leaderstats")
-- прибавляем
if stats then score += stats.Flags.Value end
-- конец перебора
end
-- больше всех
if score > bestScore then
-- новый лидер
bestTeam, bestScore, draw = team, score, false
-- столько же
elseif score == bestScore then
-- ничья
draw = true
-- конец проверки
end
-- конец перебора
end
-- белым
if not bestTeam or draw then return "Ничья!", Color3.new(1, 1, 1) end
-- цветом команды
return "Победили " .. bestTeam.Name .. "! Флагов: " .. bestScore, bestTeam.TeamColor.Color
-- конец функции
end
-- раунды по кругу
while true do
-- лобби
lobby.Value = true
-- все в лобби
SendAll(workspace.LobbySpawn)
-- ждём
Countdown(LOBBY_TIME)
-- игра
lobby.Value = false
-- обнуляем счёт
for _, player in ipairs(Players:GetPlayers()) do
-- таблица
local stats = player:FindFirstChild("leaderstats")
-- с нуля
if stats then stats.Flags.Value = 0 end
-- конец перебора
end
-- все на поле
SendAll(workspace.GameSpawn)
-- играем
Countdown(GAME_TIME)
-- показываем победителя всем
winEvent:FireAllClients(Winner())
-- пока читают
task.wait(5)
-- конец цикла
endГде: StarterGui → WinnerGui · LocalScript
Зачем: Надпись о победе.
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- событие победы
local winEvent = RS:WaitForChild("WinEvent")
-- WinnerGui
local gui = script.Parent
-- надпись
local label = gui:WaitForChild("WinLabel")
-- сколько секунд показывать
local SHOW_TIME = 5
-- сервер объявил победителя
winEvent.OnClientEvent:Connect(function(text, color)
-- текст
label.Text = text
-- цвет команды
label.TextColor3 = color
-- показываем
gui.Enabled = true
-- ждём
task.wait(SHOW_TIME)
-- прячем
gui.Enabled = false
-- конец функции
end)Запусти Play (или Run) и убедись:
Roblox · Capture the flag · lesson 6
At the end of a round the server counts each team's flags and shows everyone the winner.
Blue — what we add in this lesson.
ReplicatedStorage └─ WinEvent (RemoteEvent) ServerScriptService └─ TimerServer (Script) — counting added StarterGui └─ WinnerGui (ScreenGui) — Enabled off, ResetOnSpawn off ├─ WinLabel (TextLabel) — large, in the center └─ WinLocal (LocalScript)
Where: ServerScriptService · Script
Why: Rounds and counting the winner.
-- players
local Players = game:GetService("Players")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- is it lobby time?
local lobby = RS:WaitForChild("Lobby")
-- how many seconds are left
local timeLeft = RS:WaitForChild("TimeLeft")
-- teams
local Teams = game:GetService("Teams")
-- announce the winner
local winEvent = RS:WaitForChild("WinEvent")
-- seconds in the lobby
local LOBBY_TIME = 30
-- seconds of play (5 minutes)
local GAME_TIME = 300
-- move all players with a team to their team's points
local function SendAll(folder)
-- each player
for _, player in ipairs(Players:GetPlayers()) do
-- a team is chosen
if player.Team then
-- the team's point in this folder
player.RespawnLocation = folder:FindFirstChild(player.Team.Name)
-- respawn there (the flag returns by itself)
player:LoadCharacter()
-- end of check
end
-- end of loop
end
-- end of function
end
-- the countdown
local function Countdown(seconds)
-- from seconds down to 0
for t = seconds, 0, -1 do
-- players see the time
timeLeft.Value = t
-- a second
task.wait(1)
-- end of loop
end
-- end of function
end
-- which team brought more flags
local function Winner()
-- the best team, its score, is it a draw
local bestTeam, bestScore, draw = nil, -1, false
-- each team
for _, team in ipairs(Teams:GetTeams()) do
-- the flag total
local score = 0
-- the team's players
for _, player in ipairs(team:GetPlayers()) do
-- the board
local stats = player:FindFirstChild("leaderstats")
-- add
if stats then score += stats.Flags.Value end
-- end of loop
end
-- the most
if score > bestScore then
-- a new leader
bestTeam, bestScore, draw = team, score, false
-- the same amount
elseif score == bestScore then
-- a draw
draw = true
-- end of check
end
-- end of loop
end
-- in white
if not bestTeam or draw then return "Ничья!", Color3.new(1, 1, 1) end
-- in the team color
return "Победили " .. bestTeam.Name .. "! Флагов: " .. bestScore, bestTeam.TeamColor.Color
-- end of function
end
-- rounds in a loop
while true do
-- the lobby
lobby.Value = true
-- everyone to the lobby
SendAll(workspace.LobbySpawn)
-- wait
Countdown(LOBBY_TIME)
-- the game
lobby.Value = false
-- reset the score
for _, player in ipairs(Players:GetPlayers()) do
-- the board
local stats = player:FindFirstChild("leaderstats")
-- from zero
if stats then stats.Flags.Value = 0 end
-- end of loop
end
-- everyone to the field
SendAll(workspace.GameSpawn)
-- play
Countdown(GAME_TIME)
-- show the winner to everyone
winEvent:FireAllClients(Winner())
-- while they read
task.wait(5)
-- end of loop
endWhere: StarterGui → WinnerGui · LocalScript
Why: The victory message.
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- the victory event
local winEvent = RS:WaitForChild("WinEvent")
-- WinnerGui
local gui = script.Parent
-- a label
local label = gui:WaitForChild("WinLabel")
-- how many seconds to show
local SHOW_TIME = 5
-- the server announced the winner
winEvent.OnClientEvent:Connect(function(text, color)
-- text
label.Text = text
-- the team color
label.TextColor3 = color
-- show it
gui.Enabled = true
-- wait
task.wait(SHOW_TIME)
-- hide
gui.Enabled = false
-- end of function
end)Press Play (or Run) and make sure: