diff --git a/src/lib/components/MapPicker.svelte b/src/lib/components/MapPicker.svelte
index cfca33e1..d982d12e 100644
--- a/src/lib/components/MapPicker.svelte
+++ b/src/lib/components/MapPicker.svelte
@@ -4,13 +4,15 @@
import { toast } from '$lib/toast.svelte';
import { expLabel, isMod, lightingLabel, lightingsOn, mapLabel, zoneLabel } from '$lib/format';
import MapArt from './MapArt.svelte';
+ import MapTeamSettings from './MapTeamSettings.svelte';
import type { Catalog, CatalogItem, MapSelection } from '$lib/types';
let {
serverId,
catalog,
- disabled = false
- }: { serverId: string; catalog: Catalog; disabled?: boolean } = $props();
+ disabled = false,
+ canManageTeams = false
+ }: { serverId: string; catalog: Catalog; disabled?: boolean; canManageTeams?: boolean } = $props();
let map = $state('');
let mode = $state('');
@@ -154,3 +156,5 @@
+
+{#if canManageTeams}{/if}
diff --git a/src/lib/components/MapTeamSettings.svelte b/src/lib/components/MapTeamSettings.svelte
new file mode 100644
index 00000000..c5a10e81
--- /dev/null
+++ b/src/lib/components/MapTeamSettings.svelte
@@ -0,0 +1,164 @@
+
+
+
+
+
This is a separate automation rule, not a native game mode. Save it separately from the rotation; players on the excluded faction will be moved.
+{#if teamVersusTeam || changed}
+
+{/if}
+{#if error}
{error}
{/if}
+
+
diff --git a/src/lib/map-team-mode.ts b/src/lib/map-team-mode.ts
new file mode 100644
index 00000000..2b37511a
--- /dev/null
+++ b/src/lib/map-team-mode.ts
@@ -0,0 +1,34 @@
+import type { MapSelection } from './types';
+
+export interface MapTeamMode {
+ selection: MapSelection;
+ mode: 'standard' | 'manual' | 'random';
+ closedFaction?: string;
+}
+
+export const mapTeamKey = (s: MapSelection): string =>
+ JSON.stringify([s.map, [...s.experiences].sort(), s.lighting, s.zoneAlternator]);
+
+export interface MapTeamRule {
+ enabled: boolean;
+ config: Record;
+}
+
+/** Two-team play is an automation setting, not a different KOTH experience ID. */
+export function teamModeForSelection(
+ selection: MapSelection,
+ rule: MapTeamRule | null
+): MapTeamMode | null {
+ if (!rule?.enabled || rule.config.watchOnly === true) return null;
+ const config = rule.config;
+ const overrides = (config.mapOverrides ?? []) as MapTeamMode[];
+ const override = overrides.find((o) => mapTeamKey(o.selection) === mapTeamKey(selection));
+ if (override) return override.mode === 'standard' ? null : override;
+ if (config.mapOnly === true || (!config.closedFaction && config.randomClosedFaction !== true))
+ return null;
+ return {
+ selection,
+ mode: config.randomClosedFaction === true ? 'random' : 'manual',
+ ...(typeof config.closedFaction === 'string' ? { closedFaction: config.closedFaction } : {})
+ };
+}
diff --git a/src/lib/server/triggers-two-teams.test.ts b/src/lib/server/triggers-two-teams.test.ts
index 7b6eff4d..995dd90a 100644
--- a/src/lib/server/triggers-two-teams.test.ts
+++ b/src/lib/server/triggers-two-teams.test.ts
@@ -364,3 +364,66 @@ describe('the Team balance rule', () => {
});
});
});
+
+describe('random excluded faction', () => {
+ test('persists its choice, moves only the excluded faction and survives restart', async () => {
+ const rule = row({ randomClosedFaction: true });
+ const players = ['Lonestar', 'Valkyra', 'Manticore'].map((f, i) => player(String(i), f));
+ const first = await look(rule, tick(players, 0));
+ const saved = first.updates.find((u) => u.state)?.state as { randomClosedFaction: string };
+ expect(players.map((p) => p.faction)).toContain(saved.randomClosedFaction);
+ for (const move of first.intents.filter((i) => i.action === 'changeTeam')) {
+ expect(move.params.from).toBe(saved.randomClosedFaction);
+ expect(move.params.faction).not.toBe(saved.randomClosedFaction);
+ }
+ rule.state = saved;
+ forgetRuleMemory();
+ const restarted = await look(rule, tick(players, 1000));
+ expect(restarted.updates.some((u) => u.state)).toBe(false);
+ for (const move of restarted.intents.filter((i) => i.action === 'changeTeam'))
+ expect(move.params.from).toBe(saved.randomClosedFaction);
+ });
+ test('waits for known factions after a boundary without a player observation', async () => {
+ const rule = row({ randomClosedFaction: true });
+ rule.state = { randomClosedFaction: 'Lonestar' };
+ const boundary = tick([], 0);
+ boundary.playersObserved = false;
+ boundary.matchEnd = {} as never;
+ const ended = await look(rule, boundary);
+ expect(ended.intents).toHaveLength(0);
+ rule.state = ended.updates.find((u) => u.state)!.state;
+ expect((rule.state as { randomPending: boolean }).randomPending).toBe(true);
+ const next = await look(rule, tick([player('1', 'Lonestar')], 1000));
+ expect(
+ (next.updates.find((u) => u.state)!.state as { randomPending: boolean }).randomPending
+ ).toBe(false);
+ });
+});
+
+test('map rules move only on their configured map and cancel moves when leaving it', async () => {
+ const selection = { map: 'Map', experiences: ['mode'], lighting: 'Day', zoneAlternator: '' };
+ const rule = row({ mapOverrides: [{ selection, mode: 'manual', closedFaction: 'Lonestar' }] });
+ const ctx = tick(everyone, 0);
+ ctx.status = { ...ctx.status, experiences: ['mode'], lighting: 'Day', alternator: '' };
+ const first = await look(rule, ctx);
+ expect(moved(first)).toHaveLength(3);
+ const intent = first.intents.find((i) => i.action === 'changeTeam')!;
+ expect(
+ twoTeamsMoveVerdict({
+ triggerId: rule.id,
+ serverId: 'srv',
+ steamId: intent.steamId!,
+ params: intent.params
+ })
+ ).toBe('send');
+ const other = { ...ctx, ts: new Date(1000), status: { ...ctx.status, map: 'Other' } };
+ expect(moved(await look(rule, other))).toHaveLength(0);
+ expect(
+ twoTeamsMoveVerdict({
+ triggerId: rule.id,
+ serverId: 'srv',
+ steamId: intent.steamId!,
+ params: intent.params
+ })
+ ).not.toBe('send');
+});
diff --git a/src/lib/server/triggers.ts b/src/lib/server/triggers.ts
index a6b45dbe..9d2920b9 100644
--- a/src/lib/server/triggers.ts
+++ b/src/lib/server/triggers.ts
@@ -1,3 +1,5 @@
+import { mapTeamKey } from '$lib/map-team-mode';
+import { chooseExcludedFaction, teamConfigForMap } from './two-teams';
// Automation: per-server triggers the worker evaluates on every observation, all
// built on what the worker already sees (joins, player counts, empty stretches) plus the Steam cache:
// welcome whisper a message to players as they join (or once they have picked a faction)
@@ -1430,8 +1432,57 @@ async function evalTwoTeams(
const now = ctx.ts.getTime();
// The same fingerprint rides on every move and whisper, for delivery to check against.
const config = twoTeamsSettingsKey(cfg);
+ const selection = {
+ map: ctx.status.map,
+ experiences: ctx.status.experiences ?? [],
+ lighting: ctx.status.lighting ?? '',
+ zoneAlternator: ctx.status.alternator ?? ''
+ };
+ const effective = teamConfigForMap(cfg, selection);
+ if (!effective) {
+ twoTeamsMemory.delete(row.id);
+ return;
+ }
+ cfg = effective;
+ const mapKey = mapTeamKey(selection);
+
// The marker updateTrigger writes when the rule is switched on: it starts over then too.
- const memoryKey = `${config}:${JSON.stringify(row.state ?? null)}`;
+ let randomState: Record | undefined;
+ if (cfg.randomClosedFaction) {
+ const saved = (row.state ?? {}) as Record;
+ const pending = !!ctx.matchEnd || saved.randomPending === true;
+ const chosen = ctx.playersObserved
+ ? chooseExcludedFaction(
+ typeof saved.randomClosedFaction === 'string' &&
+ (!cfg.mapOverrides?.length || saved.randomMapKey === mapKey)
+ ? saved.randomClosedFaction
+ : undefined,
+ (ctx.status.scores ?? []).map((s) => s.name),
+ pending
+ )
+ : null;
+ if (!chosen) {
+ if (ctx.matchEnd) twoTeamsMemory.delete(row.id);
+ if (pending && !saved.randomPending)
+ out.updates.push({ id: row.id, state: { ...saved, randomPending: true } });
+ return;
+ }
+ if (chosen !== saved.randomClosedFaction || pending || saved.randomMapKey !== mapKey) {
+ randomState = {
+ ...saved,
+ randomClosedFaction: chosen,
+ randomPending: false,
+ randomMapKey: mapKey
+ };
+ out.updates.push({
+ id: row.id,
+ state: randomState,
+ lastResult: `${chosen} excluded for this match`
+ });
+ }
+ cfg = { ...cfg, closedFaction: chosen };
+ }
+ const memoryKey = `${config}:${JSON.stringify((row.state as { enabledAt?: number } | null)?.enabledAt ?? null)}:${cfg.closedFaction}:${mapKey}`;
let memory = twoTeamsMemory.get(row.id);
if (
memory?.key !== memoryKey ||
diff --git a/src/lib/server/two-teams.test.ts b/src/lib/server/two-teams.test.ts
index 899a14ad..4abe5b1d 100644
--- a/src/lib/server/two-teams.test.ts
+++ b/src/lib/server/two-teams.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, test } from 'bun:test';
import {
emptyTwoTeamsState,
+ chooseExcludedFaction,
+ teamConfigForMap,
TWO_TEAMS_ASK_WINDOW_MS,
TWO_TEAMS_FORGET_MS,
TWO_TEAMS_MAX_ASKS,
@@ -609,3 +611,71 @@ test("a rule's settings fingerprint does not depend on key order, and changes wi
expect(twoTeamsSettingsKey({ ...cfg, closedFaction: 'Valkyra' })).not.toBe(key);
expect(twoTeamsSettingsKey({ ...cfg, message: '' })).not.toBe(key);
});
+
+describe('excluded faction selection', () => {
+ test('allows random mode without a manually closed faction', () => {
+ expect(validateTwoTeams({ randomClosedFaction: true }).randomClosedFaction).toBe(true);
+ expect(() => validateTwoTeams({ randomClosedFaction: 'true' })).toThrow('boolean');
+ });
+ test('keeps the choice until a boundary, regardless of score order', () => {
+ const factions = ['Valkyra', 'Lonestar', 'Manticore'];
+ expect(chooseExcludedFaction(undefined, factions, false, () => 0)).toBe('Lonestar');
+ expect(chooseExcludedFaction('Lonestar', factions.reverse(), false, () => 0.99)).toBe(
+ 'Lonestar'
+ );
+ expect(chooseExcludedFaction('Lonestar', factions, true, () => 0.99)).toBe('Valkyra');
+ expect(chooseExcludedFaction(undefined, ['Lonestar'], true)).toBeNull();
+ });
+});
+
+describe('map team settings', () => {
+ const selection = {
+ map: 'Map',
+ experiences: ['mode', 'modifier'],
+ lighting: 'Day',
+ zoneAlternator: 'A'
+ };
+ test('matches the full map settings and preserves server defaults elsewhere', () => {
+ const config = validateTwoTeams({
+ closedFaction: 'Lonestar',
+ mapOverrides: [{ selection, mode: 'manual', closedFaction: 'Manticore' }]
+ });
+ expect(
+ teamConfigForMap(config, { ...selection, experiences: ['modifier', 'mode'] })?.closedFaction
+ ).toBe('Manticore');
+ for (const changed of [
+ { ...selection, map: 'Other' },
+ { ...selection, lighting: 'Night' },
+ { ...selection, zoneAlternator: 'B' },
+ { ...selection, experiences: ['mode'] }
+ ])
+ expect(teamConfigForMap(config, changed)?.closedFaction).toBe('Lonestar');
+ });
+ test('standard mode overrides a global closure; map-only settings stay inactive elsewhere', () => {
+ const config = validateTwoTeams({
+ closedFaction: 'Lonestar',
+ mapOverrides: [{ selection, mode: 'standard' }]
+ });
+ expect(teamConfigForMap(config, selection)).toBeNull();
+ expect(
+ teamConfigForMap({ ...config, mapOnly: true }, { ...selection, map: 'Other' })
+ ).toBeNull();
+ const only = validateTwoTeams({ mapOverrides: [{ selection, mode: 'random' }] });
+ expect(teamConfigForMap(only, selection)?.randomClosedFaction).toBe(true);
+ expect(teamConfigForMap(only, { ...selection, map: 'Other' })).toBeNull();
+ });
+ test('rejects invalid, duplicate and oversized map overrides', () => {
+ const override = { selection, mode: 'manual', closedFaction: 'Manticore' };
+ expect(() => validateTwoTeams({ mapOverrides: [override, override] })).toThrow('Duplicate');
+ expect(() =>
+ validateTwoTeams({ mapOverrides: [{ ...override, closedFaction: 'unknown' }] })
+ ).toThrow('excluded');
+ expect(() =>
+ validateTwoTeams({
+ mapOverrides: [{ ...override, selection: { ...selection, experiences: 1 } }]
+ })
+ ).toThrow('Invalid');
+ expect(() => validateTwoTeams({ mapOverrides: Array(101).fill(override) })).toThrow('100');
+ });
+});
+
diff --git a/src/lib/server/two-teams.ts b/src/lib/server/two-teams.ts
index 57cf6998..b5fad4be 100644
--- a/src/lib/server/two-teams.ts
+++ b/src/lib/server/two-teams.ts
@@ -1,3 +1,6 @@
+import type { MapTeamMode } from '$lib/map-team-mode';
+import { mapTeamKey } from '$lib/map-team-mode';
+import type { MapSelection } from '$lib/types';
// The Team balance rule's pure part (kind `two_teams`, first built as Two-team mode). Two jobs, either
// or both: a closed faction, whose players are moved to the smaller of the others, so a
// three-faction server plays as two big teams; and balancing, which keeps the open sides within a
@@ -59,6 +62,9 @@ export const TWO_TEAMS_MAX_EXEMPT = 100;
export interface TwoTeamsConfig {
/** the faction nobody plays on, '' for none; its players are moved off it */
closedFaction: string;
+ randomClosedFaction?: boolean;
+ mapOverrides?: MapTeamMode[];
+ mapOnly?: boolean;
/** what players are told the open factions are called, by faction ('' keeps the faction name) */
names: Record;
/** whispered once a moved player lands, with {team}; '' sends nothing */
@@ -76,9 +82,56 @@ export interface TwoTeamsConfig {
}
export function validateTwoTeams(c: Record): TwoTeamsConfig {
- const closedFaction = str(c.closedFaction, 100);
+ if (c.randomClosedFaction !== undefined && typeof c.randomClosedFaction !== 'boolean')
+ throw new ApiError(400, 'randomClosedFaction must be a boolean.');
+ const randomClosedFaction = c.randomClosedFaction === true;
+ const closedFaction = randomClosedFaction ? '' : str(c.closedFaction, 100);
+ const mapOverrides: MapTeamMode[] = [];
+ if (c.mapOverrides !== undefined) {
+ if (!Array.isArray(c.mapOverrides) || c.mapOverrides.length > 100)
+ throw new ApiError(400, 'At most 100 map team settings are allowed.');
+ const keys = new Set();
+ for (const raw of c.mapOverrides) {
+ const o = raw as MapTeamMode;
+ const s = o?.selection;
+ if (
+ !s ||
+ typeof s.map !== 'string' ||
+ !s.map ||
+ s.map.length > 200 ||
+ !Array.isArray(s.experiences) ||
+ !s.experiences.length ||
+ s.experiences.length > 32 ||
+ s.experiences.some((e) => typeof e !== 'string' || !e || e.length > 200) ||
+ typeof s.lighting !== 'string' ||
+ s.lighting.length > 200 ||
+ typeof s.zoneAlternator !== 'string' ||
+ s.zoneAlternator.length > 200 ||
+ !['standard', 'manual', 'random'].includes(o.mode)
+ )
+ throw new ApiError(400, 'Invalid map team settings.');
+ if (
+ o.mode === 'manual' &&
+ !['Lonestar', 'Valkyra', 'Manticore'].includes(o.closedFaction ?? '')
+ )
+ throw new ApiError(400, 'Choose the excluded faction.');
+ const key = mapTeamKey(s);
+ if (keys.has(key)) throw new ApiError(400, 'Duplicate map team settings.');
+ keys.add(key);
+ mapOverrides.push({
+ selection: {
+ map: s.map,
+ experiences: [...s.experiences],
+ lighting: s.lighting,
+ zoneAlternator: s.zoneAlternator
+ },
+ mode: o.mode,
+ ...(o.mode === 'manual' ? { closedFaction: o.closedFaction } : {})
+ });
+ }
+ }
const balance = c.balance === true;
- if (!closedFaction && !balance)
+ if (!closedFaction && !balance && !randomClosedFaction && !Array.isArray(c.mapOverrides))
throw new ApiError(400, 'Close a faction, keep the sides even, or both.');
const names: Record = {};
if (c.names && typeof c.names === 'object')
@@ -98,6 +151,9 @@ export function validateTwoTeams(c: Record): TwoTeamsConfig {
const exempt = steamIdList(c.exempt, TWO_TEAMS_MAX_EXEMPT);
return {
closedFaction,
+ ...(mapOverrides.length ? { mapOverrides } : {}),
+ ...(c.mapOnly === true ? { mapOnly: true } : {}),
+ ...(randomClosedFaction ? { randomClosedFaction: true } : {}),
names,
message: str(c.message, MAX_CHAT),
balance,
@@ -474,3 +530,31 @@ export function twoTeamsStep(
/** What players are told a faction is called. */
export const teamName = (cfg: TwoTeamsConfig, faction: string): string =>
(Object.hasOwn(cfg.names, faction) && cfg.names[faction]) || faction;
+
+/** A persisted choice survives worker restarts and is replaced only at a match boundary. */
+export function chooseExcludedFaction(
+ previous: string | undefined,
+ factions: string[],
+ newMatch: boolean,
+ random: () => number = Math.random
+): string | null {
+ const available = [...new Set(factions.filter(Boolean))].sort();
+ if (available.length !== 3) return null;
+ if (!newMatch && previous && available.includes(previous)) return previous;
+ return available[Math.floor(random() * available.length)];
+}
+
+export function teamConfigForMap(
+ cfg: TwoTeamsConfig,
+ selection: MapSelection
+): TwoTeamsConfig | null {
+ const override = cfg.mapOverrides?.find((o) => mapTeamKey(o.selection) === mapTeamKey(selection));
+ if (override?.mode === 'standard') return null;
+ if (override)
+ return {
+ ...cfg,
+ closedFaction: override.closedFaction ?? '',
+ randomClosedFaction: override.mode === 'random'
+ };
+ return !cfg.mapOnly && (cfg.closedFaction || cfg.randomClosedFaction || cfg.balance) ? cfg : null;
+}
diff --git a/src/routes/(app)/server/[id]/rotation/+page.svelte b/src/routes/(app)/server/[id]/rotation/+page.svelte
index e874cbf4..e6bebc56 100644
--- a/src/routes/(app)/server/[id]/rotation/+page.svelte
+++ b/src/routes/(app)/server/[id]/rotation/+page.svelte
@@ -722,7 +722,7 @@
Add rotation entry
-
+