diff --git a/Hunter.rbxl b/Hunter.rbxl index feb9f38..c856bae 100644 Binary files a/Hunter.rbxl and b/Hunter.rbxl differ diff --git a/citadel.project.json b/citadel.project.json index 38e4129..c3f533b 100644 --- a/citadel.project.json +++ b/citadel.project.json @@ -4,11 +4,13 @@ "$className": "DataModel", "ReplicatedStorage": { "$ignoreUnknownInstances": true, - "CitadelAssaultConfig": { "$path": "scripts/CitadelAssaultConfig.luau" } + "CitadelAssaultConfig": { "$path": "scripts/CitadelAssaultConfig.luau" }, + "Hunter": { "$path": "scripts/Hunter" } }, "ServerScriptService": { "$ignoreUnknownInstances": true, "ArenaObjectives": { "$path": "scripts/ArenaObjectives.luau" }, + "ModeRuntime": { "$path": "scripts/ModeRuntime" }, "ArenaRounds": { "$path": "scripts/ArenaRounds.server.luau" }, "CitadelCaptureService": { "$path": "scripts/CitadelCaptureService.luau" }, "CitadelScoreService": { "$path": "scripts/CitadelScoreService.luau" }, @@ -18,7 +20,8 @@ "$ignoreUnknownInstances": true, "StarterPlayerScripts": { "$ignoreUnknownInstances": true, - "ArenaRoundHud": { "$path": "scripts/ArenaRoundHud.client.luau" } + "ArenaRoundHud": { "$path": "scripts/ArenaRoundHud.client.luau" }, + "ArenaClient": { "$path": "scripts/ArenaClient" } } } } diff --git a/scripts/ArenaClient/EventRouter.luau b/scripts/ArenaClient/EventRouter.luau new file mode 100644 index 0000000..95236b1 --- /dev/null +++ b/scripts/ArenaClient/EventRouter.luau @@ -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 diff --git a/scripts/ArenaClient/FeedController.client.luau b/scripts/ArenaClient/FeedController.client.luau new file mode 100644 index 0000000..12c6d2e --- /dev/null +++ b/scripts/ArenaClient/FeedController.client.luau @@ -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) diff --git a/scripts/ArenaObjectives.luau b/scripts/ArenaObjectives.luau index 7d8551d..eb86b49 100644 --- a/scripts/ArenaObjectives.luau +++ b/scripts/ArenaObjectives.luau @@ -1,25 +1,9 @@ --!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") -local Modes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript) -local Sites = require(script.Parent:WaitForChild("ArenaObjectiveSites") :: ModuleScript) -local HotPoint = require(script.Parent:WaitForChild("HotPoint") :: 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") +local Runtime = script.Parent:WaitForChild("ModeRuntime") +local Types = require(Runtime:WaitForChild("Types") :: ModuleScript) +local Context = require(Runtime:WaitForChild("Context") :: ModuleScript) -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 = { step: (number) -> boolean, kill: (Player, Player, Vector3, number) -> (), hit: ((Player, number, boolean) -> ())?, @@ -27,655 +11,64 @@ export type Match = { 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 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? return active[arena] end -function Objectives.start(config: Config): Match - local rule, state, arena = config.rule, config.state, config.arena - local world = Modes.geometry(arena) - local geometry = Modes.collision(arena) - local map = if rule == "TeamDeathmatch" or rule == "HuntLeader" then nil else Sites.resolve(arena) - local hotPath = if rule == "HotPoint" and map then Sites.hotPath(arena, map, HotPoint.Radius) else nil - local folder = Instance.new("Folder") - folder.Name = "MatchObjectives" - 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) +function Objectives.start(config: Types.Config): Match + local mode = assert(registry[config.rule], "Unknown mode: " .. config.rule) + local ctx = Context.create(config, mode, cue) + local success, result = pcall(mode.start, ctx) + if not success then + ctx.janitor.clean() + ctx.folder:Destroy() + error(result) end - local function status(text: string) - if state:GetAttribute("ObjectiveStatus") ~= text then state:SetAttribute("ObjectiveStatus", text) end - end - 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 instance = result :: Types.ModeInstance + local lastStep = ctx.liveAt + local destroyed = false 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 = { - step = step, - hit = if hotPoint then hotPoint.hit else nil, - kill = function(player, victim, at, now) - local side = sideOf(player) - if not side then return end - 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 + step = function(now) + if destroyed then return false end + local elapsed = math.max(0, now - lastStep) + lastStep = now + return instance.step(now, math.min(elapsed, .5), Context.collect(ctx.members()), elapsed) end, + kill = instance.kill, hit = instance.hit, death = instance.death, leaving = instance.leaving, winner = function() - if rule == "Siege" then - local winner, reason = Score.winner(siegeTimes, SiegeConfig.TIE_EPSILON) - state:SetAttribute("CitadelResultReason", reason) - return winner - end - if blueScore ~= orangeScore then return if blueScore > orangeScore then "Blue" else "Orange" end - return "Draw" + local side, reason = instance.winner() + ctx.state:SetAttribute("ResultReason", reason) + return side end, destroy = function() - if siegeState then - siegeState:Destroy() - for _, p in config.members() do p:SetAttribute("CitadelZone", nil) end - end - if active[arena] == match then active[arena] = nil end - if hotPoint then hotPoint.destroy() end - for _, side in sides do clearLeader(side) end - for p in carried do p:SetAttribute("ArenaTokens", nil) end - if flag and flag.carrier then flag.carrier:SetAttribute("ArenaFlag", nil) end - for _, z in zones do z.marker.body:Destroy() end - folder:Destroy() - status("") + if destroyed then return end + destroyed = true + if active[config.arena] == match then active[config.arena] = nil end + local ok, issue = pcall(instance.destroy) + ctx.janitor.clean() + ctx.folder:Destroy() + ctx.status("") + ctx.state:SetAttribute("RoundStage", nil) + if not ok then warn(issue) end end, } - active[arena] = match + active[config.arena] = match return match end diff --git a/scripts/Hunter/EventKinds.luau b/scripts/Hunter/EventKinds.luau new file mode 100644 index 0000000..9de6f5d --- /dev/null +++ b/scripts/Hunter/EventKinds.luau @@ -0,0 +1,8 @@ +--!strict +return table.freeze({ + ZoneStarted = "ZoneStarted", ZoneCaptured = "ZoneCaptured", ZoneContested = "ZoneContested", ZoneLost = "ZoneLost", + AllObjectivesTaken = "AllObjectivesTaken", FlagPicked = "FlagPicked", FlagDropped = "FlagDropped", + FlagReturned = "FlagReturned", FlagScored = "FlagScored", TokenDropped = "TokenDropped", TokensBanked = "TokensBanked", + LeaderAssigned = "LeaderAssigned", LeaderDown = "LeaderDown", MiniRoundStarted = "MiniRoundStarted", + MiniRoundEnded = "MiniRoundEnded", RoleSwap = "RoleSwap", Streak = "Streak", +}) diff --git a/scripts/Hunter/Hints.luau b/scripts/Hunter/Hints.luau new file mode 100644 index 0000000..19ab1b7 --- /dev/null +++ b/scripts/Hunter/Hints.luau @@ -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 diff --git a/scripts/Hunter/Strings.luau b/scripts/Hunter/Strings.luau new file mode 100644 index 0000000..30c54fe --- /dev/null +++ b/scripts/Hunter/Strings.luau @@ -0,0 +1,46 @@ +--!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 flagCarrier(name: string): string return name .. " несёт флаг" end +return table.freeze({ + 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, + }), +}) diff --git a/scripts/ModeRuntime/Common.luau b/scripts/ModeRuntime/Common.luau new file mode 100644 index 0000000..1a0db8b --- /dev/null +++ b/scripts/ModeRuntime/Common.luau @@ -0,0 +1,119 @@ +--!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): 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 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): 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 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} diff --git a/scripts/ModeRuntime/Context.luau b/scripts/ModeRuntime/Context.luau new file mode 100644 index 0000000..6478895 --- /dev/null +++ b/scripts/ModeRuntime/Context.luau @@ -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 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() + local contributions: {[number]: {[string]: number}} = {} + 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, function(_, points, reason, player) + if not reason or not player then return end + local stats = contributions[player.UserId] or {} + stats[reason] = (stats[reason] or 0) + points + contributions[player.UserId] = stats + end), + events = Events.new(config.members), + status = function(value) + if state:GetAttribute("ObjectiveStatus") ~= value then state:SetAttribute("ObjectiveStatus", value) end + end, + setStage = function(stage) 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 diff --git a/scripts/ModeRuntime/Events.luau b/scripts/ModeRuntime/Events.luau new file mode 100644 index 0000000..bb37a61 --- /dev/null +++ b/scripts/ModeRuntime/Events.luau @@ -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 diff --git a/scripts/ModeRuntime/Janitor.luau b/scripts/ModeRuntime/Janitor.luau new file mode 100644 index 0000000..7c26a60 --- /dev/null +++ b/scripts/ModeRuntime/Janitor.luau @@ -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 diff --git a/scripts/ModeRuntime/Modes/CaptureFlag.luau b/scripts/ModeRuntime/Modes/CaptureFlag.luau new file mode 100644 index 0000000..d0bd77e --- /dev/null +++ b/scripts/ModeRuntime/Modes/CaptureFlag.luau @@ -0,0 +1,158 @@ +--!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 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 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 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) + 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) + local landing = if floor then floor.Position else at + putFlag(flag, landing, now + 20) + for _, fighter in (fighters or Context.collect(ctx.members())) do ctx.legacy(fighter.player, "FlagDropped") end + ctx.events.fire(Kinds.FlagDropped, {at = landing}) + 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 + 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.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 + 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.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 end, + }) +end + +return {id = "CaptureFlag", usesMap = true, start = start} diff --git a/scripts/ModeRuntime/Modes/Domination.luau b/scripts/ModeRuntime/Modes/Domination.luau new file mode 100644 index 0000000..183c319 --- /dev/null +++ b/scripts/ModeRuntime/Modes/Domination.luau @@ -0,0 +1,69 @@ +--!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 SPEC: Zones.Spec = {radius = HotPoint.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} = {} + 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): (boolean, boolean) + local blue, orange = false, false + for _, fighter in fighters do + if Zones.classify(fighter.root.Position, zone.site.position, SPEC, geometry) == "Inside" then + if fighter.side == "Blue" then blue = true else orange = true end + end + end + return blue, orange + end + local geometry = ctx.geometry + local nextScore = ctx.liveAt + 1 + return Common.instance(ctx, {step = function(now, dt, fighters) + local scoreNow = now >= nextScore + if scoreNow then nextScore = now + 1 end + local ownedBlue, ownedOrange = 0, 0 + for index, 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 + ctx.cue(fighters, false, side) + end + zone.progress += dt + if zone.progress >= 3 then + local previous = zone.owner + zone.owner, zone.progress = side, 0 + local payload = {side = side, index = index, text = zone.marker.label.Text, value = now - ctx.liveAt} + 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 + Common.paint(zone.marker, Common.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 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}) +end + +return {id = "Domination", usesMap = true, start = start} diff --git a/scripts/ModeRuntime/Modes/HotPoint.luau b/scripts/ModeRuntime/Modes/HotPoint.luau new file mode 100644 index 0000000..de6d375 --- /dev/null +++ b/scripts/ModeRuntime/Modes/HotPoint.luau @@ -0,0 +1,30 @@ +--!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 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}) + end, + status = ctx.status, + }) + return Common.instance(ctx, { + step = function(now, dt, fighters, elapsed) capture.step(fighters, now, elapsed or dt); return false end, + hit = capture.hit, death = capture.death, leaving = capture.death, destroy = capture.destroy, + }) +end + +return {id = "HotPoint", usesMap = true, start = start} diff --git a/scripts/ModeRuntime/Modes/HuntLeader.luau b/scripts/ModeRuntime/Modes/HuntLeader.luau new file mode 100644 index 0000000..79cf4f0 --- /dev/null +++ b/scripts/ModeRuntime/Modes/HuntLeader.luau @@ -0,0 +1,71 @@ +--!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 rng = Random.new() + +local function start(ctx: Types.ModeContext): Types.ModeInstance + local leaders: {[Side]: Player} = {} + 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 + 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 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] = 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) + 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, if bonus then 3 else 1, if bonus then Kinds.LeaderDown else "Elimination", player) + if bonus then + clearLeader(target) + ctx.events.fire(Kinds.LeaderDown, {side = side, userId = player.UserId, text = victim.DisplayName}) + end + end, + leaving = function(player) + local side = Common.sideOf(player) + if side and leaders[side] == player then clearLeader(side) end + end, + destroy = function() for _, side in Common.sides do clearLeader(side) end end, + }) +end + +return {id = "HuntLeader", usesMap = false, start = start} diff --git a/scripts/ModeRuntime/Modes/OneLife.luau b/scripts/ModeRuntime/Modes/OneLife.luau new file mode 100644 index 0000000..86f7394 --- /dev/null +++ b/scripts/ModeRuntime/Modes/OneLife.luau @@ -0,0 +1,56 @@ +--!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 function start(ctx: Types.ModeContext): Types.ModeInstance + local lifeActive, miniNumber = false, 0 + local lifeEnds, nextMini = math.huge, ctx.liveAt + 2 + 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 + ctx.status(Strings.lifeActive(miniNumber, b, o, math.ceil(lifeEnds - now))) + return false + end + local side: Types.Side? = if b == o then nil elseif b > o then "Blue" else "Orange" + if side then ctx.scoring.add(side, 1, Kinds.MiniRoundEnded) end + ctx.events.fire(Kinds.MiniRoundEnded, {side = side, index = miniNumber}) + if ctx.scoring.get("Blue") >= 3 or ctx.scoring.get("Orange") >= 3 then return true end + for _, p in members do ctx.bench(p) end + lifeActive, nextMini = false, now + 4 + 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 + 45 + ctx.status(Strings.lifeStart(miniNumber)) + ctx.events.fire(Kinds.MiniRoundStarted, {index = miniNumber}) + elseif not b or not o then + ctx.status(Strings.lifeWaiting) + else + 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, + }) +end + +return {id = "OneLife", usesMap = true, start = start} diff --git a/scripts/ModeRuntime/Modes/Siege.luau b/scripts/ModeRuntime/Modes/Siege.luau new file mode 100644 index 0000000..ff19160 --- /dev/null +++ b/scripts/ModeRuntime/Modes/Siege.luau @@ -0,0 +1,143 @@ +--!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 HotPoint = require(Runtime.Parent.HotPoint) +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 = HotPoint.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 data = Instance.new("Folder") + data.Name = "CitadelMatchState" + data.Parent = state + ctx.janitor.give(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 = Common.makeZone(folder, geometry, site, "Checkpoint" .. i) + zone.marker.body:SetAttribute("Index", i) + zone.marker.body.Parent = nil + ctx.janitor.give(zone.marker.body) + table.insert(zones, zone) + end + zones[1].marker.body.Parent = folder + 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 function runSiege(members: {Player}, fighters: {Fighter}, now: number, dt: number): boolean + local half = SiegeConfig.ATTACK_DURATION + local elapsed = now - ctx.liveAt + if elapsed >= half and not hadSiegeSwap then + hadSiegeSwap = true + for _, z in zones do z.marker.body.Parent = nil end + 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 >= 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") + ctx.status(Strings.siegeSwap) + return false + end + local attacker = Strings.team(siegeSide) + local zone = zones[siegeIndex] + data:SetAttribute("Index", siegeIndex) + if not zone then + data:SetAttribute("Point", nil) + data:SetAttribute("NextPoint", nil) + ctx.status(Strings.siegeComplete) + return true + end + zone.marker.body.Parent = folder + local attack, defense = false, false + for _, fighter in fighters do + local reason = Zones.classify(fighter.root.Position, zone.site.position, SPEC, geometry) + if reason == "Inside" then + if fighter.side == siegeSide then attack = true else defense = true 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 + 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)) + Common.paint(zone.marker, if phase == "Contested" then Common.orange else Common.blue) + 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) + 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) + zone.marker.body.Parent = nil + siegeIndex += 1 + siegeProgress = 0 + if siegeIndex > #zones then + ctx.events.fire(Kinds.AllObjectivesTaken, {side = siegeSide}) + return true + 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, + destroy = function() + for _, p in ctx.members() do p:SetAttribute("CitadelZone", nil) end + end, + }) +end + +return {id = "Siege", usesMap = true, start = start} diff --git a/scripts/ModeRuntime/Modes/TeamDeathmatch.luau b/scripts/ModeRuntime/Modes/TeamDeathmatch.luau new file mode 100644 index 0000000..4b283e4 --- /dev/null +++ b/scripts/ModeRuntime/Modes/TeamDeathmatch.luau @@ -0,0 +1,12 @@ +--!strict +local Types = require(script.Parent.Parent.Types) +local Common = require(script.Parent.Parent.Common) + +local function start(ctx: Types.ModeContext): Types.ModeInstance + return Common.instance(ctx, {kill = function(player: Player) + local side = Common.sideOf(player) + if side then ctx.scoring.add(side, 1, "Elimination", player) end + end}) +end + +return {id = "TeamDeathmatch", usesMap = false, start = start} diff --git a/scripts/ModeRuntime/Modes/TrophyHunt.luau b/scripts/ModeRuntime/Modes/TrophyHunt.luau new file mode 100644 index 0000000..8b25b9e --- /dev/null +++ b/scripts/ModeRuntime/Modes/TrophyHunt.luau @@ -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 +local HotPoint = require(Runtime.Parent.HotPoint) +type Drop = {marker: Common.Marker, amount: number, expires: number} + +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 Common.boundsAt(existing.marker.origin, floor, 3.5, 3) then + existing.amount += amount + existing.expires = now + 42 + existing.marker.label.Text = Strings.tokens(existing.amount) + return + end + end + if #tokens >= 60 then + local old = table.remove(tokens, 1) + 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 + 42}) + 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 + 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 + 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.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) 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 end, + }) +end + +return {id = "TrophyHunt", usesMap = true, start = start} diff --git a/scripts/ModeRuntime/Scoring.luau b/scripts/ModeRuntime/Scoring.luau new file mode 100644 index 0000000..301460f --- /dev/null +++ b/scripts/ModeRuntime/Scoring.luau @@ -0,0 +1,17 @@ +--!strict +local Types = require(script.Parent.Types) +local Scoring = {} +function Scoring.new(state: Instance, onAdd: ((Types.Side, number, string?, Player?) -> ())?): 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) + 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 diff --git a/scripts/ModeRuntime/Types.luau b/scripts/ModeRuntime/Types.luau new file mode 100644 index 0000000..4f7f0e0 --- /dev/null +++ b/scripts/ModeRuntime/Types.luau @@ -0,0 +1,27 @@ +--!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?} +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) -> (), janitor: Janitor, + 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 {} diff --git a/scripts/ModeRuntime/Zones.luau b/scripts/ModeRuntime/Zones.luau new file mode 100644 index 0000000..af4ef2c --- /dev/null +++ b/scripts/ModeRuntime/Zones.luau @@ -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 diff --git a/scripts/Tests/Hints.spec.luau b/scripts/Tests/Hints.spec.luau new file mode 100644 index 0000000..73a36c6 --- /dev/null +++ b/scripts/Tests/Hints.spec.luau @@ -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 diff --git a/scripts/Tests/Scoring.spec.luau b/scripts/Tests/Scoring.spec.luau new file mode 100644 index 0000000..911018b --- /dev/null +++ b/scripts/Tests/Scoring.spec.luau @@ -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 diff --git a/scripts/Tests/Zones.spec.luau b/scripts/Tests/Zones.spec.luau new file mode 100644 index 0000000..71274b5 --- /dev/null +++ b/scripts/Tests/Zones.spec.luau @@ -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