Files
Hunter/scripts/ArenaRounds.server.luau
T

946 lines
36 KiB
Luau

--!strict
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Teams = game:GetService("Teams")
local Modes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript)
local Rules = require(ReplicatedStorage:WaitForChild("MatchRules") :: ModuleScript)
local Hosting = require(ReplicatedStorage:WaitForChild("HostedArena") :: ModuleScript)
local Objectives = require(script.Parent:WaitForChild("ArenaObjectives") :: 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 SiegeSpawn = require(script.Parent:WaitForChild("CitadelSpawnService") :: ModuleScript)
local SkinCatalog = require(ReplicatedStorage:WaitForChild("RifleSkinCatalog") :: ModuleScript)
local lobbySpawn = workspace:WaitForChild("HunterLobby"):WaitForChild("Arrival Spawn") :: SpawnLocation
local rifleTemplate = ReplicatedStorage:WaitForChild("ArenaEquipment"):WaitForChild("SniperRifle") :: Tool
local BREAK_SECONDS = 15
local VOTE_SECONDS = 15
local TEAM_REVEAL_SECONDS = 1.05
local TEAM_LIMIT = Hosting.MaxPlayers // 2
local hosted = Hosting.isReserved()
local hostedExit = if hosted then Instance.new("BindableEvent") else nil
if hostedExit then
hostedExit.Name = "HostedArenaExit"
hostedExit.Parent = script
end
local modeRandom = Random.new()
local function makeTeam(name: string, color: BrickColor): Team
local team = Instance.new("Team")
team.Name = name
team.TeamColor = color
team.AutoAssignable = false
team.Parent = Teams
return team
end
local roster: {[Player]: Team} = {}
local joinOrder: {[Player]: number} = {}
local placedCharacter: {[Player]: Model} = {}
local lastCountedDeath: {[Player]: Model} = {}
local lastRequest: {[Player]: number} = {}
local lastSkinCycle: {[Player]: number} = {}
local lastVote: {[Player]: number} = {}
local admitted: {[Player]: boolean} = {}
local state = Instance.new("Folder")
state.Name = "ArenaRound"
state:SetAttribute("TeamLimit", TEAM_LIMIT)
state:SetAttribute("IsHosted", hosted)
state:SetAttribute("StreakWindow", 13)
local randomState = Instance.new("Folder")
randomState.Name = "Procedural"
randomState.Parent = state
type Side = Hosting.Side
type Match = {id: string, state: Folder, blue: Team, orange: Team, phase: string, endsAt: number, order: number,
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}
local pendingJoins: {[Player]: PendingJoin} = {}
local matches: {[string]: Match} = {
[Modes.Procedural] = {
id = Modes.Procedural, state = randomState,
blue = makeTeam("Синие", BrickColor.new("Cyan")),
orange = makeTeam("Оранжевые", BrickColor.new("Deep orange")),
phase = "Setup", endsAt = 0, order = 0, rule = Rules.Default, allowModeChange = true, eligible = {}, ballots = {},
},
}
local join = Instance.new("RemoteEvent")
join.Name = "JoinTeam"
join.Parent = state
local leave = Instance.new("RemoteEvent")
leave.Name = "LeaveArena"
leave.Parent = state
local cycleSkin = Instance.new("RemoteEvent")
cycleSkin.Name = "CycleRifleSkin"
cycleSkin.Parent = state
local results = Instance.new("RemoteEvent")
results.Name = "RoundResults"
results.Parent = state
local vote = Instance.new("RemoteEvent")
vote.Name = "ModeVote"
vote.Parent = state
local function setTeam(player: Player, match: Match, side: Side)
local team = if side == "Blue" then match.blue else match.orange
roster[player] = team
player.Team = team
player.Neutral = false
player:SetAttribute("ArenaMode", match.id)
player:SetAttribute("ArenaTeam", side)
end
local function assignTeam(player: Player, match: Match, side: Side)
match.order += 1
joinOrder[player] = match.order
player:SetAttribute("HostedArenaTeamNotice", nil)
setTeam(player, match, side)
end
local function countPlayers(match: Match): (number, number)
local blueCount, orangeCount = 0, 0
for _, team in roster do
if team == match.blue then blueCount += 1 elseif team == match.orange then orangeCount += 1 end
end
return blueCount, orangeCount
end
local function countSeats(match: Match): (number, number)
local blue, orange = countPlayers(match)
for _, pending in pendingJoins do
if pending.match == match and pending.endsAt == match.endsAt then
if pending.side == "Blue" then blue += 1 else orange += 1 end
end
end
return blue, orange
end
local function latestOn(team: Team): Player?
local latest: Player? = nil
local latestOrder = 0
for player, assigned in roster do
local order = joinOrder[player]
if assigned == team and order > latestOrder then latest, latestOrder = player, order end
end
return latest
end
local function balanceWaiting(match: Match)
while true do
local blue, orange = countPlayers(match)
if math.abs(blue - orange) <= 1 then return end
local player = latestOn(if blue > orange then match.blue else match.orange)
if not player then return end
setTeam(player, match, if blue > orange then "Orange" else "Blue")
end
end
local function arm(player: Player, character: Model, humanoid: Humanoid)
local backpack = player:FindFirstChildOfClass("Backpack")
if not backpack or character:FindFirstChild("SniperRifle") then return end
local rifle = backpack:FindFirstChild("SniperRifle")
if not rifle then
local clone = rifleTemplate:Clone()
clone.CanBeDropped = false
clone:SetAttribute("Skin", SkinCatalog.get(player:GetAttribute("RifleSkin")).id)
clone.Parent = backpack
rifle = clone
end
if rifle:IsA("Tool") then humanoid:EquipTool(rifle) end
end
local function clearTools(container: Instance?)
if not container then return end
for _, child in container:GetChildren() do
if child:IsA("Tool") then child:Destroy() end
end
end
local function guardInventory(player: Player, container: Instance)
local function disarmed(): boolean
return player:GetAttribute("InArena") ~= true or player:GetAttribute("ArenaWaiting") == true
or player:GetAttribute("ArenaIntermission") == true
or not Stage.combatAllowed(randomState)
end
container.ChildAdded:Connect(function(child)
if child:IsA("Tool") and disarmed() then child:Destroy() end
end)
if disarmed() then clearTools(container) end
end
local function resetStreak(player: Player)
player:SetAttribute("StreakKills", 0)
player:SetAttribute("StreakUntil", nil)
end
local function recordDeath(player: Player, character: Model)
if not roster[player] or placedCharacter[player] ~= character or lastCountedDeath[player] == character then return end
lastCountedDeath[player] = character
Stats.add(player, "deaths", 1)
player:SetAttribute("RoundDeaths", ((player:GetAttribute("RoundDeaths") :: number?) or 0) + 1)
end
local function moveToLobby(player: Player)
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
player:SetAttribute("RoundRespawnAt", nil)
placedCharacter[player] = nil
player:SetAttribute("InArena", false)
player.RespawnLocation = lobbySpawn
local character = player.Character
local backpack = player:FindFirstChildOfClass("Backpack")
clearTools(character)
clearTools(backpack)
clearTools(player:FindFirstChild("StarterGear"))
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if character and humanoid and humanoid.Health > 0 then
ArenaSpawns.place(character, lobbySpawn)
end
end
local function sendToLobby(player: Player)
roster[player] = nil
joinOrder[player] = nil
lastCountedDeath[player] = nil
Stats.remove(player)
moveToLobby(player)
player:SetAttribute("ArenaWaiting", nil)
player:SetAttribute("ArenaIntermission", nil)
player:SetAttribute("ArenaMode", nil)
player:SetAttribute("ArenaTeam", nil)
player:SetAttribute("RoundKills", 0)
player:SetAttribute("RoundDeaths", 0)
resetStreak(player)
player.Team = nil
player.Neutral = true
end
local function destinationFor(player: Player): SpawnLocation
return ArenaSpawns.choose(player)
end
local function enterArena(player: Player, character: Model, humanoid: Humanoid)
if placedCharacter[player] == character or humanoid.Health <= 0 then return end
placedCharacter[player] = character
humanoid.Health = humanoid.MaxHealth
local destination = destinationFor(player)
player.RespawnLocation = 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)
else
clearTools(character)
clearTools(player:FindFirstChildOfClass("Backpack"))
RoundPlayer.clearShield(player)
RoundPlayer.freeze(player, character, humanoid)
end
end
local function deploy(player: Player)
if not roster[player] then return end
placedCharacter[player] = nil
player:SetAttribute("ArenaWaiting", nil)
player:SetAttribute("InArena", true)
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if character and humanoid and humanoid.Health > 0 and character.PrimaryPart then
enterArena(player, character, humanoid)
else
player.RespawnLocation = destinationFor(player)
end
end
local function stageOnArena(player: Player)
RoundPlayer.clearShield(player)
placedCharacter[player] = nil
player:SetAttribute("InArena", true)
local destination = destinationFor(player)
player.RespawnLocation = destination
local character = player.Character
clearTools(character)
clearTools(player:FindFirstChildOfClass("Backpack"))
clearTools(player:FindFirstChild("StarterGear"))
return character, destination
end
local function bench(player: Player)
if not roster[player] then return end
player:SetAttribute("ArenaWaiting", true)
local character, destination = stageOnArena(player)
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if character and humanoid and humanoid.Health > 0 then
humanoid.Health = humanoid.MaxHealth
ArenaSpawns.place(character, destination)
if not Stage.combatAllowed(randomState) then RoundPlayer.freeze(player, character, humanoid) end
end
end
local function enterRound(player: Player, match: Match)
if match.rule == "OneLife" then bench(player) else deploy(player) 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 root = character:WaitForChild("HumanoidRootPart", 10)
local humanoid = character:WaitForChild("Humanoid", 10)
player:WaitForChild("Backpack", 5)
if not root or not humanoid or not humanoid:IsA("Humanoid") or player.Character ~= character then return end
local function replicateHealth()
local fraction = if humanoid.MaxHealth > 0 then humanoid.Health / humanoid.MaxHealth else 0
character:SetAttribute("ArenaHealthFraction", math.clamp(fraction, 0, 1))
end
humanoid.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff
humanoid.HealthChanged:Connect(replicateHealth)
replicateHealth()
humanoid.Died:Once(function()
if player.Character ~= character then return end
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
local match = matches[Modes.of(player)]
local engine = match.engine
local fightingStage = match.phase == "Round" and Stage.combatAllowed(match.state)
local wasFighting = roster[player] ~= nil and placedCharacter[player] == character and fightingStage
local roundRespawn = roster[player] ~= nil and match.phase == "Round" and match.rule ~= "OneLife"
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()
if match.engine == engine and roster[player] and placedCharacter[player] == character then engine.death(player, position, now) end
end)
end
end)
local respawning = player:GetAttribute("RoundRespawnAt") ~= nil
player:SetAttribute("RoundRespawnAt", nil)
if roster[player] and player:GetAttribute("InArena") == true then
if player:GetAttribute("ArenaIntermission") == true or player:GetAttribute("ArenaWaiting") == true then
local destination = player.RespawnLocation or destinationFor(player)
player.RespawnLocation = destination
ArenaSpawns.place(character, destination)
if player:GetAttribute("ArenaIntermission") ~= true and not Stage.combatAllowed(randomState) then
RoundPlayer.freeze(player, character, humanoid)
end
else
enterArena(player, character, humanoid)
if respawning and Stage.combatAllowed(randomState) then
RoundPlayer.shield(player, character, Profiles[matches[Modes.of(player)].rule].spawnProtection)
end
end
else
ArenaSpawns.place(character, lobbySpawn)
end
end
local function onPlayer(player: Player)
sendToLobby(player)
player.ChildAdded:Connect(function(child)
if child:IsA("Backpack") or child:IsA("StarterGear") then guardInventory(player, child) end
end)
for _, child in player:GetChildren() do
if child:IsA("Backpack") or child:IsA("StarterGear") then guardInventory(player, child) end
end
player.CharacterAdded:Connect(function(character)
guardInventory(player, character)
onCharacter(player, character)
end)
if player.Character then
guardInventory(player, player.Character)
task.spawn(onCharacter, player, player.Character)
else
task.defer(spawnCharacter, player, nil)
end
end
Players.CharacterAutoLoads = false
Players.PlayerAdded:Connect(onPlayer)
for _, player in Players:GetPlayers() do onPlayer(player) end
local function voteTotals(match: Match): ({[string]: number}, number)
local counts: {[string]: number} = {}
local total = 0
for _, id in match.ballots do
counts[id] = (counts[id] or 0) + 1
total += 1
end
return counts, total
end
local function votingOpen(match: Match, now: number): boolean
return match.allowModeChange and match.phase == "Vote" and now < match.endsAt - Rules.VoteLockSeconds
end
local function broadcastVotes(match: Match)
local counts, total = voteTotals(match)
for player in match.eligible do
if player.Parent == Players then
vote:FireClient(player, match.id, match.endsAt, counts, total, match.ballots[player])
end
end
end
Players.PlayerRemoving:Connect(function(player)
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
Stats.remove(player)
local wasPlaying = roster[player] ~= nil
local match = matches[Modes.of(player)]
local engine = match.engine
local root = player.Character and player.Character.PrimaryPart
if wasPlaying and engine then engine.leaving(player, root and root.Position, workspace:GetServerTimeNow()) end
roster[player] = nil
joinOrder[player] = nil
placedCharacter[player] = nil
lastCountedDeath[player] = nil
lastRequest[player] = nil
lastSkinCycle[player] = nil
lastVote[player] = nil
admitted[player] = nil
pendingJoins[player] = nil
local now = workspace:GetServerTimeNow()
for _, arenaMatch in matches do
arenaMatch.eligible[player] = nil
if votingOpen(arenaMatch, now) and arenaMatch.ballots[player] then
arenaMatch.ballots[player] = nil
broadcastVotes(arenaMatch)
end
end
if not wasPlaying or match.phase ~= "Round" or workspace:GetServerTimeNow() >= match.endsAt then return end
if match.rule == "OneLife" then return end
local blueCount, orangeCount = countPlayers(match)
if math.abs(blueCount - orangeCount) <= 1 then return end
-- A departure can leave a two-player gap. Move the latest arrival from the larger side.
local larger = if blueCount > orangeCount then match.blue else match.orange
local latest = latestOn(larger)
if latest then
local previousRoot = latest.Character and latest.Character.PrimaryPart
if engine then engine.leaving(latest, previousRoot and previousRoot.Position, workspace:GetServerTimeNow()) end
setTeam(latest, match, if larger == match.blue then "Orange" else "Blue")
local character = latest.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if character and humanoid and humanoid.Health > 0 then
local destination = destinationFor(latest)
latest.RespawnLocation = destination
ArenaSpawns.place(character, destination)
end
end
end)
local function joinError(player: Player, match: Match, side: Side, now: number): string?
if roster[player] then return "AlreadyPlaying" end
if match.phase ~= "Round" or now >= match.endsAt then return "BetweenRounds" end
local blueCount, orangeCount = countSeats(match)
local own, other = blueCount, orangeCount
if side == "Orange" then own, other = orangeCount, blueCount end
local unavailable = Hosting.teamJoinError(own, other)
if unavailable then return unavailable end
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if not character or not humanoid or humanoid.Health <= 0 or not character.PrimaryPart
or not player:FindFirstChildOfClass("Backpack") then
return "Spawning"
end
return nil
end
leave.OnServerEvent:Connect(function(player: Player)
if not roster[player] or player:GetAttribute("InArena") ~= true then return end
local match = matches[Modes.of(player)]
if match.phase ~= "Round" then return end
local root = player.Character and player.Character.PrimaryPart
if match.engine then match.engine.leaving(player, root and root.Position, workspace:GetServerTimeNow()) end
sendToLobby(player)
if hostedExit then hostedExit:Fire(player) end
end)
local function tryJoin(player: Player, match: Match, side: Side, now: number): string
local issue = joinError(player, match, side, now)
if issue then return issue end
assignTeam(player, match, side)
enterRound(player, match)
return "Joined"
end
join.OnServerEvent:Connect(function(player: Player, id: unknown, requestedMode: unknown, preference: unknown)
if id ~= "Blue" and id ~= "Orange" and id ~= "Auto" and id ~= "AutoPreview" then return end
if preference ~= nil and preference ~= "Blue" and preference ~= "Orange" then return end
if pendingJoins[player] then return end
local mode = if requestedMode == nil then Modes.Procedural else requestedMode
if typeof(mode) ~= "string" or not matches[mode] then return end
local now = workspace:GetServerTimeNow()
if now - (lastRequest[player] or -math.huge) < .3 then return end
lastRequest[player] = now
if hosted and not admitted[player] then
join:FireClient(player, if player:GetAttribute("HostedArenaFull") then "Full" else "AwaitingAdmission")
return
end
local match = matches[mode]
local side: Side
if id == "AutoPreview" and (preference == "Blue" or preference == "Orange") then
side = preference
elseif id == "Auto" or id == "AutoPreview" then
local blueCount, orangeCount = countSeats(match)
side = if blueCount <= orangeCount then "Blue" else "Orange"
else
side = id
end
if id ~= "AutoPreview" then
join:FireClient(player, tryJoin(player, match, side, now))
return
end
local issue = joinError(player, match, side, now)
if issue or now + TEAM_REVEAL_SECONDS >= match.endsAt then
join:FireClient(player, issue or "BetweenRounds")
return
end
local pending = {match = match, side = side, endsAt = match.endsAt}
pendingJoins[player] = pending
join:FireClient(player, "TeamSelected", side)
task.delay(TEAM_REVEAL_SECONDS, function()
if pendingJoins[player] ~= pending then return end
pendingJoins[player] = nil
if player.Parent ~= Players then return end
local result = if match.endsAt ~= pending.endsAt then "BetweenRounds"
else tryJoin(player, match, side, workspace:GetServerTimeNow())
join:FireClient(player, result)
end)
end)
if hosted then
local admission = Instance.new("BindableEvent")
admission.Name = "HostedArenaAdmission"
admission.Event:Connect(function(player: Player, preference: Side?)
if player.Parent ~= Players or admitted[player] then return end
admitted[player] = true
local match = matches[Modes.Procedural]
local untilTime = workspace:GetServerTimeNow() + 50
repeat
if player.Parent ~= Players then return end
if not pendingJoins[player] then
local blueCount, orangeCount = countSeats(match)
local side = preference or (if blueCount <= orangeCount then "Blue" else "Orange")
local result = tryJoin(player, match, side, workspace:GetServerTimeNow())
if result == "Joined" or result == "AlreadyPlaying" then return end
if preference and (result == "Balance" or result == "Full") then
player:SetAttribute("HostedArenaTeamNotice", result)
return
end
end
task.wait(.25)
until workspace:GetServerTimeNow() >= untilTime
end)
admission.Parent = script
end
vote.OnServerEvent:Connect(function(player: Player, arena: unknown, id: unknown)
if typeof(arena) ~= "string" then return end
local match, rule = matches[arena], Rules.find(id)
if not match or not rule or not match.eligible[player] then return end
local now = workspace:GetServerTimeNow()
if not votingOpen(match, now) or now - (lastVote[player] or -math.huge) < .18 or match.ballots[player] == rule.id then return end
lastVote[player] = now
match.ballots[player] = rule.id
broadcastVotes(match)
end)
cycleSkin.OnServerEvent:Connect(function(player: Player)
local now = workspace:GetServerTimeNow()
if now - (lastSkinCycle[player] or -math.huge) < .18 then return end
lastSkinCycle[player] = now
local match = matches[Modes.of(player)]
if match.phase ~= "Round" or now >= match.endsAt or not roster[player] or player:GetAttribute("InArena") ~= true then return end
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
local rifle = character and character:FindFirstChild("SniperRifle")
if not humanoid or humanoid.Health <= 0 or not rifle or not rifle:IsA("Tool") then return end
local selected = SkinCatalog.next(rifle:GetAttribute("Skin"))
player:SetAttribute("RifleSkin", selected.id)
rifle:SetAttribute("Skin", selected.id)
end)
local function publish(match: Match)
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
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("EndsAt", match.endsAt)
match.state:SetAttribute("Phase", match.phase)
end
for _, match in matches do
match.state:SetAttribute("BlueKills", 0)
match.state:SetAttribute("OrangeKills", 0)
match.state:SetAttribute("BlueScore", 0)
match.state:SetAttribute("OrangeScore", 0)
match.state:SetAttribute("Ruleset", match.rule)
match.state:SetAttribute("AllowModeChange", match.allowModeChange)
publish(match)
end
state.Parent = ReplicatedStorage
local function returnVoters(match: Match)
local returning: {Player} = {}
for _, player in Players:GetPlayers() do
local previousSide = match.eligible[player]
if previousSide and (not match.allowModeChange or match.ballots[player]) then
assignTeam(player, match, previousSide)
player:SetAttribute("RoundKills", 0)
player:SetAttribute("RoundDeaths", 0)
lastCountedDeath[player] = nil
resetStreak(player)
table.insert(returning, player)
end
end
table.clear(match.eligible)
table.clear(match.ballots)
if #returning == 0 then return end
balanceWaiting(match)
for _, player in returning do
player:SetAttribute("ArenaIntermission", nil)
enterRound(player, match)
end
end
local function startRound(match: Match)
local arena = Modes.geometry(match.id)
local ready, result = pcall(function()
local generator = require(script.Parent:WaitForChild("ProceduralArena") :: ModuleScript)
local previous = arena:FindFirstChild("GeneratedLayout")
local seed = generator.regenerate()
local current = arena:FindFirstChild("GeneratedLayout")
assert(current and current ~= previous and seed == arena:GetAttribute("Seed"),
"The new match requires a fresh arena layout")
return seed
end)
if not ready then
warn("Procedural arena generation failed: ", result)
match.endsAt = workspace:GetServerTimeNow() + BREAK_SECONDS
publish(match)
return
end
match.state:SetAttribute("MapSeed", result)
match.state:SetAttribute("MapGeneration", arena:GetAttribute("Generation"))
match.state:SetAttribute("MapLayout", arena:GetAttribute("LayoutVariant"))
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, {
arena = match.id, rule = match.rule, state = match.state, now = liveAt, duration = roundDuration,
bench = bench, deploy = deploy,
balanceWaiting = function() balanceWaiting(match) end,
members = function(): {Player}
local found: {Player} = {}
for p, team in roster do if team == match.blue or team == match.orange then table.insert(found, p) end end
return found
end,
})
if not ok then
warn("Unable to start match: ", engine)
match.phase, match.endsAt = "Setup", now + BREAK_SECONDS
publish(match)
return
end
match.engine = engine
match.startedAt, match.liveAt = now, liveAt
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("BlueKills", 0)
match.state:SetAttribute("OrangeKills", 0)
publish(match)
returnVoters(match)
end
type ResultPlayer = {userId: number, displayName: string, kills: number, deaths: number}
local function finishRound(match: Match)
local bluePlayers: {ResultPlayer} = {}
local orangePlayers: {ResultPlayer} = {}
local participants: {{player: Player, side: Side}} = {}
for _, player in Players:GetPlayers() do
local team = roster[player]
if team ~= match.blue and team ~= match.orange then continue end
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
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(if team == match.blue then bluePlayers else orangePlayers, {
userId = player.UserId,
displayName = player.DisplayName,
kills = (player:GetAttribute("RoundKills") :: number?) or 0,
deaths = (player:GetAttribute("RoundDeaths") :: number?) or 0,
})
end
local function byPerformance(a: ResultPlayer, b: ResultPlayer): boolean
if a.kills ~= b.kills then return a.kills > b.kills end
if a.deaths ~= b.deaths then return a.deaths < b.deaths end
return a.userId < b.userId
end
table.sort(bluePlayers, byPerformance)
table.sort(orangePlayers, byPerformance)
match.phase = "Break"
match.endsAt = workspace:GetServerTimeNow() + BREAK_SECONDS
match.order = 0
table.clear(match.eligible)
table.clear(match.ballots)
local engine = match.engine
local winner = if engine then engine.winner() else "Draw"
local siegeState = match.state:FindFirstChild("CitadelMatchState")
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 = {
mode = match.id,
ruleset = match.rule,
allowModeChange = match.allowModeChange,
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,
siegeTimes = siegeTimes,
endsAt = match.endsAt,
duration = BREAK_SECONDS,
blueScore = (match.state:GetAttribute("BlueScore") :: number?) or 0,
orangeScore = (match.state:GetAttribute("OrangeScore") :: number?) or 0,
blue = bluePlayers,
orange = orangePlayers,
}
publish(match)
for _, entry in participants do
local player = entry.player
match.eligible[player] = entry.side
RoundPlayer.thaw(player)
RoundPlayer.clearShield(player)
player:SetAttribute("RoundRespawnAt", nil)
player:SetAttribute("ArenaIntermission", true)
local wasInArena = player:GetAttribute("InArena") == true
player:SetAttribute("ArenaWaiting", nil)
local character = stageOnArena(player)
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if not wasInArena and character and humanoid and humanoid.Health > 0 then
ArenaSpawns.place(character, destinationFor(player))
end
results:FireClient(player, snapshot, entry.side)
end
if engine then engine.destroy() end
match.engine = nil
end
local function finishVote(match: Match, now: number)
local counts, total = voteTotals(match)
if total > 0 then
local highest = 0
local choices: {string} = {}
for _, rule in Rules.All do
local count = counts[rule.id] or 0
if count > highest then
highest = count
table.clear(choices)
end
if count == highest and count > 0 then table.insert(choices, rule.id) end
end
match.rule = choices[modeRandom:NextInteger(1, #choices)]
end
if next(match.eligible) then
local ballotDeadline = match.endsAt
match.phase, match.endsAt = "Reveal", now + Rules.VoteRevealSeconds
match.state:SetAttribute("Ruleset", match.rule)
publish(match)
local outcome = {winner = match.rule, endsAt = match.endsAt}
for player in match.eligible do
if player.Parent == Players then
local selection = match.ballots[player]
vote:FireClient(player, match.id, ballotDeadline, counts, total, selection, outcome)
if not selection then sendToLobby(player) end
end
end
end
match.phase = "Setup"
startRound(match)
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)
while true do
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
if match.phase == "Round" then
local engine = match.engine
if remaining <= 0 and next(roster) == nil then
if engine then engine.destroy() end
match.engine, match.phase, match.order = nil, "Setup", 0
if match.allowModeChange then
local choices: {string} = {}
for _, rule in Rules.All do
if rule.id ~= match.rule then table.insert(choices, rule.id) end
end
match.rule = choices[modeRandom:NextInteger(1, #choices)]
end
startRound(match)
elseif remaining <= 0 then
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
task.wait(remaining)
elseif match.phase == "Break" and match.allowModeChange then
match.phase, match.endsAt = "Vote", now + VOTE_SECONDS
publish(match)
broadcastVotes(match)
elseif match.phase == "Vote" then
finishVote(match, now)
else
match.phase = "Setup"
startRound(match)
end
end
end
local proceduralMatch = matches[Modes.Procedural]
local configured = false
local configure = Instance.new("BindableFunction")
configure.Name = "HostedArenaConfigure"
configure.OnInvoke = function(value: unknown): boolean
local options = Hosting.readRoundOptions(value)
if not options then return false end
local match = proceduralMatch
if hosted then
if configured then return false end
elseif match.phase ~= "Round" or next(roster) or next(pendingJoins) then
return false
end
configured = true
match.phase, match.endsAt = "Setup", 0
match.rule, match.allowModeChange = options.initialMode, options.allowModeChange
match.state:SetAttribute("Ruleset", match.rule)
match.state:SetAttribute("AllowModeChange", match.allowModeChange)
publish(match)
if match.engine then
match.engine.destroy()
match.engine = nil
end
-- A reserved arena waits for its server-side session settings before generating its first round.
if hosted then task.defer(runMatch, match) end
return true
end
configure.Parent = script
if not hosted then task.spawn(runMatch, proceduralMatch) end