## A server's match flow: lobby, countdown, drop, play and results, then back to the ## lobby for a new match on a new island. Everything is driven by step(), one call per ## server tick, so it is deterministic and has no scene-tree or clock dependency. ## ## Participants are identified by handles the server chooses (a connection, a local ## player or a bot). Joining and leaving can happen in any phase: a join during a match ## waits in the lobby for the next one, and leaving during a match counts as being ## eliminated where they stood. Each match gets a fresh Simulation, built while the ## lobby waits, so nothing carries over from the last one. class_name Match extends RefCounted const LOBBY: int = 0 const COUNTDOWN: int = 1 const DROP: int = 2 const PLAY: int = 3 const RESULTS: int = 4 const PHASE_NAMES: Array[String] = ["lobby", "countdown", "drop", "play", "results"] ## Bots added to fill a match get handles counting down from here, so they never clash ## with a server's own handles, which are positive. const FIRST_BOT_HANDLE: int = -1 var rules: MatchRules ## The seed the server was started with. Match 0 uses it as is; later matches derive ## their own from it and their index. var session_seed: int = 0 ## How many matches have started. The current or next match's index is this, or this ## minus one once it has started. var matches_started: int = 0 var phase: int = LOBBY ## Ticks spent in the current phase. var phase_ticks: int = 0 ## The current match's simulation during the drop, play and results. In the lobby and ## countdown, the next match's simulation, generated and waiting for players. var sim: Simulation ## Participant handles in join order, and which of them are bots. var participants: Array[int] = [] var bot_handles: Dictionary = {} ## Handles playing in the current match, and their entity IDs both ways. var entity_of: Dictionary = {} var handle_of: Dictionary = {} ## Handle -> team index, for the current match. var team_of: Dictionary = {} ## Finishing order of the current match, last place first: {"handle", "place", "tied", ## "by", "cause", "item", "left", "tick"}. "by" is the eliminating handle, or 0; "cause" a ## SimEntity.CAUSE_NAMES entry, or "left"; "item" the weapon that last hit them, or -1; ## "tick" the simulation tick they were placed on. Players who fall on the same tick ## share the better place and are marked "tied" (standard competition ranking). var placements: Array[Dictionary] = [] ## The kill feed: one entry per elimination or leave, oldest first, with the fields of a ## placement record. var kill_feed: Array[Dictionary] = [] ## Handle -> {"eliminations", "damage_dealt", "damage_taken"} for the current match. ## Damage counts only hits between opponents. var stats: Dictionary = {} ## Eliminated participant handle -> the living handle they're watching. A target that ## falls is replaced on the same step; see _retarget(). var spectating: Dictionary = {} ## The winning handles, empty for no winner (everyone left, or no one played). var winners: Array[int] = [] ## What happened during the last step(): phase changes, joins, leaves, placements. var events: Array[Dictionary] = [] var _next_bot_handle: int = FIRST_BOT_HANDLE ## Handles placed during the current step, for breaking a tie when the last players ## fall together. var _placed_this_step: Array[int] = [] ## How many started the current match. var _match_size: int = 0 ## The current match's handles in join order, leavers included. var _roster: Array[int] = [] ## Handle -> item code of the weapon that last hit them, this match. var _last_weapon: Dictionary = {} func _init(seed_value: int, match_rules: MatchRules = null) -> void: session_seed = seed_value rules = match_rules if match_rules != null else MatchRules.new() sim = Simulation.new(match_seed(0)) ## The seed of match `index`: the session seed for the first, then a hash of it and the ## index, kept non-negative. func match_seed(index: int) -> int: if index == 0: return session_seed return (session_seed ^ SimRng._hash_name("match:%d" % index)) & 0x7FFFFFFFFFFFFFFF ## The current or next match's seed. func current_seed() -> int: return sim.rng.match_seed func phase_name() -> String: return PHASE_NAMES[phase] func in_match() -> bool: return phase == DROP or phase == PLAY ## Adds a participant. Returns false if the handle is already here or the lobby is ## full. During a match they wait for the next one. func join(handle: int, bot: bool = false) -> bool: if participants.has(handle) or participants.size() >= rules.max_players: return false participants.append(handle) if bot: bot_handles[handle] = true events.append({"type": "joined", "handle": handle, "bot": bot}) return true ## Removes a participant. In a match, they're placed as if eliminated and their player ## leaves the simulation. Returns false if the handle isn't here. func leave(handle: int) -> bool: if not participants.has(handle): return false participants.erase(handle) bot_handles.erase(handle) events.append({"type": "left", "handle": handle}) if entity_of.has(handle): var entity_id: int = entity_of[handle] var player: SimEntity = sim.entities.find(entity_id) if in_match() and player != null and not player.eliminated: _place(handle, 0, true, _match_size - placements.size(), false) sim.remove_player(entity_id) handle_of.erase(entity_id) entity_of.erase(handle) spectating.erase(handle) if in_match(): _update_spectators() return true ## Passes a participant's command to the simulation. Returns false outside a match, for ## a handle that isn't playing, or if the simulation rejected it. func submit_command(handle: int, command: PlayerCommand) -> bool: if not in_match() or not entity_of.has(handle): return false return sim.submit_command(entity_of[handle], command) ## Handles still in the match and not eliminated, in join order. func alive() -> Array[int]: var living: Array[int] = [] if not in_match() and phase != RESULTS: return living for handle: int in entity_of: var player: SimEntity = sim.entities.find(entity_of[handle]) if player != null and not player.eliminated: living.append(handle) return living ## Advances one server tick. func step() -> void: events.clear() _placed_this_step.clear() phase_ticks += 1 match phase: LOBBY: if participants.size() < rules.min_players: phase_ticks = 0 elif participants.size() >= rules.max_players or phase_ticks >= rules.lobby_ticks: _enter(COUNTDOWN) if rules.countdown_ticks <= 0: _start() COUNTDOWN: if participants.size() < rules.min_players: _enter(LOBBY) elif phase_ticks >= rules.countdown_ticks: _start() DROP, PLAY: sim.step() _collect_damage() _collect_eliminations() if phase == DROP and sim.drop.finished: _enter(PLAY) _check_finished() _update_spectators() RESULTS: if phase_ticks >= rules.results_ticks: _reset() func _enter(next: int) -> void: events.append({"type": "phase", "from": PHASE_NAMES[phase], "to": PHASE_NAMES[next], "match": current_seed()}) phase = next phase_ticks = 0 ## Fills empty places with bots, puts every participant on the barge and places loot. func _start() -> void: if rules.fill_with_bots: while participants.size() < rules.max_players: var handle: int = _next_bot_handle _next_bot_handle -= 1 join(handle, true) var size: int = maxi(rules.team_size, 1) for index: int in participants.size(): var handle: int = participants[index] var entity_id: int = sim.add_player() entity_of[handle] = entity_id handle_of[entity_id] = handle team_of[handle] = index / size stats[handle] = {"eliminations": 0, "damage_dealt": 0, "damage_taken": 0} _match_size = participants.size() _roster = participants.duplicate() sim.start_drop() sim.start_tide() sim.place_loot() matches_started += 1 _enter(DROP) events.append({"type": "match_started", "match": current_seed(), "index": matches_started - 1, "players": participants.size()}) _check_finished() ## Adds up damage between opponents and remembers each victim's last weapon. func _collect_damage() -> void: for event: Dictionary in sim.events: if event["type"] != "player_hit" or not handle_of.has(event["victim"]): continue var victim: int = handle_of[event["victim"]] var attacker: int = int(handle_of.get(event["player"], 0)) if attacker == 0 or attacker == victim or team_of[attacker] == team_of[victim]: continue var amount: int = int(event["armor"]) + int(event["health"]) stats[attacker]["damage_dealt"] += amount stats[victim]["damage_taken"] += amount _last_weapon[victim] = int(event.get("item", -1)) ## Places everyone the simulation eliminated this tick. They share the best place of ## the range they fall into: with five standing and two falling together, both are 4th. func _collect_eliminations() -> void: var fallen: Array[Dictionary] = [] for event: Dictionary in sim.events: if event["type"] == "eliminated" and handle_of.has(event["player"]): fallen.append(event) if fallen.is_empty(): return var place: int = _match_size - placements.size() - fallen.size() + 1 for event: Dictionary in fallen: var by: int = int(handle_of.get(event["by"], 0)) var handle: int = handle_of[event["player"]] _place(handle, by, false, place, fallen.size() > 1, String(event.get("cause", "none"))) if by != 0 and by != handle and team_of[by] != team_of[handle]: stats[by]["eliminations"] += 1 ## Records a participant's finishing place, adds them to the kill feed and gives them ## someone to spectate. func _place(handle: int, by: int, left: bool, place: int, tied: bool, cause: String = "left") -> void: for placed: Dictionary in placements: if placed["handle"] == handle: return var record: Dictionary = { "handle": handle, "place": place, "tied": tied, "by": by, "cause": "left" if left else cause, "item": int(_last_weapon.get(handle, -1)) if by != 0 else -1, "left": left, "tick": sim.tick, } placements.append(record) kill_feed.append(record) if not left: _placed_this_step.append(handle) spectating[handle] = 0 var event: Dictionary = record.duplicate() event["type"] = "placed" events.append(event) ## Ends the match when at most one team has anyone standing, or when the tide's time ## limit runs out. If the last players fall on the same tick, or time runs out with ## several still standing, the tie-break picks the winner, so every match that started ## with players has one. func _check_finished() -> void: if not in_match(): return var living: Array[int] = alive() var teams: Dictionary = {} for handle: int in living: teams[team_of[handle]] = true var timed_out: bool = sim.tide != null and sim.tide.stage_at(sim.tick) == Tide.OVER if teams.size() > 1 and not timed_out: return winners.clear() if teams.size() >= 1: var best: int = living[0] if teams.size() == 1 else _tie_break(living) for handle: int in living: if team_of[handle] == team_of[best]: winners.append(handle) # Anyone else still standing at the time limit is placed by the tie-break, worst last. var losers: Array[int] = [] for handle: int in living: if not winners.has(handle): losers.append(handle) while not losers.is_empty(): var worst: int = _tie_break(losers, true) losers.erase(worst) _place(worst, 0, false, _match_size - placements.size(), false, "tide") elif not _placed_this_step.is_empty(): # Everyone fell on the same tick: the tie-break raises one team back to first, # and the rest of that tick's fallers share the place below the winners. var best: int = _tie_break(_placed_this_step) for handle: int in _placed_this_step: if team_of[handle] == team_of[best]: winners.append(handle) var kept: Array[Dictionary] = [] var shared: Array[Dictionary] = [] for record: Dictionary in placements: if winners.has(record["handle"]): continue kept.append(record) if _placed_this_step.has(record["handle"]): shared.append(record) for record: Dictionary in shared: record["place"] = winners.size() + 1 record["tied"] = shared.size() > 1 placements = kept for handle: int in winners: placements.append({ "handle": handle, "place": 1, "tied": winners.size() > 1, "by": 0, "cause": "none", "item": -1, "left": false, "tick": sim.tick, }) spectating.erase(handle) _enter(RESULTS) events.append({"type": "match_ended", "match": current_seed(), "winners": winners.duplicate(), "timed_out": timed_out}) ## The best of `handles` by the tie-break: most health, then highest feet, then the ## earliest to join. With `worst`, the worst instead. func _tie_break(handles: Array[int], worst: bool = false) -> int: var chosen: int = handles[0] for handle: int in handles: if handle == chosen: continue var better: bool = _beats(handle, chosen) if better != worst: chosen = handle return chosen func _beats(a: int, b: int) -> bool: var pa: SimEntity = sim.entities.find(entity_of[a]) var pb: SimEntity = sim.entities.find(entity_of[b]) if pa.health != pb.health: return pa.health > pb.health if not is_equal_approx(pa.position.y, pb.position.y): return pa.position.y > pb.position.y return participants.find(a) < participants.find(b) ## Back to the lobby: bots leave, the match's bookkeeping is cleared, and the next ## match's island is generated. func _reset() -> void: for handle: int in bot_handles.keys(): participants.erase(handle) bot_handles.clear() entity_of.clear() handle_of.clear() team_of.clear() placements.clear() kill_feed.clear() stats.clear() spectating.clear() _roster.clear() _last_weapon.clear() winners.clear() _next_bot_handle = FIRST_BOT_HANDLE _match_size = 0 sim = Simulation.new(match_seed(matches_started)) _enter(LOBBY) ## The living handle `handle` is watching, or 0 if they aren't spectating or nobody is ## left to watch. func spectate_target(handle: int) -> int: return int(spectating.get(handle, 0)) ## Moves an eliminated participant's view to the next (`direction` 1) or previous (-1) ## living player in join order. Returns the new target, or 0. func cycle_spectate(handle: int, direction: int = 1) -> int: if not spectating.has(handle): return 0 var living: Array[int] = alive() if living.is_empty(): return 0 var step: int = 1 if direction >= 0 else -1 var at: int = _roster.find(spectate_target(handle)) if at < 0: at = _roster.find(handle) for offset: int in range(1, _roster.size() + 1): var candidate: int = _roster[posmod(at + offset * step, _roster.size())] if living.has(candidate): spectating[handle] = candidate return candidate return 0 ## Gives every spectator whose target is gone or has fallen a new one. During results, ## spectators watch a winner who is still standing, if there is one. func _update_spectators() -> void: var living: Array[int] = alive() if phase == RESULTS and not winners.is_empty(): living = winners.duplicate() for handle: int in spectating.keys(): var target: int = spectating[handle] if living.has(target): continue spectating[handle] = _retarget(handle, target, living) if spectating[handle] != target: events.append({"type": "spectating", "handle": handle, "target": spectating[handle]}) ## Who a spectator watches next: whoever eliminated the player they were watching (or ## themselves, the first time), then a living teammate, then the next living player in ## join order after the old target. 0 when nobody is left. func _retarget(handle: int, old_target: int, living: Array[int]) -> int: if living.is_empty(): return 0 var followed: int = old_target if old_target != 0 else handle for record: Dictionary in placements: if record["handle"] == followed and living.has(record["by"]): return record["by"] for candidate: int in living: if team_of.get(candidate, -1) == team_of.get(handle, -2): return candidate var at: int = maxi(_roster.find(followed), 0) for offset: int in range(1, _roster.size() + 1): var candidate: int = _roster[(at + offset) % _roster.size()] if living.has(candidate): return candidate return 0 ## The match summary, best place first: one Dictionary per participant of the current ## match with "handle", "bot", "team", "place", "tied", "eliminations", "damage_dealt", ## "damage_taken", "survival_ticks", "survival_seconds", "by", "cause" and "left". ## Players still standing have place 0 and survival up to now. func summary() -> Array[Dictionary]: var rows: Array[Dictionary] = [] var record_of: Dictionary = {} for record: Dictionary in placements: record_of[record["handle"]] = record for handle: int in _roster: var record: Dictionary = record_of.get(handle, {}) var placed_tick: int = int(record.get("tick", sim.tick)) var row: Dictionary = stats.get(handle, {"eliminations": 0, "damage_dealt": 0, "damage_taken": 0}).duplicate() row["handle"] = handle row["bot"] = bot_handles.has(handle) row["team"] = int(team_of.get(handle, -1)) row["place"] = int(record.get("place", 0)) row["tied"] = bool(record.get("tied", false)) row["survival_ticks"] = placed_tick row["survival_seconds"] = float(placed_tick) / Tuning.TICK_RATE_HZ row["by"] = int(record.get("by", 0)) row["cause"] = String(record.get("cause", "")) row["left"] = bool(record.get("left", false)) rows.append(row) rows.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: var pa: int = a["place"] if a["place"] > 0 else 0 var pb: int = b["place"] if b["place"] > 0 else 0 if pa != pb: return pa < pb return _roster.find(a["handle"]) < _roster.find(b["handle"])) return rows