Skip to content

Instantly share code, notes, and snippets.

@delucis
Last active January 2, 2022 15:29
Show Gist options
  • Save delucis/f17c8ff87398fdc4451caa2ec63ab84d to your computer and use it in GitHub Desktop.
Save delucis/f17c8ff87398fdc4451caa2ec63ab84d to your computer and use it in GitHub Desktop.
Get a list of moves available to a specific player using boardgame.io
/**
* Get a list of the moves that are currently available to a specific player.
*
* @param {import("boardgame.io").Game} game boardgame.io game object
* @param {import("boardgame.io").Ctx} ctx current game context object
* @param {import("boardgame.io").PlayerID} playerID the ID of the player to get moves for
* @returns {string[]} an array of move names
*
* @example
* const game = {
* moves: { A: () => {} },
* };
* const ctx = { currentPlayer: '0', phase: null, activePlayers: null };
*
* getAvailableMoves(game, ctx, '0'); // ['A']
* getAvailableMoves(game, ctx, '1'); // []
*/
function getAvailableMoves(game, ctx, playerID) {
const { phase, activePlayers, currentPlayer } = ctx;
const stage = activePlayers ? activePlayers[playerID] : undefined;
// If some players are in stages, but not this one, they can’t make a move.
if (activePlayers && stage === undefined) return [];
// If no players are in stages, only the current player can make a move.
if (!activePlayers && playerID !== currentPlayer) return [];
let phaseConfig = game;
if (phase) phaseConfig = game.phases[phase];
const { moves } = stage ? phaseConfig.turn.stages[stage] : phaseConfig;
return Object.keys(moves);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment