Compare commits

..
11 Commits
78 changed files with 3469 additions and 724 deletions

No files matched your search

BIN
View File
Binary file not shown.
+1 -1
View File
@@ -25,7 +25,7 @@
## A1. Роль и цель ## A1. Роль и цель
Ты работаешь в Roblox-проекте **Hunter** (Luau, VS Code + Rojo). Это командный шутер на процедурно генерируемой арене: команды **Blue** и **Orange**, восемь режимов. Задача: превратить режимы из «сырых» в **структурированные, красивые и продуманные по ритму раунда и поведению игроков**, не ломая существующую игру. Ты работаешь в Roblox-проекте **Hunter** (Luau, VS Code + MCP). Это командный шутер на процедурно генерируемой арене: команды **Blue** и **Orange**, восемь режимов. Задача: превратить режимы из «сырых» в **структурированные, красивые и продуманные по ритму раунда и поведению игроков**, не ломая существующую игру.
Принципы: Принципы:
- **Сервер авторитетен.** Состояние матча, очки, захваты и таймеры считает только сервер. Клиент отображает и проигрывает эффекты. - **Сервер авторитетен.** Состояние матча, очки, захваты и таймеры считает только сервер. Клиент отображает и проигрывает эффекты.
+12 -2
View File
@@ -4,12 +4,20 @@
"$className": "DataModel", "$className": "DataModel",
"ReplicatedStorage": { "ReplicatedStorage": {
"$ignoreUnknownInstances": true, "$ignoreUnknownInstances": true,
"CitadelAssaultConfig": { "$path": "scripts/CitadelAssaultConfig.luau" } "CitadelAssaultConfig": { "$path": "scripts/CitadelAssaultConfig.luau" },
"Hunter": { "$path": "scripts/Hunter" },
"MatchRules": { "$path": "scripts/MatchRules.luau" },
"SniperEffects": { "$path": "scripts/SniperEffects.luau" }
}, },
"ServerScriptService": { "ServerScriptService": {
"$ignoreUnknownInstances": true, "$ignoreUnknownInstances": true,
"ArenaObjectives": { "$path": "scripts/ArenaObjectives.luau" }, "ArenaObjectives": { "$path": "scripts/ArenaObjectives.luau" },
"ArenaObjectiveSites": { "$path": "scripts/ArenaObjectiveSites.luau" },
"ModeRuntime": { "$path": "scripts/ModeRuntime" },
"ArenaRounds": { "$path": "scripts/ArenaRounds.server.luau" }, "ArenaRounds": { "$path": "scripts/ArenaRounds.server.luau" },
"ArenaSpawns": { "$path": "scripts/ArenaSpawns.luau" },
"SniperShots": { "$path": "scripts/SniperShots.server.luau" },
"HotPoint": { "$path": "scripts/HotPoint.luau" },
"CitadelCaptureService": { "$path": "scripts/CitadelCaptureService.luau" }, "CitadelCaptureService": { "$path": "scripts/CitadelCaptureService.luau" },
"CitadelScoreService": { "$path": "scripts/CitadelScoreService.luau" }, "CitadelScoreService": { "$path": "scripts/CitadelScoreService.luau" },
"CitadelSpawnService": { "$path": "scripts/CitadelSpawnService.luau" } "CitadelSpawnService": { "$path": "scripts/CitadelSpawnService.luau" }
@@ -18,7 +26,9 @@
"$ignoreUnknownInstances": true, "$ignoreUnknownInstances": true,
"StarterPlayerScripts": { "StarterPlayerScripts": {
"$ignoreUnknownInstances": true, "$ignoreUnknownInstances": true,
"ArenaRoundHud": { "$path": "scripts/ArenaRoundHud.client.luau" } "ArenaRoundHud": { "$path": "scripts/ArenaRoundHud.client.luau" },
"HealthBar": { "$path": "scripts/HealthBar.client.luau" },
"ArenaClient": { "$path": "scripts/ArenaClient" }
} }
} }
} }
@@ -0,0 +1,232 @@
--!strict
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local Input = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local UI = require(ReplicatedStorage:WaitForChild("HunterUI") :: ModuleScript)
local Rules = require(ReplicatedStorage:WaitForChild("MatchRules") :: ModuleScript)
local Sounds = require(ReplicatedStorage:WaitForChild("SniperEffects") :: ModuleScript)
local Siege = require(ReplicatedStorage:WaitForChild("CitadelAssaultConfig") :: ModuleScript)
local Hunter = ReplicatedStorage:WaitForChild("Hunter")
local Profiles = require(Hunter:WaitForChild("ModeProfiles") :: ModuleScript)
local Config = require(Hunter:WaitForChild("RoundConfig") :: ModuleScript)
local Strings = require(Hunter:WaitForChild("Strings") :: ModuleScript)
local match = ReplicatedStorage:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
local gui = Instance.new("ScreenGui")
gui.Name = "RoundPresentation"
gui.ResetOnSpawn = false
gui.IgnoreGuiInset = true
gui.DisplayOrder = 24
gui.Parent = playerGui
local vignette = Instance.new("CanvasGroup")
vignette.Name = "FinalPushVignette"
vignette.Size = UDim2.fromScale(1, 1)
vignette.BackgroundTransparency = 1
vignette.Visible = false
vignette.Parent = gui
local edges = {
{0, 0, 1, .2, 90}, {0, .8, 1, .2, 270},
{0, 0, .14, 1, 0}, {.86, 0, .14, 1, 180},
}
for _, side in edges do
local edge = Instance.new("Frame")
edge.Position = UDim2.fromScale(side[1], side[2])
edge.Size = UDim2.fromScale(side[3], side[4])
edge.BorderSizePixel = 0
edge.BackgroundColor3 = Color3.fromRGB(255, 60, 70)
edge.Parent = vignette
local gradient = Instance.new("UIGradient", edge)
gradient.Rotation = side[5]
gradient.Transparency = NumberSequence.new(.38, 1)
end
local swapShade = Instance.new("Frame")
swapShade.Name = "RoleSwapShade"
swapShade.Size = UDim2.fromScale(1, 1)
swapShade.BackgroundColor3 = UI.Panel
swapShade.BackgroundTransparency = 1
swapShade.Visible = false
swapShade.Parent = gui
local card = Instance.new("CanvasGroup")
card.Name = "Briefing"
card.AnchorPoint = Vector2.new(.5, .5)
card.Position = UDim2.fromScale(.5, .5)
card.Size = UDim2.new(.85, 0, 0, 260)
card.BackgroundTransparency = 1
card.Visible = false
card.Parent = gui
local max = Instance.new("UISizeConstraint", card)
max.MaxSize = Vector2.new(520, 260)
local plate = UI.plate(card, "Plate", UDim2.new(), UDim2.fromScale(1, 1), UI.Blue)
local contour = UI.contour(plate, UI.Blue)
UI.label(plate, "Mode", Strings.round.mode, UDim2.fromOffset(12, 12), UDim2.new(1, -24, 0, 19), 14, UI.Muted)
local title = UI.label(plate, "Title", "", UDim2.fromOffset(12, 31), UDim2.new(1, -24, 0, 40), 34, UI.Blue)
title.FontFace = UI.Display
local goal = UI.label(plate, "Goal", "", UDim2.fromOffset(18, 70), UDim2.new(1, -36, 0, 35), 18, UI.Ink)
goal.TextWrapped = true
local rules: {TextLabel} = {}
for i = 1, 3 do
local line = UI.label(plate, "Rule" .. i, "", UDim2.fromOffset(25, 108 + (i - 1) * 23), UDim2.new(1, -50, 0, 23), 15, UI.Ink)
line.TextXAlignment = Enum.TextXAlignment.Left
table.insert(rules, line)
end
local role = UI.label(plate, "Role", "", UDim2.fromOffset(18, 182), UDim2.new(1, -36, 0, 24), 17, UI.Gold)
local tutorial = UI.label(plate, "Tutorial", "", UDim2.fromOffset(18, 207), UDim2.new(1, -36, 0, 31), 14, UI.Muted)
tutorial.TextWrapped = true
local track = UI.element("ProgressBar", plate, UDim2.fromScale(.07, .94), UDim2.new(.86, 0, 0, 4))
local fill = track:WaitForChild("Fill") :: Frame
local banner = UI.plate(gui, "RoundBanner", UDim2.fromScale(.5, .28), UDim2.new(.82, 0, 0, 78), UI.Gold)
banner.AnchorPoint = Vector2.new(.5, .5)
Instance.new("UISizeConstraint", banner).MaxSize = Vector2.new(500, 78)
local bannerTitle = UI.label(banner, "Title", "", UDim2.fromOffset(0, 6), UDim2.new(1, 0, 0, 36), 27, UI.Gold)
bannerTitle.FontFace = UI.Display
local bannerDetail = UI.label(banner, "Detail", "", UDim2.fromOffset(12, 43), UDim2.new(1, -24, 0, 25), 16, UI.Ink)
local respawn = UI.label(gui, "Respawn", "", UDim2.fromScale(.5, .63), UDim2.new(.85, 0, 0, 42), 27, UI.Ink)
respawn.AnchorPoint = Vector2.new(.5, .5)
respawn.FontFace = UI.Display
UI.edge(respawn, UI.Panel, 0)
banner.Visible, respawn.Visible = false, false
local seen: {[string]: boolean} = {}
local oldStage: string? = nil
local wasInArena = false
local briefUntil, bannerUntil = 0, 0
local lastTick = -1
local barTween: Tween? = nil
local slide: Tween? = nil
local fade: Tween? = nil
local pulse: Tween? = nil
local swapTween: Tween? = nil
local shakeUntil = 0
local function showBriefing(id: string, now: number, untilAt: number, short: boolean)
local profile = Profiles[id]
if not profile then return end
local side = player:GetAttribute("ArenaTeam")
local tone = if side == "Orange" then UI.Orange else UI.Blue
title.TextColor3 = tone
title.Text = Rules.get(id).title
goal.Text = profile.goal
contour:SetAttribute("Accent", tone)
UI.tintPlate(plate, tone)
for i, line in rules do
line.Visible = not short
line.Text = "✓ " .. profile.rules[i]
end
local attacker = match:FindFirstChild("CitadelMatchState")
local attackerSide = attacker and attacker:GetAttribute("Attacker") or Siege.FIRST_ATTACKER
role.Position = UDim2.fromOffset(18, if short then 122 else 182)
role.Text = if id == "Siege" then (if side == attackerSide then Strings.round.attack else Strings.round.defend) else Strings.team(side)
tutorial.Visible = not short and not seen[id]
tutorial.Text = Strings.round.tutorial[id] or ""
if not short then seen[id] = true end
card.Size = UDim2.new(.85, 0, 0, if short then 168 else 260)
briefUntil = untilAt
card.Position, card.GroupTransparency, card.Visible = UDim2.fromScale(.5, .54), 1, true
if barTween then barTween:Cancel() end
if slide then slide:Cancel() end
if fade then fade:Cancel() end
local entrance = TweenInfo.new(.25, Enum.EasingStyle.Quart, Enum.EasingDirection.Out)
slide = TweenService:Create(card, entrance, {Position = UDim2.fromScale(.5, .5)})
fade = TweenService:Create(card, entrance, {GroupTransparency = 0})
local duration = math.max(.05, if short then Config.lateBriefingSeconds else profile.briefingSeconds)
fill.Size = UDim2.fromScale(math.clamp((untilAt - now) / duration, 0, 1), 1)
barTween = TweenService:Create(fill, TweenInfo.new(math.max(.05, untilAt - now), Enum.EasingStyle.Linear), {Size = UDim2.fromScale(0, 1)})
slide:Play()
fade:Play()
barTween:Play()
end
local function showBanner(heading: string, detail: string, untilAt: number)
bannerTitle.Text, bannerDetail.Text = heading, detail
bannerUntil = untilAt
banner.Visible = true
end
local function update()
local now = workspace:GetServerTimeNow()
local inArena = player:GetAttribute("InArena") == true
local stage = match:GetAttribute("RoundStage") :: string?
local id = Rules.get(match:GetAttribute("Ruleset")).id
local final = inArena and stage == "FinalPush"
local swapping = inArena and stage == "RoleSwap"
if swapping ~= swapShade.Visible then
swapShade.Visible = swapping
if swapTween then swapTween:Cancel(); swapTween = nil end
if swapping then
swapShade.BackgroundTransparency = 1
swapTween = TweenService:Create(swapShade, TweenInfo.new(.22), {BackgroundTransparency = .28})
swapTween:Play()
end
end
if final ~= vignette.Visible then
vignette.Visible = final
if pulse then pulse:Cancel(); pulse = nil end
if final then
vignette.GroupTransparency = .46
pulse = TweenService:Create(vignette, TweenInfo.new(.9, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, -1, true),
{GroupTransparency = .75})
pulse:Play()
end
end
if inArena and (stage ~= oldStage or not wasInArena) then
card.Visible = false
banner.Visible = false
lastTick = -1
if stage == "Briefing" then
local limit = match:GetAttribute("StageEndsAt")
if typeof(limit) == "number" and limit > now then showBriefing(id, now, limit, false) end
elseif stage == "RoleSwap" then
local limit = match:GetAttribute("StageEndsAt")
if typeof(limit) == "number" then showBanner("⇄ " .. Strings.round.swap, if player:GetAttribute("ArenaTeam") == "Orange" then Strings.round.attack else Strings.round.defend, limit) end
elseif stage == "Live" or stage == "FinalPush" then
if final then
showBanner(Strings.round.final, Strings.round.finalPush[id] or "", now + Config.finalBannerSeconds)
elseif oldStage == "Countdown" and wasInArena then
showBanner(Strings.round.fight, "", now + Config.startBannerSeconds)
Sounds.sound("RoundStart")
if Config.CameraShake and not Input.TouchEnabled then shakeUntil = os.clock() + .22 end
elseif not wasInArena then
showBriefing(id, now, now + Config.lateBriefingSeconds, true)
end
end
end
card.Visible = card.Visible and inArena and now < briefUntil
banner.Visible = banner.Visible and inArena and now < bannerUntil
local shieldAt = player:GetAttribute("RoundRespawnAt")
local left = if typeof(shieldAt) == "number" then math.ceil(shieldAt - now) else 0
respawn.Visible = inArena and left > 0
if respawn.Visible then respawn.Text = string.format(Strings.round.respawn, left) end
if final then
local endsAt = match:GetAttribute("EndsAt")
local seconds = if typeof(endsAt) == "number" then math.ceil(endsAt - now) else 0
if seconds > 0 and seconds <= Config.finalTickSeconds and seconds ~= lastTick then
lastTick = seconds
Sounds.sound("Tick")
end
end
oldStage, wasInArena = stage, inArena
end
local connection = RunService.Heartbeat:Connect(update)
local shakeName = "HunterRoundStartShake"
if Config.CameraShake and not Input.TouchEnabled then
RunService:BindToRenderStep(shakeName, Enum.RenderPriority.Camera.Value + 1, function()
local camera = workspace.CurrentCamera
local left = shakeUntil - os.clock()
if camera and left > 0 then camera.CFrame *= CFrame.Angles(math.sin(left * 85) * left * .027, 0, 0) end
end)
end
script.Destroying:Once(function()
connection:Disconnect()
if Config.CameraShake and not Input.TouchEnabled then RunService:UnbindFromRenderStep(shakeName) end
for _, tween in {barTween, slide, fade, pulse, swapTween} do if tween then tween:Cancel() end end
gui:Destroy()
end)
@@ -0,0 +1,168 @@
--!strict
local Players = game:GetService("Players")
local rs = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UI = require(rs:WaitForChild("HunterUI") :: ModuleScript)
local Sounds = require(rs:WaitForChild("SniperEffects") :: ModuleScript)
local Config = require(rs.CitadelAssaultConfig)
local Strings = require(rs.Hunter.Strings)
local Hints = require(rs.Hunter.Hints)
local Kinds = require(rs.Hunter.EventKinds)
local Stage = require(rs.Hunter.Stage)
local Provider = require(script.Parent.HintProviders.Siege)
local Router = require(script.Parent.EventRouter)
local player = Players.LocalPlayer
local pg = player:WaitForChild("PlayerGui")
local match = rs:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local T = Strings.hint.Siege
local gui = Instance.new("ScreenGui")
gui.Name, gui.DisplayOrder, gui.ResetOnSpawn, gui.Enabled = "CitadelGuide", 25, false, false
gui.Parent = pg
local panel = UI.plate(gui, "Direction", UDim2.fromScale(.5, .77), UDim2.new(.88, 0, 0, 74), UI.Outline)
panel.AnchorPoint = Vector2.new(.5, .5)
Instance.new("UISizeConstraint", panel).MaxSize = Vector2.new(326, 74)
local contour = UI.contour(panel, UI.Gold)
local arrow = UI.label(panel, "Arrow", "▲", UDim2.fromOffset(10, 15), UDim2.fromOffset(34, 34), 24, UI.Gold)
local title = UI.label(panel, "Title", "", UDim2.fromOffset(53, 5), UDim2.new(1, -59, 0, 22), 17, UI.Ink)
local distance = UI.label(panel, "Distance", "", UDim2.fromOffset(53, 27), UDim2.new(1, -59, 0, 18), 15, UI.Ink)
local nextLine = UI.label(panel, "Next", "", UDim2.fromOffset(53, 47), UDim2.new(1, -59, 0, 19), 13, UI.Muted)
for _, line in {title, distance, nextLine} do line.TextXAlignment = Enum.TextXAlignment.Left end
local hints = Hints.new()
local pending: Hints.Hint? = nil
local count = 0
local shownTutorial = false
local lastGeneration: unknown = nil
local previousZone: string? = nil
local previousStatus: string? = nil
local lastTick = 0
local charge: Sound? = nil
local currentTarget: Vector3? = nil
local function stopCharge()
if charge then charge:Destroy(); charge = nil end
end
local function eligible(): boolean
return player:GetAttribute("InArena") == true and match:GetAttribute("Ruleset") == "Siege" and match:GetAttribute("Phase") == "Round"
end
local function push(key: string, message: string, priority: number, ttl: number?)
if not Config.HintsEnabled or not eligible() then return end
pending = {key = key, text = message, priority = priority, ttl = ttl or 4, cooldown = Config.HINT_COOLDOWN}
end
local subscriptions = {
Router.on(Kinds.ZoneStarted, function(p)
if not eligible() then return end
if p.side ~= player:GetAttribute("ArenaTeam") then push("sg_def_new", T.defNew(p.index or 1), 90) end
end),
Router.on(Kinds.ZoneCaptured, function(p)
if not eligible() then return end
local i = p.index or 1
local won = p.side == player:GetAttribute("ArenaTeam")
push(if won then "sg_captured" else "sg_def_lost", if won then T.captured(i) else T.defLost(i + 1, Config.MAX_OBJECTIVES), 90)
end),
Router.on(Kinds.AllObjectivesTaken, function(p)
if p.side == player:GetAttribute("ArenaTeam") then push("sg_all", T.all, 94) end
end),
Router.on(Kinds.RoleSwap, function(p)
if not eligible() then return end
Sounds.sound("SiegeEnter")
push("sg_new_role", if p.side == player:GetAttribute("ArenaTeam") then T.newAttack else T.newDefense, 96, 5)
end),
}
local function update()
local data = match:FindFirstChild("CitadelMatchState")
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
local human = character and character:FindFirstChildOfClass("Humanoid")
if not eligible() or not data or not root or not root:IsA("BasePart") or not human or human.Health <= 0 then
gui.Enabled = false
currentTarget = nil
pg:SetAttribute("SiegeHint", nil)
stopCharge()
previousZone, previousStatus, lastTick = nil, nil, 0
if not eligible() then hints = Hints.new(); pending = nil end
return
end
local phase = data:GetAttribute("Phase")
local stage = match:GetAttribute("RoundStage")
if not Stage.combatAllowed(match) then
gui.Enabled = false
pg:SetAttribute("SiegeHint", nil)
stopCharge()
previousZone, previousStatus, lastTick = nil, nil, 0
return
end
local generation = match:GetAttribute("MapGeneration")
if lastGeneration ~= generation then count += 1; lastGeneration = generation end
local status = data:GetAttribute("Status") :: string?
local zone = player:GetAttribute("CitadelZone") :: string?
local side = player:GetAttribute("ArenaTeam")
local attacking = side == data:GetAttribute("Attacker")
local point = data:GetAttribute("Point")
local index = (data:GetAttribute("Index") :: number?) or 1
local fraction = (data:GetAttribute("Progress") :: number?) or 0
local percent = math.floor((fraction + 1e-7) * 10) * 10
local delta = if typeof(point) == "Vector3" then point - root.Position else Vector3.zero
if not shownTutorial and Config.HintsEnabled and typeof(point) == "Vector3" and not pending then
shownTutorial = true
push("sg_tutorial", T.tutorial, 95, 6)
end
local candidates = Provider.candidates({
zone = zone, status = status, attacking = attacking, seconds = (data:GetAttribute("Seconds") :: number?) or 0,
first = phase == "Attack1", distance = delta.Magnitude, dy = delta.Y, progress = percent, experienced = count > 3,
})
if pending then table.insert(candidates, pending); pending = nil end
local chosen = if Config.HintsEnabled then Hints.pick(hints, candidates, workspace:GetServerTimeNow()) else nil
pg:SetAttribute("SiegeHint", if chosen then chosen.text else nil)
if zone == "Inside" and previousZone ~= zone then Sounds.sound("SiegeEnter") end
if zone == "Inside" and status == "Capturing" and attacking then
if not charge then charge = Sounds.sound("SiegeCharge") end
if charge then charge.PlaybackSpeed = .9 + .6 * fraction end
if percent > lastTick then Sounds.sound("SiegeTick") end
elseif charge then stopCharge() end
if status ~= previousStatus and status == "Contested" then Sounds.sound("SiegeBlocked")
elseif status ~= previousStatus and status == "Decaying" and attacking then Sounds.sound("SiegeDecay") end
previousZone, previousStatus, lastTick = zone, status, percent
local results = pg:FindFirstChild("ArenaResults")
local main = pg:FindFirstChild("MainMenu")
local blocked = pg:GetAttribute("HunterVoting") == true or (results and results:GetAttribute("LiveScoreboardOpen") == true)
or (main and main:IsA("ScreenGui") and main.Enabled)
gui.Enabled = not blocked and stage ~= "RoleSwap" and typeof(point) == "Vector3" and zone ~= "Inside" and
(attacking or status == "Capturing" or status == "Contested")
currentTarget = if gui.Enabled and typeof(point) == "Vector3" then point else nil
if not gui.Enabled then return end
local tint = if not attacking then UI.Gold elseif side == "Orange" then UI.Orange else UI.Blue
contour:SetAttribute("Accent", tint)
arrow.TextColor3 = tint
title.Text = if attacking then T.point(index, tostring(data:GetAttribute("PointName") or "")) else T.defend
distance.Text = Strings.studs(delta.Magnitude) .. (if delta.Y > 8 then T.above elseif delta.Y < -8 then T.below else "")
local following = data:GetAttribute("NextPoint")
nextLine.Text = if typeof(following) == "Vector3" then T.next(index + 1, Strings.studs((following - root.Position).Magnitude)) else ""
end
local interval = 0
local tick = RunService.Heartbeat:Connect(function(dt)
interval += dt
if interval < Config.CHECK_INTERVAL then return end
interval %= Config.CHECK_INTERVAL
update()
end)
local render = RunService.RenderStepped:Connect(function()
local camera = workspace.CurrentCamera
local target = currentTarget
if not camera or not target then return end
local root = player.Character and player.Character.PrimaryPart
if not root then return end
local delta = target - root.Position
local localDelta = camera.CFrame:VectorToObjectSpace(Vector3.new(delta.X, 0, delta.Z))
arrow.Rotation = math.deg(math.atan2(localDelta.X, -localDelta.Z))
end)
script.Destroying:Once(function()
stopCharge()
tick:Disconnect()
render:Disconnect()
for _, cancel in subscriptions do cancel() end
gui:Destroy()
end)
+23
View File
@@ -0,0 +1,23 @@
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remote = ReplicatedStorage:WaitForChild("ArenaObjectiveEvent") :: RemoteEvent
type Handler = (any) -> ()
local handlers: {[string]: {Handler}} = {}
local Router = {}
function Router.on(kind: string, handler: Handler): () -> ()
local list = handlers[kind] or {}
handlers[kind] = list
table.insert(list, handler)
return function()
local index = table.find(list, handler)
if index then table.remove(list, index) end
end
end
remote.OnClientEvent:Connect(function(kind: string, payload: any)
if typeof(payload) ~= "table" then return end
for _, handler in table.clone(handlers[kind] or {}) do task.spawn(handler, payload) end
end)
return Router
@@ -0,0 +1,126 @@
--!strict
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TweenService = game:GetService("TweenService")
local UI = require(ReplicatedStorage:WaitForChild("HunterUI") :: ModuleScript)
local Strings = require(ReplicatedStorage:WaitForChild("Hunter"):WaitForChild("Strings") :: ModuleScript)
local Router = require(script.Parent:WaitForChild("EventRouter") :: ModuleScript)
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
local hud = playerGui:WaitForChild("ArenaRoundHud")
local match = ReplicatedStorage:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local MAX_ROWS, LIFETIME, FADE = 4, 6, .35
local gui = Instance.new("ScreenGui")
gui.Name = "ArenaObjectiveFeed"
gui.DisplayOrder = 12
gui.ResetOnSpawn = false
gui.Parent = playerGui
local stack = Instance.new("Frame")
stack.BackgroundTransparency = 1
stack.Position = UDim2.fromOffset(16, 194)
stack.Size = UDim2.new(.6, 0, 0, 190)
stack.Parent = gui
local limit = Instance.new("UISizeConstraint", stack)
limit.MaxSize = Vector2.new(345, 190)
local scale = Instance.new("UIScale", stack)
local layout = Instance.new("UIListLayout", stack)
layout.SortOrder = Enum.SortOrder.LayoutOrder
layout.Padding = UDim.new(0, 5)
local connections: {RBXScriptConnection} = {}
local function resize()
scale.Scale = UI.combatScale(gui)
local bottom = hud:GetAttribute("ContentBottom")
stack.Position = UDim2.fromOffset(16, math.max(194, (if typeof(bottom) == "number" then bottom else 0) + 12))
end
resize()
table.insert(connections, stack:GetPropertyChangedSignal("AbsoluteSize"):Connect(resize))
table.insert(connections, hud:GetAttributeChangedSignal("ContentBottom"):Connect(resize))
local menu = playerGui:WaitForChild("ArenaResults")
local watchedMenu: ScreenGui? = nil
local menuConnection: RBXScriptConnection? = nil
local rows: {CanvasGroup} = {}
local order = 0
local alive = true
local function refresh()
local active = player:GetAttribute("InArena") == true and match:GetAttribute("Phase") == "Round"
gui.Enabled = active and menu:GetAttribute("LiveScoreboardOpen") ~= true
and playerGui:GetAttribute("HunterVoting") ~= true and not (watchedMenu and watchedMenu.Enabled)
if not active then
for _, row in rows do row:Destroy() end
table.clear(rows)
end
end
local function watchMenu(instance: Instance)
if instance.Name ~= "MainMenu" or not instance:IsA("ScreenGui") then return end
if menuConnection then menuConnection:Disconnect() end
watchedMenu = instance
menuConnection = instance:GetPropertyChangedSignal("Enabled"):Connect(refresh)
refresh()
end
local initialMenu = playerGui:FindFirstChild("MainMenu")
if initialMenu then watchMenu(initialMenu) end
table.insert(connections, playerGui.ChildAdded:Connect(watchMenu))
table.insert(connections, playerGui.ChildRemoved:Connect(function(child)
if child ~= watchedMenu then return end
if menuConnection then menuConnection:Disconnect(); menuConnection = nil end
watchedMenu = nil
refresh()
end))
table.insert(connections, menu:GetAttributeChangedSignal("LiveScoreboardOpen"):Connect(refresh))
table.insert(connections, playerGui:GetAttributeChangedSignal("HunterVoting"):Connect(refresh))
table.insert(connections, player:GetAttributeChangedSignal("InArena"):Connect(refresh))
table.insert(connections, match:GetAttributeChangedSignal("Phase"):Connect(refresh))
refresh()
local function remove(row: CanvasGroup)
local index = table.find(rows, row)
if not index then return end
table.remove(rows, index)
row:Destroy()
end
local function add(message: string, side: string?)
if not alive or player:GetAttribute("InArena") ~= true or match:GetAttribute("Phase") ~= "Round" then return end
order -= 1
local tint = if side == "Blue" then UI.Blue elseif side == "Orange" then UI.Orange else UI.Gold
local row = Instance.new("CanvasGroup")
row.Name = "Event"
row.LayoutOrder = order
row.Size = UDim2.new(1, 0, 0, 36)
row.BackgroundTransparency = 1
row.GroupTransparency = 1
local plate = UI.plate(row, "Plate", UDim2.new(), UDim2.fromScale(1, 1), tint)
local dot = Instance.new("Frame", plate)
dot.AnchorPoint = Vector2.new(0, .5)
dot.Position = UDim2.new(0, 10, .5, 0)
dot.Size = UDim2.fromOffset(8, 8)
dot.BackgroundColor3 = tint
dot.BorderSizePixel = 0
Instance.new("UICorner", dot).CornerRadius = UDim.new(1, 0)
local label = UI.label(plate, "Message", message, UDim2.fromOffset(25, 0), UDim2.new(1, -34, 1, 0), 16, UI.Ink)
label.TextXAlignment = Enum.TextXAlignment.Left
label.TextTruncate = Enum.TextTruncate.AtEnd
row.Parent = stack
table.insert(rows, 1, row)
if #rows > MAX_ROWS then remove(rows[#rows]) end
TweenService:Create(row, TweenInfo.new(.15), {GroupTransparency = 0}):Play()
task.delay(LIFETIME - FADE, function()
if not row.Parent then return end
TweenService:Create(row, TweenInfo.new(FADE), {GroupTransparency = 1}):Play()
task.delay(FADE, remove, row)
end)
end
local unsubscribe: {() -> ()} = {}
for kind, format in Strings.feed do
table.insert(unsubscribe, Router.on(kind, function(payload) add(format(payload), payload.side) end))
end
script.Destroying:Once(function()
alive = false
for _, clean in unsubscribe do clean() end
for _, connection in connections do connection:Disconnect() end
if menuConnection then menuConnection:Disconnect() end
gui:Destroy()
end)
@@ -0,0 +1,36 @@
--!strict
local rs = game:GetService("ReplicatedStorage")
local S = require(rs.Hunter.Strings).flagHints
local H = require(rs.Hunter.Hints)
local Provider = {}
function Provider.candidates(match: Instance, player: Player): {H.Hint}
local side = match:GetAttribute("FlagCarrierSide")
local at = match:GetAttribute("FlagReturnAt")
local own = player:GetAttribute("ArenaTeam")
local key, text, priority = "flag_roof", S.roof, 30
if player:GetAttribute("ArenaFlag") == true then key,text,priority = "flag_deliver",S.deliver,90
elseif typeof(side) == "string" and side ~= own then key,text,priority = "flag_enemy",S.enemy,80
elseif side == own and typeof(side) == "string" then key,text,priority = "flag_escort",S.escort,60
elseif typeof(at) == "number" then
key,text,priority = "flag_drop",string.format(S.dropped,math.max(0,math.ceil(at-workspace:GetServerTimeNow()))),70
end
return {{key=key,text=text,priority=priority,ttl=.4}}
end
function Provider.target(match: Instance, player: Player): (Vector3?, string?, string?)
local own = player:GetAttribute("ArenaTeam")
if player:GetAttribute("ArenaFlag") == true and typeof(own) == "string" then
local base = match:GetAttribute("FlagBase_" .. own)
return if typeof(base) == "Vector3" then base else nil, S.base, own
end
local point = match:GetAttribute("FlagPosition")
local carrierSide = match:GetAttribute("FlagCarrierSide")
local name = if carrierSide == own and typeof(carrierSide) == "string" then S.escortTitle else S.title
return if typeof(point) == "Vector3" then point else nil, name, if typeof(carrierSide) == "string" then carrierSide else nil
end
function Provider.highlight(_match: Instance, _viewer: Player, member: Player): boolean
return member:GetAttribute("ArenaFlag") == true
end
return Provider
@@ -0,0 +1,26 @@
--!strict
local rs = game:GetService("ReplicatedStorage")
local Hints = require(rs.Hunter.Hints)
local S = require(rs.Hunter.Strings).domination
local Provider = {}
function Provider.candidates(match: Instance, player: Player): {Hints.Hint}
local side = player:GetAttribute("ArenaTeam")
local zone = player:GetAttribute("DominationZone")
local out: {Hints.Hint} = {}
local function add(key: string, text: string, priority: number)
table.insert(out, {key = key, text = text, priority = priority, ttl = .4})
end
if zone == "Height" then add("dp_height", S.height, 80)
elseif zone == "Blocked" then add("dp_blocked", S.blocked, 80) end
for _, key in {"A", "B", "C"} do
if match:GetAttribute("ZoneContested_" .. key) == true then add("dp_contest_" .. key, S.contested(key), 60)
elseif match:GetAttribute("ZoneOwner_" .. key) == nil then add("dp_free_" .. key, S.free(key), 40) end
end
if typeof(side) == "string" then
local rate = match:GetAttribute("ScoreRate_" .. side)
if typeof(rate) == "number" and rate > 0 then add("dp_rate", S.hold(rate), 20) end
end
return out
end
return Provider
@@ -0,0 +1,26 @@
--!strict
local rs = game:GetService("ReplicatedStorage")
local Hints = require(rs.Hunter.Hints)
local S = require(rs.Hunter.Strings).hotHints
local taught = setmetatable({}, {__mode = "k"})
local Provider = {}
function Provider.candidates(match: Instance, player: Player): {Hints.Hint}
local out: {Hints.Hint} = {}
local function add(key: string, text: string, priority: number, ttl: number?)
table.insert(out,{key=key,text=text,priority=priority,ttl=ttl or .4})
end
local phase = match:GetAttribute("HotPointPhase")
local point = match:GetAttribute("HotPointPosition")
local movesAt = match:GetAttribute("HotPointMovesAt")
local left = if typeof(movesAt) == "number" then math.ceil(movesAt - workspace:GetServerTimeNow()) else 0
if phase == "Captured" then add("hp_capture", string.format(S.captured,math.max(0,left)),90)
elseif left > 0 and left <= 5 then add("hp_next",string.format(S.next,left),85)
elseif phase == "UnderFire" and match:GetAttribute("HotPointTeam") == player:GetAttribute("ArenaTeam") then add("hp_fire",S.fire,60)
elseif typeof(point) == "Vector3" and not phase then add("hp_enter",S.enter,40)
elseif phase == "Capturing" and not taught[player] and match:GetAttribute("HotPointTeam") == player:GetAttribute("ArenaTeam") then
taught[player] = true
add("hp_team",S.team,20,4)
end
return out
end
return Provider
@@ -0,0 +1,35 @@
--!strict
local rs=game:GetService("ReplicatedStorage")
local H=require(rs.Hunter.Hints)
local S=require(rs.Hunter.Strings).leaderHints
local Provider={}
local function sides(player: Player): (string,string)
if player:GetAttribute("ArenaTeam")=="Orange" then return "Orange","Blue" end
return "Blue","Orange"
end
function Provider.candidates(match: Instance, player: Player): {H.Hint}
if player:GetAttribute("ArenaLeader")==true then return {{key="hl_self",text=S.self,priority=80,ttl=.4}} end
local own,enemy=sides(player)
local ally=match:GetAttribute("LeaderName_"..own)
local opponent=match:GetAttribute("LeaderName_"..enemy)
local root=player.Character and player.Character.PrimaryPart
local target=match:GetAttribute("LeaderPosition_"..enemy)
local nearby=root and typeof(target)=="Vector3" and (root.Position-target).Magnitude<95
if typeof(opponent)=="string" and (nearby or typeof(ally)~="string") then
return {{key="hl_enemy",text=string.format(S.enemy,opponent),priority=60,ttl=.4}}
end
if typeof(ally)=="string" then return {{key="hl_ally",text=string.format(S.ally,ally),priority=50,ttl=.4}} end
return {}
end
function Provider.target(match: Instance, player: Player): (Vector3?,string?,string?)
if player:GetAttribute("ArenaLeader")==true then return nil end
local own=sides(player)
local point=match:GetAttribute("LeaderPosition_"..own)
local name=match:GetAttribute("LeaderName_"..own)
return if typeof(point)=="Vector3" then point else nil, if typeof(name)=="string" then string.format(S.ally,name) else nil, own
end
function Provider.highlight(_match: Instance, viewer: Player, member: Player): boolean
return member:GetAttribute("InArena")==true and member:GetAttribute("ArenaLeader")==true
and member:GetAttribute("ArenaTeam")~=viewer:GetAttribute("ArenaTeam")
end
return Provider
@@ -0,0 +1,10 @@
--!strict
local rs=game:GetService("ReplicatedStorage")
local H=require(rs.Hunter.Hints)
local S=require(rs.Hunter.Strings).lifeHints
return {candidates=function(match: Instance, player: Player): {H.Hint}
if match:GetAttribute("MiniRoundActive")==true and player:GetAttribute("ArenaWaiting")==true then
return {{key="life_watch",text=S.wait,priority=60,ttl=.4}}
end
return {}
end}
@@ -0,0 +1,30 @@
--!strict
local rs = game:GetService("ReplicatedStorage")
local Strings = require(rs.Hunter.Strings)
local Config = require(rs.CitadelAssaultConfig)
local Hints = require(rs.Hunter.Hints)
local text = Strings.hint.Siege
export type Snapshot = {zone: string?, status: string?, attacking: boolean, seconds: number, first: boolean, distance: number, dy: number, progress: number, experienced: boolean}
local Provider = {}
function Provider.candidates(s: Snapshot): {Hints.Hint}
local candidates: {Hints.Hint} = {}
if not Config.HintsEnabled then return candidates end
local function add(key: string, message: string, priority: number)
table.insert(candidates, {key = key, text = message, priority = priority, ttl = .4, cooldown = Config.HINT_COOLDOWN})
end
local copy = if s.experienced then text.short else text
if s.first and s.seconds > 0 and s.seconds <= Config.SWAP_WARNING then add("sg_swap", text.swap(s.seconds), 85) end
if s.zone == "Height" then add("sg_height", if s.attacking then text.height(s.dy) else copy.defHeight, 80)
elseif s.zone == "Blocked" then add("sg_blocked", if s.attacking then copy.blocked else copy.defBlocked, 80)
elseif s.attacking then
if s.status == "Contested" then add("sg_contested", copy.contested, 70)
elseif s.status == "Decaying" then add("sg_decay", copy.decay, 60)
elseif s.zone == "Inside" and s.status == "Capturing" then add("sg_capturing", text.capturing(s.progress), 40)
elseif s.zone == "Outside" then add("sg_far", text.far(s.distance), 40) end
elseif s.zone == "Inside" then add("sg_def_block", copy.defBlock, 60)
elseif s.status == "Capturing" then add("sg_def_far", copy.defFar, 70) end
return candidates
end
return Provider
@@ -0,0 +1,14 @@
--!strict
local rs=game:GetService("ReplicatedStorage")
local H=require(rs.Hunter.Hints)
local Rules=require(rs.Hunter.TeamDeathmatchRules)
local S=require(rs.Hunter.Strings).teamDeathmatch
return {candidates=function(match: Instance, player: Player): {H.Hint}
if match:GetAttribute("RoundStage")~="FinalPush" then return {} end
local own=player:GetAttribute("ArenaTeam")
if own~="Blue" and own~="Orange" then return {} end
local rival=if own=="Blue" then "Orange" else "Blue"
local n=Rules.chaseGap((match:GetAttribute(own.."Score") :: number?) or 0,(match:GetAttribute(rival.."Score") :: number?) or 0)
if n then return {{key="tdm_gap",text=string.format(S.chase,n),priority=60,ttl=.4}} end
return {}
end}
@@ -0,0 +1,22 @@
--!strict
local rs=game:GetService("ReplicatedStorage")
local S=require(rs.Hunter.Strings).trophyHints
local H=require(rs.Hunter.Hints)
local Provider={}
function Provider.candidates(_match: Instance, player: Player): {H.Hint}
local count=player:GetAttribute("ArenaTokens")
if typeof(count)=="number" and count>=3 then
return {{key="th_bank",text=string.format(S.carry,count),priority=70,ttl=.4}}
end
local root=player.Character and player.Character.PrimaryPart
local world=workspace:FindFirstChild("ProceduralArena")
local folder=world and world:FindFirstChild("MatchObjectives")
if not root or not folder then return {} end
for _,token in folder:GetChildren() do
if token.Name=="Tokens" and token:IsA("BasePart") and (root.Position-token.Position).Magnitude<18 then
return {{key="th_near",text=S.near,priority=30,ttl=.4}}
end
end
return {}
end
return Provider
@@ -0,0 +1,148 @@
--!strict
local Players = game:GetService("Players")
local rs = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local UI = require(rs:WaitForChild("HunterUI") :: ModuleScript)
local Sounds = require(rs:WaitForChild("SniperEffects") :: ModuleScript)
local S = require(rs.Hunter.Strings)
local Hints = require(rs.Hunter.Hints)
local Kinds = require(rs.Hunter.EventKinds)
local Router = require(script.Parent.EventRouter)
local player = Players.LocalPlayer
local pg = player:WaitForChild("PlayerGui")
local match = rs:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local providers = script.Parent:WaitForChild("HintProviders")
local gui = Instance.new("ScreenGui")
gui.Name, gui.DisplayOrder, gui.ResetOnSpawn = "ModeFeedback", 24, false
gui.Parent = pg
local banner = UI.plate(gui, "EventBanner", UDim2.fromScale(.5, .34), UDim2.new(.8, 0, 0, 58), UI.Gold)
banner.AnchorPoint = Vector2.new(.5,.5)
Instance.new("UISizeConstraint", banner).MaxSize = Vector2.new(430,58)
local contour = UI.contour(banner, UI.Gold)
local title = UI.label(banner,"Title","",UDim2.fromScale(.02,0),UDim2.fromScale(.96,1),24,UI.Ink)
title.FontFace = UI.Display
banner.Visible = false
local wave = Instance.new("Part")
wave.Name = "LocalObjectiveWave"
wave.Shape, wave.Material = Enum.PartType.Cylinder, Enum.Material.Neon
wave.Anchored, wave.CanCollide, wave.CanTouch, wave.CanQuery = true, false, false, false
wave.Transparency = 1
wave.Parent = workspace
local effect: Tween? = nil
local pending: Hints.Hint? = nil
local activeMode: string? = nil
local provider: any = nil
local selection = Hints.new()
local bannerUntil = 0
local function tint(side: string?): Color3
return if side == "Blue" then UI.Blue elseif side == "Orange" then UI.Orange else UI.Gold
end
local function showWave(at: Vector3, color: Color3)
if effect then effect:Cancel() end
wave.CFrame = CFrame.new(at + Vector3.yAxis*.3) * CFrame.Angles(0, 0, math.pi/2)
wave.Size = Vector3.new(.1,12,12)
wave.Color, wave.Transparency = color, .64
effect = TweenService:Create(wave,TweenInfo.new(.5,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),
{Size=Vector3.new(.1,42,42),Transparency=1})
effect:Play()
end
local function event(kind: string, p: any)
if player:GetAttribute("InArena") ~= true or match:GetAttribute("Phase") ~= "Round" then return end
local id = match:GetAttribute("Ruleset")
local tone = tint(p.side)
if id == "CaptureFlag" and (kind == Kinds.FlagPicked or kind == Kinds.FlagScored) then
contour:SetAttribute("Accent", tone)
title.Text = if kind == Kinds.FlagScored then S.flagHints.scored
elseif p.side == player:GetAttribute("ArenaTeam") then S.flagHints.picked else S.flagHints.enemyPicked
bannerUntil = workspace:GetServerTimeNow() + 2.7
end
if id == "TeamDeathmatch" and kind == Kinds.Streak then
contour:SetAttribute("Accent",tone)
title.Text=string.format(S.teamDeathmatch.streak,p.text or "",p.value or 0)
bannerUntil=workspace:GetServerTimeNow()+2.7
if p.userId~=player.UserId then Sounds.sound("RoundStart") end
end
if id == "HuntLeader" and (kind == Kinds.LeaderAssigned or kind == Kinds.LeaderDown) then
local now=workspace:GetServerTimeNow()
if kind == Kinds.LeaderDown or now>=bannerUntil then
contour:SetAttribute("Accent",tone)
title.Text=if kind==Kinds.LeaderDown then S.leaderHints.down else string.format(S.leaderHints.new,p.text or "")
bannerUntil=now+2.5
end
if kind==Kinds.LeaderDown then
Sounds.sound("HotPointCaptured")
if typeof(p.at)=="Vector3" then showWave(p.at,tone) end
end
end
if id == "OneLife" and (kind == Kinds.MiniRoundStarted or kind == Kinds.MiniRoundEnded) then
contour:SetAttribute("Accent",tone)
local copy=S.lifeHints
local blue,orange=p.blue or 0,p.orange or 0
title.Text=if kind == Kinds.MiniRoundStarted then string.format(copy.begin,p.index or 1,blue,orange)
elseif not p.side then copy.draw else string.format(copy.win,S.team(p.side),math.max(blue,orange),math.min(blue,orange))
bannerUntil=workspace:GetServerTimeNow()+2.8
Sounds.sound(if kind==Kinds.MiniRoundStarted then "RoundStart" else "HotPointCaptured")
end
if id == "TrophyHunt" and p.userId == player.UserId then
if kind == Kinds.TokensBanked then
contour:SetAttribute("Accent", tone)
title.Text = string.format(S.trophyHints.banked, p.value or 0)
bannerUntil = workspace:GetServerTimeNow() + 2.7
elseif kind == Kinds.TokensLost then
pending = {key="th_lost",priority=60,text=S.trophyHints.lost,ttl=4}
end
end
if id == "Domination" then
if kind == Kinds.ZoneLost and p.side == player:GetAttribute("ArenaTeam") then
pending = {key="dp_lost",priority=70,text=S.domination.lost(string.sub(p.text or "A",1,1)),ttl=4}
elseif kind == Kinds.FullControl then
contour:SetAttribute("Accent",tone)
title.Text = S.domination.control
bannerUntil = workspace:GetServerTimeNow()+3
Sounds.sound("RoundStart")
elseif kind == Kinds.ZoneCaptured and typeof(p.at)=="Vector3" then
showWave(p.at,tone)
end
end
end
local subscriptions: {() -> ()} = {}
for _, kind in Kinds do table.insert(subscriptions,Router.on(kind,function(p) event(kind,p) end)) end
local elapsed = 0
local heartbeat = RunService.Heartbeat:Connect(function(dt)
elapsed += dt
if elapsed < .12 then return end
elapsed %= .12
local now = workspace:GetServerTimeNow()
local mode = match:GetAttribute("Ruleset")
local playing = player:GetAttribute("InArena") == true and match:GetAttribute("Phase")=="Round"
if not playing or typeof(mode)~="string" or mode=="Siege" then
activeMode, provider, pending, bannerUntil = nil,nil,nil,0
pg:SetAttribute("ModeHint",nil)
banner.Visible = false
return
end
if mode ~= activeMode then
activeMode, selection = mode,Hints.new()
local source = providers:FindFirstChild(mode)
provider = if source and source:IsA("ModuleScript") then require(source) else nil
end
local candidates = if provider then provider.candidates(match,player) else {}
if pending then table.insert(candidates,pending);pending=nil end
local hint = Hints.pick(selection,candidates,now)
pg:SetAttribute("ModeHint",if hint then hint.text else nil)
local results = pg:FindFirstChild("ArenaResults")
banner.Visible = now<bannerUntil and pg:GetAttribute("HunterVoting")~=true and (not results or results:GetAttribute("LiveScoreboardOpen")~=true)
end)
script.Destroying:Once(function()
heartbeat:Disconnect()
for _, remove in subscriptions do remove() end
if effect then effect:Cancel() end
wave:Destroy()
gui:Destroy()
end)
+107
View File
@@ -0,0 +1,107 @@
--!strict
local Players = game:GetService("Players")
local rs = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UI = require(rs:WaitForChild("HunterUI") :: ModuleScript)
local S = require(rs.Hunter.Strings)
local Stage = require(rs.Hunter.Stage)
local player = Players.LocalPlayer
local pg = player:WaitForChild("PlayerGui")
local match = rs:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local providers = script.Parent.HintProviders
local gui = Instance.new("ScreenGui")
gui.Name, gui.DisplayOrder, gui.ResetOnSpawn, gui.Enabled = "ModeGuide", 25, false, false
gui.Parent = pg
local panel = UI.plate(gui,"Direction",UDim2.fromScale(.5,.73),UDim2.new(.85,0,0,60),UI.Outline)
panel.AnchorPoint = Vector2.new(.5,.5)
Instance.new("UISizeConstraint",panel).MaxSize = Vector2.new(326,60)
local contour = UI.contour(panel,UI.Gold)
local arrow = UI.label(panel,"Arrow","▲",UDim2.fromOffset(11,10),UDim2.fromOffset(40,38),26,UI.Gold)
local title = UI.label(panel,"Title","",UDim2.fromOffset(54,6),UDim2.new(1,-65,0,22),18,UI.Ink)
local detail = UI.label(panel,"Distance","",UDim2.fromOffset(54,30),UDim2.new(1,-65,0,22),15,UI.Muted)
title.TextXAlignment, detail.TextXAlignment = Enum.TextXAlignment.Left, Enum.TextXAlignment.Left
local markers = Instance.new("Folder")
markers.Name = "ModeTargets"
markers.Parent = workspace
local highlights: {[Player]: Highlight} = {}
local provider: any = nil
local currentMode: string? = nil
local current: Vector3? = nil
local function color(side: unknown): Color3
return if side=="Blue" then UI.Blue elseif side=="Orange" then UI.Orange else UI.Gold
end
local function refresh()
local id = match:GetAttribute("Ruleset")
local active = player:GetAttribute("InArena")==true and match:GetAttribute("Phase")=="Round" and Stage.combatAllowed(match)
if id~=currentMode then
currentMode = if typeof(id)=="string" then id else nil
local module = if typeof(id)=="string" then providers:FindFirstChild(id) else nil
provider = if module and module:IsA("ModuleScript") then require(module) else nil
end
local ready: {[Player]: boolean} = {}
if active and provider and provider.highlight then
for _, member in Players:GetPlayers() do
local character = member.Character
if member~=player and character and provider.highlight(match,player,member) then
ready[member]=true
local entry=highlights[member]
if not entry then
entry=Instance.new("Highlight")
entry.Name = "ModeTarget"
entry.DepthMode=Enum.HighlightDepthMode.AlwaysOnTop
entry.FillTransparency=.77
entry.OutlineTransparency=.16
entry.Parent=markers
highlights[member]=entry
end
entry.Adornee=character
local tone=color(member:GetAttribute("ArenaTeam"))
entry.FillColor,entry.OutlineColor=tone,tone
end
end
end
for member,entry in highlights do
if not ready[member] then entry:Destroy(); highlights[member]=nil end
end
local root=player.Character and player.Character.PrimaryPart
local menu=pg:FindFirstChild("MainMenu")
local results=pg:FindFirstChild("ArenaResults")
local blocked=pg:GetAttribute("HunterVoting")==true or (menu and menu:IsA("ScreenGui") and menu.Enabled)
or (results and results:GetAttribute("LiveScoreboardOpen")==true)
gui.Enabled=active and not blocked
panel.Visible=false
current=nil
if not gui.Enabled or not root or not provider or not provider.target then return end
local point,label,side=provider.target(match,player)
if not point or not label then return end
local delta=point-root.Position
current=point
panel.Visible=true
title.Text=label
local copy=S.hint.Siege
detail.Text=S.studs(delta.Magnitude)..(if delta.Y>8 then copy.above elseif delta.Y < -8 then copy.below else "")
local tint=color(side)
arrow.TextColor3=tint
contour:SetAttribute("Accent",tint)
end
local elapsed=0
local step=RunService.Heartbeat:Connect(function(dt)
elapsed+=dt
if elapsed < .14 then return end
elapsed%=.14
refresh()
end)
local render=RunService.RenderStepped:Connect(function()
local camera=workspace.CurrentCamera
local root=player.Character and player.Character.PrimaryPart
if not camera or not root or not current then return end
local d=current-root.Position
local v=camera.CFrame:VectorToObjectSpace(Vector3.new(d.X,0,d.Z))
arrow.Rotation=math.deg(math.atan2(v.X,-v.Z))
end)
script.Destroying:Once(function()
step:Disconnect()
render:Disconnect()
markers:Destroy()
gui:Destroy()
end)
@@ -0,0 +1,89 @@
--!strict
local Players=game:GetService("Players")
local rs=game:GetService("ReplicatedStorage")
local RunService=game:GetService("RunService")
local UI=require(rs:WaitForChild("HunterUI") :: ModuleScript)
local S=require(rs.Hunter.Strings).lifeHints
local player=Players.LocalPlayer
local pg=player:WaitForChild("PlayerGui")
local match=rs:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local gui=Instance.new("ScreenGui")
gui.Name,gui.DisplayOrder,gui.ResetOnSpawn,gui.Enabled="OneLifeSpectator",23,false,false
gui.Parent=pg
local panel=UI.plate(gui,"Spectator",UDim2.fromScale(.5,.84),UDim2.new(.85,0,0,56),UI.Blue)
panel.AnchorPoint=Vector2.new(.5,.5)
Instance.new("UISizeConstraint",panel).MaxSize=Vector2.new(360,56)
local name=UI.label(panel,"Target","",UDim2.fromOffset(51,0),UDim2.new(1,-102,1,0),16,UI.Ink)
name.TextTruncate=Enum.TextTruncate.AtEnd
local targets: {Player}={}
local selected: Player?=nil
local control: Humanoid?=nil
local function assign()
local camera=workspace.CurrentCamera
local subject=selected and selected.Character and selected.Character:FindFirstChildOfClass("Humanoid")
if not camera or not subject then return end
control=subject
camera.CameraSubject=subject
name.Text=string.format(S.spectate, selected and selected.DisplayName or "")
end
for index, sign in {-1,1} do
local button=Instance.new("TextButton")
button.Name=if sign<0 then "Previous" else "Next"
button.AnchorPoint=Vector2.new(if sign<0 then 0 else 1,.5)
button.Position=UDim2.new(index-1,if sign<0 then 7 else -7,.5,0)
button.Size=UDim2.fromOffset(38,38)
button.BackgroundColor3=UI.Panel
button.TextColor3=UI.Ink
button.TextSize=22
button.Text=if sign<0 then "◀" else "▶"
button.Parent=panel
UI.bindButton(button, UI.Blue, true)
button.Activated:Connect(function()
if #targets<2 then return end
local current=table.find(targets,selected :: Player) or 1
selected=targets[(current+sign-1)%#targets+1]
assign()
end)
end
local function reset()
local camera=workspace.CurrentCamera
local human=player.Character and player.Character:FindFirstChildOfClass("Humanoid")
if camera and human and control and camera.CameraSubject==control then camera.CameraSubject=human end
control,selected=nil,nil
pg:SetAttribute("HunterSpectating",nil)
gui.Enabled=false
end
local elapsed=0
local step=RunService.Heartbeat:Connect(function(dt)
elapsed+=dt
if elapsed<.15 then return end
elapsed%=.15
local active=player:GetAttribute("InArena")==true and player:GetAttribute("ArenaWaiting")==true
and match:GetAttribute("Ruleset")=="OneLife" and match:GetAttribute("MiniRoundActive")==true
if not active then if control or gui.Enabled then reset() end; return end
local side=player:GetAttribute("ArenaTeam")
table.clear(targets)
for _, other in Players:GetPlayers() do
local human=other.Character and other.Character:FindFirstChildOfClass("Humanoid")
if other~=player and other:GetAttribute("ArenaTeam")==side and other:GetAttribute("InArena")==true
and other:GetAttribute("ArenaWaiting")~=true and human and human.Health>0 then
table.insert(targets,other)
end
end
if #targets==0 then reset(); return end
if not selected or not table.find(targets,selected) then selected=targets[1] end
assign()
local summary=pg:FindFirstChild("ArenaResults")
local blocked=summary and summary:GetAttribute("LiveScoreboardOpen")==true
gui.Enabled=not blocked
pg:SetAttribute("HunterSpectating",if gui.Enabled then true else nil)
end)
script.Destroying:Once(function()
step:Disconnect()
reset()
gui:Destroy()
end)
@@ -0,0 +1,80 @@
--!strict
local rs=game:GetService("ReplicatedStorage")
local Players=game:GetService("Players")
local RunService=game:GetService("RunService")
local TweenService=game:GetService("TweenService")
local UI=require(rs:WaitForChild("HunterUI") :: ModuleScript)
local Kinds=require(rs.Hunter.EventKinds)
local Router=require(script.Parent.EventRouter)
local player=Players.LocalPlayer
local match=rs:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local gui=Instance.new("ScreenGui")
gui.Name,gui.DisplayOrder,gui.ResetOnSpawn="TrophyCounter",23,false
gui.Parent=player:WaitForChild("PlayerGui")
local plate=UI.plate(gui,"Coins",UDim2.new(1,-16,1,-80),UDim2.fromOffset(106,48),UI.Gold)
plate.AnchorPoint=Vector2.new(1,1)
local art=UI.element("GoldCoin",plate,UDim2.fromOffset(6,4),UDim2.fromOffset(40,40)) :: Frame
local rig=UI.bindCoin(art)
local label=UI.label(plate,"Count","×0",UDim2.fromOffset(47,0),UDim2.fromOffset(52,48),24,UI.Gold)
label.FontFace=UI.Display
local scale=Instance.new("UIScale",plate)
local bounce: Tween?=nil
local last=0
local function update()
local count=player:GetAttribute("ArenaTokens")
local n=if typeof(count)=="number" then count else 0
gui.Enabled=player:GetAttribute("InArena")==true and match:GetAttribute("Ruleset")=="TrophyHunt" and match:GetAttribute("Phase")=="Round"
label.Text="×"..n
if gui.Enabled and n>last then
if bounce then bounce:Cancel() end
scale.Scale=1.18
bounce=TweenService:Create(scale,TweenInfo.new(.32,Enum.EasingStyle.Back,Enum.EasingDirection.Out),{Scale=1})
bounce:Play()
end
last=n
end
local connections={player:GetAttributeChangedSignal("ArenaTokens"):Connect(update),player:GetAttributeChangedSignal("InArena"):Connect(update),
match:GetAttributeChangedSignal("Ruleset"):Connect(update),match:GetAttributeChangedSignal("Phase"):Connect(update)}
local draw=RunService.RenderStepped:Connect(function()
if not gui.Enabled then return end
local t=os.clock()
UI.spinCoin(rig,t*2,math.max(0,math.cos(t*2))*.55,t%1)
end)
local pool: {Part}={}
local motions: {[Part]: Tween}={}
for i=1,6 do
local coin=Instance.new("Part")
coin.Name="TrophySpark"
coin.Shape,coin.Material,coin.Color=Enum.PartType.Cylinder,Enum.Material.Neon,UI.Gold
coin.Size=Vector3.new(.12,.62,.62)
coin.Anchored,coin.CanCollide,coin.CanQuery,coin.CanTouch=true,false,false,false
coin.Transparency=1
coin.Parent=workspace
table.insert(pool,coin)
end
local off=Router.on(Kinds.TokenDropped,function(payload)
if not gui.Enabled or typeof(payload.at)~="Vector3" then return end
for i,coin in pool do
if motions[coin] then motions[coin]:Cancel() end
local a=i*math.pi/3
local from=payload.at+Vector3.yAxis*.7
coin.CFrame=CFrame.new(from)*CFrame.Angles(a,0,0)
coin.Transparency=.1
local tween=TweenService:Create(coin,TweenInfo.new(.55,Enum.EasingStyle.Quad,Enum.EasingDirection.Out),
{CFrame=CFrame.new(from+Vector3.new(math.cos(a)*4,2.4,math.sin(a)*4))*CFrame.Angles(a,1.7,1),Transparency=1})
motions[coin]=tween
tween:Play()
end
end)
update()
script.Destroying:Once(function()
draw:Disconnect()
for _, cn in connections do cn:Disconnect() end
off()
for _, coin in pool do
if motions[coin] then motions[coin]:Cancel() end
coin:Destroy()
end
gui:Destroy()
end)
+4 -4
View File
@@ -59,8 +59,8 @@ local function fits(center: Vector3, geometry: RaycastParams, radius: number): b
return workspace:Raycast(center + Vector3.yAxis * .25, Vector3.yAxis * 9, geometry) == nil return workspace:Raycast(center + Vector3.yAxis * .25, Vector3.yAxis * 9, geometry) == nil
end end
function Sites.clearCircle(center: Vector3, geometry: RaycastParams, radius: number): Vector3 function Sites.clearCircle(center: Vector3, geometry: RaycastParams, radius: number): (Vector3, boolean)
if fits(center, geometry, radius) then return center end if fits(center, geometry, radius) then return center, true end
for distance = 3, 48, 3 do for distance = 3, 48, 3 do
for index = 0, 15 do for index = 0, 15 do
local angle = index * math.pi / 8 local angle = index * math.pi / 8
@@ -68,11 +68,11 @@ function Sites.clearCircle(center: Vector3, geometry: RaycastParams, radius: num
local floor = workspace:Raycast(at + Vector3.yAxis * 1.2, -Vector3.yAxis * 2.4, geometry) local floor = workspace:Raycast(at + Vector3.yAxis * 1.2, -Vector3.yAxis * 2.4, geometry)
if floor and floor.Normal.Y >= .95 and math.abs(floor.Position.Y - center.Y) <= .35 if floor and floor.Normal.Y >= .95 and math.abs(floor.Position.Y - center.Y) <= .35
and fits(floor.Position, geometry, radius) then and fits(floor.Position, geometry, radius) then
return floor.Position return floor.Position, true
end end
end end
end end
return center return center, false
end end
function Sites.hotPath(id: string, map: Map, radius: number): {Site} function Sites.hotPath(id: string, map: Map, radius: number): {Site}
+45 -652
View File
@@ -1,25 +1,9 @@
--!strict --!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage") local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Modes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript) local Runtime = script.Parent:WaitForChild("ModeRuntime")
local Sites = require(script.Parent:WaitForChild("ArenaObjectiveSites") :: ModuleScript) local Types = require(Runtime:WaitForChild("Types") :: ModuleScript)
local HotPoint = require(script.Parent:WaitForChild("HotPoint") :: ModuleScript) local Context = require(Runtime:WaitForChild("Context") :: ModuleScript)
local SiegeConfig = require(ReplicatedStorage:WaitForChild("CitadelAssaultConfig") :: ModuleScript)
local Capture = require(script.Parent:WaitForChild("CitadelCaptureService") :: ModuleScript)
local Score = require(script.Parent:WaitForChild("CitadelScoreService") :: ModuleScript)
local SiegeSpawn = require(script.Parent:WaitForChild("CitadelSpawnService") :: ModuleScript)
local CollectionService = game:GetService("CollectionService")
type Side = "Blue" | "Orange"
type Fighter = HotPoint.Fighter
type Marker = HotPoint.Marker & {recolor: ((Color3) -> ())?}
type Zone = {site: Sites.Site, marker: Marker, owner: Side?, claiming: Side?, progress: number}
type Flag = {
marker: Marker, stars: ParticleEmitter, mist: ParticleEmitter, light: PointLight, banner: BasePart,
carrier: Player?, tether: WeldConstraint?, droppedUntil: number,
}
type Drop = {marker: Marker, amount: number, expires: number}
type Config = {arena: string, rule: string, state: Instance, now: number, duration: number,
members: () -> {Player}, bench: (Player) -> (), deploy: (Player) -> (), balanceWaiting: () -> ()}
export type Match = { export type Match = {
step: (number) -> boolean, kill: (Player, Player, Vector3, number) -> (), step: (number) -> boolean, kill: (Player, Player, Vector3, number) -> (),
hit: ((Player, number, boolean) -> ())?, hit: ((Player, number, boolean) -> ())?,
@@ -27,655 +11,64 @@ export type Match = {
winner: () -> string, destroy: () -> (), winner: () -> string, destroy: () -> (),
} }
local registry: {[string]: Types.Mode} = {}
for _, module in Runtime:WaitForChild("Modes"):GetChildren() do
if module:IsA("ModuleScript") then
local mode = require(module) :: Types.Mode
assert(not registry[mode.id], "Duplicate mode: " .. mode.id)
registry[mode.id] = mode
end
end
local cue = Instance.new("RemoteEvent")
cue.Name = "ArenaObjectiveCue"
cue.Parent = ReplicatedStorage
local active: {[string]: Match} = {} local active: {[string]: Match} = {}
local Objectives = {} local Objectives = {}
local objectiveCue = Instance.new("RemoteEvent")
objectiveCue.Name = "ArenaObjectiveCue"
objectiveCue.Parent = ReplicatedStorage
local sides: {Side} = {"Blue", "Orange"}
local blue = Color3.fromRGB(67, 216, 255)
local orange = Color3.fromRGB(255, 150, 68)
local gold = Color3.fromRGB(255, 220, 96)
local neutral = Color3.fromRGB(188, 150, 255)
local rng = Random.new()
local function opposite(side: Side): Side
return if side == "Blue" then "Orange" else "Blue"
end
local function color(side: Side?): Color3
return if side == "Blue" then blue elseif side == "Orange" then orange else neutral
end
local function sideOf(player: Player): Side?
local side = player:GetAttribute("ArenaTeam")
return if side == "Blue" then "Blue" elseif side == "Orange" then "Orange" else nil
end
local function boundsAt(position: Vector3, target: Vector3, radius: number, height: number): boolean
local delta = position - target
return math.abs(delta.Y) < height and delta.X * delta.X + delta.Z * delta.Z <= radius * radius
end
local function label(adornee: BasePart, name: string, tint: Color3, offset: number, waypoint: boolean?): TextLabel
local gui = Instance.new("BillboardGui")
gui.Name = "ObjectiveLabel"
gui.Size = UDim2.fromOffset(220, 26)
gui.StudsOffsetWorldSpace = Vector3.yAxis * offset
gui.MaxDistance = if waypoint then 710 else 170
gui.AlwaysOnTop = waypoint == true
gui.LightInfluence = 0
gui.Parent = adornee
local text = Instance.new("TextLabel")
text.Size = UDim2.fromScale(1, 1)
text.BackgroundTransparency = 1
text.Font = Enum.Font.GothamBlack
text.TextSize = 15
text.Text, text.TextColor3 = name, tint
text.TextStrokeColor3, text.TextStrokeTransparency = Color3.fromRGB(9, 13, 25), .14
text.Parent = gui
return text
end
local function marker(parent: Instance, id: string, name: string, at: Vector3, tint: Color3, diameter: number, tall: boolean?): Marker
local part = Instance.new("Part")
part.Name = id
if not tall then part:SetAttribute("ObjectiveArrow", true) end
part.Shape = if tall then Enum.PartType.Ball else Enum.PartType.Cylinder
part.Size = if tall then Vector3.new(diameter, diameter, diameter) else Vector3.new(.16, diameter, diameter)
part.CFrame = CFrame.new(at + Vector3.yAxis * (if tall then 2.4 else .12)) * CFrame.Angles(0, 0, math.pi / 2)
part.Anchored, part.CanCollide, part.CanQuery, part.CanTouch, part.CastShadow = true, false, false, false, false
part.Material, part.Color = Enum.Material.Neon, tint
part.Transparency = if tall then .04 else .76
local aura = Instance.new("PointLight")
aura.Range, aura.Brightness, aura.Color = if tall then 13 else 9, .7, tint
aura.Parent = part
part.Parent = parent
return {body = part, label = label(part, name, tint, if tall then 2.1 else 4, id ~= "Tokens"), origin = at}
end
local function ring(parent: Instance, id: string, name: string, at: Vector3, tint: Color3): Marker
local mark = marker(parent, id, name, at, tint, HotPoint.Radius * 2)
local recolor = HotPoint.attachRing(mark)
mark.recolor = recolor
recolor(tint)
return mark
end
local function paint(mark: Marker, tint: Color3)
if mark.body.Color == tint then return end
if mark.recolor then
mark.recolor(tint)
return
end
mark.body.Color = tint
mark.label.TextColor3 = tint
local aura = mark.body:FindFirstChildOfClass("PointLight")
if aura then aura.Color = tint end
end
local function makeFlag(parent: Instance, roof: Vector3): Flag
local mark = marker(parent, "CitadelFlag", "ФЛАГ · КРЫША", roof, gold, 2.6, true)
local body = mark.body
body.Transparency = 1
body.CFrame = CFrame.new(body.Position)
local light = assert(body:FindFirstChildOfClass("PointLight"))
light.Range, light.Brightness = 21, 1.6
local function attach(name: string, size: Vector3, offset: Vector3, tint: Color3): Part
local part = Instance.new("Part")
part.Name, part.Size, part.Color = name, size, tint
part.CFrame = body.CFrame + offset
part.Material = Enum.Material.Neon
part.Massless, part.CanCollide, part.CanTouch, part.CanQuery = true, false, false, false
part.Parent = body
local weld = Instance.new("WeldConstraint")
weld.Part0, weld.Part1, weld.Parent = body, part, part
return part
end
attach("Pole", Vector3.new(.17, 4.5, .17), Vector3.zero, Color3.fromRGB(235, 235, 255))
local banner = attach("Banner", Vector3.new(2.65, 1.48, .15), Vector3.new(1.35, 1.45, 0), gold)
attach("CrownLight", Vector3.new(.33, .33, .33), Vector3.yAxis * 2.34, neutral).Shape = Enum.PartType.Ball
local aura = Instance.new("Attachment")
aura.Name = "FlagAura"
aura.Position = -Vector3.yAxis * 1.75
aura.Parent = body
local stars = Instance.new("ParticleEmitter")
stars.Name = "Stars"
stars.Texture = "rbxasset://textures/particles/sparkles_main.dds"
stars.Color = ColorSequence.new(neutral, gold)
stars.LightEmission, stars.LightInfluence = 1, 0
stars.Rate, stars.Speed, stars.Lifetime = 24, NumberRange.new(3, 6), NumberRange.new(.7, 1.4)
stars.SpreadAngle = Vector2.new(65, 65)
stars.Rotation, stars.RotSpeed = NumberRange.new(-180, 180), NumberRange.new(-90, 90)
stars.Size = NumberSequence.new({NumberSequenceKeypoint.new(0, .22), NumberSequenceKeypoint.new(.4, .52), NumberSequenceKeypoint.new(1, 0)})
stars.Parent = aura
local mist = Instance.new("ParticleEmitter")
mist.Name = "ColoredMist"
mist.Texture = "rbxasset://textures/particles/smoke_main.dds"
mist.Color = ColorSequence.new(neutral, gold)
mist.LightEmission, mist.LightInfluence = .55, 0
mist.Rate, mist.Speed, mist.Lifetime = 9, NumberRange.new(1, 4), NumberRange.new(.7, 1.2)
mist.SpreadAngle = Vector2.new(110, 110)
mist.Size = NumberSequence.new(1.4, 4)
mist.Transparency = NumberSequence.new({NumberSequenceKeypoint.new(0, .72), NumberSequenceKeypoint.new(.45, .79), NumberSequenceKeypoint.new(1, 1)})
mist.Parent = aura
return {marker = mark, stars = stars, mist = mist, light = light, banner = banner,
carrier = nil, tether = nil, droppedUntil = 0}
end
local function visibleAt(fighter: Fighter, at: Vector3, geometry: RaycastParams): boolean
return workspace:Raycast(fighter.root.Position, at - fighter.root.Position, geometry) == nil
end
local function presence(fighters: {Fighter}, zone: Zone, geometry: RaycastParams): (boolean, boolean)
local b, o = false, false
-- Separate vertically stacked objectives by avatar foot height.
for _, fighter in fighters do
if boundsAt(fighter.root.Position, zone.site.position, HotPoint.Radius, 8)
and visibleAt(fighter, zone.site.position + Vector3.yAxis * 2.7, geometry) then
if fighter.side == "Blue" then b = true else o = true end
end
end
return b, o
end
function Objectives.current(arena: string): Match? function Objectives.current(arena: string): Match?
return active[arena] return active[arena]
end end
function Objectives.start(config: Config): Match function Objectives.start(config: Types.Config): Match
local rule, state, arena = config.rule, config.state, config.arena local mode = assert(registry[config.rule], "Unknown mode: " .. config.rule)
local world = Modes.geometry(arena) local ctx = Context.create(config, mode, cue)
local geometry = Modes.collision(arena) local success, result = pcall(mode.start, ctx)
local map = if rule == "TeamDeathmatch" or rule == "HuntLeader" then nil else Sites.resolve(arena) if not success then
local hotPath = if rule == "HotPoint" and map then Sites.hotPath(arena, map, HotPoint.Radius) else nil ctx.janitor.clean()
local folder = Instance.new("Folder") ctx.folder:Destroy()
folder.Name = "MatchObjectives" error(result)
folder.Parent = world
local blueScore, orangeScore = 0, 0
local function add(side: Side, points: number)
if side == "Blue" then blueScore += points else orangeScore += points end
state:SetAttribute(side .. "Score", if side == "Blue" then blueScore else orangeScore)
end end
local function status(text: string) local instance = result :: Types.ModeInstance
if state:GetAttribute("ObjectiveStatus") ~= text then state:SetAttribute("ObjectiveStatus", text) end local lastStep = ctx.liveAt
end local destroyed = false
state:SetAttribute("BlueScore", 0)
state:SetAttribute("OrangeScore", 0)
state:SetAttribute("ObjectiveStatus", "")
local function collect(members: {Player}): {Fighter}
local found: {Fighter} = {}
for _, p in members do
local side = sideOf(p)
local c = p.Character
local h = c and c:FindFirstChildOfClass("Humanoid")
local r = c and c:FindFirstChild("HumanoidRootPart")
if side and h and h.Health > 0 and r and r:IsA("BasePart") and p:GetAttribute("InArena") == true
and p:GetAttribute("ArenaWaiting") ~= true then
table.insert(found, {player = p, side = side, root = r})
end
end
return found
end
local function cue(fighters: {Fighter}, captured: boolean, side: Side?)
for _, fighter in fighters do
if captured or fighter.side == side then objectiveCue:FireClient(fighter.player, captured) end
end
end
local function makeZone(site: Sites.Site, name: string): Zone
site = {name = site.name, position = Sites.clearCircle(site.position, geometry, HotPoint.Radius)}
return {site = site, marker = ring(folder, name, site.name, site.position, neutral), owner = nil, claiming = nil, progress = 0}
end
local zones: {Zone} = {}
local hotPoint = if hotPath then HotPoint.start({
state = state, geometry = geometry, sites = hotPath, startedAt = config.now,
marker = function(site: Sites.Site): Marker
return marker(folder, "HotPoint", "ГОРЯЧАЯ ТОЧКА", site.position, neutral, HotPoint.Radius * 2)
end,
score = add, status = status,
}) else nil
local flag = if rule == "CaptureFlag" and map then makeFlag(folder, map.roof.position) else nil
local tokens: {Drop} = {}
local carried: {[Player]: number} = {}
local leaders: {[Side]: Player} = {}
local previousLeader: {[Side]: Player} = {}
local leaderLabels: {[Player]: BillboardGui} = {}
local siegeTimes: Score.Ledger = {Blue = {}, Orange = {}}
local siegeSide: Side = if SiegeConfig.FIRST_ATTACKER == "Orange" then "Orange" else "Blue"
local siegeIndex, siegeProgress = 1, 0
local siegeCaptureStarted = false
local hadSiegeSwap = false
local siegeState: Folder? = nil
local lifeActive, miniNumber = false, 0
local lifeEnds, nextMini = math.huge, config.now + 2
local lastStep, nextScore = config.now, config.now + 1
local match: Match local match: Match
if map then
if rule == "Domination" then
for i, site in {map.west, map.gallery, map.east} do
local key = string.char(64 + i)
local zone = makeZone(site, key)
zone.marker.label.Text = key .. " · " .. site.name
table.insert(zones, zone)
end
elseif rule == "CaptureFlag" or rule == "TrophyHunt" then
map.blue = Sites.clearCircle(map.blue, geometry, HotPoint.Radius)
map.orange = Sites.clearCircle(map.orange, geometry, HotPoint.Radius)
for _, side in sides do
local at = if side == "Blue" then map.blue else map.orange
local name = if side == "Blue" then "БАЗА СИНИХ" else "БАЗА ОРАНЖЕВЫХ"
ring(folder, side .. "Base", name, at, color(side))
end
elseif rule == "Siege" then
local data = Instance.new("Folder")
data.Name = "CitadelMatchState"
data.Parent = state
siegeState = data
local sites: {Sites.Site} = {map.ground, map.gallery, map.roof}
for _, point in CollectionService:GetTagged("CitadelPoint") do
if not point:IsA("BasePart") or not point:IsDescendantOf(world) then continue end
local index = point:GetAttribute("Index")
if typeof(index) == "number" and index % 1 == 0 and sites[index] then
sites[index] = {name = sites[index].name, position = point.Position}
end
end
for i, site in sites do
local zone = makeZone(site, "Checkpoint" .. i)
zone.marker.body:SetAttribute("Index", i)
zone.marker.body.Parent = nil
table.insert(zones, zone)
end
zones[1].marker.body.Parent = folder
end
end
local function putFlag(object: Flag, at: Vector3, droppedUntil: number)
if object.carrier then object.carrier:SetAttribute("ArenaFlag", nil) end
if object.tether then object.tether:Destroy() end
object.carrier, object.tether, object.droppedUntil = nil, nil, droppedUntil
local mark = object.marker
mark.body.Anchored = true
mark.body.CFrame = CFrame.new(at + Vector3.yAxis * 2.4)
mark.label.Text = if droppedUntil > 0 then "ФЛАГ УПАЛ" else "ФЛАГ · КРЫША"
mark.label.TextColor3, object.banner.Color = gold, gold
object.stars.Enabled, object.mist.Enabled, object.light.Enabled = true, true, true
object.stars:Emit(16)
end
local function pickUpFlag(object: Flag, fighter: Fighter)
local body = object.marker.body
body.CFrame = fighter.root.CFrame * CFrame.new(0, 3.15, .65)
body.Massless = true
local tether = Instance.new("WeldConstraint")
tether.Part0, tether.Part1 = body, fighter.root
tether.Parent = body
body.Anchored = false
object.carrier, object.tether, object.droppedUntil = fighter.player, tether, 0
fighter.player:SetAttribute("ArenaFlag", true)
local tint = color(fighter.side)
object.marker.label.Text = fighter.player.DisplayName .. " · НЕСЁТ ФЛАГ"
object.marker.label.TextColor3, object.banner.Color = tint, tint
object.stars.Enabled, object.mist.Enabled, object.light.Enabled = false, false, false
object.stars:Clear()
object.mist:Clear()
end
local function floorAt(at: Vector3): Vector3
local hit = workspace:Raycast(at + Vector3.yAxis * .3, -Vector3.yAxis * 50, geometry)
return if hit then hit.Position else (if map then map.ground.position else at)
end
local function tokenDrop(at: Vector3, amount: number, now: number)
local floor = floorAt(at)
for _, existing in tokens do
if boundsAt(existing.marker.origin, floor, 3.5, 3) then
existing.amount += amount
existing.expires = now + 42
existing.marker.label.Text = "ЖЕТОНЫ ×" .. existing.amount
return
end
end
if #tokens >= 60 then
local old = table.remove(tokens, 1)
old.marker.body:Destroy()
end
table.insert(tokens, {marker = marker(folder, "Tokens", "ЖЕТОНЫ ×" .. amount, floor, gold, 1.55, true), amount = amount, expires = now + 42})
end
local function dropCarried(player: Player, at: Vector3?, now: number)
if flag and flag.carrier == player then
if at then
local floor = workspace:Raycast(at + Vector3.yAxis * .3, -Vector3.yAxis * 50, geometry)
local landing = if floor then floor.Position else at
putFlag(flag, landing, now + 20)
for _, fighter in collect(config.members()) do objectiveCue:FireClient(fighter.player, "FlagDropped") end
else
putFlag(flag, flag.marker.origin, 0)
end
end
local amount = carried[player]
if amount then
carried[player] = nil
player:SetAttribute("ArenaTokens", nil)
if at then tokenDrop(at, amount, now) end
end
end
local function clearLeader(side: Side)
local p = leaders[side]
if not p then return end
previousLeader[side] = p
leaders[side] = nil
p:SetAttribute("ArenaLeader", nil)
local badge = leaderLabels[p]
if badge then badge:Destroy() end
leaderLabels[p] = nil
end
local function updateLeaders(fighters: {Fighter})
for _, side in sides do
local roster: {Fighter} = {}
local present = false
for _, f in fighters do
if f.side ~= side then continue end
table.insert(roster, f)
if f.player == leaders[side] then present = true end
end
if present then continue end
clearLeader(side)
if #roster == 0 then continue end
local pick = rng:NextInteger(1, #roster)
if #roster > 1 and roster[pick].player == previousLeader[side] then pick = pick % #roster + 1 end
local p = roster[pick].player
local head = p.Character and p.Character:FindFirstChild("Head")
if not head or not head:IsA("BasePart") then continue end
leaders[side] = p
p:SetAttribute("ArenaLeader", true)
leaderLabels[p] = label(head, "ЛИДЕР", gold, 2.7).Parent :: BillboardGui
end
local a, b = leaders.Blue, leaders.Orange
status("Лидеры · " .. (if a then a.DisplayName else "—") .. " / " .. (if b then b.DisplayName else "—"))
end
local function runFlag(fighters: {Fighter}, now: number)
if not flag or not map then return end
if flag.carrier then
for _, fighter in fighters do
if fighter.player ~= flag.carrier then continue end
local base = if fighter.side == "Blue" then map.blue else map.orange
if boundsAt(fighter.root.Position, base, HotPoint.Radius, 7) then
add(fighter.side, 1)
cue(fighters, true, nil)
putFlag(flag, flag.marker.origin, 0)
status("Флаг вернулся на крышу цитадели")
end
return
end
local carrier = flag.carrier
local root = carrier.Character and carrier.Character.PrimaryPart
dropCarried(carrier, root and root.Position, now)
return
elseif flag.droppedUntil > 0 and now >= flag.droppedUntil then
putFlag(flag, flag.marker.origin, 0)
end
local at = flag.marker.body.Position
for _, fighter in fighters do
if boundsAt(fighter.root.Position, at, 5.5, 6.5) and visibleAt(fighter, at, geometry) then
pickUpFlag(flag, fighter)
cue(fighters, false, fighter.side)
status(fighter.player.DisplayName .. " несёт флаг")
return
end
end
status(if flag.droppedUntil > 0 then "Флаг на земле · Подберите его" else "Флаг на крыше цитадели")
end
local function runTrophies(fighters: {Fighter}, now: number)
if not map then return end
for i = #tokens, 1, -1 do
local token = tokens[i]
local collector: Fighter? = nil
if now < token.expires then
for _, f in fighters do
if boundsAt(f.root.Position, token.marker.origin, 5, 6) and visibleAt(f, token.marker.body.Position, geometry) then collector = f; break end
end
if not collector then continue end
local p = collector.player
if not carried[p] then cue(fighters, false, collector.side) end
carried[p] = (carried[p] or 0) + token.amount
p:SetAttribute("ArenaTokens", carried[p])
end
token.marker.body:Destroy()
table.remove(tokens, i)
end
for _, f in fighters do
local amount = carried[f.player]
if amount and boundsAt(f.root.Position, if f.side == "Blue" then map.blue else map.orange, HotPoint.Radius, 7) then
add(f.side, amount)
cue(fighters, true, nil)
carried[f.player] = nil
f.player:SetAttribute("ArenaTokens", nil)
end
end
status("Сдавайте собранные жетоны на своей базе")
end
local function runSiege(members: {Player}, fighters: {Fighter}, now: number, dt: number): boolean
local data = assert(siegeState)
local half = SiegeConfig.ATTACK_DURATION
local elapsed = now - config.now
if elapsed >= half and not hadSiegeSwap then
hadSiegeSwap = true
for _, z in zones do z.marker.body.Parent = nil end
siegeSide, siegeIndex, siegeProgress = opposite(siegeSide), 1, 0
siegeCaptureStarted = false
local arenaSites = assert(map)
local ordinals = {Blue = 0, Orange = 0}
for _, p in members do
config.deploy(p)
local side, character = sideOf(p), p.Character
if not side or not character or not character.PrimaryPart then continue end
local attack = side == siegeSide
ordinals[side] += 1
local at = SiegeSpawn.position(world, attack, if attack then arenaSites.blue else arenaSites.orange, ordinals[side])
character:PivotTo(CFrame.new(at + Vector3.yAxis * 4))
end
end
local swap = elapsed >= half and elapsed < half + SiegeConfig.SWAP_FREEZE
local attackStart = if hadSiegeSwap then half + SiegeConfig.SWAP_FREEZE else 0
data:SetAttribute("Phase", if swap then "RoleSwap" elseif hadSiegeSwap then "Attack2" else "Attack1")
data:SetAttribute("Attacker", siegeSide)
data:SetAttribute("Seconds", math.clamp(math.ceil(half - (elapsed - attackStart)), 0, half))
if swap then
data:SetAttribute("Progress", 0)
data:SetAttribute("Status", "Idle")
status("СМЕНА РОЛЕЙ")
return false
end
local attacker = if siegeSide == "Blue" then "Синие" else "Оранжевые"
local zone = zones[siegeIndex]
data:SetAttribute("Index", siegeIndex)
if not zone then
data:SetAttribute("Point", nil)
data:SetAttribute("NextPoint", nil)
status("Все рубежи взяты!")
return true
end
zone.marker.body.Parent = folder
local attack, defense = false, false
for _, fighter in fighters do
local delta = fighter.root.Position - zone.site.position
local reason = "Outside"
if delta.X * delta.X + delta.Z * delta.Z <= HotPoint.Radius ^ 2 then
if math.abs(delta.Y) > SiegeConfig.HEIGHT_TOLERANCE then reason = "Height"
elseif not visibleAt(fighter, zone.site.position + Vector3.yAxis * SiegeConfig.SIGHT_HEIGHT, geometry) then reason = "Blocked"
else
reason = "Inside"
if fighter.side == siegeSide then attack = true else defense = true end
end
end
fighter.player:SetAttribute("CitadelZone", reason)
end
local progress, phase = Capture.advance(siegeProgress, math.min(dt, math.max(0, elapsed - attackStart)), attack, defense,
SiegeConfig.CAPTURE_TIME, SiegeConfig.DECAY_MULTIPLIER)
if phase == "Capturing" and not siegeCaptureStarted then
cue(fighters, false, siegeSide)
siegeCaptureStarted = true
elseif progress == 0 and phase ~= "Capturing" then
siegeCaptureStarted = false
end
siegeProgress = progress
data:SetAttribute("Progress", progress)
data:SetAttribute("Status", phase)
data:SetAttribute("Point", zone.site.position)
data:SetAttribute("PointName", zone.site.name)
local nextZone = zones[siegeIndex + 1]
data:SetAttribute("NextPoint", if nextZone then nextZone.site.position else nil)
local percent = math.floor(progress / SiegeConfig.HUD_PROGRESS_STEP + 1e-8) * SiegeConfig.HUD_PROGRESS_STEP * 100
local reason = if phase == "Contested" then "Зона оспаривается!" elseif phase == "Decaying" then "Захват откатывается"
elseif phase == "Capturing" then "Захват идёт" else "Двигайтесь к синему кругу"
status(string.format("%s · Рубеж %d/%d · %d%% · %s", attacker, siegeIndex, #zones, percent, reason))
paint(zone.marker, if phase == "Contested" then orange else blue)
if phase ~= "Captured" or not Score.record(siegeTimes, siegeSide, siegeIndex, elapsed - attackStart) then return false end
add(siegeSide, SiegeConfig.POINTS_PER_OBJECTIVE)
cue(fighters, true, nil)
siegeCaptureStarted = false
data:SetAttribute(siegeSide .. "Time" .. siegeIndex, elapsed - attackStart)
zone.marker.body.Parent = nil
siegeIndex += 1
siegeProgress = 0
return siegeIndex > #zones
end
local function runOneLife(members: {Player}, fighters: {Fighter}, now: number): boolean
if lifeActive then
local b, o = 0, 0
for _, f in fighters do if f.side == "Blue" then b += 1 else o += 1 end end
if (b > 0 and o > 0) and now < lifeEnds then
status(string.format("Мини-раунд %d · Живы %d / %d · %d с", miniNumber, b, o, math.ceil(lifeEnds - now)))
return false
end
if b ~= o then add(if b > o then "Blue" else "Orange", 1) end
if blueScore >= 3 or orangeScore >= 3 then return true end
for _, p in members do config.bench(p) end
lifeActive, nextMini = false, now + 4
end
if now >= nextMini then config.balanceWaiting() end
local ready: {Player} = {}
local b, o = false, false
for _, p in members do
local c = p.Character
local h = c and c:FindFirstChildOfClass("Humanoid")
if not c or not c.PrimaryPart or not h or h.Health <= 0 then continue end
table.insert(ready, p)
if sideOf(p) == "Blue" then b = true else o = true end
end
if b and o and now >= nextMini then
for _, p in ready do config.deploy(p) end
miniNumber += 1
lifeActive, lifeEnds = true, now + 45
status("Мини-раунд " .. miniNumber)
elseif not b or not o then
status("Ждём игроков в обеих командах")
else
status("Следующий мини-раунд через " .. math.ceil(nextMini - now) .. " с")
end
return false
end
local function step(now: number): boolean
if rule == "TeamDeathmatch" then return false end
local elapsed = math.max(0, now - lastStep)
local dt = math.min(elapsed, .5)
lastStep = now
local members = config.members()
local fighters = collect(members)
if rule == "OneLife" then return runOneLife(members, fighters, now) end
if rule == "HuntLeader" then updateLeaders(fighters); return false end
if rule == "CaptureFlag" then runFlag(fighters, now); return false end
if rule == "TrophyHunt" then runTrophies(fighters, now); return false end
if rule == "Siege" then return runSiege(members, fighters, now, dt) end
if hotPoint then hotPoint.step(fighters, now, elapsed); return false end
local scoreNow = now >= nextScore
if scoreNow then nextScore = now + 1 end
local ownedBlue, ownedOrange = 0, 0
for _, zone in zones do
local b, o = presence(fighters, zone, geometry)
local side: Side? = if b == o then nil elseif b then "Blue" else "Orange"
if side and side ~= zone.owner then
if zone.claiming ~= side then
zone.claiming, zone.progress = side, 0
cue(fighters, false, side)
end
zone.progress += dt
if zone.progress >= 3 then
zone.owner, zone.progress = side, 0
cue(fighters, true, nil)
end
else
zone.claiming, zone.progress = nil, 0
end
paint(zone.marker, color(zone.owner))
if zone.owner == "Blue" then ownedBlue += 1 elseif zone.owner == "Orange" then ownedOrange += 1 end
end
if scoreNow then
if ownedBlue > 0 then add("Blue", ownedBlue) end
if ownedOrange > 0 then add("Orange", ownedOrange) end
end
status(string.format("Точки под контролем · %d / %d", ownedBlue, ownedOrange))
return false
end
match = { match = {
step = step, step = function(now)
hit = if hotPoint then hotPoint.hit else nil, if destroyed then return false end
kill = function(player, victim, at, now) local elapsed = math.max(0, now - lastStep)
local side = sideOf(player) lastStep = now
if not side then return end return instance.step(now, math.min(elapsed, .5), Context.collect(ctx.members()), elapsed)
if rule == "TeamDeathmatch" then
add(side, 1)
elseif rule == "HuntLeader" then
local target = opposite(side)
local bonus = leaders[target] == victim
add(side, if bonus then 3 else 1)
if bonus then clearLeader(target) end
elseif rule == "TrophyHunt" then
tokenDrop(at, 1, now)
end
end,
death = function(player, at, now)
if hotPoint then hotPoint.death(player) end
dropCarried(player, at, now)
if rule == "OneLife" then config.bench(player) end
end,
leaving = function(player, at, now)
if hotPoint then hotPoint.death(player) end
dropCarried(player, at, now)
local side = sideOf(player)
if side and leaders[side] == player then clearLeader(side) end
end, end,
kill = instance.kill, hit = instance.hit, death = instance.death, leaving = instance.leaving,
winner = function() winner = function()
if rule == "Siege" then local side, reason = instance.winner()
local winner, reason = Score.winner(siegeTimes, SiegeConfig.TIE_EPSILON) ctx.state:SetAttribute("ResultReason", reason)
state:SetAttribute("CitadelResultReason", reason) return side
return winner
end
if blueScore ~= orangeScore then return if blueScore > orangeScore then "Blue" else "Orange" end
return "Draw"
end, end,
destroy = function() destroy = function()
if siegeState then if destroyed then return end
siegeState:Destroy() destroyed = true
for _, p in config.members() do p:SetAttribute("CitadelZone", nil) end if active[config.arena] == match then active[config.arena] = nil end
end local ok, issue = pcall(instance.destroy)
if active[arena] == match then active[arena] = nil end ctx.janitor.clean()
if hotPoint then hotPoint.destroy() end ctx.folder:Destroy()
for _, side in sides do clearLeader(side) end ctx.status("")
for p in carried do p:SetAttribute("ArenaTokens", nil) end ctx.state:SetAttribute("RoundStage", nil)
if flag and flag.carrier then flag.carrier:SetAttribute("ArenaFlag", nil) end if not ok then warn(issue) end
for _, z in zones do z.marker.body:Destroy() end
folder:Destroy()
status("")
end, end,
} }
active[arena] = match active[config.arena] = match
return match return match
end end
+226 -34
View File
@@ -20,6 +20,11 @@ local objectiveCue = ReplicatedStorage:WaitForChild("ArenaObjectiveCue") :: Remo
local objectiveCueConnection = objectiveCue.OnClientEvent:Connect(function(captured: boolean | string) local objectiveCueConnection = objectiveCue.OnClientEvent:Connect(function(captured: boolean | string)
Sounds.sound(if captured == "FlagDropped" then "FlagDropped" elseif captured == true then "HotPointCaptured" else "HotPointStart") Sounds.sound(if captured == "FlagDropped" then "FlagDropped" elseif captured == true then "HotPointCaptured" else "HotPointStart")
end) end)
local Hunter = ReplicatedStorage:WaitForChild("Hunter")
local HunterStrings = require(Hunter:WaitForChild("Strings") :: ModuleScript)
local RoundStrings = HunterStrings.round
local SiegeResults = require(Hunter:WaitForChild("SiegeResults") :: ModuleScript)
local SiegeConfig = require(ReplicatedStorage:WaitForChild("CitadelAssaultConfig") :: ModuleScript)
local limit = state:GetAttribute("TeamLimit") :: number local limit = state:GetAttribute("TeamLimit") :: number
local modeIds = {Modes.Procedural} local modeIds = {Modes.Procedural}
local function currentMode(): string local function currentMode(): string
@@ -156,7 +161,44 @@ siegeBar.BackgroundColor3 = Color3.fromRGB(34, 45, 65)
siegeBar.BorderSizePixel = 0 siegeBar.BorderSizePixel = 0
siegeBar.Visible = false siegeBar.Visible = false
siegeBar.Parent = objective siegeBar.Parent = objective
local lifeBoard = UI.label(objective,"OneLifeBoard","",UDim2.fromOffset(15,90),UDim2.new(1,-30,0,25),17,UI.Gold)
lifeBoard.Visible=false
local dominationChips = Instance.new("Frame")
dominationChips.Name = "DominationChips"
dominationChips.Position = UDim2.fromOffset(15, 88)
dominationChips.Size = UDim2.new(1, -30, 0, 40)
dominationChips.BackgroundTransparency = 1
dominationChips.Visible = false
dominationChips.Parent = objective
local domSlots: {[string]: {chip: GuiObject, text: TextLabel, ticks: {Frame}}} = {}
for i, key in {"A", "B", "C"} do
local chip = UI.element("ScoreChip", dominationChips, UDim2.new((i - 1) / 3, 0, 0, 0), UDim2.new(1 / 3, -6, 0, 25))
local templateValue = chip:FindFirstChild("Value")
if templateValue and templateValue:IsA("TextLabel") then templateValue.Visible = false end
local text = UI.label(chip, "Zone", key, UDim2.new(), UDim2.fromScale(1, 1), 17, ink)
local ticks: {Frame} = {}
for segment = 1, 10 do
local angle = (segment - 1) * math.pi / 5 - math.pi / 2
local dot = Instance.new("Frame")
dot.Name = "CaptureProgress"
dot.AnchorPoint = Vector2.new(.5, .5)
dot.Position = UDim2.new(.5, math.cos(angle) * 12, .5, math.sin(angle) * 10)
dot.Size = UDim2.fromOffset(3, 3)
dot.BorderSizePixel = 0
dot.Visible = false
dot.Parent = chip
Instance.new("UICorner", dot).CornerRadius = UDim.new(1, 0)
table.insert(ticks, dot)
end
domSlots[key] = {chip = chip, text = text, ticks = ticks}
end
local rateLabel = UI.label(dominationChips, "ScoreRate", "", UDim2.fromOffset(0, 26), UDim2.new(1, 0, 0, 17), 13, muted)
local siegeSteps = UI.label(objective, "SiegeSteps", "", UDim2.fromOffset(16, 96), UDim2.new(1, -32, 0, 22), 15, UI.Gold)
siegeSteps.Visible = false
local siegeChip = UI.label(objective, "SiegeChip", "", UDim2.fromOffset(16, 119), UDim2.new(1, -32, 0, 21), 14, UI.Mint)
siegeChip.Visible = false
local siegeSegments: {Frame} = {} local siegeSegments: {Frame} = {}
local siegeSegmentCount = 0
for i = 1, 10 do for i = 1, 10 do
local segment = Instance.new("Frame") local segment = Instance.new("Frame")
segment.Position = UDim2.fromScale((i - 1) / 10, 0) segment.Position = UDim2.fromScale((i - 1) / 10, 0)
@@ -213,7 +255,7 @@ countdown.Visible = false
local allyCapture = Color3.fromRGB(90, 247, 170) local allyCapture = Color3.fromRGB(90, 247, 170)
local enemyCapture = Color3.fromRGB(255, 79, 105) local enemyCapture = Color3.fromRGB(255, 79, 105)
local captureHud = UI.plate(hudLayout, "HotPointCapture", UDim2.new(.5, 0, 0, 10), UDim2.fromOffset(384, 52), UI.Outline) local captureHud = UI.plate(hudLayout, "HotPointCapture", UDim2.new(.5, 0, 0, 10), UDim2.fromOffset(384, 52), UI.Outline)
captureHud.AnchorPoint, captureHud.Visible = Vector2.new(.5, 0), false captureHud.AnchorPoint, captureHud.Visible = Vector2.new(.5, 1), false
local captureArc = UI.contour(captureHud, allyCapture) local captureArc = UI.contour(captureHud, allyCapture)
local captureLabel = UI.label(captureHud, "Status", "", UDim2.fromOffset(14, 5), UDim2.new(1, -77, 0, 24), 15, ink) local captureLabel = UI.label(captureHud, "Status", "", UDim2.fromOffset(14, 5), UDim2.new(1, -77, 0, 24), 15, ink)
captureLabel.FontFace = UI.Display captureLabel.FontFace = UI.Display
@@ -225,7 +267,17 @@ local captureTrack = UI.element("ProgressBar", captureHud, UDim2.fromOffset(14,
captureTrack.Name = "CaptureProgress" captureTrack.Name = "CaptureProgress"
local captureFill = captureTrack:WaitForChild("Fill") :: Frame local captureFill = captureTrack:WaitForChild("Fill") :: Frame
captureFill.Size = UDim2.fromScale(0, 1) captureFill.Size = UDim2.fromScale(0, 1)
UI.sheen(captureFill) captureFill.Visible = false
local hotSegments: {Frame} = {}
for i = 1, 10 do
local segment = Instance.new("Frame")
segment.Name = "CaptureSegment"
segment.Position = UDim2.fromScale((i-1)/10, 0)
segment.Size = UDim2.new(.1, -2, 1, 0)
segment.BorderSizePixel = 0
segment.Parent = captureTrack
table.insert(hotSegments, segment)
end
local captureTween: Tween? = nil local captureTween: Tween? = nil
local captureTeam: string? = nil local captureTeam: string? = nil
local capturePercent = 0 local capturePercent = 0
@@ -348,9 +400,7 @@ local function fitHud()
badge.killSize.MaxTextSize = if packed then 17 else 23 badge.killSize.MaxTextSize = if packed then 17 else 23
end end
local bottom = top + (if rowCount > 0 then height * scoreScale.Scale else 0) local bottom = top + (if rowCount > 0 then height * scoreScale.Scale else 0)
local minimumTop = if countdown.Visible then 119 else 10 captureHud.Position = UDim2.new(.5, 0, 1, -83)
local captureTop = if width >= 1200 then minimumTop else math.max(minimumTop, bottom + 8)
captureHud.Position = UDim2.new(.5, 0, 0, captureTop)
captureHud.Size = UDim2.fromOffset(math.floor(math.min(384, width - 24)), 52) captureHud.Size = UDim2.fromOffset(math.floor(math.min(384, width - 24)), 52)
gui:SetAttribute("ContentBottom", if width >= 700 then 4 else bottom) gui:SetAttribute("ContentBottom", if width >= 700 then 4 else bottom)
end end
@@ -380,13 +430,17 @@ local function refreshCapture()
local accent = if not side then UI.Gold elseif allied then allyCapture else enemyCapture local accent = if not side then UI.Gold elseif allied then allyCapture else enemyCapture
captureHud.Visible = true captureHud.Visible = true
captureLabel.Text = if phase == "Captured" then "ТОЧКА ЗАХВАЧЕНА · +1" captureLabel.Text = if phase == "Captured" then "ТОЧКА ЗАХВАЧЕНА · +1"
elseif phase == "Contested" then "ТОЧКА ОСПАРИВАЕТСЯ" elseif phase == "Contested" then HunterStrings.hotHints.contest
elseif phase == "UnderFire" then (if allied then "ВАШ ЗАХВАТ ТЕРЯЕТСЯ" else "ЗАХВАТ СОПЕРНИКОВ ПАДАЕТ") elseif phase == "UnderFire" then HunterStrings.hotHints.underFire
elseif allied then "ВАША КОМАНДА ЗАХВАТЫВАЕТ" else "СОПЕРНИКИ ЗАХВАТЫВАЮТ" elseif allied then HunterStrings.hotHints.taking else "СОПЕРНИКИ ЗАХВАТЫВАЮТ"
local percent = math.clamp((match:GetAttribute("HotPointProgress") :: number?) or 0, 0, 100) local percent = math.clamp((match:GetAttribute("HotPointProgress") :: number?) or 0, 0, 100)
captureValue.Text, captureValue.TextColor3 = string.format("%d%%", percent), accent captureValue.Text, captureValue.TextColor3 = string.format("%d%%", percent), accent
captureArc:SetAttribute("Accent", accent) captureArc:SetAttribute("Accent", accent)
captureFill.BackgroundColor3 = accent captureFill.BackgroundColor3 = accent
for i, segment in hotSegments do
segment.BackgroundColor3 = accent
segment.BackgroundTransparency = if percent >= i * 10 then 0 else .85
end
if percent == capturePercent and side == captureTeam then return end if percent == capturePercent and side == captureTeam then return end
if captureTween then captureTween:Cancel() end if captureTween then captureTween:Cancel() end
local size = UDim2.fromScale(percent / 100, 1) local size = UDim2.fromScale(percent / 100, 1)
@@ -404,7 +458,9 @@ local function refreshObjective()
local visible = player:GetAttribute("InArena") == true and match:GetAttribute("Phase") == "Round" local visible = player:GetAttribute("InArena") == true and match:GetAttribute("Phase") == "Round"
local needsLayout = visible ~= objective.Visible local needsLayout = visible ~= objective.Visible
objective.Visible = visible objective.Visible = visible
siegeBar.Visible = false siegeBar.Visible, siegeSteps.Visible, siegeChip.Visible = false, false, false
dominationChips.Visible = false
lifeBoard.Visible = false
if visible then if visible then
local rule = Rules.get(match:GetAttribute("Ruleset")) local rule = Rules.get(match:GetAttribute("Ruleset"))
local accent = if player:GetAttribute("ArenaTeam") == "Orange" then orange else blue local accent = if player:GetAttribute("ArenaTeam") == "Orange" then orange else blue
@@ -419,32 +475,85 @@ local function refreshObjective()
local attacker = siege:GetAttribute("Attacker") local attacker = siege:GetAttribute("Attacker")
local seconds = (siege:GetAttribute("Seconds") :: number?) or 0 local seconds = (siege:GetAttribute("Seconds") :: number?) or 0
local zone = player:GetAttribute("CitadelZone") local zone = player:GetAttribute("CitadelZone")
local role = if attacker == player:GetAttribute("ArenaTeam") then "Вы атакуете" else "Вы защищаете" local attacking = attacker == player:GetAttribute("ArenaTeam")
local role = if attacking then "▲ " .. RoundStrings.attack else "◆ " .. RoundStrings.defend
local point = (siege:GetAttribute("PointName") :: string?) or "" local point = (siege:GetAttribute("PointName") :: string?) or ""
objectiveTitle.Text = if phase == "RoleSwap" then "СМЕНА РОЛЕЙ" else string.format("АТАКА %d/2 · %d:%02d", local roleColor = if attacking then accent else UI.Gold
objectiveTitle.Text = if phase == "RoleSwap" then RoundStrings.swap else string.format("АТАКА %d/2 · %d:%02d",
if phase == "Attack2" then 2 else 1, math.floor(seconds / 60), seconds % 60) if phase == "Attack2" then 2 else 1, math.floor(seconds / 60), seconds % 60)
objectiveText.Text = role .. " · " .. point objectiveText.Text = role .. (if point ~= "" then " · " .. point else "")
objectiveTitle.TextColor3 = roleColor
objectiveContour:SetAttribute("Accent", roleColor)
local hint = playerGui:GetAttribute("SiegeHint")
if typeof(hint) == "string" then text = hint end
if phase ~= "RoleSwap" and siege:GetAttribute("Point") then if phase ~= "RoleSwap" and siege:GetAttribute("Point") then
if zone == "Height" then text = "Найдите нужный этаж" siegeBar.Visible, siegeSteps.Visible = true, true
elseif zone == "Blocked" then text = "Нет прямой видимости центра"
elseif zone == "Inside" and role == "Вы защищаете" then text = "Вы блокируете захват. Оставайтесь в круге!" end
siegeBar.Visible = true
local progress = (siege:GetAttribute("Progress") :: number?) or 0 local progress = (siege:GetAttribute("Progress") :: number?) or 0
local filled = math.floor((progress + 1e-7) * 10)
local index = (siege:GetAttribute("Index") :: number?) or 1
local total = (siege:GetAttribute("Total") :: number?) or SiegeConfig.MAX_OBJECTIVES
local state = siege:GetAttribute("Status")
local attackColor = if attacker == "Orange" then orange else blue
local segmentColor = if state == "Contested" then SiegeConfig.CONTESTED_COLOR
elseif state == "Decaying" then attackColor:Lerp(muted, .45) else attackColor
for i, segment in siegeSegments do for i, segment in siegeSegments do
segment.Visible = progress + 1e-8 >= i / #siegeSegments segment.Visible = i <= filled
segment.BackgroundColor3 = if siege:GetAttribute("Status") == "Contested" then orange else blue segment.BackgroundColor3 = segmentColor
if i == filled and filled > siegeSegmentCount then
segment.BackgroundTransparency = .55
TweenService:Create(segment, TweenInfo.new(.2), {BackgroundTransparency = 0}):Play()
end end
end end
siegeSegmentCount = filled
local dots: {string} = {}
for i = 1, total do dots[i] = if i < index then "✓" elseif i == index then "◆" else "○" end
siegeSteps.Text = table.concat(dots, " ") .. string.format(" %d%%", filled * 10)
siegeSteps.TextColor3 = roleColor
local copy = HunterStrings.hint.Siege
siegeChip.Visible = zone == "Inside" or zone == "Height" or zone == "Blocked"
siegeChip.Text = if zone == "Inside" then copy.inside elseif zone == "Height" then copy.wrongFloor else copy.noSight
siegeChip.TextColor3 = if zone == "Inside" then UI.Mint else UI.Gold
end end
end
if rule.id == "OneLife" then
local function dots(points: number): string
local n=math.clamp(math.floor(points),0,3)
return string.rep("●",n)..string.rep("○",3-n)
end
lifeBoard.Visible=true
lifeBoard.Text=string.format(HunterStrings.lifeHints.alive,(match:GetAttribute("MiniAliveBlue") :: number?) or 0,
(match:GetAttribute("MiniAliveOrange") :: number?) or 0)
.." "..dots((match:GetAttribute("BlueScore") :: number?) or 0).." / "..dots((match:GetAttribute("OrangeScore") :: number?) or 0)
end
if rule.id == "Domination" then
dominationChips.Visible = true
for key, slot in domSlots do
local owner = match:GetAttribute("ZoneOwner_" .. key)
local claimant = match:GetAttribute("ZoneClaim_" .. key)
local progress = (match:GetAttribute("ZoneProgress_" .. key) :: number?) or 0
local ownerTint = if owner == "Blue" then blue elseif owner == "Orange" then orange else muted
slot.text.TextColor3 = ownerTint
slot.chip.BackgroundColor3 = panelColor:Lerp(ownerTint, .28)
for i, tick in slot.ticks do
tick.Visible = typeof(claimant) == "string"
tick.BackgroundColor3 = if claimant == "Blue" then blue else orange
tick.BackgroundTransparency = if progress + 1e-7 >= i / 10 then 0 else .8
end
end
rateLabel.Text = string.format("СИНИЕ +%d/с ОРАНЖЕВЫЕ +%d/с",
(match:GetAttribute("ScoreRate_Blue") :: number?) or 0, (match:GetAttribute("ScoreRate_Orange") :: number?) or 0)
end
local modeHint = playerGui:GetAttribute("ModeHint")
if rule.id ~= "Siege" and typeof(modeHint) == "string" then text = modeHint end
local tokens = (player:GetAttribute("ArenaTokens") :: number?) or 0 local tokens = (player:GetAttribute("ArenaTokens") :: number?) or 0
if player:GetAttribute("ArenaFlag") then text = "У вас флаг · Несите его на свою базу" if player:GetAttribute("ArenaFlag") and typeof(modeHint) ~= "string" then text = "У вас флаг · Несите его на свою базу"
elseif tokens > 0 then text = "Жетонов у вас: " .. tokens .. " · Вернитесь на базу" elseif tokens > 0 and typeof(modeHint) ~= "string" then text = "Жетонов у вас: " .. tokens .. " · Вернитесь на базу"
elseif player:GetAttribute("ArenaLeader") then text = "Вы лидер · За вас дают 3 очка" elseif player:GetAttribute("ArenaLeader") and typeof(modeHint) ~= "string" then text = "Вы лидер · За вас дают 3 очка"
elseif rule.id == "TrophyHunt" then text = "" end elseif rule.id == "TrophyHunt" and typeof(modeHint) ~= "string" then text = "" end
objectiveStatus.Visible = text ~= "" objectiveStatus.Visible = text ~= ""
objectiveStatus.Text = text objectiveStatus.Text = text
objectiveStatus.TextColor3 = accent:Lerp(ink, .3) objectiveStatus.TextColor3 = accent:Lerp(ink, .3)
local height = if siegeBar.Visible then 101 elseif objectiveStatus.Visible then 88 else 62 local height = if siegeBar.Visible then 145 elseif dominationChips.Visible then 133 elseif lifeBoard.Visible then 120 elseif objectiveStatus.Visible then 88 else 62
if height ~= objective.Size.Y.Offset then if height ~= objective.Size.Y.Offset then
objective.Size = UDim2.fromOffset(widthOfCard, height) objective.Size = UDim2.fromOffset(widthOfCard, height)
needsLayout = true needsLayout = true
@@ -455,7 +564,9 @@ end
type ResultPlayer = {userId: number, displayName: string, kills: number, deaths: number} type ResultPlayer = {userId: number, displayName: string, kills: number, deaths: number}
type RoundResult = {mode: string, ruleset: string, winner: string, endsAt: number, duration: number, blueScore: number, orangeScore: number, type RoundResult = {mode: string, ruleset: string, winner: string, endsAt: number, duration: number, blueScore: number, orangeScore: number,
blue: {ResultPlayer}, orange: {ResultPlayer}, allowModeChange: boolean?, siegeReason: string?} blue: {ResultPlayer}, orange: {ResultPlayer}, allowModeChange: boolean?, siegeReason: string?, reason: string?,
highlights: {mvpUserId: number?, mvpName: string?, lines: {{title: string, name: string, value: number}}}?,
contributions: {[string]: {[string]: number}}?}
type ResultRow = {body: Frame, avatar: ImageLabel, name: TextLabel, kills: TextLabel, deaths: TextLabel} type ResultRow = {body: Frame, avatar: ImageLabel, name: TextLabel, kills: TextLabel, deaths: TextLabel}
type ResultTeam = {card: Frame, score: TextLabel, empty: TextLabel, accent: Color3, rows: {ResultRow}} type ResultTeam = {card: Frame, score: TextLabel, empty: TextLabel, accent: Color3, rows: {ResultRow}}
type SummaryView = "Live" | "Final" type SummaryView = "Live" | "Final"
@@ -485,6 +596,8 @@ resultTitle.FontFace = UI.Display
resultTitle.TextXAlignment = Enum.TextXAlignment.Left resultTitle.TextXAlignment = Enum.TextXAlignment.Left
local resultWinner = UI.label(resultsPanel, "Winner", "", UDim2.fromOffset(27, 60), UDim2.fromOffset(510, 25), 17, UI.Gold) local resultWinner = UI.label(resultsPanel, "Winner", "", UDim2.fromOffset(27, 60), UDim2.fromOffset(510, 25), 17, UI.Gold)
resultWinner.TextXAlignment = Enum.TextXAlignment.Left resultWinner.TextXAlignment = Enum.TextXAlignment.Left
local resultReason = UI.label(resultsPanel, "Reason", "", UDim2.fromOffset(27, 83), UDim2.fromOffset(900, 22), 15, muted)
resultReason.TextXAlignment = Enum.TextXAlignment.Left
local resultMode = UI.label(resultsPanel, "Mode", "", UDim2.fromOffset(566, 30), UDim2.fromOffset(368, 31), 15, muted) local resultMode = UI.label(resultsPanel, "Mode", "", UDim2.fromOffset(566, 30), UDim2.fromOffset(368, 31), 15, muted)
resultMode.TextXAlignment = Enum.TextXAlignment.Right resultMode.TextXAlignment = Enum.TextXAlignment.Right
@@ -593,6 +706,20 @@ end
local blueResult = resultTeam("Blue", 23, "СИНИЕ", blue, blueDark) local blueResult = resultTeam("Blue", 23, "СИНИЕ", blue, blueDark)
local orangeResult = resultTeam("Orange", 491, "ОРАНЖЕВЫЕ", orange, orangeDark) local orangeResult = resultTeam("Orange", 491, "ОРАНЖЕВЫЕ", orange, orangeDark)
local siegeRecap = UI.label(resultsPanel, "SiegeTimes", "", UDim2.fromOffset(30, 0), UDim2.fromOffset(900, 84), 16, ink)
siegeRecap.TextWrapped = true
siegeRecap.TextXAlignment = Enum.TextXAlignment.Left
siegeRecap.Visible = false
local resultsExtra = UI.plate(resultsPanel, "ResultsExtra", UDim2.fromOffset(25, 0), UDim2.fromOffset(910, 98), UI.Gold)
local mvpChip = UI.label(resultsExtra, "MVP", "", UDim2.fromOffset(15, 4), UDim2.fromOffset(865, 28), 21, UI.Gold)
mvpChip.FontFace = UI.Display
mvpChip.TextXAlignment = Enum.TextXAlignment.Left
local contribution = UI.label(resultsExtra, "Contribution", "", UDim2.fromOffset(15, 32), UDim2.fromOffset(865, 25), 16, ink)
contribution.TextXAlignment = Enum.TextXAlignment.Left
local highlights = UI.label(resultsExtra, "Highlights", "", UDim2.fromOffset(15, 60), UDim2.fromOffset(865, 31), 15, muted)
highlights.TextWrapped = true
highlights.TextXAlignment = Enum.TextXAlignment.Left
resultsExtra.Visible = false
local nextRound = UI.label(resultsPanel, "NextRound", "", UDim2.fromOffset(25, 573), UDim2.fromOffset(910, 31), 16, ink) local nextRound = UI.label(resultsPanel, "NextRound", "", UDim2.fromOffset(25, 573), UDim2.fromOffset(910, 31), 16, ink)
local resultTrack = UI.element("ProgressBar", resultsPanel, UDim2.fromOffset(25, 609), UDim2.fromOffset(910, 3)) local resultTrack = UI.element("ProgressBar", resultsPanel, UDim2.fromOffset(25, 609), UDim2.fromOffset(910, 3))
local resultFill = resultTrack:WaitForChild("Fill") :: Frame local resultFill = resultTrack:WaitForChild("Fill") :: Frame
@@ -628,7 +755,12 @@ local function setSummaryTeams(bluePlayers: {ResultPlayer}, orangePlayers: {Resu
populateResults(blueResult, blueTotal, bluePlayers) populateResults(blueResult, blueTotal, bluePlayers)
populateResults(orangeResult, orangeTotal, orangePlayers) populateResults(orangeResult, orangeTotal, orangePlayers)
local rowSpace = 35 * math.max(3, #bluePlayers, #orangePlayers) local rowSpace = 35 * math.max(3, #bluePlayers, #orangePlayers)
local height = 280 + rowSpace local final = summaryView == "Final"
local height = 280 + rowSpace + (if final then 121 else 0) + (if final and siegeRecap.Visible then 90 else 0)
blueResult.card.Position = UDim2.fromOffset(23, if final then 112 else 97)
orangeResult.card.Position = UDim2.fromOffset(491, if final then 112 else 97)
resultsExtra.Position = UDim2.fromOffset(25, height - 164)
siegeRecap.Position = UDim2.fromOffset(30, height - 250)
if resultsPanel.Size.Y.Offset == height then return end if resultsPanel.Size.Y.Offset == height then return end
resultsPanel.Size = UDim2.fromOffset(960, height) resultsPanel.Size = UDim2.fromOffset(960, height)
blueResult.card.Size = UDim2.fromOffset(446, 117 + rowSpace) blueResult.card.Size = UDim2.fromOffset(446, 117 + rowSpace)
@@ -640,6 +772,9 @@ end
local function startSummary(view: SummaryView, ruleId: unknown) local function startSummary(view: SummaryView, ruleId: unknown)
summaryView = view summaryView = view
siegeRecap.Visible = false
resultReason.Visible = view == "Final"
resultsExtra.Visible = view == "Final"
lobbyButton.Visible = view == "Live" and player:GetAttribute("InArena") == true lobbyButton.Visible = view == "Live" and player:GetAttribute("InArena") == true
resultsGui:SetAttribute("LiveScoreboardOpen", view == "Live") resultsGui:SetAttribute("LiveScoreboardOpen", view == "Live")
resultTitle.Text = if view == "Live" then "СТАТИСТИКА МАТЧА" else "ИТОГИ РАУНДА" resultTitle.Text = if view == "Live" then "СТАТИСТИКА МАТЧА" else "ИТОГИ РАУНДА"
@@ -817,11 +952,32 @@ results.OnClientEvent:Connect(function(result: RoundResult, participantSide: str
if left <= 0 then return end if left <= 0 then return end
if resultsShade.Visible then hideResults() end if resultsShade.Visible then hideResults() end
startSummary("Final", result.ruleset) startSummary("Final", result.ruleset)
if result.ruleset == "Siege" and result.siegeTimes then
local lines = SiegeResults.rows(result.siegeTimes, SiegeConfig.MAX_OBJECTIVES)
table.insert(lines, SiegeResults.tiebreak)
siegeRecap.Text = table.concat(lines, "\n")
siegeRecap.Visible = true
end
setSummaryTeams(result.blue, result.orange, result.blueScore, result.orangeScore) setSummaryTeams(result.blue, result.orange, result.blueScore, result.orangeScore)
local winnerColor = if result.winner == "Blue" then blue elseif result.winner == "Orange" then orange else UI.Gold local winnerColor = if result.winner == "Blue" then blue elseif result.winner == "Orange" then orange else UI.Gold
resultWinner.Text = if result.winner == "Blue" then "СИНИЕ ПОБЕДИЛИ" resultWinner.Text = if result.winner == "Blue" then "СИНИЕ ПОБЕДИЛИ"
elseif result.winner == "Orange" then "ОРАНЖЕВЫЕ ПОБЕДИЛИ" else "НИЧЬЯ" elseif result.winner == "Orange" then "ОРАНЖЕВЫЕ ПОБЕДИЛИ" else "НИЧЬЯ"
if result.siegeReason then resultWinner.Text = result.siegeReason end resultReason.Text = result.reason or result.siegeReason or ""
local personal = result.contributions and result.contributions[tostring(player.UserId)] or {}
local entries: {string} = {}
local keys = RoundStrings.contributionKeys[result.ruleset] or RoundStrings.contributionKeys.TeamDeathmatch
for _, key in keys do
table.insert(entries, RoundStrings.stats[key] .. " " .. tostring(math.floor(personal[key] or 0)))
end
contribution.Text = string.format(RoundStrings.contribution, table.concat(entries, " · "))
local recap = result.highlights
mvpChip.Visible = recap ~= nil and recap.mvpName ~= nil
mvpChip.Text = if recap and recap.mvpName then string.format(RoundStrings.mvp, recap.mvpName) else ""
table.clear(entries)
if recap then
for _, line in recap.lines do table.insert(entries, string.format("%s · %s (%d)", line.title, line.name, math.floor(line.value))) end
end
highlights.Text = table.concat(entries, " / ")
if result.ruleset == "Siege" and (participantSide == "Blue" or participantSide == "Orange") then if result.ruleset == "Siege" and (participantSide == "Blue" or participantSide == "Orange") then
if result.winner == "Draw" then if result.winner == "Draw" then
showOutcome("НИЧЬЯ", ink) showOutcome("НИЧЬЯ", ink)
@@ -906,6 +1062,10 @@ ContextActionService:BindActionAtPriority(scoreboardAction, function(_, inputSta
end, false, Enum.ContextActionPriority.High.Value, Enum.KeyCode.Tab) end, false, Enum.ContextActionPriority.High.Value, Enum.KeyCode.Tab)
local lastSecond = -1 local lastSecond = -1
local lastStage: string? = nil
local priorClockStage: string? = nil
local finalClockPulse: Tween? = nil
local lastIntroBeat = -1
local lastPhase = "" local lastPhase = ""
local lastTeam: string? = nil local lastTeam: string? = nil
local lastMode = "" local lastMode = ""
@@ -923,32 +1083,52 @@ local function updateClock()
end end
end end
local seconds = remaining() local seconds = remaining()
local phase = activeState():GetAttribute("Phase") :: string local match = activeState()
local phase = match:GetAttribute("Phase") :: string
local stage = match:GetAttribute("RoundStage") :: string?
local untilLive = match:GetAttribute("LiveAt")
local intro = stage == "Briefing" or stage == "Countdown"
local introSeconds = if intro and typeof(untilLive) == "number" then math.max(0, math.ceil(untilLive - workspace:GetServerTimeNow())) else 0
if intro then seconds = introSeconds end
local team = player:GetAttribute("ArenaTeam") :: string? local team = player:GetAttribute("ArenaTeam") :: string?
local arenaMode = currentMode() local arenaMode = currentMode()
local inArena = player:GetAttribute("InArena") == true local inArena = player:GetAttribute("InArena") == true
if seconds == lastSecond and phase == lastPhase and team == lastTeam and arenaMode == lastMode and inArena == lastInArena then return end if seconds == lastSecond and phase == lastPhase and stage == lastStage and team == lastTeam and arenaMode == lastMode and inArena == lastInArena then return end
local finishing = inArena and phase == "Round" and seconds > 0 and seconds <= 5 local nextMini = match:GetAttribute("MiniRoundNextAt")
local miniBeat = if typeof(nextMini)=="number" then math.ceil(nextMini-workspace:GetServerTimeNow()) else 0
local beat = if stage=="Countdown" then introSeconds elseif miniBeat>0 and miniBeat<=3 then miniBeat else 0
local counting = inArena and beat > 0
local hadCountdown = countdown.Visible local hadCountdown = countdown.Visible
if finishing then if counting then
if not countdown.Visible or seconds ~= lastSecond or arenaMode ~= lastMode then showCountdownBeat(seconds) end if not hadCountdown or beat ~= lastIntroBeat then showCountdownBeat(beat) end
lastIntroBeat = beat
elseif countdown.Visible then elseif countdown.Visible then
countdown.Visible = false countdown.Visible = false
clearCountdownBeat() clearCountdownBeat()
end end
if captureHud.Visible and hadCountdown ~= countdown.Visible then fitHud() end if captureHud.Visible and hadCountdown ~= countdown.Visible then fitHud() end
lastSecond, lastPhase, lastTeam, lastMode, lastInArena = seconds, phase, team, arenaMode, inArena lastSecond, lastPhase, lastTeam, lastMode, lastInArena = seconds, phase, team, arenaMode, inArena
lastStage = stage
local rule = Rules.get(activeState():GetAttribute("Ruleset")) local rule = Rules.get(activeState():GetAttribute("Ruleset"))
if rule.id == "Siege" and inArena then refreshObjective() end if inArena and (rule.id == "Siege" or rule.id == "Domination" or rule.id == "OneLife") then refreshObjective() end
mode.Visible = true mode.Visible = true
mode.Text = if phase == "Vote" then "ГОЛОСОВАНИЕ" elseif phase == "Reveal" then "ДО НАЧАЛА РАУНДА" mode.Text = if intro then RoundStrings.untilStart elseif stage == "RoleSwap" then RoundStrings.swap elseif phase == "Vote" then "ГОЛОСОВАНИЕ" elseif phase == "Reveal" then "ДО НАЧАЛА РАУНДА"
elseif phase == "Break" then (if activeState():GetAttribute("AllowModeChange") == false then "ДО НАЧАЛА РАУНДА" else "ДО ГОЛОСОВАНИЯ") elseif phase == "Break" then (if activeState():GetAttribute("AllowModeChange") == false then "ДО НАЧАЛА РАУНДА" else "ДО ГОЛОСОВАНИЯ")
elseif phase == "Round" then (if inArena then "ДО КОНЦА РАУНДА" else rule.title) elseif phase == "Round" then (if inArena then "ДО КОНЦА РАУНДА" else rule.title)
else "ПОДГОТОВКА АРЕНЫ" else "ПОДГОТОВКА АРЕНЫ"
clock.Position = UDim2.fromOffset(0, 14) clock.Position = UDim2.fromOffset(0, 14)
clock.TextSize = 32 clock.TextSize = 32
clock.Text = string.format("%02d:%02d", seconds // 60, seconds % 60) clock.Text = string.format("%02d:%02d", seconds // 60, seconds % 60)
clock.TextColor3 = if seconds <= 15 and phase == "Round" then Color3.fromRGB(255, 218, 148) else ink if stage ~= priorClockStage then
priorClockStage = stage
if finalClockPulse then finalClockPulse:Cancel(); finalClockPulse = nil end
clock.TextColor3 = if stage == "FinalPush" then Color3.fromRGB(255, 106, 107) else ink
if stage == "FinalPush" then
finalClockPulse = TweenService:Create(clock, TweenInfo.new(.72, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, -1, true),
{TextColor3 = Color3.fromRGB(255, 193, 175)})
finalClockPulse:Play()
end
end
mode.TextColor3 = if team == "Blue" then blue elseif team == "Orange" then orange else muted mode.TextColor3 = if team == "Blue" then blue elseif team == "Orange" then orange else muted
roundFill.BackgroundColor3 = if seconds <= 15 and phase == "Round" then orange else mode.TextColor3:Lerp(blue, .32) roundFill.BackgroundColor3 = if seconds <= 15 and phase == "Round" then orange else mode.TextColor3:Lerp(blue, .32)
if clockMotion then clockMotion:Cancel() end if clockMotion then clockMotion:Cancel() end
@@ -960,9 +1140,21 @@ local function updateClock()
clockMotion:Play() clockMotion:Play()
refreshControls() refreshControls()
end end
local domConnections: {RBXScriptConnection} = {}
for _, key in {"A", "B", "C"} do
for _, attr in {"ZoneProgress_", "ZoneOwner_", "ZoneClaim_"} do
table.insert(domConnections, activeState():GetAttributeChangedSignal(attr .. key):Connect(refreshObjective))
end
end
local modeHintConnection = playerGui:GetAttributeChangedSignal("ModeHint"):Connect(refreshObjective)
local siegeHintConnection = playerGui:GetAttributeChangedSignal("SiegeHint"):Connect(refreshObjective)
local timerConnection = RunService.Heartbeat:Connect(updateClock) local timerConnection = RunService.Heartbeat:Connect(updateClock)
script.Destroying:Once(function() script.Destroying:Once(function()
timerConnection:Disconnect() timerConnection:Disconnect()
siegeHintConnection:Disconnect()
modeHintConnection:Disconnect()
for _, connection in domConnections do connection:Disconnect() end
if finalClockPulse then finalClockPulse:Cancel() end
votingChanged:Disconnect() votingChanged:Disconnect()
scoreboardFocus:Disconnect() scoreboardFocus:Disconnect()
ContextActionService:UnbindAction(scoreboardAction) ContextActionService:UnbindAction(scoreboardAction)
+172 -14
View File
@@ -7,13 +7,22 @@ local Rules = require(ReplicatedStorage:WaitForChild("MatchRules") :: ModuleScri
local Hosting = require(ReplicatedStorage:WaitForChild("HostedArena") :: ModuleScript) local Hosting = require(ReplicatedStorage:WaitForChild("HostedArena") :: ModuleScript)
local Objectives = require(script.Parent:WaitForChild("ArenaObjectives") :: ModuleScript) local Objectives = require(script.Parent:WaitForChild("ArenaObjectives") :: ModuleScript)
local SiegeConfig = require(ReplicatedStorage:WaitForChild("CitadelAssaultConfig") :: ModuleScript) local SiegeConfig = require(ReplicatedStorage:WaitForChild("CitadelAssaultConfig") :: ModuleScript)
local Hunter = ReplicatedStorage:WaitForChild("Hunter")
local Profiles = require(Hunter:WaitForChild("ModeProfiles") :: ModuleScript)
local Timeline = require(Hunter:WaitForChild("Timeline") :: ModuleScript)
local Stage = require(Hunter:WaitForChild("Stage") :: ModuleScript)
local RoundConfig = require(Hunter:WaitForChild("RoundConfig") :: ModuleScript)
local Strings = require(Hunter:WaitForChild("Strings") :: ModuleScript)
local Runtime = script.Parent:WaitForChild("ModeRuntime")
local RoundPlayer = require(Runtime:WaitForChild("PlayerRoundState") :: ModuleScript)
local Stats = require(Runtime:WaitForChild("Stats") :: ModuleScript)
local ArenaSpawns = require(script.Parent:WaitForChild("ArenaSpawns")) local ArenaSpawns = require(script.Parent:WaitForChild("ArenaSpawns"))
local SiegeSpawn = require(script.Parent:WaitForChild("CitadelSpawnService") :: ModuleScript)
local SkinCatalog = require(ReplicatedStorage:WaitForChild("RifleSkinCatalog") :: ModuleScript) local SkinCatalog = require(ReplicatedStorage:WaitForChild("RifleSkinCatalog") :: ModuleScript)
local lobbySpawn = workspace:WaitForChild("HunterLobby"):WaitForChild("Arrival Spawn") :: SpawnLocation local lobbySpawn = workspace:WaitForChild("HunterLobby"):WaitForChild("Arrival Spawn") :: SpawnLocation
local rifleTemplate = ReplicatedStorage:WaitForChild("ArenaEquipment"):WaitForChild("SniperRifle") :: Tool local rifleTemplate = ReplicatedStorage:WaitForChild("ArenaEquipment"):WaitForChild("SniperRifle") :: Tool
local ROUND_SECONDS = 300
local BREAK_SECONDS = 15 local BREAK_SECONDS = 15
local VOTE_SECONDS = 15 local VOTE_SECONDS = 15
local TEAM_REVEAL_SECONDS = 1.05 local TEAM_REVEAL_SECONDS = 1.05
@@ -55,7 +64,7 @@ randomState.Parent = state
type Side = Hosting.Side type Side = Hosting.Side
type Match = {id: string, state: Folder, blue: Team, orange: Team, phase: string, endsAt: number, order: number, type Match = {id: string, state: Folder, blue: Team, orange: Team, phase: string, endsAt: number, order: number,
rule: string, allowModeChange: boolean, engine: Objectives.Match?, eligible: {[Player]: Side}, ballots: {[Player]: string}} rule: string, startedAt: number?, liveAt: number?, allowModeChange: boolean, engine: Objectives.Match?, eligible: {[Player]: Side}, ballots: {[Player]: string}}
type PendingJoin = {match: Match, side: Side, endsAt: number} type PendingJoin = {match: Match, side: Side, endsAt: number}
local pendingJoins: {[Player]: PendingJoin} = {} local pendingJoins: {[Player]: PendingJoin} = {}
local matches: {[string]: Match} = { local matches: {[string]: Match} = {
@@ -161,6 +170,7 @@ local function guardInventory(player: Player, container: Instance)
local function disarmed(): boolean local function disarmed(): boolean
return player:GetAttribute("InArena") ~= true or player:GetAttribute("ArenaWaiting") == true return player:GetAttribute("InArena") ~= true or player:GetAttribute("ArenaWaiting") == true
or player:GetAttribute("ArenaIntermission") == true or player:GetAttribute("ArenaIntermission") == true
or not Stage.combatAllowed(randomState)
end end
container.ChildAdded:Connect(function(child) container.ChildAdded:Connect(function(child)
if child:IsA("Tool") and disarmed() then child:Destroy() end if child:IsA("Tool") and disarmed() then child:Destroy() end
@@ -176,10 +186,14 @@ end
local function recordDeath(player: Player, character: Model) local function recordDeath(player: Player, character: Model)
if not roster[player] or placedCharacter[player] ~= character or lastCountedDeath[player] == character then return end if not roster[player] or placedCharacter[player] ~= character or lastCountedDeath[player] == character then return end
lastCountedDeath[player] = character lastCountedDeath[player] = character
Stats.add(player, "deaths", 1)
player:SetAttribute("RoundDeaths", ((player:GetAttribute("RoundDeaths") :: number?) or 0) + 1) player:SetAttribute("RoundDeaths", ((player:GetAttribute("RoundDeaths") :: number?) or 0) + 1)
end end
local function moveToLobby(player: Player) local function moveToLobby(player: Player)
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
player:SetAttribute("RoundRespawnAt", nil)
placedCharacter[player] = nil placedCharacter[player] = nil
player:SetAttribute("InArena", false) player:SetAttribute("InArena", false)
player.RespawnLocation = lobbySpawn player.RespawnLocation = lobbySpawn
@@ -198,6 +212,7 @@ local function sendToLobby(player: Player)
roster[player] = nil roster[player] = nil
joinOrder[player] = nil joinOrder[player] = nil
lastCountedDeath[player] = nil lastCountedDeath[player] = nil
Stats.remove(player)
moveToLobby(player) moveToLobby(player)
player:SetAttribute("ArenaWaiting", nil) player:SetAttribute("ArenaWaiting", nil)
player:SetAttribute("ArenaIntermission", nil) player:SetAttribute("ArenaIntermission", nil)
@@ -221,7 +236,24 @@ local function enterArena(player: Player, character: Model, humanoid: Humanoid)
local destination = destinationFor(player) local destination = destinationFor(player)
player.RespawnLocation = destination player.RespawnLocation = destination
ArenaSpawns.place(character, destination) ArenaSpawns.place(character, destination)
local siege = randomState:FindFirstChild("CitadelMatchState")
local side = player:GetAttribute("ArenaTeam")
local attacker = siege and siege:GetAttribute("Attacker")
local base = siege and typeof(side) == "string" and siege:GetAttribute(side .. "Base")
if siege and typeof(base) == "Vector3" and typeof(attacker) == "string"
and randomState:GetAttribute("RoundStage") ~= "RoleSwap" then
local at = SiegeSpawn.position(Modes.geometry(Modes.of(player)), attacker == side, base, joinOrder[player] or 1)
character:PivotTo(CFrame.new(at + Vector3.yAxis * 4))
end
if Stage.combatAllowed(randomState) then
RoundPlayer.thaw(player)
arm(player, character, humanoid) arm(player, character, humanoid)
else
clearTools(character)
clearTools(player:FindFirstChildOfClass("Backpack"))
RoundPlayer.clearShield(player)
RoundPlayer.freeze(player, character, humanoid)
end
end end
local function deploy(player: Player) local function deploy(player: Player)
@@ -239,6 +271,7 @@ local function deploy(player: Player)
end end
local function stageOnArena(player: Player) local function stageOnArena(player: Player)
RoundPlayer.clearShield(player)
placedCharacter[player] = nil placedCharacter[player] = nil
player:SetAttribute("InArena", true) player:SetAttribute("InArena", true)
local destination = destinationFor(player) local destination = destinationFor(player)
@@ -258,6 +291,7 @@ local function bench(player: Player)
if character and humanoid and humanoid.Health > 0 then if character and humanoid and humanoid.Health > 0 then
humanoid.Health = humanoid.MaxHealth humanoid.Health = humanoid.MaxHealth
ArenaSpawns.place(character, destination) ArenaSpawns.place(character, destination)
if not Stage.combatAllowed(randomState) then RoundPlayer.freeze(player, character, humanoid) end
end end
end end
@@ -265,6 +299,17 @@ local function enterRound(player: Player, match: Match)
if match.rule == "OneLife" then bench(player) else deploy(player) end if match.rule == "OneLife" then bench(player) else deploy(player) end
end end
local function spawnCharacter(player: Player, previous: Model?)
-- Загружаем персонажа только пока действителен конкретный запрос на возрождение.
for attempt = 1, 2 do
if player.Parent ~= Players or player.Character ~= previous then return end
local ok, issue = pcall(player.LoadCharacterAsync, player)
if ok then return end
warn("Не удалось возродить игрока:", issue)
if attempt == 1 then task.wait(1) end
end
end
local function onCharacter(player: Player, character: Model) local function onCharacter(player: Player, character: Model)
local root = character:WaitForChild("HumanoidRootPart", 10) local root = character:WaitForChild("HumanoidRootPart", 10)
local humanoid = character:WaitForChild("Humanoid", 10) local humanoid = character:WaitForChild("Humanoid", 10)
@@ -278,26 +323,42 @@ local function onCharacter(player: Player, character: Model)
humanoid.HealthChanged:Connect(replicateHealth) humanoid.HealthChanged:Connect(replicateHealth)
replicateHealth() replicateHealth()
humanoid.Died:Once(function() humanoid.Died:Once(function()
if player.Character ~= character then return end
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
local match = matches[Modes.of(player)] local match = matches[Modes.of(player)]
local engine = match.engine local engine = match.engine
local wasFighting = roster[player] ~= nil and placedCharacter[player] == character local fightingStage = match.phase == "Round" and Stage.combatAllowed(match.state)
recordDeath(player, character) local wasFighting = roster[player] ~= nil and placedCharacter[player] == character and fightingStage
if player.Character == character then resetStreak(player) end local roundRespawn = roster[player] ~= nil and match.phase == "Round" and match.rule ~= "OneLife"
if wasFighting and engine and match.phase == "Round" then
local position = if root:IsA("BasePart") then root.Position else nil
local now = workspace:GetServerTimeNow() local now = workspace:GetServerTimeNow()
local delay = if roundRespawn then Profiles[match.rule].respawnDelay else Players.RespawnTime
if roundRespawn then player:SetAttribute("RoundRespawnAt", now + delay) end
task.delay(delay, spawnCharacter, player, character)
if fightingStage then recordDeath(player, character) end
resetStreak(player)
if wasFighting and engine then
local position = if root:IsA("BasePart") then root.Position else nil
task.defer(function() task.defer(function()
if match.engine == engine and roster[player] and placedCharacter[player] == character then engine.death(player, position, now) end if match.engine == engine and roster[player] and placedCharacter[player] == character then engine.death(player, position, now) end
end) end)
end end
end) end)
local respawning = player:GetAttribute("RoundRespawnAt") ~= nil
player:SetAttribute("RoundRespawnAt", nil)
if roster[player] and player:GetAttribute("InArena") == true then if roster[player] and player:GetAttribute("InArena") == true then
if player:GetAttribute("ArenaIntermission") == true or player:GetAttribute("ArenaWaiting") == true then if player:GetAttribute("ArenaIntermission") == true or player:GetAttribute("ArenaWaiting") == true then
local destination = player.RespawnLocation or destinationFor(player) local destination = player.RespawnLocation or destinationFor(player)
player.RespawnLocation = destination player.RespawnLocation = destination
ArenaSpawns.place(character, destination) ArenaSpawns.place(character, destination)
if player:GetAttribute("ArenaIntermission") ~= true and not Stage.combatAllowed(randomState) then
RoundPlayer.freeze(player, character, humanoid)
end
else else
enterArena(player, character, humanoid) enterArena(player, character, humanoid)
if respawning and Stage.combatAllowed(randomState) then
RoundPlayer.shield(player, character, Profiles[matches[Modes.of(player)].rule].spawnProtection)
end
end end
else else
ArenaSpawns.place(character, lobbySpawn) ArenaSpawns.place(character, lobbySpawn)
@@ -319,9 +380,12 @@ local function onPlayer(player: Player)
if player.Character then if player.Character then
guardInventory(player, player.Character) guardInventory(player, player.Character)
task.spawn(onCharacter, player, player.Character) task.spawn(onCharacter, player, player.Character)
else
task.defer(spawnCharacter, player, nil)
end end
end end
Players.CharacterAutoLoads = false
Players.PlayerAdded:Connect(onPlayer) Players.PlayerAdded:Connect(onPlayer)
for _, player in Players:GetPlayers() do onPlayer(player) end for _, player in Players:GetPlayers() do onPlayer(player) end
@@ -349,6 +413,9 @@ local function broadcastVotes(match: Match)
end end
Players.PlayerRemoving:Connect(function(player) Players.PlayerRemoving:Connect(function(player)
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
Stats.remove(player)
local wasPlaying = roster[player] ~= nil local wasPlaying = roster[player] ~= nil
local match = matches[Modes.of(player)] local match = matches[Modes.of(player)]
local engine = match.engine local engine = match.engine
@@ -529,8 +596,13 @@ cycleSkin.OnServerEvent:Connect(function(player: Player)
end) end)
local function publish(match: Match) local function publish(match: Match)
local duration = if match.phase == "Round" then ROUND_SECONDS elseif match.phase == "Vote" then VOTE_SECONDS local duration = if match.phase == "Round" then match.endsAt - (match.startedAt or match.endsAt) elseif match.phase == "Vote" then VOTE_SECONDS
elseif match.phase == "Reveal" then Rules.VoteRevealSeconds else BREAK_SECONDS elseif match.phase == "Reveal" then Rules.VoteRevealSeconds else BREAK_SECONDS
if match.phase ~= "Round" then
match.state:SetAttribute("RoundStage", nil)
match.state:SetAttribute("StageEndsAt", nil)
match.state:SetAttribute("LiveAt", nil)
end
match.state:SetAttribute("PhaseDuration", duration) match.state:SetAttribute("PhaseDuration", duration)
match.state:SetAttribute("EndsAt", match.endsAt) match.state:SetAttribute("EndsAt", match.endsAt)
match.state:SetAttribute("Phase", match.phase) match.state:SetAttribute("Phase", match.phase)
@@ -592,8 +664,12 @@ local function startRound(match: Match)
match.state:SetAttribute("MapGeneration", arena:GetAttribute("Generation")) match.state:SetAttribute("MapGeneration", arena:GetAttribute("Generation"))
match.state:SetAttribute("MapLayout", arena:GetAttribute("LayoutVariant")) match.state:SetAttribute("MapLayout", arena:GetAttribute("LayoutVariant"))
local now = workspace:GetServerTimeNow() local now = workspace:GetServerTimeNow()
local profile = Profiles[match.rule]
local roundDuration = profile.roundSeconds + (if match.rule == "Siege" then SiegeConfig.SWAP_FREEZE else 0)
local liveAt = Timeline.liveAt(now, profile.briefingSeconds, profile.countdownSeconds)
Stats.reset()
local ok, engine = pcall(Objectives.start, { local ok, engine = pcall(Objectives.start, {
arena = match.id, rule = match.rule, state = match.state, now = now, duration = ROUND_SECONDS, arena = match.id, rule = match.rule, state = match.state, now = liveAt, duration = roundDuration,
bench = bench, deploy = deploy, bench = bench, deploy = deploy,
balanceWaiting = function() balanceWaiting(match) end, balanceWaiting = function() balanceWaiting(match) end,
members = function(): {Player} members = function(): {Player}
@@ -609,8 +685,11 @@ local function startRound(match: Match)
return return
end end
match.engine = engine match.engine = engine
local roundDuration = if match.rule == "Siege" then SiegeConfig.MATCH_DURATION + SiegeConfig.SWAP_FREEZE else ROUND_SECONDS match.startedAt, match.liveAt = now, liveAt
match.phase, match.endsAt = "Round", now + roundDuration match.phase, match.endsAt = "Round", liveAt + roundDuration
match.state:SetAttribute("LiveAt", liveAt)
match.state:SetAttribute("StageEndsAt", now + profile.briefingSeconds)
match.state:SetAttribute("RoundStage", "Briefing")
match.state:SetAttribute("Ruleset", match.rule) match.state:SetAttribute("Ruleset", match.rule)
match.state:SetAttribute("BlueKills", 0) match.state:SetAttribute("BlueKills", 0)
match.state:SetAttribute("OrangeKills", 0) match.state:SetAttribute("OrangeKills", 0)
@@ -629,7 +708,7 @@ local function finishRound(match: Match)
if team ~= match.blue and team ~= match.orange then continue end if team ~= match.blue and team ~= match.orange then continue end
local character = player.Character local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid") local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if character and humanoid and humanoid.Health <= 0 then recordDeath(player, character) end if character and humanoid and humanoid.Health <= 0 and Stage.combatAllowed(match.state) then recordDeath(player, character) end
table.insert(participants, {player = player, side = if team == match.blue then "Blue" else "Orange"}) table.insert(participants, {player = player, side = if team == match.blue then "Blue" else "Orange"})
table.insert(if team == match.blue then bluePlayers else orangePlayers, { table.insert(if team == match.blue then bluePlayers else orangePlayers, {
userId = player.UserId, userId = player.UserId,
@@ -655,11 +734,41 @@ local function finishRound(match: Match)
local winner = if engine then engine.winner() else "Draw" local winner = if engine then engine.winner() else "Draw"
local siegeState = match.state:FindFirstChild("CitadelMatchState") local siegeState = match.state:FindFirstChild("CitadelMatchState")
local siegeTimes = if siegeState then siegeState:GetAttributes() else nil local siegeTimes = if siegeState then siegeState:GetAttributes() else nil
local rows: {Stats.Row} = {}
local contributions: {[string]: {[string]: number}} = {}
local names: {[number]: string} = {}
for _, entry in participants do
local player = entry.player
if winner == entry.side then Stats.add(player, "wins", 1) end
local record = Stats.get(player)
contributions[tostring(player.UserId)] = record
names[player.UserId] = player.DisplayName
table.insert(rows, {userId = player.UserId, stats = record})
end
local mvp = Stats.mvp(rows, RoundConfig.mvpWeights)
local lines = {}
for _, key in Strings.round.highlightOrder do
local best: Stats.Row? = nil
for _, row in rows do
local value = row.stats[key] or 0
local bestValue = if best then best.stats[key] or 0 else 0
if value > 0 and (not best or value > bestValue or (value == bestValue and row.userId < best.userId)) then
best = row
end
end
if best then
table.insert(lines, {title = Strings.round.stats[key], name = names[best.userId], value = best.stats[key]})
if #lines == 3 then break end
end
end
local snapshot = { local snapshot = {
mode = match.id, mode = match.id,
ruleset = match.rule, ruleset = match.rule,
allowModeChange = match.allowModeChange, allowModeChange = match.allowModeChange,
winner = winner, winner = winner,
reason = match.state:GetAttribute("ResultReason") or (if winner == "Draw" then Strings.round.drawReason else Strings.round.scoreReason),
highlights = {mvpUserId = mvp, mvpName = if mvp then names[mvp] else nil, lines = lines},
contributions = contributions,
siegeReason = if siegeState then match.state:GetAttribute("CitadelResultReason") else nil, siegeReason = if siegeState then match.state:GetAttribute("CitadelResultReason") else nil,
siegeTimes = siegeTimes, siegeTimes = siegeTimes,
endsAt = match.endsAt, endsAt = match.endsAt,
@@ -673,6 +782,9 @@ local function finishRound(match: Match)
for _, entry in participants do for _, entry in participants do
local player = entry.player local player = entry.player
match.eligible[player] = entry.side match.eligible[player] = entry.side
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
player:SetAttribute("RoundRespawnAt", nil)
player:SetAttribute("ArenaIntermission", true) player:SetAttribute("ArenaIntermission", true)
local wasInArena = player:GetAttribute("InArena") == true local wasInArena = player:GetAttribute("InArena") == true
player:SetAttribute("ArenaWaiting", nil) player:SetAttribute("ArenaWaiting", nil)
@@ -720,9 +832,40 @@ local function finishVote(match: Match, now: number)
startRound(match) startRound(match)
end end
local function advanceStage(match: Match, now: number): number
local profile = Profiles[match.rule]
local stage, boundary = Timeline.stage(match.startedAt or now, match.endsAt, profile.briefingSeconds,
profile.countdownSeconds, profile.finalPushSeconds, now)
local previous = match.state:GetAttribute("RoundStage")
if previous == "RoleSwap" then
return (match.state:GetAttribute("StageEndsAt") :: number?) or boundary
end
if previous ~= stage then
match.state:SetAttribute("StageEndsAt", boundary)
match.state:SetAttribute("RoundStage", stage)
if stage == "Live" or stage == "FinalPush" then
for player, team in roster do
if team ~= match.blue and team ~= match.orange then continue end
RoundPlayer.thaw(player)
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if character and humanoid and humanoid.Health > 0 and player:GetAttribute("ArenaWaiting") ~= true then
arm(player, character, humanoid)
end
end
end
end
return boundary
end
local function runMatch(match: Match) local function runMatch(match: Match)
while true do while true do
local now = workspace:GetServerTimeNow() local now = workspace:GetServerTimeNow()
local siegeDeadline = match.state:GetAttribute("SiegeEndsAt")
if match.phase == "Round" and typeof(siegeDeadline) == "number" and siegeDeadline < match.endsAt then
match.endsAt = siegeDeadline
publish(match)
end
local remaining = match.endsAt - now local remaining = match.endsAt - now
if match.phase == "Round" then if match.phase == "Round" then
local engine = match.engine local engine = match.engine
@@ -737,8 +880,23 @@ local function runMatch(match: Match)
match.rule = choices[modeRandom:NextInteger(1, #choices)] match.rule = choices[modeRandom:NextInteger(1, #choices)]
end end
startRound(match) startRound(match)
elseif remaining <= 0 or (engine and engine.step(now)) then finishRound(match) elseif remaining <= 0 then
else task.wait(math.min(remaining, if match.rule == "Siege" then SiegeConfig.CHECK_INTERVAL else .2)) end finishRound(match)
else
local boundary = advanceStage(match, now)
local wasSwap = match.state:GetAttribute("RoundStage") == "RoleSwap"
if now >= (match.liveAt or now) and engine and engine.step(now) then
finishRound(match)
else
if wasSwap and match.state:GetAttribute("RoundStage") == "Live" then
-- Режим завершил паузу и разрешил боевой этап.
match.state:SetAttribute("RoundStage", nil)
boundary = advanceStage(match, now)
end
local interval = if match.rule == "Siege" then SiegeConfig.CHECK_INTERVAL else .2
task.wait(math.min(remaining, interval, math.max(.01, boundary - now)))
end
end
elseif remaining > 0 then elseif remaining > 0 then
task.wait(remaining) task.wait(remaining)
elseif match.phase == "Break" and match.allowModeChange then elseif match.phase == "Break" and match.allowModeChange then
+14 -2
View File
@@ -3,6 +3,7 @@
local Players = game:GetService("Players") local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage") local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Modes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript) local Modes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript)
local RoundConfig = require(ReplicatedStorage:WaitForChild("Hunter"):WaitForChild("RoundConfig") :: ModuleScript)
local random = Random.new() local random = Random.new()
local ArenaSpawns = {} local ArenaSpawns = {}
@@ -20,24 +21,35 @@ function ArenaSpawns.choose(player: Player): SpawnLocation
assert(#choices > 0, arena.Name .. " has no enabled spawns for this team") assert(#choices > 0, arena.Name .. " has no enabled spawns for this team")
local best = choices[random:NextInteger(1, #choices)] local best = choices[random:NextInteger(1, #choices)]
local bestDistance = -1 local bestDistance = -1
local bestSafe: SpawnLocation? = nil
local bestSafeScore = -1
for _, marker in choices do for _, marker in choices do
local nearest = 1000 local nearest = 1000
local enemyDistance = math.huge
for _, other in Players:GetPlayers() do for _, other in Players:GetPlayers() do
local character = other.Character local character = other.Character
local root = character and character:FindFirstChild("HumanoidRootPart") local root = character and character:FindFirstChild("HumanoidRootPart")
local humanoid = character and character:FindFirstChildOfClass("Humanoid") local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if other ~= player and other:GetAttribute("InArena") == true and Modes.same(player, other) if other ~= player and other:GetAttribute("InArena") == true and Modes.same(player, other)
and root and root:IsA("BasePart") and humanoid and humanoid.Health > 0 then and root and root:IsA("BasePart") and humanoid and humanoid.Health > 0 then
nearest = math.min(nearest, (root.Position - marker.Position).Magnitude) local distance = (root.Position - marker.Position).Magnitude
nearest = math.min(nearest, distance)
local otherSide = other:GetAttribute("ArenaTeam")
if otherSide ~= nil and otherSide ~= side and other:GetAttribute("ArenaWaiting") ~= true then
enemyDistance = math.min(enemyDistance, distance)
end
end end
end end
local score = nearest + random:NextNumber(0, 24) local score = nearest + random:NextNumber(0, 24)
if enemyDistance >= RoundConfig.safeSpawnDistance and score > bestSafeScore then
bestSafe, bestSafeScore = marker, score
end
if score > bestDistance then if score > bestDistance then
bestDistance = score bestDistance = score
best = marker best = marker
end end
end end
return best return bestSafe or best
end end
function ArenaSpawns.place(character: Model, marker: SpawnLocation) function ArenaSpawns.place(character: Model, marker: SpawnLocation)
+8
View File
@@ -3,6 +3,14 @@ return table.freeze({
MATCH_DURATION = 300, MATCH_DURATION = 300,
ATTACK_DURATION = 150, ATTACK_DURATION = 150,
CAPTURE_TIME = 4, CAPTURE_TIME = 4,
CAPTURE_RADIUS = 11,
EARLY_FINISH_WHEN_ALL_TAKEN = false,
SWAP_WARNING = 10,
LIGHT_HEIGHT = 46,
MATERIALIZE_SECONDS = .6,
CAPTURE_EFFECT_SECONDS = .55,
CONFETTI_COUNT = 24,
CONTESTED_COLOR = Color3.fromRGB(255, 81, 105),
DECAY_MULTIPLIER = 0.5, DECAY_MULTIPLIER = 0.5,
HEIGHT_TOLERANCE = 7, HEIGHT_TOLERANCE = 7,
POINTS_PER_OBJECTIVE = 1, POINTS_PER_OBJECTIVE = 1,
+1 -1
View File
@@ -111,7 +111,7 @@ RunService:BindToRenderStep(renderName, Enum.RenderPriority.Camera.Value + 2, fu
local menuShown = menu ~= nil and menu.Enabled local menuShown = menu ~= nil and menu.Enabled
local resultsGui = playerGui:FindFirstChild("ArenaResults") local resultsGui = playerGui:FindFirstChild("ArenaResults")
local scoreboardShown = resultsGui ~= nil and resultsGui:GetAttribute("LiveScoreboardOpen") == true local scoreboardShown = resultsGui ~= nil and resultsGui:GetAttribute("LiveScoreboardOpen") == true
local votingShown = playerGui:GetAttribute("HunterVoting") == true local votingShown = playerGui:GetAttribute("HunterVoting") == true or playerGui:GetAttribute("HunterSpectating") == true
local inArena = player:GetAttribute("InArena") == true local inArena = player:GetAttribute("InArena") == true
UserInputService.MouseIconEnabled = not inArena or tunerShown or menuShown or scoreboardShown or votingShown UserInputService.MouseIconEnabled = not inArena or tunerShown or menuShown or scoreboardShown or votingShown
if scoreboardShown or votingShown or (not inArena and not UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton2)) then if scoreboardShown or votingShown or (not inArena and not UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton2)) then
+8
View File
@@ -44,6 +44,14 @@ gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit)
fit() fit()
local shield = UI.element("Shield", plate, UDim2.fromOffset(14, 13), nil) local shield = UI.element("Shield", plate, UDim2.fromOffset(14, 13), nil)
Instance.new("UIScale", shield).Scale = 1.13 Instance.new("UIScale", shield).Scale = 1.13
local protection = UI.element("Shield", plate, UDim2.new(1, -30, 0, -24), nil)
protection.Name = "SpawnProtection"
local function refreshProtection()
local deadline = player:GetAttribute("SpawnShield")
protection.Visible = typeof(deadline) == "number" and deadline > workspace:GetServerTimeNow()
end
player:GetAttributeChangedSignal("SpawnShield"):Connect(refreshProtection)
refreshProtection()
local text = UI.label(plate, "Value", "100", UDim2.fromOffset(46, 0), UDim2.fromOffset(55, 49), 24, UI.Ink) local text = UI.label(plate, "Value", "100", UDim2.fromOffset(46, 0), UDim2.fromOffset(55, 49), 24, UI.Ink)
text.FontFace = UI.Display text.FontFace = UI.Display
text.TextXAlignment = Enum.TextXAlignment.Left text.TextXAlignment = Enum.TextXAlignment.Left
+11 -7
View File
@@ -1,5 +1,6 @@
--!strict --!strict
local TweenService = game:GetService("TweenService") local TweenService = game:GetService("TweenService")
local Credit = require(script.Parent.ModeRuntime.HotPointCredit)
local Sites = require(script.Parent:WaitForChild("ArenaObjectiveSites") :: ModuleScript) local Sites = require(script.Parent:WaitForChild("ArenaObjectiveSites") :: ModuleScript)
type Side = "Blue" | "Orange" type Side = "Blue" | "Orange"
@@ -8,6 +9,7 @@ export type Marker = {body: Part, label: TextLabel, origin: Vector3}
type Config = { type Config = {
state: Instance, geometry: RaycastParams, sites: {Sites.Site}, startedAt: number, state: Instance, geometry: RaycastParams, sites: {Sites.Site}, startedAt: number,
marker: (Sites.Site) -> Marker, score: (Side, number) -> (), status: (string) -> (), marker: (Sites.Site) -> Marker, score: (Side, number) -> (), status: (string) -> (),
contribute: ((Player, string, number) -> ())?,
} }
type Capture = { type Capture = {
step: ({Fighter}, number, number) -> (), hit: (Player, number, boolean) -> (), step: ({Fighter}, number, number) -> (), hit: (Player, number, boolean) -> (),
@@ -28,7 +30,8 @@ local neutral = Color3.fromRGB(183, 132, 255)
local contested = Color3.fromRGB(255, 211, 124) local contested = Color3.fromRGB(255, 211, 124)
local teamColor: {[Side]: Color3} = {Blue = Color3.fromRGB(76, 228, 255), Orange = Color3.fromRGB(255, 81, 105)} local teamColor: {[Side]: Color3} = {Blue = Color3.fromRGB(76, 228, 255), Orange = Color3.fromRGB(255, 81, 105)}
function HotPoint.attachRing(mark: Marker): (Color3) -> () function HotPoint.attachRing(mark: Marker, radius: number?): (Color3) -> ()
local r = radius or HotPoint.Radius
local body = mark.body local body = mark.body
body.Transparency = .92 body.Transparency = .92
local beams: {Beam} = {} local beams: {Beam} = {}
@@ -37,7 +40,7 @@ function HotPoint.attachRing(mark: Marker): (Color3) -> ()
local radial = Vector3.new(math.cos(angle), 0, math.sin(angle)) local radial = Vector3.new(math.cos(angle), 0, math.sin(angle))
local tangent = Vector3.new(-radial.Z, 0, radial.X) local tangent = Vector3.new(-radial.Z, 0, radial.X)
local item = Instance.new("Attachment") local item = Instance.new("Attachment")
local world = CFrame.fromMatrix(mark.origin + radial * HotPoint.Radius + Vector3.yAxis * height, tangent, Vector3.yAxis) local world = CFrame.fromMatrix(mark.origin + radial * r + Vector3.yAxis * height, tangent, Vector3.yAxis)
item.CFrame = body.CFrame:ToObjectSpace(world) item.CFrame = body.CFrame:ToObjectSpace(world)
item.Parent = body item.Parent = body
return item return item
@@ -47,7 +50,7 @@ function HotPoint.attachRing(mark: Marker): (Color3) -> ()
for index = 0, 3 do for index = 0, 3 do
table.insert(corners, anchor(index * math.pi / 2, height)) table.insert(corners, anchor(index * math.pi / 2, height))
end end
local handle = 4 * (math.sqrt(2) - 1) / 3 * HotPoint.Radius local handle = 4 * (math.sqrt(2) - 1) / 3 * r
for index, start in corners do for index, start in corners do
local beam = Instance.new("Beam") local beam = Instance.new("Beam")
beam.Name = name beam.Name = name
@@ -221,6 +224,7 @@ function HotPoint.start(config: Config): Capture
for _, fighter in fighters do for _, fighter in fighters do
if not isInside(fighter, site.position) then continue end if not isInside(fighter, site.position) then continue end
table.insert(inside, fighter) table.insert(inside, fighter)
if config.contribute then config.contribute(fighter.player, "holdSeconds", dt) end
if fighter.side == "Blue" then blue += 1 else orange += 1 end if fighter.side == "Blue" then blue += 1 else orange += 1 end
end end
local remaining = math.ceil(movesAt - now) local remaining = math.ceil(movesAt - now)
@@ -245,15 +249,15 @@ function HotPoint.start(config: Config): Capture
end end
local underFire = now < hitUntil local underFire = now < hitUntil
local damageTime = math.max(0, math.min(now, hitUntil) - math.max(now - dt, hitSince)) local damageTime = math.max(0, math.min(now, hitUntil) - math.max(now - dt, hitSince))
if damageTime > 0 then credit = math.max(0, credit - damageTime * HIT_DECAY) end
if not isContested then
local count = if side == "Blue" then blue else orange local count = if side == "Blue" then blue else orange
credit += (dt - damageTime) * (if count >= 2 then TEAM_SPEED else 1) credit = Credit.advance(credit, dt, damageTime, HIT_DECAY, if count >= 2 then TEAM_SPEED else 1, isContested)
end
if credit >= CAPTURE_SECONDS then if credit >= CAPTURE_SECONDS then
capturedSide, capturedAt = side, now capturedSide, capturedAt = side, now
movesAt = now + COLLAPSE_SECONDS + CAPTURE_NOTICE_SECONDS + NEXT_POINT_WARNING_SECONDS movesAt = now + COLLAPSE_SECONDS + CAPTURE_NOTICE_SECONDS + NEXT_POINT_WARNING_SECONDS
config.score(side, 1) config.score(side, 1)
if config.contribute then
for player in capturers do config.contribute(player, "captures", 1) end
end
clearCapture() clearCapture()
publish(nil, 0, nil) publish(nil, 0, nil)
config.status("") config.status("")
+1 -1
View File
@@ -19,7 +19,7 @@ gui.DisplayOrder = 25
gui.Enabled = false gui.Enabled = false
gui.Parent = playerGui gui.Parent = playerGui
local panel = UI.plate(gui, "Direction", UDim2.fromScale(.5, .78), UDim2.new(.85, 0, 0, 60), UI.Outline) local panel = UI.plate(gui, "Direction", UDim2.fromScale(.5, .68), UDim2.new(.85, 0, 0, 60), UI.Outline)
panel.AnchorPoint = Vector2.new(.5, .5) panel.AnchorPoint = Vector2.new(.5, .5)
local sizeLimit = Instance.new("UISizeConstraint") local sizeLimit = Instance.new("UISizeConstraint")
sizeLimit.MaxSize = Vector2.new(326, 60) sizeLimit.MaxSize = Vector2.new(326, 60)
+8
View File
@@ -0,0 +1,8 @@
--!strict
return table.freeze({
ZoneStarted = "ZoneStarted", ZoneCaptured = "ZoneCaptured", ZoneContested = "ZoneContested", ZoneLost = "ZoneLost",
FullControl = "FullControl", AllObjectivesTaken = "AllObjectivesTaken", FlagPicked = "FlagPicked", FlagDropped = "FlagDropped",
FlagReturned = "FlagReturned", FlagScored = "FlagScored", TokenDropped = "TokenDropped", TokensBanked = "TokensBanked", TokensLost = "TokensLost",
LeaderAssigned = "LeaderAssigned", LeaderDown = "LeaderDown", MiniRoundStarted = "MiniRoundStarted",
MiniRoundEnded = "MiniRoundEnded", RoleSwap = "RoleSwap", Streak = "Streak",
})
+24
View File
@@ -0,0 +1,24 @@
--!strict
export type Hint = {key: string, text: string, priority: number, cooldown: number?, ttl: number?}
export type State = {shownAt: {[string]: number}, current: Hint?, currentUntil: number}
local Hints = {DEFAULT_COOLDOWN = 3, DEFAULT_TTL = 3}
function Hints.new(): State return {shownAt = {}, current = nil, currentUntil = 0} end
function Hints.pick(state: State, candidates: {Hint}, now: number): Hint?
local current = state.current
if current and now >= state.currentUntil then state.current, current = nil, nil end
local best: Hint? = nil
for _, hint in candidates do
local active = current ~= nil and current.key == hint.key
local last = state.shownAt[hint.key]
if (active or last == nil or now - last >= (hint.cooldown or Hints.DEFAULT_COOLDOWN))
and (best == nil or hint.priority > best.priority) then best = hint end
end
if best and (not current or best.key == current.key or best.priority > current.priority) then
state.current = best
state.currentUntil = now + (best.ttl or Hints.DEFAULT_TTL)
state.shownAt[best.key] = now
return best
end
return current
end
return Hints
+35
View File
@@ -0,0 +1,35 @@
--!strict
local Siege = require(script.Parent.Parent:WaitForChild("CitadelAssaultConfig") :: ModuleScript)
export type ModeProfile = {
id: string, roundSeconds: number, briefingSeconds: number, countdownSeconds: number,
finalPushSeconds: number, respawnDelay: number, spawnProtection: number,
goal: string, rules: {string}, scoreMultiplierInFinalPush: number,
}
local ROUND_SECONDS = 300
local function profile(id: string, goal: string, rules: {string}, roundSeconds: number?, finalPush: number?): ModeProfile
assert(#rules == 3, id .. ": нужно ровно три правила")
return table.freeze({
id = id, roundSeconds = roundSeconds or ROUND_SECONDS, briefingSeconds = 5, countdownSeconds = 3,
finalPushSeconds = finalPush or 30, respawnDelay = 2, spawnProtection = 2,
goal = goal, rules = table.freeze(rules), scoreMultiplierInFinalPush = 1,
})
end
local profiles: {[string]: ModeProfile} = {
TeamDeathmatch = profile("TeamDeathmatch", "Устраните больше соперников, чем они вас.",
{"Каждое устранение — 1 очко", "После гибели вы возрождаетесь", "При равном счёте — ничья"}),
HotPoint = profile("HotPoint", "Захватите активную зону раньше соперников.",
{"Оставайтесь в круге 10 секунд", "С союзником захват в 1,5 раза быстрее", "Соперник оспаривает захват"}),
Domination = profile("Domination", "Удерживайте больше точек, чем соперники.",
{"Точка берётся за 3 секунды без соперников", "Каждая ваша точка — 1 очко в секунду", "Соперники в круге прерывают захват"}),
CaptureFlag = profile("CaptureFlag", "Принесите флаг с крыши на свою базу.",
{"Флаг может взять любой игрок", "Упавший флаг лежит 20 секунд", "Доставка — 1 очко"}),
TrophyHunt = profile("TrophyHunt", "Соберите жетоны и сдайте их на базе.",
{"Жетон выпадает после устранения", "При гибели ваши жетоны выпадают", "Каждый сданный жетон — 1 очко"}),
Siege = profile("Siege", "В атаке берите рубежи, в защите удерживайте их.",
{"Рубежи берутся по очереди", "Удерживайте круг 4 секунды", "В середине матча команды меняются ролями"}, Siege.MATCH_DURATION),
OneLife = profile("OneLife", "Выиграйте три мини-раунда.",
{"В мини-раунде одна жизнь", "Выигрывает команда с большим числом живых", "Мини-раунд длится до 45 секунд"}, nil, 0),
HuntLeader = profile("HuntLeader", "Устраните лидера соперников и защитите своего.",
{"Обычное устранение — 1 очко", "Лидер соперников — 3 очка", "После гибели лидера назначается новый"}),
}
return table.freeze(profiles)
+10
View File
@@ -0,0 +1,10 @@
--!strict
return table.freeze({
safeSpawnDistance = 32,
CameraShake = false,
lateBriefingSeconds = 2,
startBannerSeconds = 1.15,
finalBannerSeconds = 3,
finalTickSeconds = 10,
mvpWeights = table.freeze({kills = 1, captures = 3, holdSeconds = .1, deliveries = 4, tokensBanked = 1, leaderKills = 3, deaths = -.25}),
})
+20
View File
@@ -0,0 +1,20 @@
--!strict
local Results = {}
function Results.clockPrecise(t: number): string
return string.format("%d:%05.2f", math.floor(t / 60), t % 60)
end
function Results.rows(times: {[string]: any}, total: number): {string}
local rows = {}
for i = 1, total do
local b, o = times["BlueTime" .. i], times["OrangeTime" .. i]
rows[i] = string.format("Рубеж %d · Синие %s · Оранжевые %s", i,
if typeof(b) == "number" then Results.clockPrecise(b) else "—",
if typeof(o) == "number" then Results.clockPrecise(o) else "—")
end
return rows
end
Results.tiebreak = "При равенстве рубежей побеждает команда, быстрее дошедшая до последнего взятого."
return table.freeze(Results)
+9
View File
@@ -0,0 +1,9 @@
--!strict
local Stage = {}
function Stage.combatAllowed(state: Instance): boolean
local stage = state:GetAttribute("RoundStage")
return stage == nil or stage == "Live" or stage == "FinalPush"
end
return table.freeze(Stage)
+160
View File
@@ -0,0 +1,160 @@
--!strict
local function team(side: string?): string
return if side == "Blue" then "Синие" elseif side == "Orange" then "Оранжевые" else "Команда"
end
local function clock(seconds: number): string
return string.format("%d:%02d", math.floor(seconds / 60), math.floor(seconds % 60))
end
local function studs(distance: number): string
local n = math.floor(distance + .5)
local m10, m100 = n % 10, n % 100
local unit = if m10 == 1 and m100 ~= 11 then "студ"
elseif m10 >= 2 and m10 <= 4 and (m100 < 12 or m100 > 14) then "студа" else "студов"
return string.format("%d %s", n, unit)
end
local siegeHints = {
far = function(n: number) return "Двигайтесь к кругу — " .. studs(n) end,
height = function(dy: number) return if dy > 0 then "Круг выше вас — найдите нужный этаж" else "Круг ниже вас — найдите нужный этаж" end,
capturing = function(percent: number) return string.format("Стойте в круге — захват %d%%", percent) end,
swap = function(seconds: number) return string.format("Смена ролей через %d с. Незавершённый захват сбросится.", seconds) end,
captured = function(index: number) return string.format("Рубеж %d взят! Следуйте к новой цели.", index) end,
defNew = function(index: number) return string.format("Не дайте взять рубеж %d!", index) end,
defLost = function(index: number, total: number) return if index <= total then string.format("Рубеж потерян! Защитите рубеж %d.", index) else "Соперники взяли последний рубеж." end,
all = "Все рубежи взяты! Держите позиции до конца атаки.",
tutorial = "Стойте в круге до заполнения полосы. Число атакующих не ускоряет захват. Защитник в круге останавливает его.",
newAttack = "Теперь вы атакуете. Возьмите первый рубеж.",
newDefense = "Теперь вы защищаете. Удерживайте первый рубеж.",
point = function(index: number, name: string) return string.format("РУБЕЖ %d · %s", index, name) end,
next = function(index: number, distance: string) return string.format("ДАЛЕЕ %d · %s", index, distance) end,
defend = "ЗАЩИТИТЕ РУБЕЖ", above = " · ВЫШЕ", below = " · НИЖЕ",
inside = "В ЗОНЕ", wrongFloor = "ДРУГОЙ ЭТАЖ", noSight = "НЕТ ВИДИМОСТИ",
blocked = "Нет прямой видимости центра — выйдите на открытое место.",
defHeight = "Вы на другом этаже и не блокируете захват.",
defBlocked = "Центр закрыт стеной. Смените позицию, чтобы блокировать захват.",
contested = "Зона оспаривается — устраните защитника.",
decay = "Захват откатывается — вернитесь в круг.",
defBlock = "Вы блокируете захват — оставайтесь в круге.",
defFar = "Враг на рубеже! Зайдите в круг, чтобы остановить захват.",
short = {
blocked = "Откройте обзор центра.", defHeight = "Смените этаж.", defBlocked = "Центр за стеной.",
contested = "Устраните защитника.", decay = "Вернитесь в круг.", defBlock = "Удерживайте круг.", defFar = "Остановите захват.",
},
}
local domination = table.freeze({
height = "Точка на другом этаже.", blocked = "Из этой позиции не видно центр точки.",
contested = function(id: string) return "Точка " .. id .. " оспаривается — захват стоит." end,
free = function(id: string) return "Точка " .. id .. " свободна — займите её." end,
lost = function(id: string) return "Точка " .. id .. " потеряна — отбейте её!" end,
hold = function(n: number) return string.format("Держите точки — +%d очков в секунду.", n) end,
control = "ПОЛНЫЙ КОНТРОЛЬ",
})
local hotHints = table.freeze({
enter = "Зайдите в круг — захват занимает 10 секунд.",
team = "С союзником захват быстрее в 1,5 раза.",
fire = "Вас обстреливают — прогресс откатывается.",
next = "Новая точка через %d с — приготовьтесь.",
captured = "Точка захвачена — следующая через %d с.",
contest = "ОСПАРИВАЕТСЯ", underFire = "ПОД ОГНЁМ", taking = "ЗАХВАТ · С СОЮЗНИКОМ ×1,5",
})
local flagHints = table.freeze({
roof="Флаг на крыше цитадели.", deliver="Несите флаг на свою базу.",
enemy="Флаг у соперника — остановите его!", escort="Сопроводите союзника с флагом.",
dropped="Флаг упал — подберите его (%d с).", dropLabel="ФЛАГ УПАЛ · %d с",
base="НА СВОЮ БАЗУ",title="ФЛАГ",escortTitle="СОПРОВОДИТЕ НОСИТЕЛЯ",
picked="ФЛАГ ВЗЯТ!", enemyPicked="СОПЕРНИКИ ВЗЯЛИ ФЛАГ!", scored="ФЛАГ ДОСТАВЛЕН! +1",
})
local trophyHints = table.freeze({
carry="У вас %d жетонов — сдайте их на базе!", near="Рядом жетоны — подберите их.",
banked="СДАНО ЖЕТОНОВ ×%d", lost="Вы погибли — жетоны выпали.",
})
local lifeHints = table.freeze({
wait = "Вы выбыли до следующего мини-раунда. Наблюдайте за союзниками.",
spectate = "Наблюдаете: %s", begin = "ВПЕРЁД! · МИНИ-РАУНД %d · %d:%d",
win = "%s выиграли мини-раунд (%d против %d)", draw = "МИНИ-РАУНД ВНИЧЬЮ",
alive = "ЖИВЫ %d · %d",
})
local leaderHints = table.freeze({
self="Вы лидер — за вас дают 3 очка.", ally="Прикройте лидера: %s", enemy="Лидер соперников: %s",
new="НОВЫЙ ЛИДЕР · %s", down="ЛИДЕР УСТРАНЁН +3",
})
local teamDeathmatch = table.freeze({
chase="Отставание %d — время рисковать!",
streak="%s · СЕРИЯ %d",
})
local function flagCarrier(name: string): string return name .. " несёт флаг" end
local round = table.freeze({
mode = "РЕЖИМ", fight = "В БОЙ!", final = "ФИНАЛЬНЫЙ РЫВОК", swap = "СМЕНА РОЛЕЙ",
attack = "Вы атакуете", defend = "Вы защищаете", respawn = "ВОЗРОЖДЕНИЕ · %d",
untilStart = "ДО НАЧАЛА БОЯ", scoreReason = "Победа по командному счёту", drawReason = "Команды набрали поровну очков",
mvp = "MVP · %s", contribution = "ВАШ ВКЛАД · %s",
highlightOrder = {"captures", "deliveries", "tokensBanked", "leaderKills", "holdSeconds", "kills"},
stats = {kills = "Устранения", deaths = "Смерти", captures = "Захваты", holdSeconds = "В зоне, с",
carries = "Подборы флага", deliveries = "Доставки", tokensBanked = "Сдано жетонов", leaderKills = "Устранено лидеров", wins = "Победы"},
contributionKeys = {
TeamDeathmatch = {"kills", "deaths"}, HotPoint = {"captures", "holdSeconds"}, Domination = {"captures", "holdSeconds"},
CaptureFlag = {"carries", "deliveries"}, TrophyHunt = {"tokensBanked", "kills"}, Siege = {"captures", "holdSeconds"},
OneLife = {"kills", "deaths"}, HuntLeader = {"leaderKills", "kills"},
},
tutorial = {
TeamDeathmatch = "Держитесь рядом с союзниками.", HotPoint = "Шевроны укажут путь к активной зоне.",
Domination = "Цвет круга показывает, кто держит точку.", CaptureFlag = "Сопровождайте своего носителя.",
TrophyHunt = "Сдавайте жетоны, пока их не потеряли.", Siege = "Сверяйте этаж и видимость центра.",
OneLife = "Выходите на бой вместе с командой.", HuntLeader = "Ищите метку над лидером соперников.",
},
finalPush = {
TeamDeathmatch = "Последний шанс изменить счёт!", HotPoint = "Боритесь за последний захват!",
Domination = "Каждая секунда на счету!", CaptureFlag = "Последний рывок к своей базе!",
TrophyHunt = "Сдайте собранные жетоны!", Siege = "Время решающего штурма!",
OneLife = "Сохраните бойцов до конца!", HuntLeader = "Защитите своего лидера!",
},
})
return table.freeze({
round = round,
studs = studs,
domination = domination,
hotHints = hotHints,
flagHints = flagHints,
trophyHints = trophyHints,
lifeHints = lifeHints,
leaderHints = leaderHints,
teamDeathmatch = teamDeathmatch,
hint = table.freeze({Siege = siegeHints}),
team = team, clock = clock,
bases = table.freeze({Blue = "БАЗА СИНИХ", Orange = "БАЗА ОРАНЖЕВЫХ"}),
hotPoint = "ГОРЯЧАЯ ТОЧКА",
leaderLabel = "ЛИДЕР",
leaders = function(blue: string?, orange: string?) return "Лидеры · " .. (blue or "—") .. " / " .. (orange or "—") end,
tokens = function(n: number) return "ЖЕТОНЫ ×" .. n end,
trophyStatus = "Сдавайте собранные жетоны на своей базе",
flagRoofLabel = "ФЛАГ · КРЫША", flagDropLabel = "ФЛАГ УПАЛ",
flagCarrierLabel = function(name: string) return name .. " · НЕСЁТ ФЛАГ" end,
flagCarrier = flagCarrier, flagReturned = "Флаг вернулся на крышу цитадели",
flagOnGround = "Флаг на земле · Подберите его", flagOnRoof = "Флаг на крыше цитадели",
dominationStatus = function(b: number, o: number) return string.format("Точки под контролем · %d / %d", b, o) end,
lifeActive = function(n: number, b: number, o: number, seconds: number)
return string.format("Мини-раунд %d · Живы %d / %d · %d с", n, b, o, seconds)
end,
lifeStart = function(n: number) return "Мини-раунд " .. n end,
lifeWaiting = "Ждём игроков в обеих командах",
lifeNext = function(s: number) return "Следующий мини-раунд через " .. s .. " с" end,
siegeSwap = "СМЕНА РОЛЕЙ", siegeComplete = "Все рубежи взяты!",
siegeStatus = function(attacker: string, index: number, total: number, percent: number, phase: string)
local reason = if phase == "Contested" then "Зона оспаривается!" elseif phase == "Decaying" then "Захват откатывается"
elseif phase == "Capturing" then "Захват идёт" else "Двигайтесь к кругу"
return string.format("%s · Рубеж %d/%d · %d%% · %s", attacker, index, total, percent, reason)
end,
feed = table.freeze({
ZoneCaptured = function(p: any)
return string.format("%s взяли %s%s", team(p.side), p.text or "точку", if p.value then " (" .. clock(p.value) .. ")" else "")
end,
ZoneLost = function(p: any) return team(p.side) .. " потеряли " .. (p.text or "точку") end,
FlagPicked = function(p: any) return flagCarrier(p.text or "Игрок") end,
FlagDropped = function(_: any) return "Флаг упал на землю" end,
FlagScored = function(p: any) return team(p.side) .. " доставили флаг" end,
TokensBanked = function(p: any) return string.format("%s сдали жетоны ×%d", team(p.side), p.value or 0) end,
LeaderDown = function(p: any) return team(p.side) .. " устранили лидера (+3)" end,
RoleSwap = function(_: any) return "Команды меняются ролями" end,
Streak = function(p: any) return string.format(teamDeathmatch.streak,p.text or "Игрок",p.value or 0) end,
}),
})
+12
View File
@@ -0,0 +1,12 @@
--!strict
local Rules={}
local STREAK={[3]=true,[5]=true,[7]=true}
local CHASE_GAP=5
function Rules.announce(kills: number): boolean
return STREAK[kills]==true
end
function Rules.chaseGap(own: number, rival: number): number?
local gap=rival-own
return if gap>=CHASE_GAP then gap else nil
end
return table.freeze(Rules)
+16
View File
@@ -0,0 +1,16 @@
--!strict
export type Stage = "Briefing" | "Countdown" | "Live" | "FinalPush" | "Ended"
local Timeline = {}
function Timeline.liveAt(startedAt: number, briefing: number, countdown: number): number
return startedAt + briefing + countdown
end
function Timeline.stage(startedAt: number, endsAt: number, briefing: number, countdown: number,
finalPush: number, now: number): (Stage, number)
local liveAt = Timeline.liveAt(startedAt, briefing, countdown)
if now < startedAt + briefing then return "Briefing", startedAt + briefing end
if now < liveAt then return "Countdown", liveAt end
if now >= endsAt then return "Ended", endsAt end
if now >= endsAt - finalPush then return "FinalPush", endsAt end
return "Live", math.max(liveAt, endsAt - finalPush)
end
return table.freeze(Timeline)
+1 -1
View File
@@ -12,7 +12,7 @@ MatchRules.All = table.freeze({
{id = "Domination", title = "Три точки", detail = "Захватывайте и удерживайте зоны, чтобы получать очки.", score = "Очки контроля"}, {id = "Domination", title = "Три точки", detail = "Захватывайте и удерживайте зоны, чтобы получать очки.", score = "Очки контроля"},
{id = "CaptureFlag", title = "Захват флага", detail = "Заберите флаг с крыши цитадели и принесите его на свою базу.", score = "Флаги"}, {id = "CaptureFlag", title = "Захват флага", detail = "Заберите флаг с крыши цитадели и принесите его на свою базу.", score = "Флаги"},
{id = "TrophyHunt", title = "Охота за трофеями", detail = "Собирайте выпавшие жетоны и сдавайте их на своей базе.", score = "Сданные жетоны"}, {id = "TrophyHunt", title = "Охота за трофеями", detail = "Собирайте выпавшие жетоны и сдавайте их на своей базе.", score = "Сданные жетоны"},
{id = "Siege", title = "Штурм цитадели", detail = "В атаке берите рубежи, в защите удерживайте их. Затем смена ролей.", score = "Захваченные рубежи"}, {id = "Siege", title = "Штурм цитадели", detail = "Обе команды по очереди атакуют три рубежа. При равенстве решает время последнего захвата.", score = "Захваченные рубежи"},
{id = "OneLife", title = "Одна жизнь", detail = "Выиграйте 3 мини-раунда. В каждом у вас одна жизнь.", score = "Победы в мини-раундах"}, {id = "OneLife", title = "Одна жизнь", detail = "Выиграйте 3 мини-раунда. В каждом у вас одна жизнь.", score = "Победы в мини-раундах"},
{id = "HuntLeader", title = "Охота на лидера", detail = "Устраняйте отмеченного лидера соперников. За него дают 3 очка.", score = "Очки за убийства"}, {id = "HuntLeader", title = "Охота на лидера", detail = "Устраняйте отмеченного лидера соперников. За него дают 3 очка.", score = "Очки за убийства"},
} :: {Rule}) } :: {Rule})
+123
View File
@@ -0,0 +1,123 @@
--!strict
local Types = require(script.Parent.Types)
local HotPoint = require(script.Parent.Parent.HotPoint)
local Sites = require(script.Parent.Parent.ArenaObjectiveSites)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
type Side = Types.Side
type Fighter = Types.Fighter
export type Marker = HotPoint.Marker & {recolor: ((Color3) -> ())?}
export type Zone = {site: Sites.Site, marker: Marker, owner: Side?, claiming: Side?, progress: number}
local sides: {Side} = {"Blue", "Orange"}
local blue = Color3.fromRGB(67, 216, 255)
local orange = Color3.fromRGB(255, 150, 68)
local gold = Color3.fromRGB(255, 220, 96)
local neutral = Color3.fromRGB(188, 150, 255)
local function opposite(side: Side): Side
return if side == "Blue" then "Orange" else "Blue"
end
local function color(side: Side?): Color3
return if side == "Blue" then blue elseif side == "Orange" then orange else neutral
end
local function sideOf(player: Player): Side?
local side = player:GetAttribute("ArenaTeam")
return if side == "Blue" then "Blue" elseif side == "Orange" then "Orange" else nil
end
local function boundsAt(position: Vector3, target: Vector3, radius: number, height: number): boolean
local delta = position - target
return math.abs(delta.Y) < height and delta.X * delta.X + delta.Z * delta.Z <= radius * radius
end
local function label(adornee: BasePart, name: string, tint: Color3, offset: number, waypoint: boolean?): TextLabel
local gui = Instance.new("BillboardGui")
gui.Name = "ObjectiveLabel"
gui.Size = UDim2.fromOffset(220, 26)
gui.StudsOffsetWorldSpace = Vector3.yAxis * offset
gui.MaxDistance = if waypoint then 710 else 170
gui.AlwaysOnTop = waypoint == true
gui.LightInfluence = 0
gui.Parent = adornee
local text = Instance.new("TextLabel")
text.Size = UDim2.fromScale(1, 1)
text.BackgroundTransparency = 1
text.Font = Enum.Font.GothamBlack
text.TextSize = 15
text.Text, text.TextColor3 = name, tint
text.TextStrokeColor3, text.TextStrokeTransparency = Color3.fromRGB(9, 13, 25), .14
text.Parent = gui
return text
end
local function marker(parent: Instance, id: string, name: string, at: Vector3, tint: Color3, diameter: number, tall: boolean?): Marker
local part = Instance.new("Part")
part.Name = id
if not tall then part:SetAttribute("ObjectiveArrow", true) end
part.Shape = if tall then Enum.PartType.Ball else Enum.PartType.Cylinder
part.Size = if tall then Vector3.new(diameter, diameter, diameter) else Vector3.new(.16, diameter, diameter)
part.CFrame = CFrame.new(at + Vector3.yAxis * (if tall then 2.4 else .12)) * CFrame.Angles(0, 0, math.pi / 2)
part.Anchored, part.CanCollide, part.CanQuery, part.CanTouch, part.CastShadow = true, false, false, false, false
part.Material, part.Color = Enum.Material.Neon, tint
part.Transparency = if tall then .04 else .76
local aura = Instance.new("PointLight")
aura.Range, aura.Brightness, aura.Color = if tall then 13 else 9, .7, tint
aura.Parent = part
part.Parent = parent
return {body = part, label = label(part, name, tint, if tall then 2.1 else 4, id ~= "Tokens"), origin = at}
end
local function ring(parent: Instance, id: string, name: string, at: Vector3, tint: Color3, radius: number?): Marker
local r = radius or HotPoint.Radius
local mark = marker(parent, id, name, at, tint, r * 2)
local recolor = HotPoint.attachRing(mark, r)
mark.recolor = recolor
recolor(tint)
return mark
end
local function paint(mark: Marker, tint: Color3)
if mark.body.Color == tint then return end
if mark.recolor then
mark.recolor(tint)
return
end
mark.body.Color = tint
mark.label.TextColor3 = tint
local aura = mark.body:FindFirstChildOfClass("PointLight")
if aura then aura.Color = tint end
end
local function visibleAt(fighter: Fighter, at: Vector3, geometry: RaycastParams): boolean
return workspace:Raycast(fighter.root.Position, at - fighter.root.Position, geometry) == nil
end
local function makeZone(folder: Folder, geometry: RaycastParams, site: Sites.Site, name: string, radius: number?, tint: Color3?): Zone
local r = radius or HotPoint.Radius
local center, fits = Sites.clearCircle(site.position, geometry, r)
if radius and not fits then warn("Нет свободного места для рубежа:", site.name) end
site = {name = site.name, position = center}
return {site = site, marker = ring(folder, name, site.name, center, tint or neutral, r), owner = nil, claiming = nil, progress = 0}
end
local function bases(folder: Folder, geometry: RaycastParams, map: Sites.Map)
map.blue = Sites.clearCircle(map.blue, geometry, HotPoint.Radius)
map.orange = Sites.clearCircle(map.orange, geometry, HotPoint.Radius)
for _, side in sides do
local at = if side == "Blue" then map.blue else map.orange
ring(folder, side .. "Base", Strings.bases[side], at, color(side))
end
end
local function winner(scoring: Types.Scoring): (string, string?)
local b, o = scoring.get("Blue"), scoring.get("Orange")
local side = if b == o then "Draw" elseif b > o then "Blue" else "Orange"
return side, nil
end
local function instance(ctx: Types.ModeContext, callbacks: {[string]: any}): Types.ModeInstance
local function noop() end
return {
step = callbacks.step or function() return false end, kill = callbacks.kill or noop,
hit = callbacks.hit, death = callbacks.death or noop, leaving = callbacks.leaving or noop,
winner = callbacks.winner or function() return winner(ctx.scoring) end, destroy = callbacks.destroy or noop,
}
end
return {sides = sides, blue = blue, orange = orange, gold = gold, neutral = neutral, opposite = opposite,
color = color, sideOf = sideOf, boundsAt = boundsAt, label = label, marker = marker, ring = ring,
paint = paint, visibleAt = visibleAt, makeZone = makeZone, bases = bases, instance = instance}
+62
View File
@@ -0,0 +1,62 @@
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ArenaModes = require(ReplicatedStorage.ArenaModes)
local Sites = require(script.Parent.Parent.ArenaObjectiveSites)
local Types = require(script.Parent.Types)
local Common = require(script.Parent.Common)
local Scoring = require(script.Parent.Scoring)
local Events = require(script.Parent.Events)
local Janitor = require(script.Parent.Janitor)
local Stats = require(script.Parent.Stats)
local Profiles = require(ReplicatedStorage.Hunter.ModeProfiles)
local Context = {}
function Context.collect(members: {Player}): {Types.Fighter}
local found: {Types.Fighter} = {}
for _, p in members do
local side = Common.sideOf(p)
local c = p.Character
local h = c and c:FindFirstChildOfClass("Humanoid")
local r = c and c:FindFirstChild("HumanoidRootPart")
if side and h and h.Health > 0 and r and r:IsA("BasePart") and p:GetAttribute("InArena") == true
and p:GetAttribute("ArenaWaiting") ~= true then
table.insert(found, {player = p, side = side, root = r})
end
end
return found
end
function Context.create(config: Types.Config, mode: Types.Mode, legacy: RemoteEvent): Types.ModeContext
local state = config.state
local world = ArenaModes.geometry(config.arena)
local geometry = ArenaModes.collision(config.arena)
local map = if mode.usesMap then Sites.resolve(config.arena) else nil
local folder = Instance.new("Folder")
folder.Name = "MatchObjectives"
folder.Parent = world
local janitor = Janitor.new()
state:SetAttribute("ObjectiveStatus", "")
state:SetAttribute("ResultReason", nil)
return {
arena = config.arena, rule = config.rule, state = state, liveAt = config.now, duration = config.duration,
world = world, geometry = geometry, map = map, folder = folder, janitor = janitor,
members = config.members, bench = config.bench, deploy = config.deploy, balanceWaiting = config.balanceWaiting,
scoring = Scoring.new(state, nil, Profiles[config.rule].scoreMultiplierInFinalPush),
contribute = Stats.add,
events = Events.new(config.members),
status = function(value)
if state:GetAttribute("ObjectiveStatus") ~= value then state:SetAttribute("ObjectiveStatus", value) end
end,
setStage = function(stage, stageEndsAt)
if stageEndsAt then state:SetAttribute("StageEndsAt", stageEndsAt) end
state:SetAttribute("RoundStage", stage)
end,
cue = function(fighters, captured, side)
for _, fighter in fighters do
if captured or fighter.side == side then legacy:FireClient(fighter.player, captured) end
end
end,
legacy = function(player, name) legacy:FireClient(player, name) end,
}
end
return Context
+10
View File
@@ -0,0 +1,10 @@
--!strict
local Rules = {CAPTURE_SECONDS = 3}
function Rules.claimSide(blue: boolean, orange: boolean): ("Blue" | "Orange")?
return if blue == orange then nil elseif blue then "Blue" else "Orange"
end
function Rules.tick(now: number, nextAt: number): (boolean, number)
if now < nextAt then return false, nextAt end
return true, now + 1
end
return table.freeze(Rules)
+24
View File
@@ -0,0 +1,24 @@
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local Types = require(script.Parent.Types)
local existing = ReplicatedStorage:FindFirstChild("ArenaObjectiveEvent")
local remote = if existing and existing:IsA("RemoteEvent") then existing else Instance.new("RemoteEvent")
remote.Name = "ArenaObjectiveEvent"
remote.Parent = ReplicatedStorage
local Events = {}
function Events.new(members: () -> {Player}): Types.Events
return {fire = function(kind, payload, audience)
local packet = table.clone(payload or {}) :: {[string]: any}
packet.t = workspace:GetServerTimeNow()
for _, player in members() do
if player.Parent ~= Players then continue end
local side = player:GetAttribute("ArenaTeam")
local want = audience == nil or audience == "All" or audience == side
if not want and typeof(audience) == "table" then want = table.find(audience, player) ~= nil end
if want then remote:FireClient(player, kind, packet) end
end
end}
end
return Events
+6
View File
@@ -0,0 +1,6 @@
--!strict
local Rules = {RETURN_SECONDS = 20}
function Rules.remaining(deadline: number, now: number): number
return math.max(0, math.ceil(deadline - now))
end
return table.freeze(Rules)
+8
View File
@@ -0,0 +1,8 @@
--!strict
local Credit = {}
function Credit.advance(value: number, elapsed: number, underFire: number, decay: number, speed: number, contested: boolean): number
if underFire > 0 then value = math.max(0, value - underFire * decay) end
if not contested then value += (elapsed - underFire) * speed end
return value
end
return table.freeze(Credit)
+18
View File
@@ -0,0 +1,18 @@
--!strict
local Types = require(script.Parent.Types)
local Janitor = {}
function Janitor.new(): Types.Janitor
local items: {(() -> ()) | Instance | RBXScriptConnection} = {}
return {
give = function(item) table.insert(items, item) end,
clean = function()
for i = #items, 1, -1 do
local item = table.remove(items, i)
if typeof(item) == "Instance" then item:Destroy()
elseif typeof(item) == "RBXScriptConnection" then item:Disconnect()
else item() end
end
end,
}
end
return Janitor
+9
View File
@@ -0,0 +1,9 @@
--!strict
local Rules = {}
function Rules.points(isLeader: boolean): number
return if isLeader then 3 else 1
end
function Rules.nextIndex(index: number, count: number, sameAsPrevious: boolean): number
return if count > 1 and sameAsPrevious then index%count+1 else index
end
return table.freeze(Rules)
+189
View File
@@ -0,0 +1,189 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
local Context = require(Runtime.Context)
local Rules = require(Runtime.FlagRules)
local HotPoint = require(Runtime.Parent.HotPoint)
type Fighter = Types.Fighter
type Flag = {
marker: Common.Marker, stars: ParticleEmitter, mist: ParticleEmitter, light: PointLight, banner: BasePart,
carrier: Player?, tether: WeldConstraint?, droppedUntil: number,
}
local function makeFlag(parent: Instance, roof: Vector3): Flag
local mark = Common.marker(parent, "CitadelFlag", Strings.flagRoofLabel, roof, Common.gold, 2.6, true)
local body = mark.body
body.Transparency = 1
body.CFrame = CFrame.new(body.Position)
local light = assert(body:FindFirstChildOfClass("PointLight"))
light.Range, light.Brightness = 21, 1.6
local function attach(name: string, size: Vector3, offset: Vector3, tint: Color3): Part
local part = Instance.new("Part")
part.Name, part.Size, part.Color = name, size, tint
part.CFrame = body.CFrame + offset
part.Material = Enum.Material.Neon
part.Massless, part.CanCollide, part.CanTouch, part.CanQuery = true, false, false, false
part.Parent = body
local weld = Instance.new("WeldConstraint")
weld.Part0, weld.Part1, weld.Parent = body, part, part
return part
end
attach("Pole", Vector3.new(.17, 4.5, .17), Vector3.zero, Color3.fromRGB(235, 235, 255))
local banner = attach("Banner", Vector3.new(2.65, 1.48, .15), Vector3.new(1.35, 1.45, 0), Common.gold)
attach("CrownLight", Vector3.new(.33, .33, .33), Vector3.yAxis * 2.34, Common.neutral).Shape = Enum.PartType.Ball
local aura = Instance.new("Attachment")
aura.Name = "FlagAura"
aura.Position = -Vector3.yAxis * 1.75
aura.Parent = body
local stars = Instance.new("ParticleEmitter")
stars.Name = "Stars"
stars.Texture = "rbxasset://textures/particles/sparkles_main.dds"
stars.Color = ColorSequence.new(Common.neutral, Common.gold)
stars.LightEmission, stars.LightInfluence = 1, 0
stars.Rate, stars.Speed, stars.Lifetime = 24, NumberRange.new(3, 6), NumberRange.new(.7, 1.4)
stars.SpreadAngle = Vector2.new(65, 65)
stars.Rotation, stars.RotSpeed = NumberRange.new(-180, 180), NumberRange.new(-90, 90)
stars.Size = NumberSequence.new({NumberSequenceKeypoint.new(0, .22), NumberSequenceKeypoint.new(.4, .52), NumberSequenceKeypoint.new(1, 0)})
stars.Parent = aura
local mist = Instance.new("ParticleEmitter")
mist.Name = "ColoredMist"
mist.Texture = "rbxasset://textures/particles/smoke_main.dds"
mist.Color = ColorSequence.new(Common.neutral, Common.gold)
mist.LightEmission, mist.LightInfluence = .55, 0
mist.Rate, mist.Speed, mist.Lifetime = 9, NumberRange.new(1, 4), NumberRange.new(.7, 1.2)
mist.SpreadAngle = Vector2.new(110, 110)
mist.Size = NumberSequence.new(1.4, 4)
mist.Transparency = NumberSequence.new({NumberSequenceKeypoint.new(0, .72), NumberSequenceKeypoint.new(.45, .79), NumberSequenceKeypoint.new(1, 1)})
mist.Parent = aura
return {marker = mark, stars = stars, mist = mist, light = light, banner = banner,
carrier = nil, tether = nil, droppedUntil = 0}
end
local function start(ctx: Types.ModeContext): Types.ModeInstance
local map, geometry = assert(ctx.map), ctx.geometry
local flag = makeFlag(ctx.folder, map.roof.position)
Common.bases(ctx.folder, geometry, map)
local state = ctx.state
local lastSeconds = -1
state:SetAttribute("FlagPosition", flag.marker.origin)
state:SetAttribute("FlagBase_Blue", map.blue)
state:SetAttribute("FlagBase_Orange", map.orange)
local function putFlag(object: Flag, at: Vector3, droppedUntil: number)
if object.carrier then object.carrier:SetAttribute("ArenaFlag", nil) end
if object.tether then object.tether:Destroy() end
object.carrier, object.tether, object.droppedUntil = nil, nil, droppedUntil
state:SetAttribute("FlagCarrierSide", nil)
state:SetAttribute("FlagPosition", at)
state:SetAttribute("FlagReturnAt", if droppedUntil > 0 then droppedUntil else nil)
lastSeconds = -1
local mark = object.marker
mark.body.Anchored = true
mark.body.CFrame = CFrame.new(at + Vector3.yAxis * 2.4)
mark.label.Text = if droppedUntil > 0 then Strings.flagDropLabel else Strings.flagRoofLabel
mark.label.TextColor3, object.banner.Color = Common.gold, Common.gold
object.stars.Enabled, object.mist.Enabled, object.light.Enabled = true, true, true
object.stars:Emit(16)
end
local function pickUpFlag(object: Flag, fighter: Fighter)
local body = object.marker.body
body.CFrame = fighter.root.CFrame * CFrame.new(0, 3.15, .65)
body.Massless = true
local tether = Instance.new("WeldConstraint")
tether.Part0, tether.Part1 = body, fighter.root
tether.Parent = body
body.Anchored = false
object.carrier, object.tether, object.droppedUntil = fighter.player, tether, 0
fighter.player:SetAttribute("ArenaFlag", true)
state:SetAttribute("FlagCarrierSide", fighter.side)
state:SetAttribute("FlagReturnAt", nil)
state:SetAttribute("FlagPosition", fighter.root.Position)
local tint = Common.color(fighter.side)
object.marker.label.Text = Strings.flagCarrierLabel(fighter.player.DisplayName)
object.marker.label.TextColor3, object.banner.Color = tint, tint
object.stars.Enabled, object.mist.Enabled, object.light.Enabled = false, false, false
object.stars:Clear()
object.mist:Clear()
end
local function dropCarried(player: Player, at: Vector3?, now: number, fighters: {Fighter}?)
if flag.carrier == player then
if at then
local floor = workspace:Raycast(at + Vector3.yAxis * .3, -Vector3.yAxis * 50, geometry)
if floor then
putFlag(flag, floor.Position, now + Rules.RETURN_SECONDS)
for _, fighter in (fighters or Context.collect(ctx.members())) do ctx.legacy(fighter.player, "FlagDropped") end
ctx.events.fire(Kinds.FlagDropped, {at = floor.Position})
else
putFlag(flag, flag.marker.origin, 0)
ctx.events.fire(Kinds.FlagReturned, {at = flag.marker.origin})
end
else
putFlag(flag, flag.marker.origin, 0)
ctx.events.fire(Kinds.FlagReturned, {at = flag.marker.origin})
end
end
end
local function runFlag(fighters: {Fighter}, now: number)
if flag.carrier then
for _, fighter in fighters do
if fighter.player ~= flag.carrier then continue end
state:SetAttribute("FlagPosition", fighter.root.Position)
state:SetAttribute("FlagCarrierSide", fighter.side)
local base = if fighter.side == "Blue" then map.blue else map.orange
if Common.boundsAt(fighter.root.Position, base, HotPoint.Radius, 7) then
ctx.scoring.add(fighter.side, 1, Kinds.FlagScored, fighter.player)
ctx.contribute(fighter.player, "deliveries", 1)
ctx.events.fire(Kinds.FlagScored, {side = fighter.side, userId = fighter.player.UserId})
ctx.cue(fighters, true, nil)
putFlag(flag, flag.marker.origin, 0)
ctx.events.fire(Kinds.FlagReturned, {at = flag.marker.origin})
ctx.status(Strings.flagReturned)
end
return
end
local carrier = flag.carrier
local root = carrier.Character and carrier.Character.PrimaryPart
dropCarried(carrier, root and root.Position, now, fighters)
return
elseif flag.droppedUntil > 0 and now >= flag.droppedUntil then
putFlag(flag, flag.marker.origin, 0)
ctx.events.fire(Kinds.FlagReturned, {at = flag.marker.origin})
end
if flag.droppedUntil > 0 then
local seconds = Rules.remaining(flag.droppedUntil, now)
if seconds ~= lastSeconds then
lastSeconds = seconds
flag.marker.label.Text = string.format(Strings.flagHints.dropLabel, seconds)
end
end
local at = flag.marker.body.Position
for _, fighter in fighters do
if Common.boundsAt(fighter.root.Position, at, 5.5, 6.5) and Common.visibleAt(fighter, at, geometry) then
pickUpFlag(flag, fighter)
ctx.contribute(fighter.player, "carries", 1)
ctx.events.fire(Kinds.FlagPicked, {side = fighter.side, userId = fighter.player.UserId, text = fighter.player.DisplayName})
ctx.cue(fighters, false, fighter.side)
ctx.status(Strings.flagCarrier(fighter.player.DisplayName))
return
end
end
ctx.status(if flag.droppedUntil > 0 then Strings.flagOnGround else Strings.flagOnRoof)
end
return Common.instance(ctx, {
step = function(now, _, fighters) runFlag(fighters, now); return false end,
death = dropCarried, leaving = dropCarried,
destroy = function()
if flag.carrier then flag.carrier:SetAttribute("ArenaFlag", nil) end
for _, name in {"FlagPosition","FlagCarrierSide","FlagReturnAt","FlagBase_Blue","FlagBase_Orange"} do state:SetAttribute(name,nil) end
end,
})
end
return {id = "CaptureFlag", usesMap = true, start = start}
+111
View File
@@ -0,0 +1,111 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
local Zones = require(Runtime.Zones)
local HotPoint = require(Runtime.Parent.HotPoint)
type Fighter = Types.Fighter
type Side = Types.Side
local Run = require(Runtime.DominationRules)
local RADIUS = HotPoint.Radius -- Общий радиус зон до отдельного баланса режима.
local SPEC: Zones.Spec = {radius = RADIUS, height = 8, sightHeight = 2.7, exclusiveHeight = true}
local function start(ctx: Types.ModeContext): Types.ModeInstance
local map = assert(ctx.map)
local zones: {Common.Zone} = {}
local contested: {[number]: boolean} = {}
local affected: {[Player]: boolean} = {}
local state = ctx.state
local full: Side? = nil
for i, site in {map.west, map.gallery, map.east} do
local key = string.char(64 + i)
local zone = Common.makeZone(ctx.folder, ctx.geometry, site, key)
zone.marker.label.Text = key .. " · " .. site.name
table.insert(zones, zone)
end
local function presence(fighters: {Fighter}, zone: Common.Zone, geometry: RaycastParams, dt: number, reasons: {[Player]: string}): (boolean, boolean, {Fighter})
local blue, orange = false, false
local inside: {Fighter} = {}
for _, fighter in fighters do
local reason = Zones.classify(fighter.root.Position, zone.site.position, SPEC, geometry)
if reason ~= "Outside" and reasons[fighter.player] ~= "Inside" then reasons[fighter.player] = reason end
if reason == "Inside" then
table.insert(inside, fighter)
ctx.contribute(fighter.player, "holdSeconds", dt)
if fighter.side == "Blue" then blue = true else orange = true end
end
end
return blue, orange, inside
end
local geometry = ctx.geometry
local nextScore = ctx.liveAt + 1
return Common.instance(ctx, {step = function(now, dt, fighters)
local scoreNow, nextAt = Run.tick(now, nextScore)
nextScore = nextAt
local reasons: {[Player]: string} = {}
local ownedBlue, ownedOrange = 0, 0
for index, zone in zones do
local b, o, inside = presence(fighters, zone, geometry, dt, reasons)
local key = string.char(64 + index)
if b and o and not contested[index] then ctx.events.fire(Kinds.ZoneContested, {index = index, text = key}) end
contested[index] = b and o
local side = Run.claimSide(b, o)
if side and side ~= zone.owner then
if zone.claiming ~= side then
zone.claiming, zone.progress = side, 0
ctx.cue(fighters, false, side)
end
zone.progress += dt
if zone.progress >= Run.CAPTURE_SECONDS then
local previous = zone.owner
zone.owner, zone.progress = side, 0
for _, fighter in inside do ctx.contribute(fighter.player, "captures", 1) end
local payload = {side = side, index = index, text = zone.marker.label.Text, value = now - ctx.liveAt, at = zone.site.position}
ctx.events.fire(Kinds.ZoneCaptured, payload)
if previous then ctx.events.fire(Kinds.ZoneLost, {side = previous, index = index, text = payload.text}) end
ctx.cue(fighters, true, nil)
end
else
zone.claiming, zone.progress = nil, 0
end
local shade = Common.color(zone.owner)
Common.paint(zone.marker, if contested[index] then shade:Lerp(Color3.fromRGB(80, 88, 103), .55) else shade)
state:SetAttribute("ZoneOwner_" .. key, zone.owner)
state:SetAttribute("ZoneClaim_" .. key, zone.claiming)
state:SetAttribute("ZoneProgress_" .. key, math.clamp(zone.progress / Run.CAPTURE_SECONDS, 0, 1))
state:SetAttribute("ZoneContested_" .. key, contested[index])
if zone.owner == "Blue" then ownedBlue += 1 elseif zone.owner == "Orange" then ownedOrange += 1 end
end
for player in affected do
if not reasons[player] then player:SetAttribute("DominationZone", nil); affected[player] = nil end
end
for player, reason in reasons do
affected[player] = true
player:SetAttribute("DominationZone", reason)
end
state:SetAttribute("ScoreRate_Blue", ownedBlue)
state:SetAttribute("ScoreRate_Orange", ownedOrange)
local owner: Side? = if ownedBlue == #zones then "Blue" elseif ownedOrange == #zones then "Orange" else nil
if owner ~= full then
full = owner
if owner then ctx.events.fire(Kinds.FullControl, {side = owner}) end
end
if scoreNow then
if ownedBlue > 0 then ctx.scoring.add("Blue", ownedBlue) end
if ownedOrange > 0 then ctx.scoring.add("Orange", ownedOrange) end
end
ctx.status(Strings.dominationStatus(ownedBlue, ownedOrange))
return false
end, destroy = function()
for player in affected do player:SetAttribute("DominationZone", nil) end
for _, id in {"A", "B", "C"} do
for _, name in {"ZoneOwner_", "ZoneClaim_", "ZoneProgress_", "ZoneContested_"} do state:SetAttribute(name .. id, nil) end
end
state:SetAttribute("ScoreRate_Blue", nil)
state:SetAttribute("ScoreRate_Orange", nil)
end})
end
return {id = "Domination", usesMap = true, start = start}
+41
View File
@@ -0,0 +1,41 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
local HotPoint = require(Runtime.Parent.HotPoint)
local Sites = require(Runtime.Parent.ArenaObjectiveSites)
local function start(ctx: Types.ModeContext): Types.ModeInstance
local path = Sites.hotPath(ctx.arena, assert(ctx.map), HotPoint.Radius)
local nowAt = ctx.liveAt
local wasContested = false
local capture = HotPoint.start({
state = ctx.state, geometry = ctx.geometry, sites = path, startedAt = ctx.liveAt,
marker = function(site)
ctx.events.fire(Kinds.ZoneStarted, {text = site.name, at = site.position})
return Common.marker(ctx.folder, "HotPoint", Strings.hotPoint, site.position, Common.neutral, HotPoint.Radius * 2)
end,
score = function(side, points)
ctx.scoring.add(side, points, Kinds.ZoneCaptured)
ctx.events.fire(Kinds.ZoneCaptured, {side = side, text = Strings.hotPoint, value = nowAt - ctx.liveAt})
end,
status = ctx.status, contribute = ctx.contribute,
})
return Common.instance(ctx, {
step = function(now, dt, fighters, elapsed)
nowAt = now
capture.step(fighters, now, elapsed or dt)
local contested = ctx.state:GetAttribute("HotPointPhase") == "Contested"
if contested and not wasContested then
ctx.events.fire(Kinds.ZoneContested, {text = Strings.hotPoint})
end
wasContested = contested
return false
end,
hit = capture.hit, death = capture.death, leaving = capture.death, destroy = capture.destroy,
})
end
return {id = "HotPoint", usesMap = true, start = start}
+83
View File
@@ -0,0 +1,83 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
type Fighter = Types.Fighter
type Side = Types.Side
local Rules = require(Runtime.LeaderRules)
local rng = Random.new()
local function start(ctx: Types.ModeContext): Types.ModeInstance
local leaders: {[Side]: Player} = {}
local state = ctx.state
local previousLeader: {[Side]: Player} = {}
local leaderLabels: {[Player]: BillboardGui} = {}
local function clearLeader(side: Side)
local p = leaders[side]
if not p then return end
previousLeader[side] = p
leaders[side] = nil
state:SetAttribute("LeaderName_"..side,nil)
state:SetAttribute("LeaderPosition_"..side,nil)
p:SetAttribute("ArenaLeader", nil)
local badge = leaderLabels[p]
if badge then badge:Destroy() end
leaderLabels[p] = nil
end
local function updateLeaders(fighters: {Fighter})
for _, side in Common.sides do
local roster: {Fighter} = {}
local present = false
for _, f in fighters do
if f.side ~= side then continue end
table.insert(roster, f)
if f.player == leaders[side] then
present = true
state:SetAttribute("LeaderPosition_"..side,f.root.Position)
end
end
if present then continue end
clearLeader(side)
if #roster == 0 then continue end
local pick = rng:NextInteger(1, #roster)
pick = Rules.nextIndex(pick,#roster,roster[pick].player == previousLeader[side])
local p = roster[pick].player
local head = p.Character and p.Character:FindFirstChild("Head")
if not head or not head:IsA("BasePart") then continue end
leaders[side] = p
state:SetAttribute("LeaderName_"..side,p.DisplayName)
state:SetAttribute("LeaderPosition_"..side,roster[pick].root.Position)
p:SetAttribute("ArenaLeader", true)
leaderLabels[p] = Common.label(head, Strings.leaderLabel, Common.gold, 2.7).Parent :: BillboardGui
ctx.events.fire(Kinds.LeaderAssigned, {side = side, userId = p.UserId, text = p.DisplayName})
end
local a, b = leaders.Blue, leaders.Orange
ctx.status(Strings.leaders(if a then a.DisplayName else nil, if b then b.DisplayName else nil))
end
return Common.instance(ctx, {
step = function(_, _, fighters) updateLeaders(fighters); return false end,
kill = function(player, victim, at)
local side = Common.sideOf(player)
if not side then return end
local target = Common.opposite(side)
local bonus = leaders[target] == victim
ctx.scoring.add(side, Rules.points(bonus), if bonus then Kinds.LeaderDown else "Elimination", player)
if bonus then
ctx.contribute(player, "leaderKills", 1)
clearLeader(target)
ctx.events.fire(Kinds.LeaderDown, {side = side, userId = player.UserId, text = victim.DisplayName, at = at})
end
end,
death = function(player)
for _, side in Common.sides do if leaders[side] == player then clearLeader(side) end end
end,
leaving = function(player)
for _, side in Common.sides do if leaders[side] == player then clearLeader(side) end end
end,
destroy = function() for _, side in Common.sides do clearLeader(side) end end,
})
end
return {id = "HuntLeader", usesMap = false, start = start}
+68
View File
@@ -0,0 +1,68 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
local Rules = require(Runtime.OneLifeRules)
type Fighter = Types.Fighter
local function start(ctx: Types.ModeContext): Types.ModeInstance
local lifeActive, miniNumber = false, 0
local lifeEnds, nextMini = math.huge, ctx.liveAt
local state = ctx.state
local function runOneLife(members: {Player}, fighters: {Fighter}, now: number): boolean
if lifeActive then
local b, o = 0, 0
for _, f in fighters do if f.side == "Blue" then b += 1 else o += 1 end end
state:SetAttribute("MiniAliveBlue", b)
state:SetAttribute("MiniAliveOrange", o)
if (b > 0 and o > 0) and now < lifeEnds then
ctx.status(Strings.lifeActive(miniNumber, b, o, math.ceil(lifeEnds - now)))
return false
end
local side = Rules.winner(b,o)
if side then ctx.scoring.add(side, 1, Kinds.MiniRoundEnded) end
state:SetAttribute("MiniRoundActive", false)
ctx.events.fire(Kinds.MiniRoundEnded, {side = side, index = miniNumber, blue = b, orange = o})
if Rules.finished(ctx.scoring.get("Blue"),ctx.scoring.get("Orange")) then return true end
for _, p in members do ctx.bench(p) end
lifeActive, nextMini = false, now + Rules.INTERMISSION
end
if now >= nextMini then ctx.balanceWaiting() end
local ready: {Player} = {}
local b, o = false, false
for _, p in members do
local c = p.Character
local h = c and c:FindFirstChildOfClass("Humanoid")
if not c or not c.PrimaryPart or not h or h.Health <= 0 then continue end
table.insert(ready, p)
if Common.sideOf(p) == "Blue" then b = true else o = true end
end
if b and o and now >= nextMini then
for _, p in ready do ctx.deploy(p) end
miniNumber += 1
lifeActive, lifeEnds = true, now + Rules.DURATION
state:SetAttribute("MiniRoundActive",true)
state:SetAttribute("MiniRoundNextAt",nil)
ctx.status(Strings.lifeStart(miniNumber))
ctx.events.fire(Kinds.MiniRoundStarted, {index = miniNumber, blue = ctx.scoring.get("Blue"), orange = ctx.scoring.get("Orange")})
elseif not b or not o then
state:SetAttribute("MiniRoundNextAt",nil)
ctx.status(Strings.lifeWaiting)
else
state:SetAttribute("MiniRoundNextAt",nextMini)
ctx.status(Strings.lifeNext(math.ceil(nextMini - now)))
end
return false
end
return Common.instance(ctx, {
step = function(now, _, fighters) return runOneLife(ctx.members(), fighters, now) end,
death = function(player) ctx.bench(player) end,
destroy = function()
for _, name in {"MiniRoundActive","MiniRoundNextAt","MiniAliveBlue","MiniAliveOrange"} do state:SetAttribute(name,nil) end
end,
})
end
return {id = "OneLife", usesMap = true, start = start}
+200
View File
@@ -0,0 +1,200 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
local CollectionService = game:GetService("CollectionService")
local Zones = require(Runtime.Zones)
local Effects = require(Runtime.SiegeEffects)
local Sites = require(Runtime.Parent.ArenaObjectiveSites)
local SiegeConfig = require(game.ReplicatedStorage.CitadelAssaultConfig)
local Capture = require(Runtime.Parent.CitadelCaptureService)
local Score = require(Runtime.Parent.CitadelScoreService)
local SiegeSpawn = require(Runtime.Parent.CitadelSpawnService)
type Fighter = Types.Fighter
type Side = Types.Side
local SPEC: Zones.Spec = {radius = SiegeConfig.CAPTURE_RADIUS, height = SiegeConfig.HEIGHT_TOLERANCE, sightHeight = SiegeConfig.SIGHT_HEIGHT}
local function start(ctx: Types.ModeContext): Types.ModeInstance
local map, world, geometry, folder, state = assert(ctx.map), ctx.world, ctx.geometry, ctx.folder, ctx.state
local zones: {Common.Zone} = {}
local visuals: {Effects.Rig} = {}
local visibleIndex = 0
local data = Instance.new("Folder")
data.Name = "CitadelMatchState"
data.Parent = state
ctx.janitor.give(data)
data:SetAttribute("Radius", SiegeConfig.CAPTURE_RADIUS)
data:SetAttribute("BlueBase", map.blue)
data:SetAttribute("OrangeBase", map.orange)
local sites: {Sites.Site} = {map.ground, map.gallery, map.roof}
for _, point in CollectionService:GetTagged("CitadelPoint") do
if not point:IsA("BasePart") or not point:IsDescendantOf(world) then continue end
local index = point:GetAttribute("Index")
if typeof(index) == "number" and index % 1 == 0 and sites[index] then
sites[index] = {name = sites[index].name, position = point.Position}
end
end
for i, site in sites do
local zone = Common.makeZone(folder, geometry, site, "Checkpoint" .. i, SiegeConfig.CAPTURE_RADIUS, Common.gold)
zone.marker.body:SetAttribute("Index", i)
zone.marker.body.Parent = nil
ctx.janitor.give(zone.marker.body)
table.insert(zones, zone)
table.insert(visuals, Effects.new(zone.marker, folder, ctx.janitor))
end
data:SetAttribute("Total", #zones)
local siegeTimes: Score.Ledger = {Blue = {}, Orange = {}}
local siegeSide: Side = if SiegeConfig.FIRST_ATTACKER == "Orange" then "Orange" else "Blue"
local siegeIndex, siegeProgress = 1, 0
local siegeCaptureStarted = false
local hadSiegeSwap = false
local swapAt = SiegeConfig.ATTACK_DURATION
local lastStatus: string? = nil
local marked: {[Player]: boolean} = {}
local function runSiege(members: {Player}, fighters: {Fighter}, now: number, dt: number): boolean
local half = SiegeConfig.ATTACK_DURATION
local elapsed = now - ctx.liveAt
if elapsed >= swapAt and not hadSiegeSwap then
ctx.setStage("RoleSwap", ctx.liveAt + swapAt + SiegeConfig.SWAP_FREEZE)
hadSiegeSwap = true
for i, z in zones do
visuals[i].hide()
z.marker.body.Parent = nil
end
visibleIndex, lastStatus = 0, nil
siegeSide, siegeIndex, siegeProgress = Common.opposite(siegeSide), 1, 0
siegeCaptureStarted = false
local arenaSites = map
ctx.events.fire(Kinds.RoleSwap, {side = siegeSide})
local ordinals = {Blue = 0, Orange = 0}
for _, p in members do
ctx.deploy(p)
local side, character = Common.sideOf(p), p.Character
if not side or not character or not character.PrimaryPart then continue end
local attack = side == siegeSide
ordinals[side] += 1
local at = SiegeSpawn.position(world, attack, if attack then arenaSites.blue else arenaSites.orange, ordinals[side])
character:PivotTo(CFrame.new(at + Vector3.yAxis * 4))
end
end
local swap = elapsed >= swapAt and elapsed < swapAt + SiegeConfig.SWAP_FREEZE
local attackStart = if hadSiegeSwap then swapAt + SiegeConfig.SWAP_FREEZE else 0
data:SetAttribute("Phase", if swap then "RoleSwap" elseif hadSiegeSwap then "Attack2" else "Attack1")
data:SetAttribute("Attacker", siegeSide)
data:SetAttribute("Seconds", math.clamp(math.ceil((if hadSiegeSwap then half else swapAt) - (elapsed - attackStart)), 0, half))
if swap then
data:SetAttribute("Progress", 0)
data:SetAttribute("Status", "Idle")
ctx.status(Strings.siegeSwap)
return false
end
if state:GetAttribute("RoundStage") == "RoleSwap" then ctx.setStage("Live") end
if hadSiegeSwap and elapsed >= attackStart + half then return true end
local attacker = Strings.team(siegeSide)
local zone = zones[siegeIndex]
data:SetAttribute("Index", siegeIndex)
for player in marked do
if not table.find(members, player) then
player:SetAttribute("CitadelZone", nil)
marked[player] = nil
end
end
for _, player in members do marked[player] = true end
if not zone then
data:SetAttribute("Point", nil)
data:SetAttribute("NextPoint", nil)
data:SetAttribute("Status", "Complete")
for player in marked do player:SetAttribute("CitadelZone", nil) end
ctx.status(Strings.siegeComplete)
return false
end
local visual = visuals[siegeIndex]
if visibleIndex ~= siegeIndex then
visibleIndex, lastStatus = siegeIndex, nil
zone.marker.body.Parent = folder
visual.show()
ctx.events.fire(Kinds.ZoneStarted, {side = siegeSide, index = siegeIndex, text = zone.site.name, at = zone.site.position})
end
local updated: {[Player]: boolean} = {}
local attack, defense = false, false
local attackers: {Player} = {}
for _, fighter in fighters do
local reason = Zones.classify(fighter.root.Position, zone.site.position, SPEC, geometry)
if reason == "Inside" then
ctx.contribute(fighter.player, "holdSeconds", dt)
if fighter.side == siegeSide then
attack = true
table.insert(attackers, fighter.player)
else
defense = true
end
end
updated[fighter.player] = true
fighter.player:SetAttribute("CitadelZone", reason)
end
for player in marked do if not updated[player] then player:SetAttribute("CitadelZone", nil) end end
local progress, phase = Capture.advance(siegeProgress, math.min(dt, math.max(0, elapsed - attackStart)), attack, defense,
SiegeConfig.CAPTURE_TIME, SiegeConfig.DECAY_MULTIPLIER)
if phase == "Capturing" and not siegeCaptureStarted then
ctx.cue(fighters, false, siegeSide)
siegeCaptureStarted = true
elseif progress == 0 and phase ~= "Capturing" then
siegeCaptureStarted = false
end
siegeProgress = progress
data:SetAttribute("Progress", progress)
data:SetAttribute("Status", phase)
data:SetAttribute("Point", zone.site.position)
data:SetAttribute("PointName", zone.site.name)
local nextZone = zones[siegeIndex + 1]
data:SetAttribute("NextPoint", if nextZone then nextZone.site.position else nil)
local percent = math.floor(progress / SiegeConfig.HUD_PROGRESS_STEP + 1e-8) * SiegeConfig.HUD_PROGRESS_STEP * 100
ctx.status(Strings.siegeStatus(attacker, siegeIndex, #zones, percent, phase))
local teamTint = Common.color(siegeSide)
local tint = if phase == "Idle" then Common.gold elseif phase == "Contested" then SiegeConfig.CONTESTED_COLOR
elseif phase == "Decaying" then teamTint:Lerp(Color3.fromRGB(150, 162, 182), .45) else teamTint
Common.paint(zone.marker, tint)
visual.update(tint, phase, progress, phase ~= lastStatus)
if phase == "Contested" and lastStatus ~= phase then
ctx.events.fire(Kinds.ZoneContested, {side = siegeSide, index = siegeIndex, at = zone.site.position})
end
lastStatus = phase
if phase ~= "Captured" or not Score.record(siegeTimes, siegeSide, siegeIndex, elapsed - attackStart) then return false end
ctx.scoring.add(siegeSide, SiegeConfig.POINTS_PER_OBJECTIVE, Kinds.ZoneCaptured)
for _, player in attackers do ctx.contribute(player, "captures", 1) end
ctx.events.fire(Kinds.ZoneCaptured, {side = siegeSide, index = siegeIndex, text = zone.site.name, value = elapsed - attackStart})
ctx.cue(fighters, true, nil)
siegeCaptureStarted = false
data:SetAttribute(siegeSide .. "Time" .. siegeIndex, elapsed - attackStart)
visual.capture(teamTint)
siegeIndex += 1
siegeProgress = 0
if siegeIndex > #zones then
ctx.events.fire(Kinds.AllObjectivesTaken, {side = siegeSide})
if SiegeConfig.EARLY_FINISH_WHEN_ALL_TAKEN then
if hadSiegeSwap then return true end
swapAt = elapsed
state:SetAttribute("SiegeEndsAt", ctx.liveAt + swapAt + SiegeConfig.SWAP_FREEZE + half)
end
end
return false
end
return Common.instance(ctx, {
step = function(now, dt, fighters) return runSiege(ctx.members(), fighters, now, dt) end,
winner = function()
local winner, reason = Score.winner(siegeTimes, SiegeConfig.TIE_EPSILON)
state:SetAttribute("CitadelResultReason", reason)
return winner, reason
end,
death = function(p) p:SetAttribute("CitadelZone", nil) end,
leaving = function(p) marked[p] = nil; p:SetAttribute("CitadelZone", nil) end,
destroy = function()
state:SetAttribute("SiegeEndsAt", nil)
for p in marked do p:SetAttribute("CitadelZone", nil) end
end,
})
end
return {id = "Siege", usesMap = true, start = start}
@@ -0,0 +1,20 @@
--!strict
local Types = require(script.Parent.Parent.Types)
local Common = require(script.Parent.Parent.Common)
local Hunter=game.ReplicatedStorage.Hunter
local Rules=require(Hunter.TeamDeathmatchRules)
local Kinds=require(Hunter.EventKinds)
local function start(ctx: Types.ModeContext): Types.ModeInstance
return Common.instance(ctx, {kill = function(player: Player)
local side = Common.sideOf(player)
if not side then return end
ctx.scoring.add(side, 1, "Elimination", player)
local streak=player:GetAttribute("StreakKills")
if typeof(streak)=="number" and Rules.announce(streak) then
ctx.events.fire(Kinds.Streak,{side=side,userId=player.UserId,text=player.DisplayName,value=streak})
end
end})
end
return {id = "TeamDeathmatch", usesMap = false, start = start}
+100
View File
@@ -0,0 +1,100 @@
--!strict
local Runtime = script.Parent.Parent
local Types = require(Runtime.Types)
local Common = require(Runtime.Common)
local Kinds = require(game.ReplicatedStorage.Hunter.EventKinds)
local Strings = require(game.ReplicatedStorage.Hunter.Strings)
type Fighter = Types.Fighter
local HotPoint = require(Runtime.Parent.HotPoint)
local Rules = require(Runtime.TrophyRules)
local TweenService = game:GetService("TweenService")
type Drop = {marker: Common.Marker, amount: number, expires: number, fade: Tween?}
local function start(ctx: Types.ModeContext): Types.ModeInstance
local map, geometry, folder = assert(ctx.map), ctx.geometry, ctx.folder
Common.bases(folder, geometry, map)
local tokens: {Drop} = {}
local carried: {[Player]: number} = {}
local function floorAt(at: Vector3): Vector3
local hit = workspace:Raycast(at + Vector3.yAxis * .3, -Vector3.yAxis * 50, geometry)
return if hit then hit.Position else map.ground.position
end
local function tokenDrop(at: Vector3, amount: number, now: number)
local floor = floorAt(at)
ctx.events.fire(Kinds.TokenDropped, {at = floor, value = amount})
for _, existing in tokens do
if Rules.canMerge(existing.marker.origin, floor) then
existing.amount += amount
existing.expires = now + Rules.LIFETIME
if existing.fade then existing.fade:Cancel(); existing.fade = nil end
existing.marker.body.Transparency = .04
existing.marker.label.Text = Strings.tokens(existing.amount)
return
end
end
if #tokens >= Rules.MAX_DROPS then
local old = table.remove(tokens, 1)
if old.fade then old.fade:Cancel() end
old.marker.body:Destroy()
end
table.insert(tokens, {marker = Common.marker(folder, "Tokens", Strings.tokens(amount), floor, Common.gold, 1.55, true), amount = amount, expires = now + Rules.LIFETIME})
end
local function runTrophies(fighters: {Fighter}, now: number)
for i = #tokens, 1, -1 do
local token = tokens[i]
local collector: Fighter? = nil
if now < token.expires then
if token.expires - now <= Rules.FLASH_SECONDS and not token.fade then
token.fade = TweenService:Create(token.marker.body,TweenInfo.new(.38,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut,-1,true),{Transparency=.76})
token.fade:Play()
end
for _, f in fighters do
if Common.boundsAt(f.root.Position, token.marker.origin, 5, 6) and Common.visibleAt(f, token.marker.body.Position, geometry) then collector = f; break end
end
if not collector then continue end
local p = collector.player
if not carried[p] then ctx.cue(fighters, false, collector.side) end
carried[p] = (carried[p] or 0) + token.amount
p:SetAttribute("ArenaTokens", carried[p])
end
if token.fade then token.fade:Cancel() end
token.marker.body:Destroy()
table.remove(tokens, i)
end
for _, f in fighters do
local amount = carried[f.player]
if amount and Common.boundsAt(f.root.Position, if f.side == "Blue" then map.blue else map.orange, HotPoint.Radius, 7) then
ctx.scoring.add(f.side, amount, Kinds.TokensBanked, f.player)
ctx.contribute(f.player, "tokensBanked", amount)
ctx.events.fire(Kinds.TokensBanked, {side = f.side, userId = f.player.UserId, value = amount})
ctx.cue(fighters, true, nil)
carried[f.player] = nil
f.player:SetAttribute("ArenaTokens", nil)
end
end
ctx.status(Strings.trophyStatus)
end
local function drop(player: Player, at: Vector3?, now: number)
local amount = carried[player]
if not amount then return end
carried[player] = nil
player:SetAttribute("ArenaTokens", nil)
if at then
tokenDrop(at, amount, now)
ctx.events.fire(Kinds.TokensLost, {userId=player.UserId,value=amount})
end
end
return Common.instance(ctx, {
step = function(now, _, fighters) runTrophies(fighters, now); return false end,
kill = function(player, _, at, now)
if Common.sideOf(player) then tokenDrop(at, 1, now) end
end,
death = drop, leaving = drop,
destroy = function()
for p in carried do p:SetAttribute("ArenaTokens", nil) end
for _, token in tokens do if token.fade then token.fade:Cancel() end end
end,
})
end
return {id = "TrophyHunt", usesMap = true, start = start}
+9
View File
@@ -0,0 +1,9 @@
--!strict
local Rules = {WINS = 3, DURATION = 45, INTERMISSION = 4}
function Rules.winner(blue: number, orange: number): ("Blue" | "Orange")?
return if blue == orange then nil elseif blue > orange then "Blue" else "Orange"
end
function Rules.finished(blue: number, orange: number): boolean
return math.max(blue, orange) >= Rules.WINS
end
return table.freeze(Rules)
+53
View File
@@ -0,0 +1,53 @@
--!strict
local RoundState = {}
type Movement = {humanoid: Humanoid, root: BasePart, walk: number, jumpHeight: number, jumpPower: number, wasAnchored: boolean}
local frozen: {[Player]: Movement} = {}
function RoundState.thaw(player: Player)
local old = frozen[player]
if not old then return end
frozen[player] = nil
old.root.Anchored = old.wasAnchored
if old.humanoid.WalkSpeed == 0 then old.humanoid.WalkSpeed = old.walk end
if old.humanoid.JumpHeight == 0 then old.humanoid.JumpHeight = old.jumpHeight end
if old.humanoid.JumpPower == 0 then old.humanoid.JumpPower = old.jumpPower end
end
function RoundState.freeze(player: Player, character: Model, humanoid: Humanoid)
local root = character:FindFirstChild("HumanoidRootPart")
if not root or not root:IsA("BasePart") then return end
if frozen[player] and frozen[player].root == root then return end
RoundState.thaw(player)
frozen[player] = {humanoid = humanoid, root = root, walk = humanoid.WalkSpeed,
jumpHeight = humanoid.JumpHeight, jumpPower = humanoid.JumpPower, wasAnchored = root.Anchored}
root.AssemblyLinearVelocity = Vector3.zero
root.AssemblyAngularVelocity = Vector3.zero
root.Anchored = true
humanoid.WalkSpeed = 0
humanoid.JumpHeight = 0
humanoid.JumpPower = 0
end
function RoundState.clearShield(player: Player)
player:SetAttribute("SpawnShield", nil)
local character = player.Character
local old = character and character:FindFirstChild("RoundSpawnShield")
if old then old:Destroy() end
end
function RoundState.shield(player: Player, character: Model, seconds: number)
RoundState.clearShield(player)
if seconds <= 0 then return end
local untilAt = workspace:GetServerTimeNow() + seconds
local field = Instance.new("ForceField")
field.Name = "RoundSpawnShield"
field.Visible = false
field.Parent = character
player:SetAttribute("SpawnShield", untilAt)
task.delay(seconds, function()
field:Destroy()
if player:GetAttribute("SpawnShield") == untilAt then player:SetAttribute("SpawnShield", nil) end
end)
end
return RoundState
+18
View File
@@ -0,0 +1,18 @@
--!strict
local Types = require(script.Parent.Types)
local Scoring = {}
function Scoring.new(state: Instance, onAdd: ((Types.Side, number, string?, Player?) -> ())?, finalMultiplier: number?): Types.Scoring
local score: {[Types.Side]: number} = {Blue = 0, Orange = 0}
state:SetAttribute("BlueScore", 0)
state:SetAttribute("OrangeScore", 0)
return {
add = function(side, points, reason, credit)
if state:GetAttribute("RoundStage") == "FinalPush" then points *= finalMultiplier or 1 end
score[side] += points
state:SetAttribute(side .. "Score", score[side])
if onAdd then onAdd(side, points, reason, credit) end
end,
get = function(side) return score[side] end,
}
end
return Scoring
+109
View File
@@ -0,0 +1,109 @@
--!strict
local TweenService = game:GetService("TweenService")
local Runtime = script.Parent
local Common = require(Runtime.Common)
local Types = require(Runtime.Types)
local Config = require(game.ReplicatedStorage.CitadelAssaultConfig)
export type Rig = {show: () -> (), hide: () -> (), update: (Color3, string, number, boolean) -> (), capture: (Color3) -> ()}
local function newPart(name: string, parent: Instance): Part
local p = Instance.new("Part")
p.Name, p.Shape, p.Material = name, Enum.PartType.Cylinder, Enum.Material.Neon
p.CanCollide, p.CanQuery, p.CanTouch, p.Anchored, p.CastShadow = false, false, false, true, false
p.Transparency = 1
p.Parent = parent
return p
end
local Effects = {}
function Effects.new(mark: Common.Marker, folder: Folder, janitor: Types.Janitor): Rig
local root = Instance.new("Folder")
root.Name = "SiegeLight"
root.Parent = folder
local column = newPart("Column", root)
local wave = newPart("Shockwave", root)
local anchor = Instance.new("Attachment")
anchor.Parent = wave
local sparks = Instance.new("ParticleEmitter")
sparks.Texture = "rbxasset://textures/particles/sparkles_main.dds"
sparks.Speed, sparks.Lifetime, sparks.Rate = NumberRange.new(12, 25), NumberRange.new(.45, 1.2), 0
sparks.SpreadAngle = Vector2.new(145, 145)
sparks.LightEmission = 1
sparks.Parent = anchor
local diameter = Config.CAPTURE_RADIUS * 2
local rotation = CFrame.Angles(0, 0, math.pi / 2)
local floor = CFrame.new(mark.origin + Vector3.yAxis * .21) * rotation
wave.CFrame = floor
local width = 3.5
local fullColumn = CFrame.new(mark.origin + Vector3.yAxis * (Config.LIGHT_HEIGHT / 2)) * rotation
local motion: Tween? = nil
local lightMotion: Tween? = nil
local effect: Tween? = nil
local run = 0
local function cancel()
run += 1
if motion then motion:Cancel() end
if lightMotion then lightMotion:Cancel() end
if effect then effect:Cancel() end
end
local function hide()
cancel()
column.Transparency, wave.Transparency = 1, 1
sparks:Clear()
end
janitor.give(hide)
return {
hide = hide,
show = function()
hide()
mark.body:SetAttribute("ObjectiveArrowHidden", nil)
mark.label.Visible = true
mark.body.Size = Vector3.new(.16, diameter * .15, diameter * .15)
mark.body.Transparency = .92
Common.paint(mark, Common.gold)
column.Color = Common.gold
column.Size, column.CFrame = Vector3.new(.2, width, width), floor
column.Transparency = .85
local t = TweenInfo.new(Config.MATERIALIZE_SECONDS, Enum.EasingStyle.Quart, Enum.EasingDirection.Out)
motion = TweenService:Create(mark.body, t, {Size = Vector3.new(.16, diameter, diameter)})
lightMotion = TweenService:Create(column, t, {CFrame = fullColumn, Size = Vector3.new(Config.LIGHT_HEIGHT, width, width)})
motion:Play()
lightMotion:Play()
end,
update = function(tint, phase, progress, changed)
column.Color = tint
column.Transparency = if phase == "Capturing" then 1 - (.55 + .45 * progress) * .25
elseif phase == "Decaying" then .94 else .86
if phase == "Contested" and changed then
wave.Color, wave.Transparency = tint, .68
wave.Size = Vector3.new(.12, diameter, diameter)
if effect then effect:Cancel() end
effect = TweenService:Create(wave, TweenInfo.new(.25), {Transparency = 1})
effect:Play()
end
end,
capture = function(tint)
cancel()
local token = run
Common.paint(mark, Color3.new(1, 1, 1))
mark.body:SetAttribute("ObjectiveArrowHidden", true)
mark.label.Visible = false
wave.Size = Vector3.new(.11, diameter, diameter)
wave.Color, wave.Transparency = tint, .55
sparks.Color = ColorSequence.new(tint)
sparks:Emit(Config.CONFETTI_COUNT)
local t = TweenInfo.new(Config.CAPTURE_EFFECT_SECONDS, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
motion = TweenService:Create(mark.body, t, {Size = Vector3.new(.16, .1, .1), Transparency = 1})
lightMotion = TweenService:Create(column, t, {Size = Vector3.new(.2, width, width), CFrame = floor, Transparency = 1})
effect = TweenService:Create(wave, t, {Size = Vector3.new(.11, diameter * 1.6, diameter * 1.6), Transparency = 1})
motion:Play()
lightMotion:Play()
effect:Play()
task.delay(Config.CAPTURE_EFFECT_SECONDS, function()
if token == run and mark.body.Parent == folder then mark.body.Parent = nil end
end)
end,
}
end
return Effects
+40
View File
@@ -0,0 +1,40 @@
--!strict
export type Row = {userId: number, stats: {[string]: number}}
local Stats = {}
local byPlayer: {[Player]: {[string]: number}} = {}
function Stats.reset()
table.clear(byPlayer)
end
function Stats.add(player: Player, key: string, amount: number)
local record = byPlayer[player]
if not record then
record = {}
byPlayer[player] = record
end
record[key] = (record[key] or 0) + amount
end
function Stats.get(player: Player): {[string]: number}
return table.clone(byPlayer[player] or {})
end
function Stats.remove(player: Player)
byPlayer[player] = nil
end
function Stats.mvp(rows: {Row}, weights: {[string]: number}): number?
local best: number? = nil
local bestScore = -math.huge
for _, row in rows do
local score = 0
for key, weight in weights do score += (row.stats[key] or 0) * weight end
if score > bestScore or (score == bestScore and best ~= nil and row.userId < best) then
best, bestScore = row.userId, score
end
end
return best
end
return Stats
+7
View File
@@ -0,0 +1,7 @@
--!strict
local Rules = {LIFETIME = 42, FLASH_SECONDS = 8, MAX_DROPS = 60}
function Rules.canMerge(a: Vector3, b: Vector3): boolean
local d = a - b
return math.abs(d.Y) < 3 and d.X*d.X+d.Z*d.Z <= 3.5^2
end
return table.freeze(Rules)
+28
View File
@@ -0,0 +1,28 @@
--!strict
local Sites = require(script.Parent.Parent.ArenaObjectiveSites)
export type Side = "Blue" | "Orange"
export type Fighter = {player: Player, side: Side, root: BasePart}
export type Audience = "All" | Side | {Player}
export type EventPayload = {side: Side?, userId: number?, index: number?, value: number?, text: string?, at: Vector3?, blue: number?, orange: number?}
export type Janitor = {give: ((() -> ()) | Instance | RBXScriptConnection) -> (), clean: () -> ()}
export type Scoring = {add: (Side, number, string?, Player?) -> (), get: (Side) -> number}
export type Events = {fire: (string, EventPayload?, Audience?) -> ()}
export type Config = {arena: string, rule: string, state: Instance, now: number, duration: number,
members: () -> {Player}, bench: (Player) -> (), deploy: (Player) -> (), balanceWaiting: () -> ()}
export type ModeContext = {
arena: string, rule: string, state: Instance, liveAt: number, duration: number, world: Model,
geometry: RaycastParams, folder: Folder, map: Sites.Map?,
members: () -> {Player}, bench: (Player) -> (), deploy: (Player) -> (), balanceWaiting: () -> (),
scoring: Scoring, events: Events, status: (string) -> (), setStage: (string, number?) -> (), janitor: Janitor,
contribute: (Player, string, number) -> (),
cue: ({Fighter}, boolean, Side?) -> (), legacy: (Player, string) -> (),
}
export type ModeInstance = {
step: (number, number, {Fighter}, number?) -> boolean,
kill: (Player, Player, Vector3, number) -> (),
hit: ((Player, number, boolean) -> ())?,
death: (Player, Vector3?, number) -> (), leaving: (Player, Vector3?, number) -> (),
winner: () -> (string, string?), destroy: () -> (),
}
export type Mode = {id: string, usesMap: boolean, start: (ModeContext) -> ModeInstance}
return {}
+19
View File
@@ -0,0 +1,19 @@
--!strict
export type Spec = {radius: number, height: number, sightHeight: number, exclusiveHeight: boolean?}
export type Reason = "Outside" | "Height" | "Blocked" | "Inside"
local Zones = {}
function Zones.reason(delta: Vector3, spec: Spec, blocked: boolean): Reason
if delta.X * delta.X + delta.Z * delta.Z > spec.radius * spec.radius then return "Outside" end
local height = math.abs(delta.Y)
if height > spec.height or (height == spec.height and spec.exclusiveHeight) then return "Height" end
return if blocked then "Blocked" else "Inside"
end
function Zones.classify(position: Vector3, center: Vector3, spec: Spec, geometry: RaycastParams): Reason
local candidate = Zones.reason(position - center, spec, false)
if candidate ~= "Inside" then return candidate end
local target = center + Vector3.yAxis * spec.sightHeight
return if workspace:Raycast(position, target - position, geometry) then "Blocked" else "Inside"
end
return Zones
+8 -1
View File
@@ -40,7 +40,14 @@ local SOUNDS: { [string]: SoundDef } = {
Elimination = { id = "rbxassetid://15675043410", volume = 0.78, speed = 1.18, near = 0, far = 0, group = "Kill", cut = 0.52 }, Elimination = { id = "rbxassetid://15675043410", volume = 0.78, speed = 1.18, near = 0, far = 0, group = "Kill", cut = 0.52 },
StreakAccent = { id = "rbxassetid://3120909354", volume = 0.5, speed = 1, near = 0, far = 0, group = "Kill" }, -- Level_up StreakAccent = { id = "rbxassetid://3120909354", volume = 0.5, speed = 1, near = 0, far = 0, group = "Kill" }, -- Level_up
ReloadReady = { id = "rbxassetid://15675085146", volume = 0.24, speed = 1.15, near = 0, far = 0, group = "Reload", cut = 0.19 }, ReloadReady = { id = "rbxassetid://15675085146", volume = 0.24, speed = 1.15, near = 0, far = 0, group = "Reload", cut = 0.19 },
RoundCountdown = { id = "rbxassetid://113416294133952", volume = 0.48, speed = 1, near = 0, far = 0, group = "HUD" }, -- timer tick SiegeEnter = { id = "rbxassetid://113416294133952", volume = .23, speed = 1.30, near = 0, far = 0, group = "HUD" },
SiegeCharge = { id = "rbxassetid://2789428506", volume = .22, speed = 1, near = 0, far = 0, group = "HUD" },
SiegeTick = { id = "rbxassetid://113416294133952", volume = .22, speed = 1.48, near = 0, far = 0, group = "HUD" },
SiegeBlocked = { id = "rbxassetid://2789428506", volume = .25, speed = .70, near = 0, far = 0, group = "HUD" },
SiegeDecay = { id = "rbxassetid://2789428506", volume = .20, speed = .58, near = 0, far = 0, group = "HUD" },
RoundStart = { id = "rbxassetid://4612374036", volume = .27, speed = 1.15, near = 0, far = 0, group = "HUD" },
Tick = { id = "rbxassetid://113416294133952", volume = .22, speed = 1.12, near = 0, far = 0, group = "HUD" },
RoundCountdown = { id = "rbxassetid://113416294133952", volume = 0.25, speed = 1, near = 0, far = 0, group = "HUD" }, -- timer tick
ButtonHover = { id = "rbxassetid://84648433095796", volume = 0.22, speed = 1, near = 0, far = 0, group = "HUD" }, ButtonHover = { id = "rbxassetid://84648433095796", volume = 0.22, speed = 1, near = 0, far = 0, group = "HUD" },
ButtonPress = { id = "rbxassetid://121882355123711", volume = 0.27, speed = 1, near = 0, far = 0, group = "HUD" }, ButtonPress = { id = "rbxassetid://121882355123711", volume = 0.27, speed = 1, near = 0, far = 0, group = "HUD" },
FlagDropped = { id = "rbxassetid://2789428506", volume = 0.23, speed = .72, near = 0, far = 0, group = "HUD" }, FlagDropped = { id = "rbxassetid://2789428506", volume = 0.23, speed = .72, near = 0, far = 0, group = "HUD" },
+19 -4
View File
@@ -45,6 +45,11 @@ local SAMPLE_STEP = 1 / 30
local round = ReplicatedStorage:WaitForChild("ArenaRound") local round = ReplicatedStorage:WaitForChild("ArenaRound")
local ArenaModes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript) local ArenaModes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript)
local Objectives = require(script.Parent:WaitForChild("ArenaObjectives") :: ModuleScript) local Objectives = require(script.Parent:WaitForChild("ArenaObjectives") :: ModuleScript)
local Hunter = ReplicatedStorage:WaitForChild("Hunter")
local Stage = require(Hunter:WaitForChild("Stage") :: ModuleScript)
local Runtime = script.Parent:WaitForChild("ModeRuntime")
local Stats = require(Runtime:WaitForChild("Stats") :: ModuleScript)
local RoundPlayer = require(Runtime:WaitForChild("PlayerRoundState") :: ModuleScript)
local TrophyDrops = require(script.Parent:WaitForChild("TrophyDrops")) local TrophyDrops = require(script.Parent:WaitForChild("TrophyDrops"))
local PowerDrops = require(script.Parent:WaitForChild("PowerUpDrops")) local PowerDrops = require(script.Parent:WaitForChild("PowerUpDrops"))
local PowerEffects = require(script.Parent:WaitForChild("PowerUpEffects")) local PowerEffects = require(script.Parent:WaitForChild("PowerUpEffects"))
@@ -67,15 +72,16 @@ local function recordArenaKill(player: Player, victim: Player, origin: Vector3,
if side ~= "Blue" and side ~= "Orange" then return nil end if side ~= "Blue" and side ~= "Orange" then return nil end
local scoreAttribute = side .. "Kills" local scoreAttribute = side .. "Kills"
local state = ArenaModes.state(round, mode) local state = ArenaModes.state(round, mode)
Stats.add(player, "kills", 1)
player:SetAttribute("RoundKills", ((player:GetAttribute("RoundKills") :: number?) or 0) + 1) player:SetAttribute("RoundKills", ((player:GetAttribute("RoundKills") :: number?) or 0) + 1)
state:SetAttribute(scoreAttribute, ((state:GetAttribute(scoreAttribute) :: number?) or 0) + 1) state:SetAttribute(scoreAttribute, ((state:GetAttribute(scoreAttribute) :: number?) or 0) + 1)
local streak = ((player:GetAttribute("StreakKills") :: number?) or 0) + 1
player:SetAttribute("StreakUntil", now + (round:GetAttribute("StreakWindow") :: number))
player:SetAttribute("StreakKills", streak)
local match = Objectives.current(mode) local match = Objectives.current(mode)
if match then match.kill(player, victim, origin, now) end if match then match.kill(player, victim, origin, now) end
TrophyDrops.spawn(player, origin) TrophyDrops.spawn(player, origin)
PowerDrops.spawn(origin, nil, mode) PowerDrops.spawn(origin, nil, mode)
local streak = ((player:GetAttribute("StreakKills") :: number?) or 0) + 1
player:SetAttribute("StreakUntil", now + (round:GetAttribute("StreakWindow") :: number))
player:SetAttribute("StreakKills", streak)
return streak return streak
end end
@@ -125,6 +131,8 @@ local function applyHit(
player: Player, character: Model, shooter: Humanoid, model: Model, humanoid: Humanoid, player: Player, character: Model, shooter: Humanoid, model: Model, humanoid: Humanoid,
victim: Player?, hit: ShotHistory.Hit, origin: Vector3, params: RaycastParams, mode: string victim: Player?, hit: ShotHistory.Hit, origin: Vector3, params: RaycastParams, mode: string
) )
local now = workspace:GetServerTimeNow()
if not Stage.combatAllowed(ArenaModes.state(round, mode)) then return end
local eye = headOf(character) local eye = headOf(character)
if player.Character ~= character or not inMode(player, mode) or shooter.Health <= 0 if player.Character ~= character or not inMode(player, mode) or shooter.Health <= 0
or not model.Parent or humanoid.Health <= 0 or not hit.part:IsDescendantOf(model) or not model.Parent or humanoid.Health <= 0 or not hit.part:IsDescendantOf(model)
@@ -139,6 +147,11 @@ local function applyHit(
return return
end end
local shield = victim and victim:GetAttribute("SpawnShield")
if typeof(shield) == "number" and shield > now then
broadcast(mode, remote, character, hit.position)
return
end
local before = humanoid.Health local before = humanoid.Health
PowerEffects.damage(model, humanoid, math.floor(damageFor(hit.zone) + .5), workspace:GetServerTimeNow()) PowerEffects.damage(model, humanoid, math.floor(damageFor(hit.zone) + .5), workspace:GetServerTimeNow())
local damage = before - humanoid.Health local damage = before - humanoid.Health
@@ -173,7 +186,8 @@ remote.OnServerEvent:Connect(function(player: Player, direction: unknown, camera
or timestamp ~= timestamp or math.abs(timestamp) == math.huge then return end or timestamp ~= timestamp or math.abs(timestamp) == math.huge then return end
local received = workspace:GetServerTimeNow() local received = workspace:GetServerTimeNow()
local mode = ArenaModes.of(player) local mode = ArenaModes.of(player)
if player:GetAttribute("InArena") ~= true or not ArenaModes.open(round, mode, received) then return end if player:GetAttribute("InArena") ~= true or not ArenaModes.open(round, mode, received)
or not Stage.combatAllowed(ArenaModes.state(round, mode)) then return end
local oneWay = math.clamp(player:GetNetworkPing() * .5, 0, .20) local oneWay = math.clamp(player:GetNetworkPing() * .5, 0, .20)
local ageLimit = math.clamp(oneWay + .10, .12, .30) local ageLimit = math.clamp(oneWay + .10, .12, .30)
if timestamp > received + .035 or timestamp < received - ageLimit then return end if timestamp > received + .035 or timestamp < received - ageLimit then return end
@@ -198,6 +212,7 @@ remote.OnServerEvent:Connect(function(player: Player, direction: unknown, camera
world.FilterDescendantsInstances = excluded world.FilterDescendantsInstances = excluded
world.RespectCanCollide = true world.RespectCanCollide = true
if obstruction(eye, cameraOrigin, world) then return end if obstruction(eye, cameraOrigin, world) then return end
if player:GetAttribute("SpawnShield") ~= nil then RoundPlayer.clearShield(player) end
local origin, dir = cameraOrigin, direction.Unit local origin, dir = cameraOrigin, direction.Unit
local worldHit = workspace:Raycast(origin, dir * RANGE, world) local worldHit = workspace:Raycast(origin, dir * RANGE, world)
+9
View File
@@ -0,0 +1,9 @@
--!strict
return function(rules: any)
assert(rules.claimSide(true, true) == nil)
assert(rules.claimSide(true, false) == "Blue")
assert(rules.claimSide(false, true) == "Orange")
local due, nextAt = rules.tick(4.2, 1)
assert(due and nextAt == 5.2)
assert(not rules.tick(4.9, nextAt))
end
+6
View File
@@ -0,0 +1,6 @@
--!strict
return function(rules: any)
assert(rules.remaining(30,10)==20)
assert(rules.remaining(30,29.99)==1)
assert(rules.remaining(30,30)==0 and rules.remaining(30,31)==0)
end
+13
View File
@@ -0,0 +1,13 @@
--!strict
return function(hints: any)
local s = hints.new()
local low = {key = "low", text = "Подсказка", priority = 1, ttl = .4}
local high = {key = "high", text = "Приоритет", priority = 2, ttl = 1, cooldown = 3}
assert(hints.pick(s, {low}, 0) == low)
assert(hints.pick(s, {low}, .25) == low)
assert(hints.pick(s, {high, low}, .5) == high)
assert(hints.pick(s, {low}, .6) == high)
assert(hints.pick(s, {}, 1.5) == nil)
assert(hints.pick(s, {high}, 2) == nil)
assert(hints.pick(s, {high}, 3.5) == high)
end
+8
View File
@@ -0,0 +1,8 @@
--!strict
return function(credit: any)
assert(credit.advance(0, 1, 0, .8, 1, false) == 1)
assert(credit.advance(0, 1, 0, .8, 1.5, false) == 1.5)
assert(credit.advance(4, 2, 0, .8, 1, true) == 4)
assert(credit.advance(.1, 1, .75, .8, 1, true) == 0)
assert(math.abs(credit.advance(1, 1, .5, .8, 1.5, false) - 1.35) < 1e-6)
end
+5
View File
@@ -0,0 +1,5 @@
--!strict
return function(rules: any)
assert(rules.points(false)==1 and rules.points(true)==3)
assert(rules.nextIndex(1,1,true)==1 and rules.nextIndex(2,2,true)==1 and rules.nextIndex(2,3,false)==2)
end
+6
View File
@@ -0,0 +1,6 @@
--!strict
return function(rules: any)
assert(rules.winner(2,1)=="Blue" and rules.winner(1,2)=="Orange")
assert(rules.winner(2,2)==nil and rules.winner(0,0)==nil)
assert(rules.finished(3,1) and rules.finished(0,3) and not rules.finished(2,2))
end
+14
View File
@@ -0,0 +1,14 @@
--!strict
return function(scoring: any)
local state = Instance.new("Folder")
local observed: number? = nil
local score = scoring.new(state, function(side: string, points: number, reason: string)
assert(side == "Blue" and reason == "Test")
observed = points
end)
assert(state:GetAttribute("BlueScore") == 0 and state:GetAttribute("OrangeScore") == 0)
score.add("Blue", 3, "Test")
assert(observed == 3 and score.get("Blue") == 3 and state:GetAttribute("BlueScore") == 3)
assert(score.get("Orange") == 0 and state:GetAttribute("OrangeScore") == 0)
state:Destroy()
end
+18
View File
@@ -0,0 +1,18 @@
--!strict
return function(capture: any, score: any, results: any)
assert(capture.advance(0, 4, true, false, 4, .5) == 1)
assert(capture.advance(1, 4, true, true, 4, .5) == .5)
assert(capture.advance(1, 8, true, true, 4, .5) == 0)
assert(capture.advance(0, 4, false, false, 4, .5) == 0)
for count = 1, 3 do
local a, b = {}, {}
for i = 1, count do a[i], b[i] = i * 12, i * 12 + .1 end
assert(score.winner({Blue = a, Orange = b}, .05) == "Blue")
assert(score.winner({Blue = b, Orange = a}, .05) == "Orange")
assert(score.winner({Blue = a, Orange = a}, .05) == "Draw")
end
assert(score.winner({Blue = {}, Orange = {}}, .05) == "Draw")
local ledger = {Blue = {}, Orange = {}}
assert(score.record(ledger, "Blue", 1, 8) and not score.record(ledger, "Blue", 1, 9))
assert(results.rows({BlueTime1 = 72.4}, 1)[1] == "Рубеж 1 · Синие 1:12.40 · Оранжевые —")
end
+7
View File
@@ -0,0 +1,7 @@
--!strict
return function(stats: any)
assert(stats.mvp({}, {kills = 1}) == nil)
local rows = {{userId = 9, stats = {kills = 2}}, {userId = 3, stats = {captures = 1}}, {userId = 2, stats = {kills = 2}}}
assert(stats.mvp(rows, {kills = 1, captures = 3}) == 3)
assert(stats.mvp(rows, {kills = 1}) == 2)
end
@@ -0,0 +1,6 @@
--!strict
return function(rules: any)
for i=0,9 do assert(rules.announce(i)==(i==3 or i==5 or i==7)) end
assert(rules.chaseGap(10,14)==nil and rules.chaseGap(10,15)==5)
assert(rules.chaseGap(0,17)==17 and rules.chaseGap(8,1)==nil)
end
+10
View File
@@ -0,0 +1,10 @@
--!strict
return function(timeline: any)
local expected = {{0,"Briefing",5},{5,"Countdown",8},{8,"Live",78},{77.99,"Live",78},{78,"FinalPush",108},{108,"Ended",108}}
for _, row in expected do
local stage, boundary = timeline.stage(0,108,5,3,30,row[1])
assert(stage == row[2] and boundary == row[3])
end
assert(timeline.stage(0,12,5,3,30,7) == "Countdown")
assert(timeline.stage(0,12,5,3,30,8) == "FinalPush")
end
+6
View File
@@ -0,0 +1,6 @@
--!strict
return function(rules: any)
assert(rules.canMerge(Vector3.zero,Vector3.new(3.5,2.99,0)))
assert(not rules.canMerge(Vector3.zero,Vector3.new(3.51,0,0)))
assert(not rules.canMerge(Vector3.zero,Vector3.new(0,3,0)))
end
+9
View File
@@ -0,0 +1,9 @@
--!strict
return function(zones: any)
local spec = {radius = 18, height = 7, sightHeight = 2}
assert(zones.reason(Vector3.new(18.01, 0, 0), spec, true) == "Outside")
assert(zones.reason(Vector3.new(18, 7, 0), spec, false) == "Inside")
assert(zones.reason(Vector3.new(0, -7.01, 0), spec, false) == "Height")
assert(zones.reason(Vector3.new(0, -7, 0), spec, true) == "Blocked")
assert(zones.reason(Vector3.new(0, 8, 0), {radius = 18, height = 8, sightHeight = 2.7, exclusiveHeight = true}, false) == "Height")
end