Skip to content

Lobbies · Modules

14 modules · 73 exports · 2 repositories · 67 e2e tests · 3 routes

Who imports who · hover a node
Depends onLobbies modulesUsed byMapListmap-list-generatorMapVotesmatch-profileVoiceEject.servervoiceRunCompsimg-exportMatchesscanner-ingestWeaponRangecomp-analyzerLeaderboard4 exportsLobbyActivity.server3 …LobbyMapList.server2 ex…LobbyProgression.serverLobbyRating4 exportsLobbySet15 exportsLobbyState11 exportsLobbyTransition4 exportsLobbyVoice.server2 expo…PlayerRoles2 exportsScoreboardAttributionTeamShuffle3 exportsWaitlist1 exportWeaponRoll20 exportsLoaders1 fileRepositories2 filesFeedItems.serverfeedComponents7 filesUserActivity.serveruser…Other4 filesActions2 filesScenarios.serverdev-too…Routines1 fileRoutes1 fileScripts1 file

Leaderboard

app/features/lobbies/core/Leaderboard.ts

Rankings tab of a lobby: each player's set and map record over the lobby's finished sets and the weapons they played, and how every player fared against every other.

Imports
LobbySet
Used by
1 loader1 repository1 module1 component

Types

interface

LeaderboardRow

:10

A player's record over the lobby's finished sets.

export interface LeaderboardRow {
	userId: number;
	setWins: number;
	setLosses: number;
	mapWins: number;
	mapLosses: number;
	/** 0-100, `null` with no maps played */
	mapWinPercentage: number | null;
	/** Weapons played on the maps, most used first */
	weaponSplIds: MainWeaponId[];
	/** 1-based, shared by players with the same record */
	placement: number;
}
Only used inside the module
interface

HeadToHeadRecord

:118

A player's record against one opponent over the finished sets they played on opposite sides.

export interface HeadToHeadRecord {
	setWins: number;
	setLosses: number;
	mapWins: number;
	mapLosses: number;
}

Functions & values

function

rows

:31

Leaderboard of the lobby's players from its finished (confirmed or forfeited) sets: set and map records and the weapons played. Sorted by set wins, then map win percentage. Players tied on all of these share the placement.

  • @param

    weapons one per player per map played, reported by hand or read by the scanner

  • @param

    roomMemberIds get a row of zeros until the lobby's first set is over

export function rows({
	sets,
	weapons,
	roomMemberIds = [],
}: {
	sets: LobbySet.SetLike[];
	weapons: Array<{ userId: number; weaponSplId: MainWeaponId }>;
	roomMemberIds?: number[];
}): LeaderboardRow[]
Unit tests (8)
function

headToHead

:129

Head-to-head records of the lobby's finished (confirmed or forfeited) sets, looked up as records[userId]?.[opponentId]. A pair that never played on opposite sides has no record.

export function headToHead(
	sets: LobbySet.SetLike[],
): Record<number, Record<number, HeadToHeadRecord>>
Unit tests (4)

LobbyActivity

serverapp/features/lobbies/core/LobbyActivity.server.ts

In-memory index of the lobby each user is active in, read through UserActivity: shown to friends and checked so a user isn't in SendouQ or a tournament at the same time. Also who a lobby's ready check is waiting on, for their header status.

Imports
no other modules
Used by
2 modules1 other

Functions & values

function

findByUserId

:15

The lobby the user is active in (present and not dropping), from memory. Kept fresh by LobbyProgression.advance.

export function findByUserId(userId: number): ActiveParticipation | null
function

findReadyCheckLobbyIdByUserId

:20

Id of the lobby whose open ready check asks the user to confirm they're ready, from memory.

export function findReadyCheckLobbyIdByUserId(userId: number): number | null
function

refresh

:25

Reloads who is active in which lobby from the database.

export async function refresh()

LobbyMapList

serverapp/features/lobbies/core/LobbyMapList.server.ts

Map list of a lobby set, generated when the set starts from the host's map pool or the players' match profile map preferences, and who of the players voted for its maps.

Imports
MapListMapVotes
Used by
1 loader1 module

Functions & values

function

generate

:29

Maps of a set between two shuffled teams. With the host's map pool set, its maps in plain rotation, none picked for either side. Otherwise picked like SendouQ's from the players' match profile map preferences, among the modes the host picked, each with the side(s) it was picked for. Continues from the maps already played in the lobby: those are less likely to come up, recent ones not right away, and the set starts with a different mode than the last one played.

export async function generate({
	alpha,
	bravo,
	modes,
	mapPool,
	bestOf,
	playedMaps,
}: {
	alpha: TeamPreferences;
	bravo: TeamPreferences;
	modes: ModeShort[];
	mapPool: ModeWithStage[] | null;
	bestOf: number;
	/** Maps reported in the lobby's earlier sets, oldest first, a map once per time played */
	playedMaps: ModeWithStage[];
}): Promise<Array<ModeWithStage & { source: LobbyMapSource }>>
Unit tests (4)
function

voters

:99

Players who voted for the map: of the side(s) it was picked for, those whose match profile pool has it. None for a map neither side voted for, or one of a set started before the sides were stored.

export function voters({
	map,
	participants,
	profiles,
}: {
	map: ModeWithStage & { source: LobbyMapSource | null };
	participants: Array<{ userId: number; side: LobbySide | null }>;
	profiles: Array<{
		userId: number;
		mapModePreferences: UserMapModePreferences | null;
	}>;
}): number[]
Unit tests (1)

LobbyProgression

serverapp/features/lobbies/core/LobbyProgression.server.ts

Applies the transitions LobbyTransition decides on to the database, then publishes the change to the lobby's page, updates the chat rooms and sends the notifications.

Imports
LobbyActivity.serverLobbyMapList.serverLobbyRatingLobbySetLobbyTransitionLobbyVoice.serverPlayerRolesTeamShuffleWeaponRoll
Used by
2 actions1 module1 routine

Functions & values

function

advance

:62

The only place lobby transitions happen. Loads the lobby, asks LobbyTransition what is due next and applies it, until nothing is: opening check-in, starting the lobby, shuffling after a confirmed set, filling the room, ready checks, applying drops, passing on the host and auto-closing. Then publishes the change to the lobby's page and sends the notifications. Idempotent: called after every lobby action and by a routine, so a missed call is fixed by the next one. Calls for the same lobby run one at a time.

  • @param

    hasChanged the caller already changed the lobby (e.g. reported a map), publish even if nothing else happens

  • @param

    affectedUserIds users the caller's change concerns who may not be participants anymore, e.g. who left

  • @param

    listingChanged the caller's change shows on the lobbies list (e.g. a sign up), publish it there too

export function advance(
	lobbyId: number,
	{
		hasChanged = false,
		affectedUserIds = [],
		listingChanged = false,
	}: {
		hasChanged?: boolean;
		affectedUserIds?: number[];
		listingChanged?: boolean;
	} = {},
): Promise<void>
Unit tests (21)

LobbyRating

app/features/lobbies/core/LobbyRating.ts

Lobby-local skill ratings, rebuilt from the lobby's finished sets, that TeamShuffle balances the teams with.

Imports
LobbySet
Used by
2 modules

Types

type

RatedSet

:11

A set counted towards the lobby's ratings, in the order they were played.

export type RatedSet = LobbySet.SetLike;
Only used inside the module

Functions & values

function

ratings

:20

Lobby-local openskill ratings computed from the lobby's game history. Everyone starts at the default rating and only finished (confirmed or forfeited) sets count, so nothing needs fixing when a set is voided or a player leaves. Each played map is one rating update and winning the set is one more on top: winning 2–1 counts as 3 wins and 1 loss. A forfeited set rates the maps actually played plus the set win of the side that didn't forfeit. Never touches the global SendouQ ratings.

export function ratings(sets: RatedSet[]): Map<number, Rating>
Unit tests (6)
function

ratingOf

:64

Rating of the user, the default one for someone who hasn't played a rated set yet.

export function ratingOf(ratingsByUserId: Map<number, Rating>, userId: number)
Unit tests (1)
function

winProbability

:69

Predicted probability (0-1) of the alpha team beating the bravo team.

export function winProbability(alpha: Rating[], bravo: Rating[])
Unit tests (2)

LobbySet

app/features/lobbies/core/LobbySet.ts

Rules of a lobby set (a best-of between two shuffled teams): the score, its status from reporting through confirmation and who of the players may report, undo, confirm or dispute.

Imports
no other modules
Used by
1 loader1 action1 repository6 modules4 components2 other

Types

interface

SetLike

:8

What a set's state is derived from: its games (maps) in order and who played on which side.

export interface SetLike {
	bestOf: number;
	forfeitingSide: LobbySide | null;
	disputedAt: number | null;
	confirmedAt: number | null;
	games: Array<{
		winnerSide: LobbySide | null;
		reportedByUserId: number | null;
	}>;
	participants: Array<{ userId: number; side: LobbySide | null }>;
}
type

SetStatus

:27

- REPORTING: maps being played and reported - AWAITING_CONFIRMATION: decided, the team that didn't report the deciding map has to confirm - DISPUTED: the confirming team said the result is wrong, stays so until the result changes or they confirm - CONFIRMED: both teams agree, the set counts - FORFEITED: a player left mid-set, their team lost without confirmation needed

export type SetStatus =
	| "REPORTING"
	| "AWAITING_CONFIRMATION"
	| "DISPUTED"
	| "CONFIRMED"
	| "FORFEITED";
Only used inside the module

Functions & values

function

score

:35

Maps won by each side and how many it takes to win the set.

export function score(set: Pick<SetLike, "bestOf" | "games">)
Unit tests (1)
function

winnerSide

:43

Side that won the set, by maps or by the other side forfeiting. null while undecided.

export function winnerSide(
	set: Pick<SetLike, "bestOf" | "games" | "forfeitingSide">,
): LobbySide | null
Unit tests (1)
function

status

:56

Current state of the set, see {@link SetStatus}.

export function status(set: SetLike): SetStatus
Unit tests (1)
function

currentGameIndex

:73

Index of the map being played, null when the set is decided.

export function currentGameIndex(set: SetLike)
Unit tests (1)
function

reportedCount

:82

How many maps have been reported.

export function reportedCount(set: Pick<SetLike, "games">)
Unit tests (1)
function

sideOf

:87

Side the user played on, null if they sat the set out or weren't in it.

export function sideOf(set: Pick<SetLike, "participants">, userId: number)
Unit tests (1)
function

playersOf

:95

User ids of the side's players.

export function playersOf(set: Pick<SetLike, "participants">, side: LobbySide)
Unit tests (1)
function

canReport

:102

Whether the user may report the winner of the current map.

export function canReport(set: SetLike, userId: number)
Unit tests (1)
function

canUndo

:111

Whether the user may undo the latest map report. While reporting anyone playing may, once decided only the side that reported the deciding map (the other side confirms or disputes instead). The host may any time before the set is finished.

export function canUndo(
	set: SetLike,
	userId: number,
	{ isHost = false }: { isHost?: boolean } = {},
)
Unit tests (2)
function

canConfirm

:131

Whether the user may confirm the decided result, i.e. plays on the side that didn't report it.

export function canConfirm(set: SetLike, userId: number)
Unit tests (1)
function

canDispute

:143

Whether the user may say the decided result is wrong.

export function canDispute(set: SetLike, userId: number)
Unit tests (1)
function

otherSide

:148

The opposing side.

export function otherSide(side: LobbySide): LobbySide
Unit tests (1)

LobbyState

app/features/lobbies/core/LobbyState.ts

Lobby status over time (upcoming, check-in, pending, active, ended), when check-in opens, when an idle lobby closes, who takes over as host and what the viewer may do on the lobby page.

Imports
no other modules
Used by
1 action1 module2 components2 other

Types

type

LobbyStatus

:20

- UPCOMING: before check-in opens, people sign up - CHECK_IN: check-in is open, the lobby starts at its start time - PENDING: started but no set is being played (fewer than 8 in the room) - ACTIVE: a set is being played - ENDED: ended by the host or closed for inactivity

export type LobbyStatus =
	| "UPCOMING"
	| "CHECK_IN"
	| "PENDING"
	| "ACTIVE"
	| "ENDED";
Only used inside the module
interface

ViewerActions

:164

What the viewer may do on the lobby page, see {@link viewerActions}.

export interface ViewerActions {
	/** Sign up, or apply to a lobby requiring it */
	SIGN_UP: boolean;
	CHECK_IN: boolean;
	/** Leave the lobby right away, forfeiting a set being played */
	LEAVE: boolean;
	/** Toggle leaving once the set being played is confirmed */
	DROP_AFTER_SET: boolean;
}
Only used inside the module

Functions & values

function

isCheckInOpen

:56

Whether check-in is open: once enough for a set have signed up and the start is at most some minutes away (or past). Stays open after it has opened, even if people leave.

export function isCheckInOpen({
	lobby,
	participants,
	now,
}: {
	lobby: { startsAt: number; checkInOpenedAt: number | null };
	participants: Array<{ status: LobbyParticipantStatus }>;
	now: number;
})
Unit tests (1)
function

statusAndCheckIn

:74

The lobby's {@link status} together with the {@link isCheckInOpen} it's derived from.

export function statusAndCheckIn({
	lobby,
	participants,
	isPlaying,
	now,
}: {
	lobby: {
		startsAt: number;
		endedAt: number | null;
		checkInOpenedAt: number | null;
	};
	participants: Array<{ status: LobbyParticipantStatus }>;
	/** The room's latest set is unfinished */
	isPlaying: boolean;
	now: number;
})
function

checkInOpensAt

:99

Earliest check-in can open: some minutes before the start, if enough have signed up by then.

export function checkInOpensAt(startsAt: number)
Unit tests (1)
function

nextStatusChangeAt

:107

When the status next changes by the clock alone: check-in opening (if enough have signed up already), then the start. null once started.

export function nextStatusChangeAt({
	status: lobbyStatus,
	startsAt,
	participants,
}: {
	status: LobbyStatus;
	startsAt: number;
	participants: Array<{ status: LobbyParticipantStatus }>;
})
Unit tests (1)
function

isAutoCloseDue

:128

Whether a lobby has gone long enough without anything happening to be closed.

export function isAutoCloseDue({
	status: lobbyStatus,
	lastActivityAt,
	pendingSince,
	now,
}: {
	status: LobbyStatus;
	/** Latest map reported or set started */
	lastActivityAt: number | null;
	pendingSince: number | null;
	now: number;
})
Unit tests (1)
function

nextHost

:153

Who becomes the host when the current one leaves: the participant who signed up the earliest.

export function nextHost<T extends { userId: number; joinedAt: number }>(
	participants: T[],
): number | null
Unit tests (2)
function

viewerActions

:175

What the viewer may do in the lobby right now.

export function viewerActions({
	status: lobbyStatus,
	viewer,
	isPlayingUnfinishedSet,
	hasFriendCode,
	isKicked,
	application,
	isCheckInOpen: checkInOpen,
	activeCount: presentCount,
	roomSize,
	now,
	startsAt,
}: {
	status: LobbyStatus;
	viewer: { status: LobbyParticipantStatus } | null;
	isPlayingUnfinishedSet: boolean;
	hasFriendCode: boolean;
	/** The host kicked the viewer out of the lobby */
	isKicked: boolean;
	/** The viewer's application to the lobby, while it requires applying */
	application: LobbyApplicationState | null;
	/** See {@link isCheckInOpen} */
	isCheckInOpen: boolean;
	/** Participants present (checked in or in the room) */
	activeCount: number;
	roomSize: number;
	now: number;
	startsAt: number;
}): ViewerActions
Unit tests (1)
function

activeCount

:240

Participants present: checked in or in the room.

export function activeCount(
	participants: Array<{ status: LobbyParticipantStatus }>,
)
function

signedUpCount

:249

Participants holding a spot, i.e. everyone but the waitlisted.

export function signedUpCount(
	participants: Array<{ status: LobbyParticipantStatus }>,
)
Unit tests not about one export (1)

Not shown, only used by tests: status

LobbyTransition

app/features/lobbies/core/LobbyTransition.ts

Decides the next change a lobby goes through (opening check-in, starting, promoting from the waitlist, filling the room, ready checks, starting a set, passing on the host, ending or deleting) from its current state. Pure, applied by LobbyProgression.

Imports
LobbySetLobbyStateWaitlist
Used by
1 module

Types

interface

ProgressionState

:15

Everything the next transition of a lobby is decided from.

export interface ProgressionState {
	lobby: {
		hostUserId: number;
		startsAt: number;
		roomSize: number;
		pendingSince: number | null;
		endedAt: number | null;
		checkInOpenedAt: number | null;
	};
	/** In sign-up order */
	participants: Array<{
		userId: number;
		status: LobbyParticipantStatus;
		joinedAt: number;
		isDroppingAfterSet: boolean;
		/** Set by the host, takes a room slot but plays no sets */
		isSittingOut: boolean;
	}>;
	latestSet:
		| (LobbySet.SetLike & {
				/** Latest map report or the set's start */
				lastActivityAt: number;
		  })
		| null;
	readyChecks: Array<{
		id: number;
		expiresAt: number;
		users: Array<{ userId: number; confirmedAt: number | null }>;
	}>;
}
type

Transition

:47

A change to the lobby's state, applied by LobbyProgression.advance one at a time.

export type Transition =
	| { type: "END" }
	/** Before the start: everyone left, nothing of the lobby is worth keeping */
	| { type: "DELETE" }
	| { type: "TRANSFER_HOST"; userId: number }
	/** Marks check-in open for good, notifying those with a spot */
	| { type: "OPEN_CHECK_IN" }
	/** Before the start: waitlisted get spots freed in the room */
	| { type: "PROMOTE"; userIds: number[] }
	/** Fills the room with the checked in, once those with a spot who didn't check in are removed */
	| { type: "START"; userIds: number[] }
	| { type: "REMOVE"; userIds: number[] }
	| { type: "START_SET" }
	| { type: "OPEN_SLOT_CHECK" }
	/** Moves participants into the room's free slots */
	| { type: "FILL_SLOTS"; userIds: number[] }
	| { type: "CLOSE_CHECK"; readyCheckId: number }
	| { type: "SET_PENDING_SINCE"; pendingSince: number | null };

Functions & values

function

next

:70

The next transition the lobby should go through, null when it's settled. Applying the result and asking again eventually settles: every transition moves the lobby closer to a state where nothing is due.

export function next(state: ProgressionState, now: number): Transition | null
Unit tests (32)
function

waitlist

:152

Queue of the waitlist, everyone not in the room, highest first.

export function waitlist(state: Pick<ProgressionState, "participants">)
Unit tests (1)

LobbyVoice

serverapp/features/lobbies/core/LobbyVoice.server.ts

Keeps the voice calls of a lobby's chats to those still in them: a user who leaves the lobby, or sits out the next set, is ejected from the calls they no longer belong in.

Imports
VoiceEject.serverLobbySet
Used by
1 action1 module

Functions & values

function

ejectLeavers

:14

Ends the calls of users no longer in the lobby, in its chat and their team's chat of the latest set.

export function ejectLeavers({
	lobby,
	latestSet,
	userIds,
}: {
	lobby: { chatRoomId: number | null; participantUserIds: number[] };
	latestSet: SetWithChats | undefined;
	userIds: number[];
})
function

ejectSittingOut

:37

Ends the calls in the previous set's team chats of its players who don't play the next set.

export function ejectSittingOut({
	previousSet,
	playingUserIds,
}: {
	previousSet: SetWithChats;
	playingUserIds: number[];
})

PlayerRoles

app/features/lobbies/core/PlayerRoles.ts

Role tags of a player (Tacticooler, backline) from their weapon pool, which TeamShuffle spreads evenly across the teams.

Imports
RunCompsWeaponRoll
Used by
2 modules

Types

type

PlayerRole

:13

Roles that TeamShuffle spreads across the teams. TACTICOOLER and BACKLINE make a team lopsided when stacked on one side, BACKLINE_IN_POOL players can fill the backline so each team should get one.

export type PlayerRole = "TACTICOOLER" | "BACKLINE" | "BACKLINE_IN_POOL";

Functions & values

function

fromWeaponPool

:23

Role tags of a player derived from their match profile weapon pool: TACTICOOLER if the pool is mostly Tacticooler kits, BACKLINE if mostly backline weapons (see WeaponRoll.tierOf) and BACKLINE_IN_POOL if it has any. An empty pool has no roles.

export function fromWeaponPool(weaponPool: MainWeaponId[]): PlayerRole[]
Unit tests (1)

ScoreboardAttribution

app/features/lobbies/core/ScoreboardAttribution.ts

Who of a lobby's players sat on which row of a game's scanned scoreboard. A row only carries an in-game name, which can differ from the one on the site or be misread, so names are learned over the whole lobby: teams reshuffle after every set, and a name keeps landing on the side of the one player who plays under it.

Reads of a name (OCR variants pooled, the scanner's isSameNameRead) are scored against every player: a point for each game they shared a side, ANCHOR_WEIGHT more for each game an anchor ties them (the POV seat of a scan, the only row of the side with a weapon the player reported, the player's in-game name on the site). Each side of a game then takes its highest scoring row → player assignment. A row is left unattributed when another equally scoring assignment gives it someone else, so a name only seen with the same teammates stays unknown, while a name new mid-set (a name change) is still placed once the side's other rows are. A name whose top scorer didn't play on the row's side (someone playing on another's seat or Switch) says nothing about whose seat the row is, so its row is only placed that way too.

Imports
Matches
Used by
1 loader

Functions & values

function

rowUserIds

:50

Attributes the scoreboard rows of a lobby's games to its players, see the top of the file.

  • @param

    games every game of the lobby with a scoreboard, the more the better

  • @returns

    per game, the user id of each row (index-aligned with rows), null where it can't be told

export function rowUserIds(
	games: AttributionGame[],
): Array<Array<number | null>>
Unit tests (10)

Not shown, only used by tests: AttributionGame

TeamShuffle

app/features/lobbies/core/TeamShuffle.ts

Splits the players in a lobby's room into two teams of four for the next set.

How it works:

1. If the room has more than 8 players, some sit the set out (see {@link pickSitOuts}). 2. Every possible 4v4 split of the remaining 8 is tried (there are only 35) and scored with a cost, the sum of the weighted cost terms below. The cheapest split wins, ties are broken randomly.

Cost terms, in priority order:

1. {@link balanceCost}: how far the predicted win probability is from 50%, from the lobby-local ratings 2. {@link backlineCoverageCost}: a team with nobody who has a backline weapon in their pool 3. {@link roleStackCost} of BACKLINE: stacking players who mostly play backline on one team 4. {@link teammateRepeatCost}: playing with the same teammates again, especially those of the previous set 5. {@link roleStackCost} of TACTICOOLER: stacking Tacticooler players on one team

To add a cost term: write a function of the shape (split, context) => number where a lower number is better, export a weight constant for it next to the others and add it to {@link splitCost}. Add a test.each row to TeamShuffle.test.ts showing the split it should prefer.

Imports
LobbyRating
Used by
1 module

Types

interface

TeammateHistory

:79

Who has been whose teammate in this lobby.

export interface TeammateHistory {
	/** Sets played together on the same team, keyed by {@link pairKey} */
	setsTogether: Map<string, number>;
	/** Pairs ({@link pairKey}) that were on the same team in the room's previous set */
	previousSetPairs: Set<string>;
}
Only used inside the module

Functions & values

function

teammateHistory

:243

Builds the teammate history from the teams of earlier sets, oldest first.

export function teammateHistory(
	sets: Array<{ alpha: number[]; bravo: number[] }>,
): TeammateHistory
Unit tests (1)
Unit tests not about one export (8)

Not shown, only used by tests: BALANCE_WEIGHT, BACKLINE_COVERAGE_WEIGHT, BACKLINE_STACK_WEIGHT, TEAMMATE_REPEAT_WEIGHT, PREVIOUS_SET_TEAMMATE_WEIGHT, TACTICOOLER_STACK_WEIGHT, ShufflePlayer, ShuffleResult, pickSitOuts, splitCost, balanceCost, backlineCoverageCost, teammateRepeatCost, roleStackCost, pairKey

Waitlist

app/features/lobbies/core/Waitlist.ts

Who of the waitlist gets the room's open slots when a ready check asks them to confirm.

Imports
no other modules
Used by
1 module

Functions & values

function

slotWinners

:13

Who of the waitlist gets the room's open slots. During the priority window a slot goes to the highest in the waitlist who confirmed, decided early once nobody above them can still claim it. After the window everyone who confirmed within it is ranked by waitlist order, then later confirmers first come, first served.

  • @param

    queue user ids of the waitlist in order, highest first

export function slotWinners({
	slotCount,
	queue,
	confirmedAtByUserId,
	priorityEndsAt,
	now,
}: {
	slotCount: number;
	queue: number[];
	confirmedAtByUserId: Map<number, number>;
	priorityEndsAt: number;
	now: number;
}): number[]
Unit tests (1)

WeaponRoll

app/features/lobbies/core/WeaponRoll.ts

Rolls random weapons for the two sides of a lobby game, balanced with what SendouQ results say about them.

How it works:

1. {@link WeaponRollOptions.candidates} times, 8 weapons of different base weapons are drawn, each as likely as its SendouQ usage share raised to {@link WeaponRollOptions.popularityExponent}, less likely if the lobby rolled it in one of its last sets (see {@link repeatFactor}). 2. Every 4v4 split of the 8 is scored with a cost, the sum of the weighted cost terms below, and the cheapest split is that candidate's. 3. The cheapest candidate wins, more candidates trade variety for balance. Every weight 0 is a plain random roll.

Cost terms:

1. {@link strengthCost}: how far the win probability predicted from the weapons alone is from 50% 2. {@link shapeCost}: how rare each team's frontline/midline/backline counts are in real SendouQ teams 3. {@link shapeMismatchCost}: how differently shaped the two teams are 4. {@link specialStackCost}: weapons of a team sharing a special

The weapon data is generated by scripts/compute-weapon-roll-data.ts, its top comment explains the model.

Imports
WeaponRange
Used by
1 route2 modules1 script

Types

interface

WeaponRollOptions

no JSDoc:47
export interface WeaponRollOptions {
	/** Mode of the game, picks the mode specific weapon strengths. `null` uses the all modes ones. */
	mode: ModeShort | null;
	/** Draws of 8 weapons tried, the cheapest wins */
	candidates: number;
	/** 0 = every weapon equally likely, 1 = as likely as in SendouQ */
	popularityExponent: number;
	/** Per percentage point the weapons' predicted win probability is off 50% */
	strengthWeight: number;
	/** Per unit of {@link shapeCost} */
	shapeWeight: number;
	/** Per player of {@link shapeMismatchCost} */
	shapeMismatchWeight: number;
	/** Per weapon of {@link specialStackCost} */
	specialStackWeight: number;
	/** How likely a weapon rolled in the previous set is drawn compared to normally, 1 = no penalty, 0 = never */
	repeatWeight: number;
	/** Over how many sets the repeat penalty fades away */
	repeatFadeSets: number;
}
type

WeaponTier

no JSDoc:101
export type WeaponTier = (typeof WEAPON_TIERS)[number];
interface

WeaponRollData

:133

Generated weapon data, see scripts/compute-weapon-roll-data.ts.

export interface WeaponRollData {
	generatedAt: string;
	mapCount: number;
	/** Keyed by weapon id, alt skins folded to their base */
	weapons: Record<string, WeaponRollDataWeapon>;
	/** Share of real SendouQ teams per {@link shapeKey} */
	shapes: Record<string, number>;
}
interface

WeaponRollResult

no JSDoc:173
export interface WeaponRollResult {
	alpha: MainWeaponId[];
	bravo: MainWeaponId[];
	/** Alpha's win probability predicted from the weapons alone */
	alphaWinProbability: number;
	cost: WeaponRollCost;
}

Functions & values

const

DEFAULT_WEAPON_ROLL_OPTIONS

no JSDoc:69
export const DEFAULT_WEAPON_ROLL_OPTIONS: WeaponRollOptions = {
	mode: null,
	candidates: 20,
	popularityExponent: 0.4,
	strengthWeight: 0.7,
	shapeWeight: 0.8,
	shapeMismatchWeight: 0.9,
	specialStackWeight: 1.2,
	repeatWeight: 0.25,
	repeatFadeSets: 3,
};
const

WEAPON_TIERS

no JSDoc:100
export const WEAPON_TIERS = ["FRONTLINE", "MIDLINE", "BACKLINE"] as const;
const

WEAPON_ROLL_DATA

no JSDoc:153
export const WEAPON_ROLL_DATA: WeaponRollData = rawWeaponRollData;
const

ROLLABLE_WEAPON_IDS

:161

Weapons that can be rolled: every weapon with its own kit, alt skins left out.

export const ROLLABLE_WEAPON_IDS = mainWeaponIds.filter(
	(weaponId) => weaponIdToType(weaponId) !== "ALT_SKIN",
);
function

roll

:185

Rolls the weapons of both sides, see the top of the file. recentRolls are the weapons of the lobby's previous sets, newest first. noScreen never rolls a weapon with Splattercolor Screen. random is injectable for tests.

export function roll(
	options: WeaponRollOptions,
	{
		recentRolls = [],
		noScreen = false,
		random = Math.random,
	}: {
		recentRolls?: MainWeaponId[][];
		noScreen?: boolean;
		random?: () => number;
	} = {},
): WeaponRollResult
Unit tests (8)
function

rollForSet

:232

Rolls the weapons each side of a set gets with the lobby's randomizer, recentRolls being its previous sets' newest first. noScreen when a player of the set avoids Splattercolor Screen.

export function rollForSet(
	randomizer: Exclude<LobbyWeaponRandomizer, "OFF">,
	{
		recentRolls = [],
		noScreen = false,
	}: { recentRolls?: LobbyRolledWeapons[]; noScreen?: boolean } = {},
): LobbyRolledWeapons
Unit tests (3)
function

evaluate

:270

Scores the given teams with the cost terms, see the top of the file.

export function evaluate(
	{ alpha, bravo }: { alpha: MainWeaponId[]; bravo: MainWeaponId[] },
	options: WeaponRollOptions,
): WeaponRollResult
function

shapeMismatchCost

:315

How many players of one team would need to change tier for the teams to be shaped the same.

export function shapeMismatchCost(
	alpha: MainWeaponId[],
	bravo: MainWeaponId[],
)
Unit tests (1)
function

specialStackCost

:330

Weapons of the team whose special another weapon of the team already has.

export function specialStackCost(team: MainWeaponId[])
Unit tests (1)
function

shapeShare

:335

Share of real SendouQ teams with the shape, see {@link shapeKey}.

export function shapeShare(key: string)
function

shapeKey

:340

Frontline, midline and backline counts of a team, e.g. "2-1-1".

export function shapeKey(team: MainWeaponId[])
Unit tests (1)
function

tierOf

:348

Where on the map the weapon plays, from its category or else its range.

export function tierOf(weaponId: MainWeaponId): WeaponTier
Unit tests (1)
function

rangeOf

:369

Simulated range of the weapon, see WeaponRange.

export function rangeOf(weaponId: MainWeaponId)
function

strengthOf

:380

Strength of the weapon in the mode, the all modes one if the mode has no data. 0 for weapons without data.

export function strengthOf(weaponId: MainWeaponId, mode: ModeShort | null)
function

usageOf

:388

Share of the SendouQ reported weapons that are this weapon.

export function usageOf(weaponId: MainWeaponId)
function

specialOf

:394

Special of the weapon's kit.

export function specialOf(weaponId: MainWeaponId): SpecialWeaponId
Unit tests not about one export (5)

Not shown, only used by tests: repeatFactor, winProbability