Skip to content

Score, stats and achievements ​

Numbers the rules count for each player as the game goes (kills, losses, resources, damage, your own stats), a classic RTS score screen with a graph, and achievements. A game that sets no score counts nothing and pays nothing.

Quick start ​

ts
import { presetScore } from '@v12-engine/engine'

export const myMode: Rules = {
	// ...
	settings: { score: presetScore() } // every engine stat, a graph point every 10 seconds
}

The end-of-game screen gets a Score button with tabs for units, heroes, combat and resources, and a graph. The pause menu has a Score line too.

Common tasks ​

Count only some stats ​

ts
settings: { score: presetScore({ only: ['unitsKilled', 'gathered'], every: 5 }) } // gathered = every gathered.<id>
settings: { score: presetScore({ without: ['army'] }) }

Count a stat of your own ​

ts
const towersLost = defineStat({
	id: 'towersLost',
	label: 'Towers lost',
	category: 'units',
	from: scoreOn(entityDied, ({ entity }) => (entity.def.id === 'guardTower' ? entity.owner : undefined))
})
const gatesHeld = defineStat({ id: 'gatesHeld', label: 'Gates held', category: 'glory', kind: 'max', timeline: true })
const gold = defineStat({ id: 'goldBanked', label: 'Gold in the bank', sample: (world, player) => world.player(player).resources.gold })

settings: { score: presetScore({ stats: [towersLost, gatesHeld, gold] }) }

Count from code ​

ts
world.score.add(player, 'gatesHeld', 1)
world.score.set(player, 'gatesHeld', 3)
world.score.get(player, 'unitsKilled')

A stat not listed in the rules throws. Your own purchases should call spend and giveBack so they count as spending.

Add achievements ​

ts
export const myView: GameView = {
	achievements: defineAchievements([
		{ id: 'butcher', name: 'Butcher', description: 'Kill 50 units in a game', when: { stat: 'unitsKilled', atLeast: 50 } },
		{ id: 'flawless', name: 'Flawless', description: 'Win losing nothing', when: { all: [{ won: true }, { stat: 'unitsLost', atMost: 0 }] } }
	])
}

Each is earned once, kept in the player's browser profile (browserProfile), and announced in the game. profileScene({ game, back }) (@v12-engine/client/app) shows games played, wins and achievements.

Change the score screen ​

ts
export const myView: GameView = {
	hud: {
		score: {
			atEnd: 'open', // at the end: a button (the default), open at once, or none
			menu: true, // the pause menu's line
			labels: { unitsKilled: 'Kills' },
			format: (stat, value) => (stat.id === 'damageDealt' ? `${(value / 1000).toFixed(1)}k` : undefined),
			graph: ['army', 'gathered.gold'],
			hide: ['combat']
		}
	}
}

Open it from code with client.score.show(tab), hide(), shown().

Build your own score screen ​

Replace the HUD part (hud.widgets: [{ id: 'score', component: Mine }]) and use the pieces Score, ScoreBoard, ScoreTable, ScoreGraph (@v12-engine/client/hud), or read client.score directly.

Show allies' numbers only at the end ​

ts
settings: { score: presetScore({ live: 'own', end: 'everyone' }) }

Reference ​

Engine stats (presetScore, engineStats(game)) ​

TabStats
unitsunitsProduced (trained and hired), unitsKilled, unitsLost, buildingsBuilt, buildingsRazed, buildingsLost, army (supply used now), largestArmy
heroesheroesKilled, heroesLost, highestHeroLevel, experience, creepsKilled, itemsObtained, abilitiesCast
combatdamageDealt (to enemies), damageTaken, healing
resourcesPer resource: gathered.<id>, spent.<id> (less refunds), upkeep.<id>; bounty, tradedOut, tradedIn (with allies)

A kill counts for the killer's owner when they are enemies (a deny is no kill). A loss is any death except a cancelled construction, an expired summon, a removal, a felled tree or an empty mine. Many stats are also kept by type (byType): kills by type killed, damage by dealer type, abilities by ability, spending by what it went on (unit, upgrade, structure, item, hire, repair).

Stat (ScoreStatDef) ​

FieldWhat it does
id, label, descriptionIts id, name and tip
categoryIts tab (other if left out)
kindsum (default), count, max, min, last
fromscoreOn(event, count) or a list; count returns nothing, a player, { player, amount, type }, or a list
sample(world, player)A gauge read each second and at each graph point (kind last by default)
byTypeAlso keep it by what it was counted of
timelineA point every every seconds for the graph
hiddenCounted but not shown (for achievements and missions)
formatnumber, decimal, percent (0..1), time (seconds)

Score settings (ScoreSettings) ​

FieldDefaultWhat it does
statsA list, or (game) => [...engineStats(game), mine]
every10Seconds between graph points (0 for none)
maxPoints360Past this, every other point is dropped so the whole game fits
liveallies (observers: everyone)Who sees a player's numbers during the game: own, allies, everyone, none, or (world, viewer, player) => boolean
endeveryoneThe same once the game is decided
refresh1Seconds between updates to the screens
countsall but neutral and creeps(world, player) => boolean: whose numbers are kept
categoriesthose of the statsThe tabs, in order, with names

world.score ​

add(player, id, amount), set(player, id, value), get(player, id), byType(player, id), team(team, id), timeline(player, id), players(). A source or gauge that throws is reported like a listener's error (listener:score:<id>, system:score:<id>, see Rules.onError). Spending fires resourcesSpent ({ player, cost, on, id, refund }); upkeep taken from a load is in resourcesDeposited.upkeep.

Saved and sent ​

The score is world state (scoreData, core.score), so saves, loads and replays count the same. Snapshots carry Snapshot.score (rounded to hundredths, only when changed) and Snapshot.scoreLine (the timeline). Melee's full score costs no measurable tick time and about 5.5 kB per ten minutes in a save.

client.score ​

state() and line() (signals), get(player, id), team(team, id), byType, timeline(player, id), players(), stats(), label(stat), format(stat, value), on(listener), look, show(tab), hide(), shown(). The debug panel's Score window (section score) shows every stat live, hidden ones too.

Achievement conditions ​

ConditionTrue when
{ stat, atLeast }, { stat, atMost }A stat of the player's (hidden ones too)
{ objective: id }, status: 'failed'An objective is done (or failed)
{ won: true }The game is won (or lost)
all, any, notOf others
A function of AchievementFactsstat(id), objective(id), outcome, seconds

Achievements are checked on the player's screen (client.achievements, an AchievementTracker), never in the simulation.