Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/lib/components/MapPicker.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -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('');
Expand Down Expand Up @@ -154,3 +156,5 @@
</div>
</div>
</div>

{#if canManageTeams}<MapTeamSettings {serverId} selection={{ map, experiences: [mode, ...mods].filter(Boolean), lighting, zoneAlternator: zone }} disabled={disabled || !map || !mode} />{/if}
164 changes: 164 additions & 0 deletions src/lib/components/MapTeamSettings.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<script lang="ts">
import { api, errorMessage } from '$lib/api';
import { mapTeamKey, type MapTeamMode } from '$lib/map-team-mode';
import { toast } from '$lib/toast.svelte';
import type { MapSelection, TriggerView } from '$lib/types';
const t = (message: string) => message;
let {
serverId,
selection,
disabled = false,
teamVersusTeam = $bindable(false)
}: {
serverId: string;
selection: MapSelection;
disabled?: boolean;
teamVersusTeam?: boolean;
} = $props();
let rules = $state<TriggerView[]>([]);
let loaded = $state('');
let error = $state('');
let busy = $state(false);
let random = $state(false);
let mode = $derived<MapTeamMode['mode']>(
teamVersusTeam ? (random ? 'random' : 'manual') : 'standard'
);
let closedFaction = $state('Lonestar');
let rule = $derived(rules.find((r) => r.kind === 'two_teams'));
let saved = $derived(
(rule?.config.mapOverrides as MapTeamMode[] | undefined)?.find(
(o) => mapTeamKey(o.selection) === mapTeamKey(selection)
)
);
$effect(() => {
teamVersusTeam = saved?.mode === 'manual' || saved?.mode === 'random';
random = saved?.mode === 'random';
closedFaction = saved?.closedFaction ?? 'Lonestar';
});
$effect(() => {
const target = serverId;
let stopped = false;
loaded = '';
error = '';
api<{ triggers: TriggerView[] }>('GET', `/api/servers/${encodeURIComponent(target)}/triggers`)
.then((r) => {
if (!stopped) {
rules = r.triggers;
loaded = target;
}
})
.catch((e) => {
if (!stopped) error = errorMessage(e);
});
return () => {
stopped = true;
};
});
let changed = $derived(
teamVersusTeam
? mode !== saved?.mode || (mode === 'manual' && closedFaction !== saved?.closedFaction)
: saved?.mode === 'manual' || saved?.mode === 'random'
);
export function ready() {
return loaded === serverId && !busy && !error;
}
export async function save(): Promise<boolean> {
if (!ready()) return false;
if (!changed) return true;
const target = serverId;
const chosen = structuredClone($state.snapshot(selection));
const key = mapTeamKey(chosen);
const pickedMode = mode,
pickedFaction = closedFaction;
busy = true;
try {
const path = `/api/servers/${encodeURIComponent(target)}/triggers`;
const fresh = await api<{ triggers: TriggerView[] }>('GET', path);
const current = fresh.triggers.find((r) => r.kind === 'two_teams');
const overrides = ((current?.config.mapOverrides as MapTeamMode[] | undefined) ?? []).filter(
(o) => mapTeamKey(o.selection) !== key
);
overrides.push({
selection: chosen,
mode: pickedMode,
...(pickedMode === 'manual' ? { closedFaction: pickedFaction } : {})
});
if (!current && !overrides.length) return true;
// A disabled server-wide rule must not become active on other maps when saving this map.
const base = current?.config ?? { closedFaction: '', balance: false, message: '' };
const mapOnly = current ? !current.enabled || base.mapOnly === true : true;
const config = { ...base, mapOnly, mapOverrides: overrides };
const hasGlobal =
!mapOnly && !!(base.closedFaction || base.randomClosedFaction || base.balance);
const body = {
kind: 'two_teams',
name: current?.name ?? 'Team balance',
enabled: hasGlobal || overrides.length > 0,
config
};
await api(
current ? 'PATCH' : 'POST',
current ? `${path}/${encodeURIComponent(current.id)}` : path,
body
);
const updated = await api<{ triggers: TriggerView[] }>('GET', path);
if (serverId === target) rules = updated.triggers;
return true;
} catch (e) {
toast(errorMessage(e), 'err');
return false;
} finally {
busy = false;
}
}
</script>

<div class="mt-4 border-t border-white/10 pt-4">
<label class="flex items-center gap-2"><input type="checkbox" bind:checked={teamVersusTeam} disabled={disabled || busy || loaded !== serverId} /> Use two-team balance for this map</label>
<p class="note">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.</p>
{#if teamVersusTeam || changed}
<fieldset
class="mt-3 border-t border-white/10 pt-3"
disabled={disabled || busy || loaded !== serverId}
>
<div class="flex flex-wrap items-end gap-2">
{#if teamVersusTeam}
<label class="block w-full min-w-0 sm:w-56">
<span class="label-sm mb-1.5">{t('Excluded faction')}</span>
<select
class="input"
value={random ? '' : closedFaction}
onchange={(e) => {
closedFaction = e.currentTarget.value;
random = false;
}}
>
<option value="" disabled>{t('Random each match')}</option>
{#each ['Lonestar', 'Valkyra', 'Manticore'] as faction}<option value={faction}
>{faction}</option
>{/each}
</select>
</label>
<button
type="button"
class="btn"
class:btn-primary={random}
aria-pressed={random}
onclick={() => (random = !random)}>{t('Random')}</button
>
{/if}
</div>
<p class="mt-2 text-[12px] leading-relaxed text-mist-400">
{t(
teamVersusTeam
? random
? 'Random excluded faction each match'
: 'Players on the excluded faction move to the other two teams.'
: 'All factions will be restored when this map selection is applied.'
)}
</p>
</fieldset>
{/if}
{#if error}<p class="mt-2 text-danger">{error}</p>{/if}
<button type="button" class="btn mt-3" disabled={disabled || busy || loaded !== serverId || !changed} onclick={save}>Save map team settings</button>
</div>
34 changes: 34 additions & 0 deletions src/lib/map-team-mode.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
}

/** 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 } : {})
};
}
63 changes: 63 additions & 0 deletions src/lib/server/triggers-two-teams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
53 changes: 52 additions & 1 deletion src/lib/server/triggers.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -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<string, unknown> | undefined;
if (cfg.randomClosedFaction) {
const saved = (row.state ?? {}) as Record<string, unknown>;
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 ||
Expand Down
Loading