yahtzee-api
v1.2.0
Published
A library providing an API for playing Yahtzee.
Readme
Yahtzee API
Try the online demo.
Provides a simple API for playing the game of Yahtzee.
import { Game, ComputerPlayer, HumanPlayer } from 'yahtzee-api'
const p1 = new HumanPlayer({
randomSeed: 0,
name: 'Alice',
})
const p2 = new ComputerPlayer({
randomSeed: 1,
throttle: 200,
})
const game = new Game({
players: [p1, p2],
logHooks: {
async onInfo(...message) {
Promise.resolve(console.log('INFO:', ...message))
}
}
})
await game.step() // initialize and roll Alice's dice
await game.step('QWR') // Alice holds some dice
await game.step('QWRT') // Alice holds again for the final roll
await game.step('chance') // score; the computer plays, then Alice rolls again
// ... continue until the game is overInstallation
npm install yahtzee-apiRequires Node.js 22 or newer. The package supports both ESM imports and
CommonJS require('yahtzee-api'), with declarations for both module formats.
Import from the public package entry point, not internal build paths.
Rules and compatibility
Every game uses the same standard rules: five six-sided dice, three rolls per
turn, and all 13 scoring categories. GAME_DEFAULTS and Game.DEFAULT_OPTIONS
expose the frozen defaults; the former gameOptions constructor property and
GameOptions type have been removed. Passing the old property at runtime throws.
- An upper-section subtotal of at least 63 earns a 35-point bonus.
- An additional Yahtzee earns 100 points when scored, provided the Yahtzee box already contains 50. Rerolling or holding dice never awards bonus points.
- Additional Yahtzees use the forced-choice Joker rule, including when Yahtzee was scratched: fill the matching upper box if available; otherwise fill an available lower box, where Full House/Small Straight/Large Straight score 25/30/40. If no lower boxes remain, use another upper box for zero. A scratched Yahtzee box never earns the extra 100 points.
- Filled categories, including zero scores, cannot be overwritten.
Use scorecard.getLegalCategories(dice) when offering scoring choices.
upperTotal(), upperBonus(), and totalScore() include the standard upper
bonus calculation; totalScore() also includes accumulated Yahtzee bonuses.
These are intentional changes from the previous nonstandard scoring. Saved category scores and accumulated Yahtzee bonuses are retained, but future turns use the new rules and totals now include any earned upper bonus. Old seeded results are therefore not expected to match. Serialized dice must also obey the fixed five-dice/six-side rules.
Classes
Player
Represents a player in the game. Extend the abstract Player for custom input
sources, or use the built-in ComputerPlayer and HumanPlayer. HumanPlayer
always waits for input through game.step(input); it needs only randomSeed,
name, and optional player hooks.
See the examples section for usage.
type PlayerConstructorProps = {
randomSeed: number,
name: string,
// simulates a delay in the player's actions,
// useful for computer players.
throttle?: number,
// if true, the game will enter a state of waiting
// for user input before proceeding to the next step.
// This is useful for human players in a stepped
// execution mode.
suspend?: boolean,
}
abstract class Player {
constructor(opts: PlayerConstructorProps)
// do something to get the player's input
// for held dice.
// can use a side-effect like a prompt or pass
// the input directly to the `step` method.
getHeldDice(userInput?: string): Promise<string | undefined>
// do something to get the player's input
// for scoring a category.
// can use a side-effect like a prompt or pass
// the input directly to the `step` method.
getScore(userInput?: string): Promise<string | undefined>
// advance the player's current turn by one step.
step(log: Log, userInput?: string): Promise<TurnState>
// serialize the player to JSON.
// can be used to save the game state or resume later.
asJSON(): SerializedPlayer
// deserialize a player from JSON.
// can be used to resume a game from a saved state.
static fromJSON<T extends Player>(
data: SerializedPlayer,
PlayerClass: new (props: PlayerConstructorProps) => T
): T
}Computer players can be instantiated directly and implement their own logic for holding dice and scoring.
class ComputerPlayer extends Player {
constructor(opts: {
randomSeed: number,
throttle?: number,
})
}Computer AI
The computer player uses a full-game dynamic-programming solver as its only AI. It maximizes expected final score under the standard rules above and fair, independent dice, rather than approximating the value of future turns.
- Evaluates every distinct hold and possible reroll outcome over the remaining one or two rolls, weighting outcomes by their actual probabilities.
- Scores categories using points now + optimal expected points from every remaining turn. This includes the future benefit of scoring the first Yahtzee.
- Solves 355,392 compressed states covering available categories, progress toward the upper bonus, and Yahtzee bonus eligibility, using actual scoring functions and legal Joker categories.
- Can switch categories after a reroll, release previous holds, and sacrifice a slot when doing so improves the expected final score. Filled categories are never overwritten, including scratched Yahtzees.
Continuation values are generated ahead of time and bundled as losslessly encoded Float64 data: about 3.8 MB of Base64 source and 2.84 MB of decoded values. Gameplay calculates only the current turn's decisions, not the entire game tree. The calculated expected score from a fresh card is 254.587729 points. This is a mathematical expectation, not a guarantee for any particular game or sample of seeds.
The solver supports five six-sided dice and three rolls per turn. It is optimal for the fixed forced-choice-Joker rules, using floating-point arithmetic, including the upper bonus and score-time Yahtzee bonuses. It does not maximize the probability of beating a particular opponent or support configurable rules. Holding an already-made Yahtzee preserves it for scoring; repeatedly holding or rerolling it cannot collect multiple bonuses in one turn.
There is no strategy selector. ComputerPlayerProps is exported for typed
integrations.
Decisions are deterministic and do not consume random numbers. Existing
randomSeed, throttle, and save/resume behavior are preserved. Older saves with
an obsolete strategy field are restored using the optimal solver; new saves do
not include that field. Direct calls to
holdDiceHandler use player.rollsLeft, defaulting to two remaining rolls when no
turn is active. getNewStrategy(dice, log) still returns
{ category, distance, score }, describing the best category if scoring now.
Distance is the minimum number of dice replacements needed to score that category.
How the solver works
The solver separates the game into decisions within a turn and the value of future turns. It evaluates every legal action rather than choosing a target category using rules of thumb.
1. Represent only the state that affects future decisions.
At the start of a turn, the solver needs:
- A 13-bit mask identifying the categories that are still available.
- A flag indicating whether the Yahtzee slot has a positive score, making future Yahtzee bonuses possible. A scratched slot does not enable bonuses.
- Points still needed for the 63-point upper threshold. States where the bonus is already earned or mathematically unreachable are merged, since neither can earn a future upper bonus.
Already-earned additive points are excluded, but upper-section progress is not: it can change the value of future scoring choices. During a turn, the solver also considers the current dice and the number of rerolls remaining.
There are 1,851 reachable upper-mask/progress combinations. Each has 192 valid lower-mask/bonus combinations: 128 without bonus eligibility and 64 with the Yahtzee box already filled positively. That gives 355,392 start-of-turn states. The table stores only these combinations, rather than a mostly redundant category-mask/upper-subtotal/bonus cube.
2. Enumerate dice outcomes without treating them as equally likely.
StrategyModel.ts groups hands by face
counts, so [1, 2, 3, 4, 5] and [5, 4, 3, 2, 1] are the same state. There are
252 unordered five-dice hands and 462 possible held multisets of zero through
five dice. A particular hand has at most 32 distinct holds, including holding
nothing or everything.
For each hold, the model enumerates all possible rerolled hands. An outcome's probability accounts for how many ordered rolls produce it:
P(outcome) = n! / (count1! * ... * count6!) / 6^nHere, n is the number of dice rerolled. For example, rolling [1, 1, 2] has
three possible orderings and probability 3 / 216, not 1 / 216.
3. Solve future turns by working backward.
FullGameSolver.ts defines a continuation
value, V(mask, bonusEligible, upperNeed): the best expected number of points still to be
earned, starting before the first roll of a fresh turn. When no categories remain,
this value is zero.
For every possible final hand, the solver evaluates each legal category:
categoryValue = points scored now
+ any additional Yahtzee bonus
+ any newly earned upper bonus
+ V(mask with category removed, next bonus eligibility, next upperNeed)Scoring a positive Yahtzee enables bonuses in the continuation state; scratching it does not. Upper-category scores update progress toward 63, awarding 35 only when the threshold is first crossed. Joker restrictions determine which categories are legal for each hand. Removing a category always produces a smaller mask, so the generator can calculate each state's continuations before calculating the state itself.
For example, suppose only Chance and Yahtzee remain, with no rerolls left and
dice [1, 2, 3, 4, 5]. Taking 15 in Chance leaves a future Yahtzee turn worth
about 2.30 expected points, for a combined value of about 17.30. Taking zero in
Yahtzee instead preserves a fresh Chance turn worth about 23.33 expected points.
The solver chooses the zero because it produces the higher expected final score.
4. Work backward through the remaining rerolls.
Starting with those final-hand values, the solver evaluates every hold:
holdValue = sum over reroll outcomes of:
P(outcome) * best value after that outcomeOne application gives the best decision with one reroll remaining; a second gives the best decision with two remaining. Each resulting hand can choose its own best hold or scoring category, so the AI does not commit prematurely to one target. The terminal scoring values already include any bonus awarded at submission; the reroll recursion never awards bonuses separately.
Finally, averaging the two-reroll values over the initial five-dice roll gives the start-of-turn value stored in the generated table. This calculation is exhaustive, using floating-point arithmetic, rather than a Monte Carlo estimate.
5. Reuse the generated values during play.
scripts/generateAI.ts performs the full backward calculation ahead of time. At runtime, the solver looks up continuation values for the player's available categories and evaluates only the current turn. Planning neither consumes random numbers nor looks ahead at the player's seeded rolls. Numerically tied holds prefer keeping more dice.
Benchmarking and regenerating values
To benchmark the computer player:
npm run benchmark:ai
npm run benchmark:ai -- 2000The default benchmark runs 200 seeds (0-199), using the current game rules and no throttle:
| Seeds | Average score | | --- | ---: | | 0-199 | 256.405 | | 0-1999 | 256.914 |
Sample averages vary with the chosen seeds; timings also vary by machine. The test suite checks the 200-seed average and independent analytical/ordered-roll endgame calculations. The local release check separately regenerates and compares the entire continuation table.
After changing scoring rules or the solver, use scripts/generateAI.ts to regenerate and verify the bundled values:
npm run generate:ai
npm run generate:ai -- --checkGeneration takes about 26 seconds on the development machine, using backward induction with no simulation or sampling. A signature of category payouts and modeled rule constants guards against stale tables; a mismatch fails explicitly. Any future rules introducing new dependencies require extending the state model before regeneration, not merely regenerating payouts.
Game
Starts the game and manages the turns of each player. The game continues until all players have filled their scorecards.
Orientation and log level belong to each game, not global state. Missing or
invalid human input leaves the game waiting without spending a roll or scoring
a category. Holding accepts Q/W/E/R/T, optional commas/whitespace, and an empty
string to reroll everything. Invalid input is reported through the info log hook.
Custom input providers should throw PlayerInputError for recoverable mistakes;
other errors propagate to the caller rather than being retried forever.
Player/game turn-start and turn-end hooks fire once per turn, and game completion is notified once. Scoring hooks run before submission. A custom score handler must return a scorecard with exactly one previously unused category filled.
type LogHooks = {
onInfo?: (...message: string[]) => Promise<void>
onError?: (...message: string[]) => Promise<void>
onDebug?: (...message: string[]) => Promise<void>
}
type GameHooks = {
onGameStart?: <T extends Player>(game: Game<T>) => Promise<void>
onGameEnd?: <T extends Player>(game: Game<T>) => Promise<void>
onTurnStart?: <T extends Player>(player: T, game: Game<T>) => Promise<void>
onTurnEnd?: <T extends Player>(player: T, game: Game<T>) => Promise<void>
}
type GameConstructorProps<T extends Player> = {
players: T[]
gameHooks?: GameHooks
logHooks?: LogHooks
logLevel?: LogLevel
gameOrientation?: GameOrientation
}
class Game<T extends Player> {
constructor(props: GameConstructorProps<T>)
// advances the game by one step.
// if the game is in a state where it can proceed,
// it will call the current player's `step` method.
// if the game is waiting for user input, it will
// pass the input to the current player's `step` method.
step(userInput?: string): Promise<GameState>
// execute the game until it is over.
run(): Promise<void>
// serialize the game to JSON.
asJSON(): SerializedGame
// deserialize a game from JSON.
static fromJSON<T extends Player>(
data: SerializedGame,
props: GameConstructorProps<T>
): Game<T>
}Examples
With CLI Prompts
This example shows how to create a player that uses CLI prompts to get input from the user for held dice and scoring categories. The PromptPlayer class extends the Player class and overrides the getHeldDice and getScore class functions to use the readline module for input.
import readline from 'node:readline/promises'
import {
ComputerPlayer,
Game,
Player,
type PlayerConstructorProps,
} from 'yahtzee-api'
class PromptPlayer extends Player {
public constructor(props: PlayerConstructorProps) {
super(props)
}
public getHeldDice = async () => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const heldDice = await rl.question('Enter the labels of the dice to hold (Q, W, E, R, T), separated by commas: ')
rl.close()
if (heldDice.trim() === '') {
return ''
}
return heldDice
}
public getScore = async () => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const category = await rl.question(`Enter the category to score: ${this.scorecard.getLegalCategories(this.dice).join(', ')}: `)
rl.close()
return category
}
}
const p1 = new PromptPlayer({
randomSeed: 0,
name: 'Alice',
})
const p2 = new ComputerPlayer({
randomSeed: 1,
throttle: 200,
})
const game = new Game({
players: [p1, p2],
logHooks: {
async onInfo(...message) {
Promise.resolve(console.log(...message))
}
},
gameHooks: {
async onGameStart() {
console.log('Game started!')
},
async onGameEnd() {
console.log('Game ended!')
},
async onTurnStart(player) {
console.log(`It's ${player.name}'s turn!`)
},
async onTurnEnd(player) {
console.log(`${player.name} ended their turn!`)
}
}
})
await game.run()Stepped Execution
This example shows how to create a player that does not wait for user input, but instead uses the input provided to the step method. This is useful for testing or when you want to control the game flow by other means.
import { Game, ComputerPlayer, HumanPlayer } from 'yahtzee-api'
const p1 = new HumanPlayer({
randomSeed: 0,
name: 'Alice',
})
const p2 = new ComputerPlayer({
randomSeed: 1,
throttle: 200,
})
const game = new Game({
players: [p1, p2],
logHooks: {
async onInfo(...message) {
Promise.resolve(console.log(...message))
}
},
gameHooks: {
async onGameStart() {
console.log('Game started!')
},
async onGameEnd() {
console.log('Game ended!')
},
async onTurnStart(player) {
console.log(`It's ${player.name}'s turn!`)
},
async onTurnEnd(player) {
console.log(`${player.name} ended their turn!`)
}
}
})
// iife to run the game
;(async () => {
await game.step() // initialize and roll p1's dice
await game.step('wet') // p1 holds dice
await game.step('qwet') // p1 holds dice
await game.step('smallStraight') // p1 score low straight
// print the game state
console.log(game.asJSON())
console.log(p1.asJSON())
console.log(p2.asJSON())
}
)()Resume Game from JSON
This example shows how to resume a game from a saved state. The Game.fromJSON and Player.fromJSON methods can be used to create a new game instance from a JSON string representing the game state.
import {
Game,
ComputerPlayer,
GameState,
HumanPlayer,
LogLevel,
GameOrientation
} from 'yahtzee-api'
const p1 = HumanPlayer.fromJSON(
{
className: 'HumanPlayer',
name: 'Alice',
scorecard: {
ones: undefined,
twos: undefined,
threes: undefined,
fours: undefined,
fives: undefined,
sixes: undefined,
threeOfAKind: undefined,
fourOfAKind: undefined,
fullHouse: undefined,
smallStraight: 30,
largeStraight: 40,
yahtzee: undefined,
chance: undefined,
yahtzeeBonus: 0
},
dice: [
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false }
],
rng: { state: 27473487195 },
throttle: 0,
suspend: true,
currentTurnState: undefined,
rollsLeft: undefined
},
HumanPlayer
)
const p2 = ComputerPlayer.fromJSON(
{
className: 'ComputerPlayer',
name: 'Computer',
scorecard: {
ones: undefined,
twos: undefined,
threes: undefined,
fours: undefined,
fives: undefined,
sixes: undefined,
threeOfAKind: undefined,
fourOfAKind: undefined,
fullHouse: 25,
smallStraight: undefined,
largeStraight: undefined,
yahtzee: undefined,
chance: undefined,
yahtzeeBonus: 0
},
dice: [
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false },
{ value: 0, sides: 6, hold: false }
],
rng: { state: 12820960692 },
throttle: 200,
suspend: false,
currentTurnState: undefined,
rollsLeft: undefined
},
ComputerPlayer
)
const game = Game.fromJSON(
{
currentPlayerIndex: 1,
gameState: GameState.TURN,
logLevel: LogLevel.INFO,
gameOrientation: GameOrientation.HORIZONTAL
},
{
players: [p1, p2],
logHooks: {
async onInfo(...message) {
Promise.resolve(console.log(...message))
}
}
}
)
// iife to run the game
;(async () => {
await game.step() // p2 resumes turn
}
)()Development and local release checks
npm ci
npm run build
npm run check:releaseThe local release command runs non-mutating lint, strict type checking of source, tests, and scripts, the test suite with coverage, full AI-table reproducibility, installed-tarball checks, and example validation. It does not configure or depend on a CI service.
The package check verifies the packed file list, installs the tarball offline, and exercises ESM/CommonJS imports, consumer types, and game actions. Only the built distribution is published, not source tests, coverage, or development files.
The example check strictly compiles the runnable README snippets and runtime demos against the public package API. It executes the non-interactive examples; the prompt example is type-checked without waiting for terminal input.
Individual commands:
npm run lint
npm run lint:fix
npm run typecheck
npm test -- --run
npm run check:ai
npm run check:package
npm run check:examples # run after building