repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
boardzilla-core
github_2023
boardzilla
typescript
GameElement.position
position() { return this._t.parent?._t.children.indexOf(this) ?? -1; }
/** * Returns the index of this element within its parent, starting at zero * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L771-L773
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.branch
branch() { const branches = []; let node = this as GameElement; while (node._t.parent) { const index = node.position(); if (index === -1) throw Error(`Reference to element ${this.constructor.name}${this.name ? ':' + this.name : ''} is no longer current`); branches.unshift(index); node = node._t.parent; } branches.unshift(this._ctx.removed === node ? 1 : 0); return branches.join("/"); }
/** * Returns a string identifying the tree position of the element suitable for * anonymous reference * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L780-L791
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.atBranch
atBranch(b: string) { let branch = b.split('/'); let index = parseInt(branch[0]); let node = index === 0 ? this._ctx.top : this._ctx.removed._t.children[index - 1]; branch.shift(); while (branch[0] !== undefined) { node = node._t.children[parseInt(branch[0])]; branch.shift(); } return node; }
/** * Returns the element at the given position returned by {@link branch} * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L797-L807
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.atID
atID(id: number): GameElement | undefined { let el = this._t.children.find(c => c._t.id === id); if (el) return el; for (const child of this._t.children) { el = child.atID(id); if (el) return el; } }
/** * Returns the element for the given id * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L813-L820
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.atRef
atRef(ref: number): GameElement | undefined { let el = this._t.children.find(c => c._t.ref === ref); if (el) return el; for (const child of this._t.children) { el = child.atRef(ref); if (el) return el; } }
/** * Returns the element for the given ref * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L826-L833
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.setShape
setShape(...shape: string[]) { if (this._ctx.gameManager?.phase === 'started') throw Error('Cannot change shape once game has started.'); if (shape.some(s => s.length !== shape[0].length)) throw Error("Each row in shape must be same size. Invalid shape:\n" + shape); this._size = { shape, width: shape[0].length, height: shape.length } }
/** * Set an irregular shape for this element. This is only meaningful for the * purposes of finding specifically adjacent cells when placed into a * PieceGrid. See {@link PieceGrid#adjacenciesByCell}. When rendered in a * PieceGrid, the element will have a size large enough to fill the * appropriate number of spaces in the grid, but it's appearance is otherwise * unaffected and will be based on {@link appearance}. When not rendered in a * PieceGrid, the element will take up a single cell but will be scaled * relatively to other elements with a shape in the same layout. * * @param shape - A set of single characters used as labels for each cell. The * cell label characters are provided as an array of strings, with each string * being one row of cell labels, with spaces used to indicate empty "holes" in * the shape. Each row must be the same length. The specific non-space * characters used are used for labelling the adjacencies in {@link * PieceGrid#adjacenciesByCell} but are otherwise unimportant. * @category Adjacency * * @example * * domino12.setShape( * '12' * ); * tetrisPiece.setShape( * 'XX ', * ' XX' * ); */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L876-L884
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.setEdges
setEdges(edges: Record<string, Partial<Record<Direction, string>>> | Partial<Record<Direction, string>>) { if (this._ctx.gameManager?.phase === 'started') throw Error('Cannot change shape once game has started.'); if (Object.keys(edges)[0].length === 1) { const missingCell = Object.keys(edges).find(c => this._size?.shape.every(s => !s.includes(c))); if (missingCell) throw Error(`No cell '${missingCell}' defined in shape`); this._size!.edges = edges as Record<string, Record<Direction, string>>; } else { if (this._size) throw Error("setEdges must use the cell characters from setShape as keys"); this._size = {shape: ['.'], width: 1, height: 1, edges: {'.': edges}}; } }
/** * Set the edge labels for this element. These are only meaningful for the * purposes of finding specifically adjacent edges when placed into a * PieceGrid. See {@link PieceGrid#adjacenciesByEdge}. * @category Adjacency * * @param edges - A set of edge labels for each cell label provided by {@link * setShape}. For simple 1-celled shapes, the edges can be provided without * cell labels. * * @example * * // a bridge tile with a road leading from left to right and a river leading * // from top to bottom. * simpleTile.setEdge( * up: 'river', * down: 'river', * left: 'road' * right: 'road' * }); * * // A tetris-shaped tile with sockets coming out either "end" * tetrisPiece.setShape( * 'AX ', * ' XB' * ); * tetrisPiece.setEdge({ * A: { * left: 'socket' * }, * B: { * right: 'socket' * } * }); */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L921-L931
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.isDescendantOf
isDescendantOf(el: GameElement): boolean { return this._t.parent === el || !!this._t.parent?.isDescendantOf(el) }
/** * Whether this element has the given element in its parent hierarchy * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L937-L939
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.toJSON
toJSON(seenBy?: number) { let attrs = this.attributeList(); // remove hidden attributes if (seenBy !== undefined && !this.isVisibleTo(seenBy)) { attrs = Object.fromEntries(Object.entries(attrs).filter( ([attr]) => ['_visible', 'row', 'column', '_rotation', '_size'].includes(attr) || (attr !== 'name' && (this.constructor as typeof GameElement).visibleAttributes?.includes(attr)) )) as typeof attrs; } const json: ElementJSON = Object.assign(serializeObject(attrs, seenBy !== undefined), { className: this.constructor.name }); if (this._t.order) json.order = this._t.order; if (seenBy === undefined) json._id = this._t.id; if (json._id !== this._t.ref) json._ref = this._t.ref; // do not expose moves within deck (shuffles) if (seenBy !== undefined && this._t.wasRef !== undefined && this.isVisibleTo(seenBy)) json._wasRef = this._t.wasRef; if (this._t.children.length && ( !seenBy || !('_screen' in this) || this._screen === undefined || (this._screen === 'all-but-owner' && this.owner?.position === seenBy) || (this._screen instanceof Array && this._screen.includes(this.owner?.position)) )) { json.children = Array.from(this._t.children.map(c => c.toJSON(seenBy))); } if (globalThis.window) { // guard-rail in dev try { structuredClone(json); } catch (e) { console.error(`invalid properties on ${this}:\n${JSON.stringify(json, undefined, 2)}`); throw(e); } } return json; }
/** * JSON representation * @param seenBy - optional player position viewing the game * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L957-L990
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.layout
layout( applyTo: typeof this._ui.layouts[number]['applyTo'], attributes: Partial<LayoutAttributes> ) { let {slots, area, size, aspectRatio, scaling, gap, margin, offsetColumn, offsetRow} = attributes if (slots && (area || margin || scaling || gap || margin || offsetColumn || offsetRow)) { console.warn('Layout has `slots` which overrides supplied grid parameters'); delete attributes.area; delete attributes.margin; delete attributes.gap; delete attributes.scaling; delete attributes.offsetRow; delete attributes.offsetColumn; } if (area && margin) { console.warn('Both `area` and `margin` supplied in layout. `margin` is ignored'); delete attributes.margin; } if (size && aspectRatio) { console.warn('Both `size` and `aspectRatio` supplied in layout. `aspectRatio` is ignored'); delete attributes.aspectRatio; } if (size && scaling) { console.warn('Both `size` and `scaling` supplied in layout. `scaling` is ignored'); delete attributes.scaling; } if (gap && (offsetColumn || offsetRow)) { console.warn('Both `gap` and `offset` supplied in layout. `gap` is ignored'); delete attributes.gap; } this._ui.layouts.push({ applyTo, attributes: { alignment: 'center', direction: 'square', ...attributes} }); }
/** * Apply a layout to some of the elements directly contained within this * element. See also {@link ElementCollection#layout} * @category UI * * @param applyTo - Which elements this layout applies to. Provided value can be: * - A specific {@link GameElement} * - The name of an element * - A specific set of elements ({@link ElementCollection}) * - A class of elements * * If multiple layout declarations would apply to the same element, only one * will be used. The order of specificity is as above. If a class is used and * mutiple apply, the more specific class will be used. * * @param {Object} attributes - A list of attributes describing the * layout. All units of measurement are percentages of this elements width and * height from 0-100, unless otherwise noted (See `margin` and `gap`) */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L1079-L1110
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.layoutAsDrawer
layoutAsDrawer(applyTo: Space<G, P> | string, attributes: { area?: Box, openDirection: 'left' | 'right' | 'down' | 'up', tab?: React.ReactNode, closedTab?: React.ReactNode, openIf?: (actions: { name: string, args: Record<string, Argument> }[]) => boolean, closeIf?: (actions: { name: string, args: Record<string, Argument> }[]) => boolean, }) { const { area, ...container } = attributes; this.layout(applyTo, { area, __container__: { type: 'drawer', attributes: container }}); }
/** * Creates a collapsible drawer layout for a Space within this Element. This * is like {@link GameElement#layout} except for one specific Space, with * additional parameters that set the behaviour/appearance of the drawer. A * tab will be attached the drawer that will allow it be opened/closed. * * @param applyTo - The Space for the drawer. Either the Space itself or its * name. * @param area - The area for the drawer when opened expressed in percentage * sizes of this element. * @param openDirection - the direction the drawer will open * @param tab - JSX for the appearance of the tab * @param closedTab - JSX for the appearance of the tab when closed if * different * @param openIf - A function that will be checked at each game state. If it * returns true, the drawer will automatically open. * @param closeIf - A function that will be checked at each game state. If it * returns true, the drawer will automatically close. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L1131-L1141
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.layoutAsTabs
layoutAsTabs(tabs: Record<string, Space<G, P> | string>, attributes: { area?: Box, tabDirection: 'left' | 'right' | 'down' | 'up', tabs?: Record<string, React.ReactNode>, setTabTo?: (actions: { name: string, args: Record<string, Argument> }[]) => string, }) { const { area, ...container } = attributes; const id = uuid(); for (const [key, tab] of Object.entries(tabs)) { this.layout(tab, { area, __container__: { type: 'tabs', id, key, attributes: container }}); } }
/** * Creates a tabbed layout for a set of Space's within this Element. This is * like {@link GameElement#layout} except for a set of Spaces, with additional * parameters that set the behaviour/appearance of the tabs. Each Space will * be laid out into the same area, with a set of tabs attached to allow the * Player or the game rules to select which tab is shown. * * @param applyTo - The Spaces for the drawer as a set of key-value * pairs. Each value is a Space or a name of a Space. * @param area - The area for the tabs expressed in percentage sizes of this * element. * @param tabDirection - the side on which the tabs will be placed * @param tabs - JSX for the appearance of the tabs as a set of key-value pairs * @param setTabTo - A function that will be checked at each game state. If it * returns a string, the tab with the matching key will be shown. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L1159-L1170
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.layoutAsPopout
layoutAsPopout(applyTo: Space<G, P> | string, attributes: { area?: Box, button: React.ReactNode, popoutMargin?: number | { top: number, bottom: number, left: number, right: number }, }) { const { area, ...container } = attributes; this.layout(applyTo, { area, __container__: { type: 'popout', attributes: container }}); }
/** * Hides a Space within this element and replaces it with popout * button. Clicking on the button opens this Space in a full-board modal. This * is like {@link GameElement#layout} except for one Space, with additional * parameters that set the behaviour/appearance of the popout modal. * * @param applyTo - The Space for the popout. Either a Space or the name of a * Space. * @param area - The area for the tabs expressed in percentage sizes of this * element. * @param button - JSX for the appearance of the popout button * @param popoutMargin - Alter the default margin around the opened * popout. Takes a percentage or an object with percentages for top, bottom, * left and right. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L1187-L1194
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.configureLayout
configureLayout(layoutConfiguration: Partial<LayoutAttributes>) { this._ui.layouts[0] = { applyTo: GameElement, attributes: { ...this._ui.getBaseLayout(), ...layoutConfiguration, } }; }
/** * Change the layout attributes for this space's layout. * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L1200-L1208
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.appearance
appearance(appearance: ElementUI<this>['appearance']) { Object.assign(this._ui.appearance, appearance); }
/** * Define the appearance of this element. Any values provided override * previous ones. See also {@link ElementCollection#appearance} * @category UI * * @param appearance - Possible values are: * @param appearance.className - A class name to add to the dom element * * @param appearance.render - A function that takes this element as its only * argument and returns JSX for the element. See {@link ../ui/appearance} for * more on usage. * * @param appearance.aspectRatio - The aspect ratio for this element. This * value is a ratio of width over height. All layouts defined in {@link * layout} will respect this aspect ratio. * * @param appearance.info - Return JSX for more info on this element. If * returning true, an info modal will be available for this element but with * only the rendered element and no text * * @param appearance.connections - If the elements immediately within this * element are connected using {@link Space#connectTo}, this makes those * connections visible as connecting lines. Providing a `label` will place a * label over top of this line by calling the provided function with the * distance of the connection specified in {@link Space#connectTo} and using * the retured JSX. If `labelScale` is provided, the label is scaled by this * amount. * * @param appearance.effects - Provides a CSS class that will be applied to * this element if its attributes change to match the provided ones. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L1241-L1243
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.registerClasses
registerClasses(...classList: ElementClass[]) { this._ctx.classRegistry = this._ctx.classRegistry.concat(classList); }
// no longer needed - remove in next minor release
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L161-L163
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.defineFlow
defineFlow(...flow: FlowStep[]) { this.defineSubflow('__main__', ...flow); }
/** * Define your game's main flow. May contain any of the following: * - {@link playerActions} * - {@link loop} * - {@link whileLoop} * - {@link forEach} * - {@link forLoop} * - {@link eachPlayer} * - {@link everyPlayer} * - {@link ifElse} * - {@link switchCase} * @category Definition */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L178-L180
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.defineSubflow
defineSubflow(name: string, ...flow: FlowStep[]) { if (this._ctx.gameManager.phase !== 'new') throw Error('cannot call defineFlow once started'); this._ctx.gameManager.flows[name] = new Flow({ name, do: flow }); this._ctx.gameManager.flows[name].gameManager = this._ctx.gameManager; }
/** * Define an addtional flow that the main flow can enter. A subflow has a * unique name and can be entered at any point by calling {@link * Do|Do.subflow}. * * @param name - Unique name of flow * @param flow - Steps of the flow */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L190-L194
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.defineActions
defineActions(actions: Record<string, (player: P) => Action<Record<string, Argument>>>) { if (this._ctx.gameManager.phase !== 'new') throw Error('cannot call defineActions once started'); this._ctx.gameManager.actions = actions; }
/** * Define your game's actions. * @param actions - An object consisting of actions where the key is the name * of the action and value is a function that accepts a player taking the * action and returns the result of calling {@link action} and chaining * choices, results and messages onto the result * @category Definition */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L204-L207
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.setting
setting(key: string) { return this._ctx.gameManager.settings[key]; }
/** * Retrieve the selected setting value for a setting defined in {@link * render}. * @category Definition */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L214-L216
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.action
action<A extends Record<string, Argument> = NonNullable<unknown>>(definition: { prompt?: string, description?: string, condition?: Action<A>['condition'], } = {}) { return new Action<A>(definition); }
/** * Create an {@link Action}. An action is a single move that a player can * take. Some actions require choices, sometimes several, before they can be * executed. Some don't have any choices, like if a player can simply * 'pass'. What defines where one action ends and another begins is how much * you as a player can decide before you "commit". For example, in chess you * select a piece to move and then a place to put it. These are a single move, * not separate. (Unless playing touch-move, which is rarely done in digital * chess.) In hearts, you pass 3 cards to another players. These are a single * move, not 3. You can change your mind as you select the cards, rather than * have to commit to each one. Similarly, other players do not see any * information about your choices until you actually commit the entire move. * * This function is called for each action in the game `actions` you define in * {@link defineActions}. These actions are initially declared with an optional * prompt and condition. Further information is added to the action by chaining * methods that add choices and behaviour. See {@link Action}. * * If this action accepts prior arguments besides the ones chosen by the * player during the execution of this action (especially common for {@link * followUp} actions) then a generic can be added for these arguments to help * Typescript type these parameters, e.g.: * `player => action<{ cards: number}>(...)` * * @param definition.prompt - The prompt that will appear for the player to * explain what the action does. Further prompts can be defined for each choice * they subsequently make to complete the action. * * @param definition.condition - A boolean or a function returning a boolean * that determines whether the action is currently allowed. Note that the * choices you define for your action will further determine if the action is * allowed. E.g. if you have a play card action and you add a choice for cards * in your hand, Boardzilla will automatically disallow this action if there * are no cards in your hand based on the face that there are no valid choices * to complete the action. You do not need to specify a `condition` for these * types of limitations. If using the function form, the function will receive * an object with any arguments passed to this action, e.g. from {@link * followUp}. * * @example * action({ * prompt: 'Flip one of your cards' * }).chooseOnBoard({ * choices: game.all(Card, {mine: true}) * }).do( * card => card.hideFromAll() * ) * * @category Definition */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L268-L274
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.followUp
followUp(action: ActionStub) { Do.subflow('__followup__', action); }
/** * Queue up a follow-up action while processing an action. If called during * the processing of a game action, the follow-up action given will be added * as a new action immediately following the current one, before the game's * flow can resume normally. This is common for card games where the play of a * certain card may require more actions be taken. * * @param {Object} action - The action added to the follow-up queue. * * @example * defineAction({ * ... * playCard: player => action() * .chooseOnBoard('card', cards) * .do( * ({ card }) => { * if (card.damage) { * // this card allows another action to do damage to another Card * game.followUp({ * name: 'doDamage', * args: { amount: card.damage } * }); * } * } * ) * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L303-L305
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.finish
finish(winner?: P | P[], announcement?: string) { this._ctx.gameManager.phase = 'finished'; if (winner) this._ctx.gameManager.winner = winner instanceof Array ? winner : [winner]; this._ctx.gameManager.announcements.push(announcement ?? '__finish__'); }
/** * End the game * * @param winner - a player or players that are the winners of the game. In a * solo game if no winner is provided, this is considered a loss. * @param announcement - an optional announcement from {@link render} to * replace the standard boardzilla announcement. * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L348-L352
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.getWinners
getWinners() { let winner = this._ctx.gameManager.winner; if (!(winner instanceof Array)) winner = [winner]; return this._ctx.gameManager.phase === 'finished' ? winner : undefined; }
/** * Return array of game winners, or undefined if game is not yet finished * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L358-L362
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.addDelay
addDelay() { this.resetMovementTracking(); if (this.game._ctx.trackMovement) { this._ctx.gameManager.sequence += 1; } else if (this._ctx.gameManager.intermediateUpdates.length) { return; // even if not tracking, record one intermediate to allow UI to extract proper state to animate towards } this._ctx.gameManager.intermediateUpdates.push(this.players.map( p => this._ctx.gameManager.getState(p) // TODO unnecessary for all players if in context of player )); }
/** * Add a delay in the animation of the state change at this point for player * as they receive game updates. * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L369-L379
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.message
message(text: string, args?: Record<string, Argument>) { this._ctx.gameManager.messages.push({body: n(text, args, true)}); }
/** * Add a message that will be broadcast in the chat at the next game update, * based on the current state of the game. * * @param text - The text of the message to send. This can contain interpolated strings * with double braces, i.e. {{player}} that are defined in args. Of course, * strings can be interpolated normally using template literals. However game * objects (e.g. players or pieces) passed in as args will be displayed * specially by Boardzilla. * * @param args - An object of key-value pairs of strings for interpolation in * the message. * * @example * game.message( * '{{player}} has a score of {{score}}', * { player, score: player.score() } * ); * * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L402-L404
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.messageTo
messageTo(player: (BasePlayer | number) | (BasePlayer | number)[], text: string, args?: Record<string, Argument>) { if (!(player instanceof Array)) player = [player]; for (const p of player) { this._ctx.gameManager.messages.push({ body: n(text, args, true), position: typeof p === 'number' ? p : p.position }); } }
/** * Add a message that will be broadcast to the given player(s) in the chat at * the next game update, based on the current state of the game. * * @param player - Player or players to receive the message * * @param text - The text of the message to send. This can contain interpolated strings * with double braces, i.e. {{player}} that are defined in args. Of course, * strings can be interpolated normally using template literals. However game * objects (e.g. players or pieces) passed in as args will be displayed * specially by Boardzilla. * * @param args - An object of key-value pairs of strings for interpolation in * the message. * * @example * game.message( * '{{player}} has a score of {{score}}', * { player, score: player.score() } * ); * * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L429-L437
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.announce
announce(announcement: string) { this._ctx.gameManager.announcements.push(announcement); this.addDelay(); this._ctx.gameManager.announcements = []; }
/** * Broadcast a message to all players that interrupts the game and requires * dismissal before actions can be taken. * * @param announcement - The modal name to announce, as provided in {@link render}. * * @example * game.message( * '{{player}} has a score of {{score}}', * { player, score: player.score() } * ); * * @category Game Management */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L453-L457
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.allJSON
allJSON(seenBy?: number): ElementJSON[] { return [this.toJSON(seenBy)].concat( this._ctx.removed._t.children.map(el => el.toJSON(seenBy)) ); }
// also gets removed elements
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L460-L464
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.fromJSON
fromJSON(boardJSON: ElementJSON[]) { let { className, children, _id, order, ...rest } = boardJSON[0]; if (this.constructor.name !== className) throw Error(`Cannot create board from JSON. ${className} must equal ${this.constructor.name}`); // reset all on self - think this is unnecessary? if it is, need to figure out how to use unserializableAttributes for (const key of Object.keys(this)) { if (!Game.unserializableAttributes.includes(key) && !(key in rest)) rest[key] = undefined; } this.createChildrenFromJSON(children || [], '0'); this._ctx.removed.createChildrenFromJSON(boardJSON.slice(1), '1'); if (order) this._t.order = order; if (this._ctx.gameManager) rest = deserializeObject({...rest}, this); Object.assign(this, {...rest}); this.assignAttributesFromJSON(children || [], '0'); this._ctx.removed.assignAttributesFromJSON(boardJSON.slice(1), '1'); }
// hydrate from json, and assign all attrs. requires that players be hydrated first
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L467-L484
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.resetUI
resetUI() { super.resetUI(); this._ui.stepLayouts = {}; }
// restore default layout rules before running setupLayout
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L515-L518
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.layoutControls
layoutControls(attributes: ActionLayout) { this._ui.stepLayouts["*"] = attributes; }
/** * Apply default layout rules for all the placement of all player prompts and * choices, in relation to the playing area * * @param attributes - see {@link ActionLayout} * * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L543-L545
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.layoutStep
layoutStep(step: string, attributes: ActionLayout) { if (!this._ctx.gameManager.getFlowStep(step)) throw Error(`No such step: ${step}`); this._ui.stepLayouts["step:" + step] = attributes; }
/** * Apply layout rules to a particular step in the flow, controlling where * player prompts and choices appear in relation to the playing area * * @param step - the name of the step as defined in {@link playerActions} * @param attributes - see {@link ActionLayout} * * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L556-L559
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.layoutAction
layoutAction(action: string, attributes: ActionLayout) { this._ui.stepLayouts["action:" + action] = attributes; }
/** * Apply layout rules to a particular action, controlling where player prompts * and choices appear in relation to the playing area * * @param action - the name of the action as defined in {@link game#defineActions} * @param attributes - see {@link ActionLayout} * * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L570-L572
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.disableDefaultAppearance
disableDefaultAppearance() { this._ui.disabledDefaultAppearance = true; }
/** * Remove all built-in default appearance. If any elements have not been given a * custom appearance, this causes them to be hidden. * * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L580-L582
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Game.showLayoutBoundingBoxes
showLayoutBoundingBoxes() { this._ui.boundingBoxes = true; }
/** * Show bounding boxes around every layout * * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/game.ts#L589-L591
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PieceGrid.cellsAround
cellsAround(piece: Piece<G>, pos: Vector) { const adjacencies: Partial<Record<DirectionWithDiagonals, string>> = { up: piece._cellAt({y: pos.y - 1, x: pos.x}), down: piece._cellAt({y: pos.y + 1, x: pos.x}), left: piece._cellAt({y: pos.y, x: pos.x - 1}), right: piece._cellAt({y: pos.y, x: pos.x + 1}) }; if (this.diagonalAdjacency) { adjacencies.upleft = piece._cellAt({y: pos.y - 1, x: pos.x - 1}); adjacencies.upright = piece._cellAt({y: pos.y - 1, x: pos.x + 1}); adjacencies.downleft = piece._cellAt({y: pos.y + 1, x: pos.x - 1}); adjacencies.downright = piece._cellAt({y: pos.y + 1, x: pos.x + 1}); } return adjacencies; }
// internal
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece-grid.ts#L80-L94
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PieceGrid.isOverlapping
isOverlapping(piece: Piece<G>, other?: Piece<G>): boolean { if (!other) { return this._t.children.some(p => p !== piece && this.isOverlapping(piece, p as Piece<G>)); } const p1: Vector = {x: piece.column!, y: piece.row!}; const p2: Vector = {x: other.column!, y: other.row!}; if (!piece._size && !other._size) return p2.y === p1.y && p2.x === p1.x; if (piece.rotation % 90 !== 0 || other.rotation % 90 !== 0) return false; // unsupported to calculate for irregular shapes at non-orthoganal orientations if (!piece._size) return (other._cellAt({y: p1.y - p2.y, x: p1.x - p2.x}) ?? ' ') !== ' '; if (!other._size) return (piece._cellAt({y: p2.y - p1.y, x: p2.x - p1.x}) ?? ' ') !== ' '; const gridSize1 = this._sizeNeededFor(piece); const gridSize2 = this._sizeNeededFor(other); if ( p2.y >= p1.y + gridSize1.height || p2.y + gridSize2.height <= p1.y || p2.x >= p1.x + gridSize1.width || p2.x + gridSize2.width <= p1.x ) return false; const size = Math.max(piece._size.height, piece._size.width); for (let x = 0; x !== size; x += 1) { for (let y = 0; y !== size; y += 1) { if ((piece._cellAt({x, y}) ?? ' ') !== ' ' && (other._cellAt({x: x + p1.x - p2.x, y: y + p1.y - p2.y}) ?? ' ') !== ' ') { return true; } } } return false; }
// internal
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece-grid.ts#L97-L124
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PieceGrid._fitPieceInFreePlace
_fitPieceInFreePlace(piece: Piece<G>, rows: number, columns: number, origin: {column: number, row: number}) { const tryLaterally = (vertical: boolean, d: number): boolean => { for (let lateral = 0; lateral < d + (vertical ? 0 : 1); lateral = -lateral + (lateral < 1 ? 1 : 0)) { if (vertical) { if (row + lateral <= 0 || row + lateral + gridSize.height - 1 > rows) continue; piece.row = row + lateral + origin.row - 1; } else { if (column + lateral <= 0 || column + lateral + gridSize.width - 1 > columns) continue; piece.column = column + lateral + origin.column - 1; } if (!this.isOverlapping(piece)) return true; } return false; } let gridSize = this._sizeNeededFor(piece); piece._rotation ??= 0; const row = piece.row === undefined ? Math.floor((rows - gridSize.height) / 2) : piece.row - origin.row + 1; const column = piece.column === undefined ? Math.floor((columns - gridSize.width) / 2) : piece.column - origin.column + 1; let possibleRotations = [piece._rotation, ...(piece._size ? [piece._rotation + 90, piece._rotation + 180, piece._rotation + 270] : [])]; while (possibleRotations.length) { piece._rotation = possibleRotations.shift()!; gridSize = this._sizeNeededFor(piece); for (let distance = 0; distance < rows || distance < columns; distance += 1) { if (column - distance > 0 && column - distance + gridSize.width - 1 <= columns) { piece.column = column - distance + origin.column - 1; if (tryLaterally(true, distance || 1)) return; } if (distance && column + distance > 0 && column + distance + gridSize.width - 1 <= columns) { piece.column = column + distance + origin.column - 1; if (tryLaterally(true, distance)) return; } if (distance && row - distance > 0 && row - distance + gridSize.height - 1 <= rows) { piece.row = row - distance + origin.row - 1; if (tryLaterally(false, distance)) return; } if (distance && row + distance > 0 && row + distance + gridSize.height - 1 <= rows) { piece.row = row + distance + origin.row - 1; if (tryLaterally(false, distance)) return; } } } piece.row = undefined; piece.column = undefined; }
// internal
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece-grid.ts#L127-L171
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PieceGrid.adjacenciesByCell
adjacenciesByCell(piece: Piece<G>, other?: Piece<G>): {piece: Piece<G>, from: string, to: string}[] { if (!other) { return this._t.children.reduce( (all, p) => all.concat(p !== piece ? this.adjacenciesByCell(piece, p as Piece<G>) : []), [] as {piece: Piece<G>, from: string, to: string}[] ); } const p1: Vector = {x: piece.column!, y: piece.row!}; const p2: Vector = {x: other.column!, y: other.row!}; // unsupported to calculate at non-orthoganal orientations if (p1.y === undefined || p1.x === undefined || piece.rotation % 90 !== 0 || p2.y === undefined || p2.x === undefined || other.rotation % 90 !== 0) return []; if (!piece._size) { return Object.values(this.cellsAround(other, {x: p1.x - p2.x, y: p1.y - p2.y})).reduce( (all, adj) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: '.', to: adj}] : []), [] as {piece: Piece<G>, from: string, to: string}[] ); } if (!other._size) { return Object.values(this.cellsAround(piece, {x: p2.x - p1.x, y: p2.y - p1.y})).reduce( (all, adj) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: adj, to: '.'}] : []), [] as {piece: Piece<G>, from: string, to: string}[] ); } const gridSize1 = this._sizeNeededFor(piece); const gridSize2 = this._sizeNeededFor(other); if ( p2.y >= p1.y + 1 + gridSize1.height || p2.y + 1 + gridSize2.height <= p1.y || p2.x >= p1.x + 1 + gridSize1.width || p2.x + 1 + gridSize2.width <= p1.x ) return []; const size = Math.max(piece._size.height, piece._size.width); const adjacencies = [] as {piece: Piece<G>, from: string, to: string}[]; for (let x = 0; x !== size; x += 1) { for (let y = 0; y !== size; y += 1) { const thisCell = piece._cellAt({x, y}); if (thisCell === undefined || thisCell === ' ') continue; for (const cell of Object.values(this.cellsAround(other, {x: x + p1.x - p2.x, y: y + p1.y - p2.y}))) { if (cell !== undefined && cell !== ' ') { adjacencies.push({piece: other, from: thisCell, to: cell}); } } } } return adjacencies; }
/** * Returns a list of other Pieces in the grid that have a touching edge (or * touching corner if {@link diagonalAdjacency} is true} with this shape. Each * item in the list contains the adjacent Piece, as well as the string * representation of cells in both pieces, as provided in {@link * Piece#setShape}. * @category Adjacency * * @param piece - The piece to check for adjacency * @param other - An optional other piece to check against. If undefined, it * will check for all pieces against the first argument * * @example * * A domino named "domino12" is adjacent to a domino named "domino34" with the * 2 touching the 3: * * domino12.setShape('12'); * domino34.setShape('34'); * board.adjacenciesByCell(domino12) => * [ * { * piece: domino34, * from: '2', * to: '3' * } * ] */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece-grid.ts#L201-L248
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PieceGrid.adjacenciesByEdge
adjacenciesByEdge(piece: Piece<G>, other?: Piece<G>): {piece: Piece<G>, from?: string, to?: string}[] { if (!other) { const children = this._t.children; return children.reduce( (all, p) => all.concat(p !== piece ? this.adjacenciesByEdge(piece, p as Piece<G>) : []), [] as {piece: Piece<G>, from?: string, to?: string}[] ); } const p1: Vector = {x: piece.column!, y: piece.row!}; const p2: Vector = {x: other.column!, y: other.row!}; if (p2.y === undefined || p2.x === undefined || other.rotation % 90 !== 0) return []; if (piece.rotation % 90 !== 0 || other.rotation % 90 !== 0) return []; // unsupported to calculate at non-orthoganal orientations if (!piece._size) { return (Object.entries(this.cellsAround(other, {x: p1.x - p2.x, y: p1.y - p2.y})) as [Direction, string][]).reduce( (all, [dir, adj]) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: undefined, to: other._size?.edges?.[adj][rotateDirection(dir, 180 - other.rotation)]}] : []), [] as {piece: Piece<G>, from?: string, to?: string}[] ); } if (!other._size) { return (Object.entries(this.cellsAround(piece, {x: p2.x - p1.x, y: p2.y - p1.y})) as [Direction, string][]).reduce( (all, [dir, adj]) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: piece._size?.edges?.[adj][rotateDirection(dir, 180 - piece.rotation)], to: undefined}] : []), [] as {piece: Piece<G>, from?: string, to?: string}[] ); } const gridSize1 = this._sizeNeededFor(piece); const gridSize2 = this._sizeNeededFor(other); if ( p2.y >= p1.y + 1 + gridSize1.height || p2.y + 1 + gridSize2.height <= p1.y || p2.x >= p1.x + 1 + gridSize1.width || p2.x + 1 + gridSize2.width <= p1.x ) return []; const size = Math.max(piece._size.height, piece._size.width); const adjacencies = [] as {piece: Piece<G>, from?: string, to?: string}[]; for (let x = 0; x !== size; x += 1) { for (let y = 0; y !== size; y += 1) { const thisCell = piece._cellAt({x, y}); if (thisCell === undefined || thisCell === ' ') continue; for (const [dir, cell] of Object.entries(this.cellsAround(other, {x: x + p1.x - p2.x, y: y + p1.y - p2.y})) as [Direction, string][]) { if (cell !== undefined && cell !== ' ') { adjacencies.push({ piece: other, from: piece._size?.edges?.[thisCell][rotateDirection(dir, -piece.rotation)], to: other._size?.edges?.[cell][rotateDirection(dir, 180 - other.rotation)] }); } } } } return adjacencies; }
/** * Returns a list of other Pieces in the grid that have a touching edge with * this shape. Each item in the list contains the adjacent Piece, as well as * the string representation of the edges in both pieces, as provided in * {@link Piece#setEdges}. * @category Adjacency * * @param piece - The piece to check for adjacency * @param other - An optional other piece to check against. If undefined, it * will check for all pieces against the first argument * * @example * * A tile named "corner" is adjacent directly to the left of a tile named * "bridge". * * corner.setEdges({ * up: 'road', * right: 'road' * }); * * bridge.setEdges({ * up: 'river', * down: 'river', * left: 'road' * right: 'road' * }); * * board.adjacenciesByCell(corner) => * [ * { * piece: bridge, * from: 'road', * to: 'road' * } * ] */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece-grid.ts#L287-L338
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.showToAll
showToAll() { delete(this._visible); }
/** * Show this piece to all players * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L31-L33
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.showOnlyTo
showOnlyTo(player: Player | number) { if (typeof player !== 'number') player = player.position; this._visible = { default: false, except: [player] }; }
/** * Show this piece only to the given player * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L39-L45
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.showTo
showTo(...player: Player[] | number[]) { if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position); if (this._visible === undefined) return; if (this._visible.default) { if (!this._visible.except) return; this._visible.except = this._visible.except.filter(i => !(player as number[]).includes(i)); } else { this._visible.except = Array.from(new Set([...(this._visible.except instanceof Array ? this._visible.except : []), ...(player as number[])])) } }
/** * Show this piece to the given players without changing it's visibility to * any other players. * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L52-L61
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.hideFromAll
hideFromAll() { this._visible = {default: false}; }
/** * Hide this piece from all players * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L67-L69
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.hideFrom
hideFrom(...player: Player[] | number[]) { if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position); if (this._visible?.default === false && !this._visible.except) return; if (this._visible === undefined || this._visible.default === true) { this._visible = { default: true, except: Array.from(new Set([...(this._visible?.except instanceof Array ? this._visible.except : []), ...(player as number[])])) }; } else { if (!this._visible.except) return; this._visible.except = this._visible.except.filter(i => !(player as number[]).includes(i)); } }
/** * Hide this piece from the given players without changing it's visibility to * any other players. * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L76-L88
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.isVisibleTo
isVisibleTo(player: Player | number) { if (typeof player !== 'number') player = player.position; if (this._visible === undefined) return true; if (this._visible.default) { return !this._visible.except || !(this._visible.except.includes(player)); } else { return this._visible.except?.includes(player) || false; } }
/** * Returns whether this piece is visible to the given player * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L94-L102
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.isVisible
isVisible() { if (this._ctx.player) return this.isVisibleTo(this._ctx.player.position); return this._visible?.default !== false && (this._visible?.except ?? []).length === 0; }
/** * Returns whether this piece is visible to all players, or to the current * player if called when in a player context (during an action taken by a * player or while the game is viewed by a given player.) * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L110-L113
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.revealWhenHidden
static revealWhenHidden<T extends Piece<BaseGame>>(this: ElementClass<T>, ...attrs: (string & keyof T)[]): void { this.visibleAttributes = attrs; }
/** * Provide list of attributes that remain visible even when these pieces are * not visible to players. E.g. In a game with multiple card decks with * different backs, identified by Card#deck, the identity of the card when * face-down is hidden, but the deck it belongs to is not, since the card art * on the back would identify the deck. In this case calling * `Card.revealWhenHidden('deck')` will cause all attributes other than 'deck' * to be hidden when the card is face down, while still revealing which deck * it is. * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L126-L128
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.putInto
putInto(to: GameElement, options?: {position?: number, row?: number, column?: number, fromTop?: number, fromBottom?: number}) { if (to.isDescendantOf(this)) throw Error(`Cannot put ${this} into itself`); let pos: number = to._t.order === 'stacking' ? 0 : to._t.children.length; if (options?.position !== undefined) pos = options.position >= 0 ? options.position : to._t.children.length + options.position + 1; if (options?.fromTop !== undefined) pos = options.fromTop; if (options?.fromBottom !== undefined) pos = to._t.children.length - options.fromBottom; const previousParent = this._t.parent; const position = this.position(); if (this.hasMoved() || to.hasMoved()) this.game.addDelay(); const refs = previousParent === to && options?.row === undefined && options?.column === undefined && to.childRefsIfObscured(); this._t.parent!._t.children.splice(position, 1); this._t.parent = to; to._t.children.splice(pos, 0, this); if (refs) to.assignChildRefs(refs); if (previousParent !== to && previousParent instanceof Space) previousParent.triggerEvent("exit", this); if (previousParent !== to && this._ctx.trackMovement) this._t.moved = true; delete this.column; delete this.row; if (options?.row !== undefined) this.row = options.row; if (options?.column !== undefined) this.column = options.column; if (previousParent !== to && to instanceof Space) to.triggerEvent("enter", this); }
/** * Move this piece into another element. This triggers any {@link * Space#onEnter | onEnter} callbacks in the destination. * @category Structure * * @param to - Destination element * @param options.position - Place the piece into a specific numbered position * relative to the other elements in this space. Positive numbers count from * the beginning. Negative numbers count from the end. * @param options.fromTop - Place the piece into a specific numbered position counting * from the first element * @param options.fromBottom - Place the piece into a specific numbered position * counting from the last element */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L144-L168
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Piece.remove
remove() { return this.putInto(this._ctx.removed); }
/** * Remove this piece from the playing area and place it into {@link * Game#pile} * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/piece.ts#L192-L194
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.contentsWillBeShown
contentsWillBeShown() { this._visOnEnter = {default: true}; }
/** * Show pieces to all players when they enter this space * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L35-L37
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.contentsWillBeShownToOwner
contentsWillBeShownToOwner() { this._visOnEnter = {default: false, except: 'owner'}; }
/** * Show pieces when they enter this space to its owner * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L43-L45
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.contentsWillBeShownTo
contentsWillBeShownTo(...players: P[]) { this._visOnEnter = {default: false, except: players.map(p => p.position)}; }
/** * Show piece to these players when they enter this space * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L51-L53
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.contentsWillBeHidden
contentsWillBeHidden() { this._visOnEnter = {default: false}; }
/** * Hide pieces to all players when they enter this space * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L59-L61
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.contentsWillBeHiddenFrom
contentsWillBeHiddenFrom(...players: P[]) { this._visOnEnter = {default: true, except: players.map(p => p.position)}; }
/** * Hide piece to these players when they enter this space * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L67-L69
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.blockViewFor
blockViewFor(players: 'all' | 'none' | 'all-but-owner' | Player[]) { this._screen = players === 'none' ? undefined : players instanceof Array ? players.map(p => p.position) : players }
/** * Call this to screen view completely from players. Blocked spaces completely * hide their contents, like a physical screen. No information about the * number, type or movement of contents inside this Space will be revealed to * the specified players * * @param players = Players for whom the view is blocked * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L80-L82
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.onEnter
onEnter<T extends GameElement>(type: ElementClass<T>, callback: (el: T) => void) { this.addEventHandler<T>("enter", { callback, type }); }
/** * Attach a callback to this space for every element that enters or is created * within. * @category Structure * * @param type - the class of element that will trigger this callback * @param callback - Callback will be called each time an element enters, with * the entering element as the only argument. * * @example * deck.onEnter(Card, card => card.hideFromAll()) // card placed in the deck are automatically turned face down */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L109-L111
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Space.onExit
onExit<T extends GameElement>(type: ElementClass<T>, callback: (el: T) => void) { this.addEventHandler<T>("exit", { callback, type }); }
/** * Attach a callback to this space for every element that is moved out of this * space. * @category Structure * * @param type - the class of element that will trigger this callback * @param callback - Callback will be called each time an element exits, with * the exiting element as the only argument. * * @example * deck.onExit(Card, card => card.showToAll()) // cards drawn from the deck are automatically turned face up */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/space.ts#L125-L127
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
D6.roll
roll() { this.current = Math.ceil((this.game.random || Math.random)() * this.sides); this.rollSequence = this._ctx.gameManager.sequence; }
/** * Randomly choose a new face, causing the roll animation * @category D6 */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/components/d6/d6.ts#L28-L31
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flippable
const Flippable = ({ children }: { children?: React.ReactNode, }) => { let frontContent: React.ReactNode = null; let backContent: React.ReactNode = null; React.Children.forEach(children, child => { if (!React.isValidElement(child)) return; if (child.type === Flippable.Front) { frontContent = child; } else if (child.type === Flippable.Back) { backContent = child; } else { throw Error("Flippable must contain only <Front/> and <Back/>"); } }); return ( <div className='bz-flippable'> <div className="front"> {frontContent} </div> <div className="back"> {backContent} </div> </div> ); }
/** * A Piece with two sides: front and back. When the Piece is hidden, the back is * shown. When visible, the front is shown. When the visibility changes, the CSS * animates a 3d flip. * * @example * import { Flippable } from '@boardzilla/core/components'; * ... * Piece.appearance({ * render: piece => ( * <Flippable> * <Flippable.Front>{piece.name}</Flippable.Front> * <Flippable.Back></Flippable.Back> * </Flippable> * ); * }); * // The DOM structure inside the Piece element will be: * <div class="bz-flippable"> * <div class="front">{piece.name}</div> * <div class="back"></div> * </div> */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/components/flippable/Flippable.tsx#L27-L54
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ActionStep.allowedActions
allowedActions(): string[] { return this.position ? [] : this.actions.map(a => a.name); }
// current actions that can process. does not check player
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/action-step.ts#L106-L108
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ActionStep.processMove
processMove(move: { player: number, name: string, args: Record<string, Argument>, }): string | SubflowSignal['data'][] | undefined { if ((move.name !== '__continue__' || !this.continueIfImpossible) && !this.allowedActions().includes(move.name)) { throw Error(`No action ${move.name} available at this point. Waiting for ${this.allowedActions().join(", ")}`); } const gameManager = this.gameManager; if (!gameManager.players.currentPosition.includes(move.player)) { throw Error(`Move ${move.name} from player #${move.player} not allowed. Current players: #${gameManager.players.currentPosition.join('; ')}`); } const player = gameManager.players.atPosition(move.player); if (!player) return `No such player position: ${move.player}`; if (move.name === '__pass__' || move.name === '__continue__') { this.setPosition(move); return; } const gameAction = gameManager.getAction(move.name, player); const error = gameAction._process(player, move.args); if (error) { // failed with a selection required return error; } else { // succeeded this.setPosition(this.position ? {...this.position} : move); if (interruptSignal[0]) { const interrupt = interruptSignal.splice(0); if (interrupt[0].signal === InterruptControl.subflow) return (interrupt as SubflowSignal[]).map(s => s.data); const loop = this.currentLoop(interrupt[0].data); if (!loop) { if (interrupt[0].data) throw Error(`No loop found "${interrupt[0].data}" for interrupt`); if (interrupt[0].signal === InterruptControl.continue) throw Error("Cannot use Do.continue when not in a loop"); if (interrupt[0].signal === InterruptControl.repeat) throw Error("Cannot use Do.repeat when not in a loop"); throw Error("Cannot use Do.break when not in a loop"); } else { loop.interrupt(interrupt[0].signal); return; } } } }
// returns error (string) or subflow {args, name} or ok (undefined)
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/action-step.ts#L137-L183
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
EveryPlayer.withPlayer
withPlayer<T>(value: number, fn: () => T, mutate=false): T { this.value = value; this.sequence = this.position.sequences[this.value]; this.setPosition(this.position, this.sequence); const result = fn(); if (mutate) { const currentPlayer = this.getPlayers()[this.value]; // capture position from existing player before returning to all player mode this.position.sequences[this.value] = this.sequence; if (currentPlayer && this.step instanceof Flow) this.position.positions[this.value] = this.step.branchJSON(); } this.value = -1; this.setPosition(this.position); return result; }
// specific player and pretend to be a normal flow with just one subflow
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/every-player.ts#L43-L57
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
EveryPlayer.branchJSON
branchJSON(forPlayer=true): FlowBranchJSON[] { if (this.position === undefined && this.sequence === undefined) return []; // probably invalid let branch: FlowBranchJSON = { type: this.type, position: {positions: [], sequences: this.position.sequences, completed: this.completed} }; if (this.name) branch.name = this.name; for (let i = 0; i !== this.getPlayers().length; i++) { this.withPlayer(i, () => { if (this.step instanceof Flow) branch.position.positions[i] = this.step.branchJSON(forPlayer); }); } return [branch]; }
// reimpl ourselves to collect json from all players
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/every-player.ts#L64-L78
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
EveryPlayer.setPosition
setPosition(positionJSON: any, sequence?: number) { const player = this.getPlayers()[this.value]; this.completed = positionJSON.completed; if (player) { player.setCurrent(); positionJSON.sequences[this.value] = sequence; } else { // not looking at an individual player. set game state to accept all players const players: P[] = []; for (let i = 0; i !== this.getPlayers().length; i++) { if (this.completed[i] === false) players.push(this.getPlayers()[i]); } this.gameManager.players.setCurrent(players); } super.setPosition(positionJSON, positionJSON.sequences[this.value]); if (this.step instanceof Flow && this.position.positions[this.value]) { this.step.setBranchFromJSON(this.position.positions[this.value]); } }
// add player management, hydration of flow for the correct player, sequences[] management
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/every-player.ts#L81-L99
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
EveryPlayer.playOneStep
playOneStep(): InterruptSignal[] | FlowControl | Flow { // step through each player over top of the normal super stepping const player = this.getPlayers().findIndex((_, p) => this.completed[p] === undefined); if (player !== -1) { // run for next player without a resolution return this.withPlayer(player, () => { let result = super.playOneStep(); // capture the complete state ourselves, pretend everything is fine if (result instanceof Flow || result === FlowControl.complete) this.completed![player] = result === FlowControl.complete; return FlowControl.ok; }, true); } // no more players to step through. return the all-complete return this.completed.every(r => r) ? FlowControl.complete : this; }
// without us checking all branches
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/every-player.ts#L128-L145
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.playOneStep
playOneStep(): InterruptSignal[] | FlowControl | Flow { const step = this.step; let result: InterruptSignal[] | FlowControl | Flow = FlowControl.complete; if (step instanceof Function) { if (!interruptSignal[0]) step(this.flowStepArgs()); result = FlowControl.complete; if (interruptSignal[0] && interruptSignal[0].signal !== InterruptControl.subflow) result = interruptSignal.splice(0); } else if (step instanceof Flow) { result = step.playOneStep(); } if (result === FlowControl.ok || result instanceof Flow) return result; if (result !== FlowControl.complete) { if ('interrupt' in this && typeof this.interrupt === 'function' && (!result[0].data || result[0].data === this.name)) return this.interrupt(result[0].signal) return result; } // completed step, advance this block if able const block = this.currentBlock(); if (block instanceof Array) { if ((this.sequence ?? 0) + 1 !== block.length) { this.setPosition(this.position, (this.sequence ?? 0) + 1); return FlowControl.ok; } } // completed block, advance self return this.advance(); }
/** * Advance flow one step and return FlowControl.complete if complete, * FlowControl.ok if can continue, Do to interrupt the current loop. Returns * ActionStep if now waiting for player input. override for self-contained * flows that do not have subflows. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L253-L280
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.play
play() { interruptSignal.splice(0); let step; do { if (this.gameManager.phase !== 'finished') step = this.playOneStep(); if (!(step instanceof Flow)) console.debug(`Advancing flow:\n ${this.stacktrace()}`); } while (step === FlowControl.ok && interruptSignal[0]?.signal !== InterruptControl.subflow && this.gameManager.phase !== 'finished') if (interruptSignal[0]?.signal === InterruptControl.subflow) return interruptSignal.map(s => s.data as {name: string, args: Record<string, any>}); if (step instanceof Flow) return step; if (step instanceof Array) { if (step[0].signal === InterruptControl.continue) throw Error("Cannot use Do.continue when not in a loop"); if (step[0].signal === InterruptControl.repeat) throw Error("Cannot use Do.repeat when not in a loop"); throw Error("Cannot use Do.break when not in a loop"); } // flow complete }
// play until action required (returns ActionStep) or flow complete (undefined) or subflow started {name, args}
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L283-L298
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.reset
reset() { this.setPosition(undefined); }
// must override. reset runs any logic needed and call setPosition. Must not modify own state.
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L301-L303
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.currentBlock
currentBlock(): FlowDefinition | undefined { return this.block; }
// must override. must rely solely on this.position
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L306-L308
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.toJSON
toJSON(_forPlayer=true): any { return this.position; }
// override if position contains objects that need serialization
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L311-L313
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.fromJSON
fromJSON(json: any): typeof this.position { return json; }
// override if position contains objects that need deserialization
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L316-L318
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.advance
advance(): FlowControl { return FlowControl.complete; }
// override for steps that advance through their subflows. call setPosition if needed. return ok/complete
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L321-L323
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Flow.allSteps
allSteps(): FlowDefinition | undefined { return this.block; }
// override return all subflows
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/flow/flow.ts#L326-L328
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.atPosition
atPosition(position: number) { return this.find(p => p.position === position); }
/** * Returns the player at a given table position. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L41-L43
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.current
current(): P | undefined { if (this.currentPosition.length > 1) throw Error(`Using players.current when ${this.currentPosition.length} players may act`); return this.atPosition(this.currentPosition[0] ?? -1); }
/** * Returns the player that may currently act. It is an error to call current * when multiple players can act */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L49-L52
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.allCurrent
allCurrent(): P[] { return this.currentPosition.map(p => this.atPosition(p)!); }
/** * Returns the array of all players that may currently act. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L57-L59
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.host
host(): P { return this.find(p => p.host)!; }
/** * Returns the host player */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L64-L66
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.notCurrent
notCurrent() { return this.filter(p => !this.currentPosition.includes(p.position)); }
/** * Returns the array of players that may not currently act. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L71-L73
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.inPositionOrder
inPositionOrder() { return this.sort((p1, p2) => (p1.position > p2.position ? 1 : -1)); }
/** * Returns the array of players in the order of table positions. Does not * alter the actual player order. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L79-L81
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.setCurrent
setCurrent(players: number | P | number[] | P[]) { if (!(players instanceof Array)) players = [players] as number[] | P[]; players = players.map(p => typeof p === 'number' ? p : p.position); this.currentPosition = players; }
/** * Set the current player(s). * * @param players - The {@link Player} or table position of the player to act, * or an array of either. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L89-L93
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.next
next() { if (this.currentPosition.length === 0) { this.currentPosition = [this[0].position]; } else if (this.currentPosition.length === 1) { this.currentPosition = [this.after(this.currentPosition[0]).position]; } return this.current()! }
/** * Advance the current player to act to the next player based on player order. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L98-L105
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.after
after(player: number | P) { return this[(this.turnOrderOf(player) + 1) % this.length]; }
/** * Return the next player to act based on player order. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L110-L112
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.seatedNext
seatedNext(player: P, steps = 1) { return this.atPosition((player.position + steps - 1) % this.length + 1)!; }
/** * Return the player next to this player at the table. * @param steps - 1 = one step to the left, -1 = one step to the right, etc */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L118-L120
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.turnOrderOf
turnOrderOf(player: number | P) { if (typeof player !== 'number') player = player.position; const index = this.findIndex(p => p.position === player); if (index === -1) throw Error("No such player"); return index; }
/** * Returns the turn order of the given player, starting with 0. This is * distinct from {@link Player#position}. Turn order can be altered during a * game, whereas table position cannot. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L127-L132
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.sortBy
sortBy(key: Sorter<P> | (Sorter<P>)[], direction?: "asc" | "desc") { const rank = (p: P, k: Sorter<P>) => typeof k === 'function' ? k(p) : p[k] const [up, down] = direction === 'desc' ? [-1, 1] : [1, -1]; return this.sort((a, b) => { const keys = key instanceof Array ? key : [key]; for (const k of keys) { const r1 = rank(a, k); const r2 = rank(b, k); if (r1 > r2) return up; if (r1 < r2) return down; } return 0; }); }
/** * Sorts the players by some means, changing the turn order. * @param key - A key of function for sorting, or a list of such. See {@link * Sorter} * @param direction - `"asc"` to cause players to be sorted from lowest to * highest, `"desc"` for highest to lower */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L141-L154
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
PlayerCollection.sortedBy
sortedBy(key: Sorter<P> | (Sorter<P>)[], direction: "asc" | "desc" = "asc") { return (this.slice(0, this.length) as this).sortBy(key, direction); }
/** * Returns a copy of this collection sorted by some {@link Sorter}. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/collection.ts#L159-L161
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Player.hide
static hide<P extends BasePlayer>(this: {new(): P; hiddenAttributes: string[]}, ...attrs: (keyof P)[]): void { this.hiddenAttributes = attrs as string[]; }
/** * Provide list of attributes that are hidden from other players */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/player.ts#L59-L61
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Player.setCurrent
setCurrent(this: P) { return this._players.setCurrent(this); }
/** * Set this player as the current player */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/player.ts#L72-L74
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Player.others
others(): P[] { return Array.from(this._players).filter(p => p as Player !== this); }
/** * Returns an array of all other players. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/player.ts#L79-L81
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Player.other
other(): P { if (this._players.length !== 2) throw Error('Can only use `other` for 2 player games'); return this._players.find(p => p as Player !== this)!; }
/** * Returns the other player. Only allowed in 2 player games */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/player/player.ts#L86-L89
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
getArea
function getArea(absolutePosition: Box, margin?: number | { top: number, bottom: number, left: number, right: number }, area?: Box): Box { if (area) return area; if (!margin) return { left: 0, top: 0, width: 100, height: 100 }; // margins are absolute, so translate const transform: Vector = { x: absolutePosition.width / 100, y: absolutePosition.height / 100 } margin = (typeof margin === 'number') ? { left: margin, right: margin, top: margin, bottom: margin } : {...margin}; margin.left /= transform.x; margin.right /= transform.x; margin.top /= transform.y; margin.bottom /= transform.y; return { left: margin.left, top: margin.top, width: 100 - margin.left - margin.right, height: 100 - margin.top - margin.bottom }; }
/** * calculate working area * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/ui/render.ts#L920-L942
d701cb628e876cbe59171e837862ee09c925d6c9
ev0-astro-theme
github_2023
gndx
typescript
e
const e = (str: string) => encodeURIComponent(encodeURIComponent(str));
// double escape for commas and slashes
https://github.com/gndx/ev0-astro-theme/blob/77777faab2e966a42411a5b8bd0f7e9b652d4e27/src/utils/createOgImage.ts#L23-L23
77777faab2e966a42411a5b8bd0f7e9b652d4e27
moonlight
github_2023
moonlight-mod
typescript
downloadStable
async function downloadStable(): Promise<[ArrayBuffer, string]> { const json = await getStableRelease(); const asset = json.assets.find((a) => a.name === artifactName); if (!asset) throw new Error("Artifact not found"); logger.debug(`Downloading ${asset.browser_download_url}`); const req = await fetch(asset.browser_download_url, { cache: "no-store", headers: { "User-Agent": userAgent } }); return [await req.arrayBuffer(), json.name]; }
// Note: this won't do anything on browser, we should probably disable it
https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/core-extensions/src/moonbase/native.ts#L66-L80
12cd3c869f2a9478b65033033d64bd82790396fd
moonlight
github_2023
moonlight-mod
typescript
MoonbaseSettingsStore.isModified
private isModified() { const orig = JSON.stringify(this.savedConfig); const curr = JSON.stringify(this.config); return orig !== curr; }
// Jank
https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/core-extensions/src/moonbase/webpackModules/stores.ts#L159-L163
12cd3c869f2a9478b65033033d64bd82790396fd
moonlight
github_2023
moonlight-mod
typescript
MoonbaseSettingsStore.showNotice
showNotice() { return this.modified; }
// Required for the settings store contract
https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/core-extensions/src/moonbase/webpackModules/stores.ts#L170-L172
12cd3c869f2a9478b65033033d64bd82790396fd
moonlight
github_2023
moonlight-mod
typescript
MoonbaseSettingsStore.clone
private clone<T>(obj: T): T { return structuredClone(obj); }
// This sucks.
https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/core-extensions/src/moonbase/webpackModules/stores.ts#L535-L537
12cd3c869f2a9478b65033033d64bd82790396fd
moonlight
github_2023
moonlight-mod
typescript
call
const call = (event: string, ...args: any[]) => realEmit.call(this, event, ...args);
// Arrow functions don't bind `this` :D
https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/core-extensions/src/nativeFixes/host.ts#L141-L141
12cd3c869f2a9478b65033033d64bd82790396fd
moonlight
github_2023
moonlight-mod
typescript
linkVenmic
function linkVenmic() { if (patchbay == null) return false; try { const pid = app .getAppMetrics() .find((proc) => proc.name === "Audio Service") ?.pid?.toString() ?? ""; logger.info("Audio Service PID:", pid); patchbay.unlink(); return patchbay.link({ exclude: [{ "application.process.id": pid }, { "media.class": "Stream/Input/Audio" }], ignore_devices: true, only_speakers: true, only_default_speakers: true }); } catch (error) { logger.error("Failed to link venmic:", error); return false; } }
// TODO: figure out how to map source to window with venmic
https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/core-extensions/src/rocketship/host/venmic.ts#L24-L47
12cd3c869f2a9478b65033033d64bd82790396fd