Last active
January 2, 2022 15:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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