yahtzee-api
v1.1.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',
suspend: true
})
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() // init the game
await game.step() // Alice rolls the dice
await game.step('QWR') // Alice holds some dice
await game.step('QWRT') // Alice rolls again, holds new dice
await game.step('smallStraight') // Alice scores
await game.step() // Computer player rolls the dice
// ... continue until the game is overInstallation
npm install yahtzee-apiClasses
Player
Represents a player in the game. The Player class is abstract and should be extended to create custom players. The ComputerPlayer class is a built-in implementation that can be used directly.
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>
// 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<ScorecardCategory>
// 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,
})
}Game
Starts the game and manages the turns of each player. The game continues until all players have filled their scorecards.
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
}
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(): 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,
Scorecard,
type ScorecardCategory
} 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: ${Scorecard.SCORECARD_CATEGORIES.join(', ')}: `)
rl.close()
if (!Scorecard.SCORECARD_CATEGORIES.includes(category as ScorecardCategory)) {
throw new Error(`Invalid category: ${category}. Please enter a valid category from: ${Scorecard.SCORECARD_CATEGORIES.join(', ')}`)
}
if (this.scorecard.getScore(category as ScorecardCategory).value !== undefined) {
throw new Error(`Category ${category} has already been scored. Please choose another category.`)
}
return category as ScorecardCategory
}
}
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!`)
}
}
})
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, Player} from 'yahtzee-api'
class HumanPlayer extends Player {
public getHeldDice = async (userInput?: string) => {
return userInput
}
public getScore = async (userInput?: string) => {
return userInput
}
}
const p1 = new HumanPlayer({
randomSeed: 0,
name: 'Alice',
suspend: true
})
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() // init game
await game.step() // p1 initial roll
await game.step('wet') // p1 holds dice
await game.step('qwet') // p1 holds dice
await game.step('smallStraight') // p1 score low straight
await game.step() // p2 takes entire turn
// 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,
Player
} from 'yahtzee-api'
class HumanPlayer extends Player {
public getHeldDice = async (userInput?: string) => {
return userInput
}
public getScore = async (userInput?: string) => {
return userInput
}
}
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: 'TURN' as GameState
},
{
players: [p1, p2],
logHooks: {
async onInfo(...message) {
Promise.resolve(console.log(...message))
}
}
}
)
// iife to run the game
;(async () => {
await game.step() // p2 resumes turn
}
)()