feat(modes): matches now end, and something is at stake when they do

There was a string — `current_gamemode`, always "Deathmatch" — an OptionButton
with one entry in it, and a five-minute timer that counted to zero, set
`match_active = false`, and did nothing else. No winner was declared, no summary
appeared, the clock froze at 00:00, and players carried on shooting each other
in a match that had stopped counting. Nothing was tracked beyond a running kill
count. A match did not end so much as stop mattering, and everything a player
does in the last minute only matters if there is a last minute.

globals/game_mode.gd answers the three questions a mode has to answer — how you
score, when it ends, who won — for three modes:

  Deathmatch        25 frags or 10 minutes.
  Team Deathmatch   two squads to 50, teams balanced by COUNT on join (a 4v4
                    that loses three from one side must refill the short side;
                    round-robin on join order leaves it 4v1 forever), friendly
                    fire off and enforced on the server before damage is even
                    broadcast — a mode where the damage lands but the kill does
                    not count is worse than either.
  Gun Game          every kill promotes you a rung and swaps your weapon. The
                    score IS the rung and the limit IS the ladder's length, so
                    finishing the ladder and reaching the score limit are the
                    same event and only one win condition exists.

`check_win` is a pure function of the stats and the clock, deliberately, because
a win condition that can only be exercised by playing a whole match is one
nobody tests — and the previous one never was. debug/game_mode_check.gd runs 30
cases over it: a tie is a DRAW rather than a win for whoever came first out of
the dictionary; a team match is decided on the TEAM's total, which a per-player
check never reaches; every ladder rung names a weapon that exists, or that rung
softlocks the mode; and promoting past the top clamps, because the winning kill
promotes before the match-end RPC lands.

Tracking now covers score, team, current streak, best streak and ladder rung.
Score and kills are separate numbers because in Gun Game they coincide and in
anything with an objective they would not. The scoreboard ranks by score, shows
the mode's own noun for it, and puts the limit on the top line — a win condition
players cannot see is one they cannot play toward.

ui/match_summary.gd gives the ending somewhere to happen: who won, WHY (time and
frag limit are different stories about the same scoreline), team totals, full
standings, and a way out that is not alt-F4. Play Again is host-only on a server.

Three bugs found on the way, all of which only became bugs once matches could
actually end: loading a level reset the clock but not the scores, so the second
match on a server would have ended on its first kill; `.rpc()` on an offline
peer does not call locally, so singleplayer had no killfeed and no stat sync at
all; and a rocket already in the air at the whistle could change the result
after the summary was on screen.

spawn smoke 0, game modes 30/30, movement 11/11.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
Nicholas Butzke
2026-07-28 12:28:32 -04:00
co-authored by Claude Opus 5
parent f1a4f7df52
commit 986179854d
12 changed files with 1030 additions and 76 deletions
+265
View File
@@ -0,0 +1,265 @@
extends Object
class_name GameMode
## What a match IS: how you score, when it ends, and who won.
##
## Before this there was a string — `NetworkManager.current_gamemode`, always
## "Deathmatch" — an OptionButton with one entry in it, and a five-minute timer
## that counted to zero, set `match_active = false`, and did nothing else. No
## winner was ever declared, no summary was ever shown, and nothing was tracked
## beyond a running kill count. A match did not end so much as stop mattering.
##
## The three things a mode has to answer are answered here:
##
## HOW YOU SCORE what a kill is worth, and to whom. In Gun Game a kill is
## worth a rung on a ladder rather than a point.
## WHEN IT ENDS a score limit, a time limit, or both, whichever comes
## first. A mode with neither cannot end and is not a mode.
## WHO WON the top player, or the top TEAM, which are different
## questions and used to be the same one.
##
## Deliberately a plain data table with static helpers rather than an autoload:
## the menu, the lobby, the HUD and the server all need to ask what a mode is,
## and half of them run before any autoload would be ready.
const DEATHMATCH := "deathmatch"
const TEAM_DEATHMATCH := "team_deathmatch"
const GUN_GAME := "gun_game"
## The order they appear in menus. Deathmatch first because it is the one that
## needs no explanation.
const ORDER := [DEATHMATCH, TEAM_DEATHMATCH, GUN_GAME]
## `score_limit` of 0 means the mode has no score limit and ends on time alone.
## `time_limit` is in seconds; 0 means it ends on score alone. At least one of
## the two must be non-zero or the match cannot end — `is_valid` checks that.
const MODES := {
DEATHMATCH: {
"name": "Deathmatch",
"blurb": "Everyone for themselves. First to the frag limit takes it.",
"score_limit": 25,
"time_limit": 600.0,
"teams": 0,
"friendly_fire": true,
"score_noun": "KILLS",
# What one kill is worth to the killer.
"kill_score": 1,
# What dying costs. Zero: a deathmatch that punishes dying rewards
# hiding, and this is a game about momentum.
"death_score": 0,
},
TEAM_DEATHMATCH: {
"name": "Team Deathmatch",
"blurb": "Two squads. Team score is what counts.",
"score_limit": 50,
"time_limit": 600.0,
"teams": 2,
"friendly_fire": false,
"score_noun": "SCORE",
"kill_score": 1,
"death_score": 0,
},
GUN_GAME: {
"name": "Gun Game",
"blurb": "Every kill promotes you to the next weapon. Finish the ladder.",
# The limit IS the ladder length, filled in from LADDER below so the two
# can never disagree.
"score_limit": 0,
"time_limit": 900.0,
"teams": 0,
"friendly_fire": true,
"score_noun": "RUNG",
"kill_score": 1,
"death_score": 0,
},
}
## Gun Game's ladder, by weapon id (see LoadoutManager.weapon_db). Ordered
## roughly easiest to hardest to get a kill with, so the last rung is a real
## finish rather than a formality.
const LADDER := ["ak47", "m4", "mp7", "dmr", "plasma_gun", "nail_gun",
"double_barrel_shotgun", "rocket_launcher", "awp", "knife"]
static func all_ids() -> Array:
return ORDER.duplicate()
static func get_mode(id: String) -> Dictionary:
return MODES.get(id, MODES[DEATHMATCH])
static func display_name(id: String) -> String:
return String(get_mode(id).get("name", id))
static func blurb(id: String) -> String:
return String(get_mode(id).get("blurb", ""))
## The score that ends the match. For Gun Game this is the ladder's length, so
## adding a weapon to the ladder cannot leave the win condition unreachable.
static func score_limit(id: String) -> int:
if id == GUN_GAME:
return LADDER.size()
return int(get_mode(id).get("score_limit", 0))
static func time_limit(id: String) -> float:
return float(get_mode(id).get("time_limit", 0.0))
static func team_count(id: String) -> int:
return int(get_mode(id).get("teams", 0))
static func is_team_mode(id: String) -> bool:
return team_count(id) > 1
static func friendly_fire(id: String) -> bool:
return bool(get_mode(id).get("friendly_fire", true))
static func score_noun(id: String) -> String:
return String(get_mode(id).get("score_noun", "SCORE"))
## A mode with neither a score limit nor a time limit can never end. This is the
## one invariant worth asserting about the table itself, and debug/game_mode_check
## runs it over every entry.
static func is_valid(id: String) -> bool:
return score_limit(id) > 0 or time_limit(id) > 0.0
## The weapon a player on `rung` of the Gun Game ladder is holding.
static func ladder_weapon(rung: int) -> String:
if LADDER.is_empty():
return ""
return LADDER[clampi(rung, 0, LADDER.size() - 1)]
## Team colours, for the scoreboard, the killfeed and the HUD. Index 0 is no
## team — free-for-all — which reads as the game's own papaya.
const TEAM_COLORS := [Color(1.00, 0.47, 0.10), Color(0.22, 0.94, 1.00),
Color(1.00, 0.18, 0.52)]
const TEAM_NAMES := ["", "CYAN", "MAGENTA"]
static func team_color(team: int) -> Color:
return TEAM_COLORS[clampi(team, 0, TEAM_COLORS.size() - 1)]
static func team_name(team: int) -> String:
if team <= 0 or team >= TEAM_NAMES.size():
return ""
return TEAM_NAMES[team]
## Which team a joining player goes on: the smallest, ties broken toward team 1.
##
## Assigned by COUNT rather than round-robin on join order, because players
## leave. Round-robin on a 4v4 that loses three from one side stays 4v1 forever;
## this refills the short side.
static func assign_team(id: String, stats: Dictionary) -> int:
var teams := team_count(id)
if teams < 2:
return 0
var counts := []
counts.resize(teams + 1)
counts.fill(0)
for pid in stats:
var t: int = int(stats[pid].get("team", 0))
if t >= 1 and t <= teams:
counts[t] += 1
var best := 1
for t in range(1, teams + 1):
if counts[t] < counts[best]:
best = t
return best
## Every team's total, as `team index -> score`. Team 0 is never included.
static func team_scores(id: String, stats: Dictionary) -> Dictionary:
var out := {}
if not is_team_mode(id):
return out
for t in range(1, team_count(id) + 1):
out[t] = 0
for pid in stats:
var t: int = int(stats[pid].get("team", 0))
if out.has(t):
out[t] += int(stats[pid].get("score", 0))
return out
## Has anyone won yet? Returns `{}` if not, else the reason and the winner.
##
## Server-side only — this is the authority on when a match stops. It is a pure
## function of the stats so it can be unit-tested without a match running, which
## debug/game_mode_check.gd does.
static func check_win(id: String, stats: Dictionary, time_left: float) -> Dictionary:
var limit := score_limit(id)
if is_team_mode(id):
var totals := team_scores(id, stats)
if limit > 0:
for t in totals:
if totals[t] >= limit:
return {"reason": "score", "team": t,
"name": team_name(t) + " TEAM"}
if time_left <= 0.0:
var best := 0
var best_score := -1
var tied := false
for t in totals:
if totals[t] > best_score:
best_score = totals[t]
best = t
tied = false
elif totals[t] == best_score:
tied = true
if tied:
return {"reason": "time", "team": 0, "name": "DRAW"}
return {"reason": "time", "team": best,
"name": team_name(best) + " TEAM"}
return {}
# Free-for-all.
if limit > 0:
for pid in stats:
if int(stats[pid].get("score", 0)) >= limit:
return {"reason": "score", "player": pid,
"name": String(stats[pid].get("username", "Player"))}
if time_left <= 0.0:
var top = null
var top_score := -1
var drawn := false
for pid in stats:
var sc: int = int(stats[pid].get("score", 0))
if sc > top_score:
top_score = sc
top = pid
drawn = false
elif sc == top_score:
drawn = true
if top == null or drawn:
return {"reason": "time", "player": 0, "name": "DRAW"}
return {"reason": "time", "player": top,
"name": String(stats[top].get("username", "Player"))}
return {}
## Players sorted best-first, by score then by fewest deaths.
##
## Fewest deaths as the tiebreak, not most kills: at equal score the kills are
## equal by definition in every mode here, so kills would not break anything.
static func standings(stats: Dictionary) -> Array:
var ids: Array = stats.keys()
ids.sort_custom(func(a, b):
var sa: int = int(stats[a].get("score", 0))
var sb: int = int(stats[b].get("score", 0))
if sa != sb:
return sa > sb
return int(stats[a].get("deaths", 0)) < int(stats[b].get("deaths", 0)))
return ids
+1
View File
@@ -0,0 +1 @@
uid://b8k2ha37f47ji
+206 -28
View File
@@ -7,18 +7,34 @@ signal connection_succeeded
signal match_state_updated
signal stats_updated
signal killfeed_event(victim: String, killer: String, weapon: String, v_color: String, k_color: String)
## The match is over. `result` carries the reason ("score" / "time"), the winner's
## name, and the final standings. The HUD raises the summary screen on this.
signal match_ended(result: Dictionary)
## A Gun Game player moved up a rung and needs their weapon swapped.
signal ladder_promoted(peer_id: int, rung: int, weapon_id: String)
const DEFAULT_PORT = 31415
var connected_players: Array[int] = []
# Dict of ID -> { "username": String, "kills": int, "deaths": int, "assists": int, "ping": int }
## ID -> { username, kills, deaths, assists, ping, color, score, team, streak,
## best_streak, rung }
##
## `score` is what the MODE counts and is what decides the match — in Deathmatch
## it tracks kills, in Gun Game it is the ladder rung. `kills` stays a plain
## kill count regardless, because the scoreboard shows both and they are not the
## same number in every mode.
var player_stats: Dictionary = {}
var match_active: bool = false
var match_time_remaining: float = 0.0
var current_gamemode: String = "Deathmatch"
## A GameMode id — see globals/game_mode.gd. Was a display string ("Deathmatch")
## compared by equality in three places; an id is what the mode table is keyed on
## and what survives being sent over the wire.
var current_gamemode: String = GameMode.DEATHMATCH
var current_scene_path: String = ""
## Set when the match ends, so a late-arriving HUD can still show the summary.
var last_result: Dictionary = {}
var _ping_timer: Timer
@@ -62,31 +78,48 @@ func disconnect_game() -> void:
match_active = false
_ping_timer.stop()
func start_singleplayer_match(gamemode: String = "Deathmatch") -> void:
func start_singleplayer_match(gamemode: String = GameMode.DEATHMATCH) -> void:
# Ensure peer is offline if not already connected
if not multiplayer.has_multiplayer_peer() or multiplayer.multiplayer_peer is OfflineMultiplayerPeer:
multiplayer.multiplayer_peer = OfflineMultiplayerPeer.new()
connected_players.clear()
connected_players.append(1)
_init_player_stats(1, SettingsManager.username)
match_active = true
match_time_remaining = 300.0
current_gamemode = gamemode
player_stats.clear()
_init_player_stats(1, SettingsManager.username)
last_result = {}
match_active = true
# The mode's own clock, not a hardcoded five minutes. Gun Game is a fifteen
# minute mode and Deathmatch a ten minute one; both used to be five.
match_time_remaining = GameMode.time_limit(gamemode)
rpc("sync_match_state", match_active, match_time_remaining, current_gamemode)
func _init_player_stats(id: int, username: String) -> void:
# Keep existing color if player re-joins, or generate new
var p_color = Color(randf_range(0.2, 1.0), randf_range(0.2, 1.0), randf_range(0.2, 1.0)).to_html(false)
var team := GameMode.assign_team(current_gamemode, player_stats)
if team > 0:
# In a team mode the player's colour IS their team's, because a killfeed
# where a teammate and an enemy are both "some random colour" is a
# killfeed that cannot be read at a glance.
p_color = GameMode.team_color(team).to_html(false)
player_stats[id] = {
"username": username,
"kills": 0,
"deaths": 0,
"assists": 0,
"ping": 0,
"color": p_color
"color": p_color,
# What the MODE counts. See the note on player_stats.
"score": 0,
"team": team,
"streak": 0,
"best_streak": 0,
# Gun Game ladder position.
"rung": 0,
}
stats_updated.emit()
@@ -169,20 +202,93 @@ func rpc_load_level(scene_path: String) -> void:
print("Loading level: ", scene_path)
current_scene_path = scene_path
if multiplayer.is_server():
# Reset the scores as well as the clock. Loading a level used to restart
# the timer and leave every kill from the previous match standing, so the
# second match on a server started with someone already at the frag limit
# — and now that reaching the limit ENDS the match, it would have ended
# on the first kill.
last_result = {}
for pid in player_stats:
for key in ["kills", "deaths", "assists", "score", "streak",
"best_streak", "rung"]:
player_stats[pid][key] = 0
match_active = true
match_time_remaining = 300.0 # 5 minutes
match_time_remaining = GameMode.time_limit(current_gamemode)
rpc("sync_player_stats", player_stats)
rpc("sync_match_state", match_active, match_time_remaining, current_gamemode)
get_tree().change_scene_to_file(scene_path)
func _process(delta: float) -> void:
if match_active:
if match_time_remaining > 0:
match_time_remaining -= delta
if match_time_remaining <= 0:
match_time_remaining = 0
match_active = false
# We emit this so HUDs can update their timers smoothly
match_state_updated.emit()
if not match_active:
return
if match_time_remaining > 0:
match_time_remaining -= delta
if match_time_remaining <= 0:
match_time_remaining = 0
# Time is a win CONDITION, not an off switch. This used to set
# `match_active = false` and stop, so the clock reached zero, the
# timer froze at 00:00 and nothing else happened — no winner, no
# summary, no way back to the menu. The match did not end so much as
# stop mattering.
if _is_authority():
_check_win()
# We emit this so HUDs can update their timers smoothly
match_state_updated.emit()
## Whether this peer decides the match. True for the server, and true in
## singleplayer, where there is no peer but somebody still has to call it.
func _is_authority() -> bool:
if not multiplayer.has_multiplayer_peer():
return true
if multiplayer.multiplayer_peer is OfflineMultiplayerPeer:
return true
return multiplayer.is_server()
## Has anyone won? Called on the server after every kill and when the clock runs
## out. GameMode.check_win is a pure function of the stats, so the rule lives
## next to the mode that defines it and can be tested without a match running.
func _check_win() -> void:
if not match_active:
return
var result := GameMode.check_win(current_gamemode, player_stats,
match_time_remaining)
if result.is_empty():
return
result["mode"] = current_gamemode
result["standings"] = GameMode.standings(player_stats)
result["stats"] = player_stats.duplicate(true)
if _is_authority() and multiplayer.has_multiplayer_peer() \
and not multiplayer.multiplayer_peer is OfflineMultiplayerPeer:
rpc("end_match", result)
else:
end_match(result)
@rpc("authority", "call_local", "reliable")
func end_match(result: Dictionary) -> void:
if not match_active:
return
match_active = false
last_result = result
match_state_updated.emit()
match_ended.emit(result)
## Wipe the scores and start the clock again on the same map and mode. The
## summary screen's "Play Again".
@rpc("authority", "call_local", "reliable")
func restart_match() -> void:
for pid in player_stats:
for key in ["kills", "deaths", "assists", "score", "streak",
"best_streak", "rung"]:
player_stats[pid][key] = 0
last_result = {}
match_active = true
match_time_remaining = GameMode.time_limit(current_gamemode)
stats_updated.emit()
match_state_updated.emit()
# --- PING SYSTEM ---
func _on_ping_timer() -> void:
@@ -208,19 +314,54 @@ func receive_ping_response(server_time: int) -> void:
# --- GAMEPLAY EVENTS ---
@rpc("any_peer", "call_local", "reliable")
func register_kill(victim_id: int, killer_id: int, weapon_name: String, custom_victim_name: String = "", assist_ids: Array = []) -> void:
if multiplayer.is_server():
if killer_id != 0 and killer_id != victim_id:
if player_stats.has(killer_id):
player_stats[killer_id]["kills"] += 1
if _is_authority():
# A kill after the final whistle counts for nothing. Without this a
# rocket already in the air when the clock hit zero could change the
# result after the summary was on screen.
if not match_active:
return
var clean_kill := killer_id != 0 and killer_id != victim_id
# A team kill is not a score. Friendly fire may be ON in a mode and the
# kill still must not advance the killer — otherwise the fastest way to
# win Team Deathmatch is to shoot your own team.
if clean_kill and GameMode.is_team_mode(current_gamemode) \
and player_stats.has(killer_id) and player_stats.has(victim_id) \
and player_stats[killer_id]["team"] == player_stats[victim_id]["team"]:
clean_kill = false
if clean_kill and player_stats.has(killer_id):
var ks: Dictionary = player_stats[killer_id]
ks["kills"] += 1
ks["streak"] += 1
ks["best_streak"] = maxi(ks["best_streak"], ks["streak"])
if current_gamemode == GameMode.GUN_GAME:
# A kill is a RUNG, not a point, and the rung IS the score — so
# reaching the top of the ladder is the same event as reaching
# the score limit, and only one win condition has to exist.
ks["rung"] += 1
ks["score"] = ks["rung"]
var weapon := GameMode.ladder_weapon(ks["rung"])
ladder_promoted.emit(killer_id, ks["rung"], weapon)
rpc("notify_promotion", killer_id, ks["rung"], weapon)
else:
ks["score"] += int(GameMode.get_mode(current_gamemode).get(
"kill_score", 1))
if victim_id != -1:
if player_stats.has(victim_id):
player_stats[victim_id]["deaths"] += 1
player_stats[victim_id]["streak"] = 0
var penalty := int(GameMode.get_mode(current_gamemode).get(
"death_score", 0))
if penalty != 0:
player_stats[victim_id]["score"] = maxi(
player_stats[victim_id]["score"] - penalty, 0)
for aid in assist_ids:
if player_stats.has(aid) and aid != killer_id and aid != victim_id:
player_stats[aid]["assists"] += 1
var v_name = player_stats[victim_id]["username"] if player_stats.has(victim_id) else (custom_victim_name if custom_victim_name != "" else "Unknown")
var k_name = player_stats[killer_id]["username"] if player_stats.has(killer_id) else "Unknown"
@@ -238,9 +379,46 @@ func register_kill(victim_id: int, killer_id: int, weapon_name: String, custom_v
if killer_id == 0 or killer_id == victim_id:
k_name = "" # Suicide or world death
broadcast_killfeed.rpc(v_name, k_name, weapon_name, v_color, k_color)
sync_player_stats.rpc(player_stats)
# `.rpc()` on an offline peer does not call locally, so singleplayer got
# no killfeed and no stat sync at all. Both paths now go through the
# same two calls.
if multiplayer.has_multiplayer_peer() \
and not multiplayer.multiplayer_peer is OfflineMultiplayerPeer:
broadcast_killfeed.rpc(v_name, k_name, weapon_name, v_color, k_color)
sync_player_stats.rpc(player_stats)
else:
broadcast_killfeed(v_name, k_name, weapon_name, v_color, k_color)
sync_player_stats(player_stats)
# The scores just changed, so this is exactly when a match can end.
_check_win()
@rpc("authority", "call_local", "reliable")
func broadcast_killfeed(victim: String, killer: String, weapon: String, v_color: String = "cccccc", k_color: String = "cccccc") -> void:
killfeed_event.emit(victim, killer, weapon, v_color, k_color)
## A Gun Game player moved up. Broadcast so every client's killfeed can say so
## and the promoted player's own client can swap their weapon.
@rpc("authority", "call_local", "reliable")
func notify_promotion(peer_id: int, rung: int, weapon_id: String) -> void:
ladder_promoted.emit(peer_id, rung, weapon_id)
## Whether `a` may damage `b`, per the mode. The only place friendly fire is
## decided, so a mode that turns it off turns it off everywhere.
func can_damage(attacker_id: int, victim_id: int) -> bool:
if attacker_id == victim_id:
return true
if GameMode.friendly_fire(current_gamemode):
return true
if not player_stats.has(attacker_id) or not player_stats.has(victim_id):
return true
var ta: int = int(player_stats[attacker_id].get("team", 0))
var tb: int = int(player_stats[victim_id].get("team", 0))
return ta == 0 or ta != tb
## Which team a peer is on, 0 for free-for-all.
func team_of(peer_id: int) -> int:
return int(player_stats.get(peer_id, {}).get("team", 0))