Showing preview only (792K chars total). Download the full file or copy to clipboard to get everything.
Repository: boardzilla/boardzilla-core
Branch: main
Commit: c857b309ff6b
Files: 104
Total size: 756.1 KB
Directory structure:
gitextract_pasq2vds/
├── .eslintrc
├── .github/
│ └── workflows/
│ ├── check.yml
│ └── test.yml
├── .gitignore
├── .mocharc.json.ignore
├── .npmignore
├── CHANGELOG.md
├── CLA.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── decl.d.ts
├── esbuild.mjs
├── package.json
├── scripts/
│ ├── postpack
│ └── prepack
├── src/
│ ├── action/
│ │ ├── action.ts
│ │ ├── index.ts
│ │ ├── selection.ts
│ │ └── utils.ts
│ ├── board/
│ │ ├── adjacency-space.ts
│ │ ├── connected-space-map.ts
│ │ ├── element-collection.ts
│ │ ├── element.ts
│ │ ├── fixed-grid.ts
│ │ ├── game.ts
│ │ ├── hex-grid.ts
│ │ ├── index.ts
│ │ ├── piece-grid.ts
│ │ ├── piece.ts
│ │ ├── single-layout.ts
│ │ ├── space.ts
│ │ ├── square-grid.ts
│ │ ├── stack.ts
│ │ └── utils.ts
│ ├── components/
│ │ ├── d6/
│ │ │ ├── assets/
│ │ │ │ ├── dice.ogg
│ │ │ │ └── index.scss
│ │ │ ├── d6.ts
│ │ │ ├── index.ts
│ │ │ └── useD6.tsx
│ │ ├── flippable/
│ │ │ ├── Flippable.tsx
│ │ │ ├── assets/
│ │ │ │ └── index.scss
│ │ │ └── index.ts
│ │ └── index.ts
│ ├── flow/
│ │ ├── action-step.ts
│ │ ├── each-player.ts
│ │ ├── enums.ts
│ │ ├── every-player.ts
│ │ ├── flow.ts
│ │ ├── for-each.ts
│ │ ├── for-loop.ts
│ │ ├── if-else.ts
│ │ ├── index.ts
│ │ ├── switch-case.ts
│ │ └── while-loop.ts
│ ├── game-creator.ts
│ ├── game-manager.ts
│ ├── index.ts
│ ├── interface.ts
│ ├── player/
│ │ ├── collection.ts
│ │ ├── index.ts
│ │ └── player.ts
│ ├── test/
│ │ ├── actions_test.ts
│ │ ├── compiler.cjs
│ │ ├── fixtures/
│ │ │ └── games.ts
│ │ ├── flow_test.ts
│ │ ├── game_manager_test.ts
│ │ ├── game_test.ts
│ │ ├── render_test.ts
│ │ ├── setup-debug.js
│ │ ├── setup.js
│ │ └── ui_test.ts
│ ├── test-runner.ts
│ ├── ui/
│ │ ├── Main.tsx
│ │ ├── assets/
│ │ │ ├── click.ogg.ts
│ │ │ ├── click_004.ogg
│ │ │ └── index.scss
│ │ ├── game/
│ │ │ ├── Game.tsx
│ │ │ └── components/
│ │ │ ├── ActionForm.tsx
│ │ │ ├── AnnouncementOverlay.tsx
│ │ │ ├── BoardDebug.tsx.wip
│ │ │ ├── Debug.tsx
│ │ │ ├── DebugArgument.tsx
│ │ │ ├── DebugChoices.tsx
│ │ │ ├── Drawer.tsx
│ │ │ ├── Element.tsx
│ │ │ ├── FlowDebug.tsx
│ │ │ ├── InfoOverlay.tsx
│ │ │ ├── PlayerControls.tsx
│ │ │ ├── Popout.tsx
│ │ │ ├── ProfileBadge.tsx
│ │ │ ├── Selection.tsx
│ │ │ └── Tabs.tsx
│ │ ├── index.tsx
│ │ ├── lib.ts
│ │ ├── queue.ts
│ │ ├── render.ts
│ │ ├── setup/
│ │ │ ├── Setup.tsx
│ │ │ └── components/
│ │ │ ├── Seating.tsx
│ │ │ └── settingComponents.tsx
│ │ └── store.ts
│ └── utils.ts
├── tsconfig.json
└── tsfmt.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintrc
================================================
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react-hooks/recommended"
],
"rules": {
'@typescript-eslint/no-unused-vars': [
'error', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
'no-unused-vars': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/ban-ts-comment': 0,
'@typescript-eslint/no-non-null-assertion': 0,
'@typescript-eslint/no-empty-function': 0,
'no-underscore-dangle': 0,
'arrow-parens': 0,
'no-nested-ternary': 0,
'max-classes-per-file': 0,
'object-curly-newline': 0,
'max-len': 0,
'prefer-destructuring': 0,
'no-console': 0,
"no-constant-condition": 0,
"prefer-const": 0,
}
}
================================================
FILE: .github/workflows/check.yml
================================================
on:
push:
branches:
- main
pull_request:
branches:
- main
name: Check
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: 18.18.2
- uses: actions/checkout@v3
- run: yarn
- run: yarn run compile
================================================
FILE: .github/workflows/test.yml
================================================
on:
push:
branches:
- main
pull_request:
branches:
- main
name: Check
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: 18.18.2
- uses: actions/checkout@v3
- run: yarn
- run: yarn test
- run: yarn run dep-check
================================================
FILE: .gitignore
================================================
# temp files
.DS_Store
\#*
.\#*
# npm
node_modules
yarn-error.log
# build artifacts
/dist
/docs
todos.txt
notes.txt
**/scratch.*
================================================
FILE: .mocharc.json.ignore
================================================
{
"require": [ "ts-node/register" ],
"loader": "ts-node/esm",
"extensions": ["ts", "tsx"],
"spec": [
"src/test/**"
]
}
================================================
FILE: .npmignore
================================================
!/dist
================================================
FILE: CHANGELOG.md
================================================
# v0.2.14
* Game elements now have next/previous selectors to find adjacent elements in
the same space.
* Invalid options in selections now retain their position
* Corrected a bug with nested follow-ups
# v0.2.13
* Game settings provided now all accept an initial default value
(e.g. numberSetting, etc)
* The `everyPlayer` flow now passes the currently acting player to the flow
args, just like `eachPlayer`
* Corrected an issue with `everyPlayer` hanging when using an array `do` block
* Corrected a bug with `layout.haphazardly`.
# v0.2.12
* Added action#confirm as an alternate means to add confirmation prompts
* Providing a `validate` function in a `chooseFrom` now shows invalid choices
with error messages if clicked
# v0.2.11 Hideable Space Layouts
* Added 3 new layouts for Spaces that save screen real estate
* `element#layoutAsDrawer` puts Space in a expandable drawer (replaces the
drawer 'attribute' in layout)
* `element#layoutAsTabs` puts several Spaces into a switchable layout of tabs
* `element#layoutAsPopout` hides a Space behind a button that opens it as a
popout modal
# v0.2.10
* Fixed Info and Debug overlays
# v0.2.9
* Removed deprecated index.scss import
# v0.2.8 Stack and Flippable
* Added Stack class for decks within hidden elements and internal moves
* Added Flippable component with back/front and animated flips
# v0.2.7 Animation overhaul
* Overhauled the animation logic that decides how elements move for various
players, correcting several glitches
* Pieces now animate on to and off of the board, into and out of the bottom of
decks even if unrendered
# v0.2.6 Subflows
* Subflows allow you to define entire new flows that branch of your main flow,
e.g. playing a particular Card causes a set of new actions to happen
* Follow-ups are still available but these are now actually just Subflows under
the hood that automatically perform only a single action
* Some small flow and animation fixes included
# v0.2.5
* Added `action.swap` to allow players to exchange Pieces
* Added `action.reorder` to allow players to reorder a collection of Pieces
* Also made some improvements in the dragging and moving to remove flicker and
quirkiness
# v0.2.4 Component modules
* Added Component modules. The `D6` class is the first example and it has been
moved into a separate self-contained import. See
https://docs.boardzilla.io/game/modules
* It is no longer necessary to include `@boardzilla/core/index.css` in
`ui/index.tsx`. This line can be removed.
* Added `actionStep.continueIfImpossible` to allow a step to be skipped if no
actions are valid
* Added `actionStep.repeatUntil` to make a set of actions repeatable until a
'pass' action
* Added `Player.hiddenAttributes` to make some attributes hidden from other
players
* Some consistency fixes to prompts.
# v0.2.3
* Board Sizes now accepts more detailed matchers, with a range of "best fit"
aspect ratios, a setting to choose scrollbars or letterbox and mobile
orientation fixing
* Show/hide methods moved to Piece only
* Space now has new convenience methods to attach content show/hide event
handlers
* Space now has "screen" methods to make contents completely invisible to
players
* Added Test Runner mocks and updatePlayers
# v0.2 Grids
* Added subclasses of `Space` for various grids, including more options for
square, hex and the brand new PieceGrid. These replace `Space#createGrid`.
* Grids can now be shaped, e.g. to create a hex grid in a square shape
* `PieceGrid` allows the placement and tiling of irregular shapes, with an
extendible grid that correctly sizes shaped pieces inside it.
* Pieces now have a `setShape` and `setEdges` for adding irregular shapes and
labelling the cells and edges for the purposes of adjacency.
* Connecting spaces now allows bidirectional distances
* Generics have been given a full rework, removing lots of unnecessary generics
and making the importing of more game classes more straightfoward and
extendable.
* `createGameClasses` is gone. `Space` and `Piece` can be imported directly from
core.
* `Game#registerClasses` is no longer necessary and can be removed.
* `Piece#putInto` now accepts `row`, `column`.
* Now using incremental Typescript compilation for much faster rebuilds
* History reprocessing in development has been completely reworked for much
better performance
* Added a new associated starter template using PieceGrid and irregular tiles.
# v0.1 Lobby
* Brand new lobby with seating controls, allowing self-seating, async game start
and better UI.
* renamed `Board` to `Game` and gave this class all exposed API methods that
were previously in `Game`. `Game` renamed to `GameManager` and intended as an
internal class.
================================================
FILE: CLA.md
================================================
# Contributor Agreement
# Individual Contributor Exclusive License Agreement
Thank you for your interest in contributing to Boardzilla ("We" or "Us").
The purpose of this contributor agreement ("Agreement") is to clarify and
document the rights granted to Us by contributors to the Boardzilla core
library. To make this document effective, please contact andrew@boardzilla.io.
## How to use this Contributor Agreement
If You are an employee and have created the Contribution as part of your
employment, You need to have Your employer approve this Agreement or sign the
Entity version of this document. If You do not own the Copyright in the entire
work of authorship, any other author of the Contribution should also sign this –
in any event, please contact Us at andrew@boardzilla.io
## 1. Definitions
"You" means the individual Copyright owner who Submits a Contribution to Us.
"Contribution" means any original work of authorship, including any original
modifications or additions to an existing work of authorship, Submitted by You
to Us, in which You own the Copyright.
"Copyright" means all rights protecting works of authorship, including
copyright, moral and neighboring rights, as appropriate, for the full term of
their existence.
"Material" means the software or documentation made available by Us to third
parties. When this Agreement covers more than one software project, the Material
means the software or documentation to which the Contribution was
Submitted. After You Submit the Contribution, it may be included in the
Material.
"Submit" means any act by which a Contribution is transferred to Us by You by
means of tangible or intangible media, including but not limited to electronic
mailing lists, source code control systems, and issue tracking systems that are
managed by, or on behalf of, Us, but excluding any transfer that is
conspicuously marked or otherwise designated in writing by You as "Not a
Contribution."
"Documentation" means any non-software portion of a Contribution.
## 2. License grant
### 2.1 Copyright license to Us
Subject to the terms and conditions of this Agreement, You hereby grant to Us a
worldwide, royalty-free, Exclusive, perpetual and irrevocable (except as stated
in Section 8.2) license, with the right to transfer an unlimited number of
non-exclusive licenses or to grant sublicenses to third parties, under the
Copyright covering the Contribution to use the Contribution by all means,
including, but not limited to:
- publish the Contribution,
- modify the Contribution,
- prepare derivative works based upon or containing the Contribution and/or to
combine the Contribution with other Materials,
- reproduce the Contribution in original or modified form,
- distribute, to make the Contribution available to the public, display and
publicly perform the Contribution in original or modified form.
### 2.2 Moral rights
Moral Rights remain unaffected to the extent they are recognized and not
waivable by applicable law. Notwithstanding, You may add your name to the
attribution mechanism customary used in the Materials you Contribute to, such as
the header of the source code files of Your Contribution, and We will respect
this attribution when using Your Contribution.
### 2.3 Copyright license back to You
Upon such grant of rights to Us, We immediately grant to You a worldwide,
royalty-free, non-exclusive, perpetual and irrevocable license, with the right
to transfer an unlimited number of non-exclusive licenses or to grant
sublicenses to third parties, under the Copyright covering the Contribution to
use the Contribution by all means, including, but not limited to:
- publish the Contribution,
- modify the Contribution,
- prepare derivative works based upon or containing the Contribution and/or to
combine the Contribution with other Materials,
- reproduce the Contribution in original or modified form,
- distribute, to make the Contribution available to the public, display and
publicly perform the Contribution in original or modified form. This license
back is limited to the Contribution and does not provide any rights to the
Material.
## 3. Patents
### 3.1 Patent license
Subject to the terms and conditions of this Agreement You hereby grant to Us and
to recipients of Materials distributed by Us a worldwide, royalty-free,
non-exclusive, perpetual and irrevocable (except as stated in Section 3.2)
patent license, with the right to transfer an unlimited number of non-exclusive
licenses or to grant sublicenses to third parties, to make, have made, use,
sell, offer for sale, import and otherwise transfer the Contribution and the
Contribution in combination with any Material (and portions of such
combination). This license applies to all patents owned or controlled by You,
whether already acquired or hereafter acquired, that would be infringed by
making, having made, using, selling, offering for sale, importing or otherwise
transferring of Your Contribution(s) alone or by combination of Your
Contribution(s) with any Material.
### 3.2 Revocation of patent license
You reserve the right to revoke the patent license stated in section 3.1 if We
make any infringement claim that is targeted at your Contribution and not
asserted for a Defensive Purpose. An assertion of claims of the Patents shall be
considered for a "Defensive Purpose" if the claims are asserted against an
entity that has filed, maintained, threatened, or voluntarily participated in a
patent infringement lawsuit against Us or any of Our licensees.
## 4. License obligations by Us
We agree to license the Contribution only under the terms of the license or
licenses that We are using on the Submission Date for the Material (including
any rights to adopt any future version of a license).
We agree to license patents owned or controlled by You only to the extent
necessary to (sub)license Your Contribution(s) and the combination of Your
Contribution(s) with the Material under the terms of the license or licenses
that We are using on the Submission Date.
## 5. Disclaimer
THE CONTRIBUTION IS PROVIDED "AS IS". MORE PARTICULARLY, ALL EXPRESS OR IMPLIED
WARRANTIES INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTY OF SATISFACTORY
QUALITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY
DISCLAIMED BY YOU TO US AND BY US TO YOU. TO THE EXTENT THAT ANY SUCH WARRANTIES
CANNOT BE DISCLAIMED, SUCH WARRANTY IS LIMITED IN DURATION AND EXTENT TO THE
MINIMUM PERIOD AND EXTENT PERMITTED BY LAW.
## 6. Consequential damage waiver
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL YOU OR WE BE
LIABLE FOR ANY LOSS OF PROFITS, LOSS OF ANTICIPATED SAVINGS, LOSS OF DATA,
INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL AND EXEMPLARY DAMAGES ARISING OUT
OF THIS AGREEMENT REGARDLESS OF THE LEGAL OR EQUITABLE THEORY (CONTRACT, TORT OR
OTHERWISE) UPON WHICH THE CLAIM IS BASED.
## 7. Approximation of disclaimer and damage waiver
IF THE DISCLAIMER AND DAMAGE WAIVER MENTIONED IN SECTION 5. AND
SECTION 6. CANNOT BE GIVEN LEGAL EFFECT UNDER APPLICABLE LOCAL LAW, REVIEWING
COURTS SHALL APPLY LOCAL LAW THAT MOST CLOSELY APPROXIMATES AN ABSOLUTE WAIVER
OF ALL CIVIL OR CONTRACTUAL LIABILITY IN CONNECTION WITH THE CONTRIBUTION.
## 8. Term
8.1 This Agreement shall come into effect upon Your acceptance of the terms and
conditions.
8.2 This Agreement shall apply for the term of the copyright and patents
licensed here. However, You shall have the right to terminate the Agreement if
We do not fulfill the obligations as set forth in Section 4. Such termination
must be made in writing.
8.3 In the event of a termination of this Agreement Sections 5, 6, 7, 8 and 9
shall survive such termination and shall remain in full force thereafter. For
the avoidance of doubt, Free and Open Source Software (sub)licenses that have
already been granted for Contributions at the date of the termination shall
remain in full force after the termination of this Agreement.
## 9 Miscellaneous
9.1 This Agreement and all disputes, claims, actions, suits or other proceedings
arising out of this agreement or relating in any way to it shall be governed by
the laws of Canada excluding its private international law provisions.
9.2 This Agreement sets out the entire agreement between You and Us for Your
Contributions to Us and overrides all other agreements or understandings.
9.3 In case of Your death, this agreement shall continue with Your heirs. In
case of more than one heir, all heirs must exercise their rights through a
commonly authorized person.
9.4 If any provision of this Agreement is found void and unenforceable, such
provision will be replaced to the extent possible with a provision that comes
closest to the meaning of the original provision and that is enforceable. The
terms and conditions set forth in this Agreement shall apply notwithstanding any
failure of essential purpose of this Agreement or any limited remedy to the
maximum extent possible under law.
9.5 You agree to notify Us of any facts or circumstances of which you become
aware that would make this Agreement inaccurate in any respect.
You
Date: ____________________________________________________
Name: ____________________________________________________
Title: ____________________________________________________
Address: ____________________________________________________
Us
Date: ____________________________________________________
Name: ____________________________________________________
Title: ____________________________________________________
Address: ____________________________________________________
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
Any open source product is only as good as the community behind it. You can
participate by sharing code, ideas, or simply helping others. No matter what
your skill level is, every contribution counts.
## Games vs Core
These contributions guidelines do not apply in any way to games submitted to the
Boardzilla platform. **You retain full copyright for your game code and
assets.** This only only applies to code submitted to the actual Boardzilla
core library.
## Copyright
**IMPORTANT:** By supplying code to Boardzilla core in issues and pull requests,
you agree to assign copyright of that code to us, on the condition that we also
release that code under the AGPL license.
We ask for this so that the ownership in the license is clear and unambiguous,
and so that community involvement doesn't stop us from being able to sustain the
project by releasing this code under a permissive licenses in addition to the
open source AGPL license. This copyright assignment won't prevent you from using
the code in any way you see fit.
See our [Contributor License Agreement](CLA.md) for the legal details.
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: README.md
================================================
👋 This is Boardzilla, a framework to make writing a digital board game easy. Boardzilla takes care of
- player management
- structuring game rules
- persisting game & player state
- animations
and much more!
Visit us at https://boardzilla.io.
See documentation at https://docs.boardzilla.io.
(c)2024 Andrew Hull
================================================
FILE: decl.d.ts
================================================
declare module "*.ogg";
================================================
FILE: esbuild.mjs
================================================
import * as esbuild from 'esbuild'
import {sassPlugin} from 'esbuild-sass-plugin'
await esbuild.build({
entryPoints: ['./src/ui/assets/index.scss'],
assetNames: '[name]',
bundle: true,
format: 'esm',
outdir: 'dist/ui/assets/',
loader: {
'.ogg': 'dataurl',
'.jpg': 'file',
},
sourcemap: 'inline',
plugins: [sassPlugin()],
})
await esbuild.build({
entryPoints: ['./src/components/d6/index.ts'],
assetNames: '[name]',
bundle: true,
format: 'esm',
outdir: 'dist/components/d6/assets/',
loader: {
'.ogg': 'copy',
},
sourcemap: 'inline',
plugins: [sassPlugin()],
})
await esbuild.build({
entryPoints: ['./src/components/flippable/index.ts'],
assetNames: '[name]',
bundle: true,
format: 'esm',
outdir: 'dist/components/flippable/assets/',
sourcemap: 'inline',
plugins: [sassPlugin()],
})
================================================
FILE: package.json
================================================
{
"name": "@boardzilla/core",
"version": "0.2.14",
"author": "Andrew Hull <aghull@gmail.com>",
"license": "AGPL-3.0",
"scripts": {
"clean": "rm -rf dist docs",
"build": "yarn build:test && rm -rf dist/test",
"prepublish": "git diff-index --quiet HEAD || (echo 'git unclean' && exit 1)",
"prepack": "./scripts/prepack",
"postpack": "./scripts/postpack",
"build:test": "yarn assets && yarn compile && find dist/ -type f|grep js$|xargs grep -l scss|xargs sed -i~ 's/\\.scss/.css/g' && find dist/ -type f|grep js~$|xargs rm",
"assets": "node esbuild.mjs",
"test": "NODE_ENV=test yarn run build:test && mocha src/test/setup.js dist/test/*_test.js",
"test:debug": "NODE_ENV=test yarn run build:test && mocha --inspect-brk --timeout 3600000 src/test/setup-debug.js dist/test/*_test.js",
"compile": "tsc",
"docs": "typedoc",
"lint": "eslint . --ext .ts",
"dep-check": "dpdm --no-warning --no-tree -T ./src/index.ts"
},
"type": "module",
"exports": {
".": "./entry/index.js",
"./components": "./entry/components/index.js"
},
"files": [
"entry/**/*"
],
"types": "entry/index.d.ts",
"sideEffects": [
"./src/ui/assets/index.scss"
],
"dependencies": {
"classnames": "^2.3.1",
"graphology": "^0.25.4",
"graphology-shortest-path": "^2.0.2",
"graphology-traversal": "^0.3.1",
"graphology-types": "^0.24.7",
"random-seed": "^0.3.0",
"react": "^18.2",
"react-color": "^2.19.3",
"react-dom": "^18.2",
"react-draggable": "^4.4.5",
"uuid-random": "^1.3.2",
"zustand": "^4.4.0"
},
"devDependencies": {
"@types/chai": "^4.3.1",
"@types/chai-spies": "^1.0.3",
"@types/jest": "^28.1.4",
"@types/node": "^20.6.2",
"@types/random-seed": "^0.3.3",
"@types/react": "^18.2.25",
"@types/react-color": "^3.0.6",
"@types/react-dom": "^18.2.14",
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",
"chai": "^4.3.8",
"chai-spies": "^1.0.0",
"dpdm": "^3.14.0",
"esbuild": "^0.19.5",
"esbuild-sass-plugin": "^2.16.0",
"eslint": "^8.53.0",
"eslint-plugin-react-hooks": "^4.6.0",
"mocha": "^10.2.0",
"ts-node": "^10.8.2",
"typedoc": "^0.25.2",
"typedoc-plugin-markdown": "^3.17.1",
"typedoc-plugin-merge-modules": "^5.1.0",
"typescript": "^5.2.0"
},
"typedocOptions": {
"entryPoints": [
"src",
"src/game.ts",
"src/board",
"src/flow",
"src/action",
"src/player",
"src/ui"
],
"plugin": [
"typedoc-plugin-markdown",
"typedoc-plugin-merge-modules"
],
"sort": "source-order",
"categorizeByGroup": false,
"excludeInternal": true,
"excludeNotDocumented": true,
"out": "docs",
"name": "@boardzilla/core"
}
}
================================================
FILE: scripts/postpack
================================================
#!/bin/bash
set -e
rm -r entry
ln -s src entry
================================================
FILE: scripts/prepack
================================================
#!/bin/bash
set -e
yarn clean
yarn build
rm -r entry
mv dist entry
================================================
FILE: src/action/action.ts
================================================
import Selection from './selection.js';
import GameElement from '../board/element.js';
import Piece from '../board/piece.js';
import ElementCollection from '../board/element-collection.js';
import { n } from '../utils.js';
import type { ResolvedSelection, BoardQueryMulti } from './selection.js';
import type { Game, PieceGrid } from '../board/index.js';
import type { Player } from '../player/index.js';
import type { default as GameManager, ActionDebug, PendingMove } from '../game-manager.js';
/**
* A single argument
* @category Actions
*/
export type SingleArgument = string | number | boolean | GameElement | Player;
/**
* An argument that can be added to an {@link Action}. Each value is chosen by
* player or in some cases passed from a previous action. Arguments can be:
* - a number
* - a string
* - a boolean
* - a {@link GameElement}
* - a {@link Player}
* - an array of one these in the case of a multi-choice selection
* @category Actions
*/
export type Argument = SingleArgument | SingleArgument[];
/**
* A follow-up action
* @category Actions
*/
export type ActionStub = {
/**
* The name of the action, as defined in `{@link Game#defineactions}`.
*/
name: string,
/**
* The player to take this action, if different than the current player
*/
player?: Player,
/**
* Action prompt. If specified, overrides the `action.prompt` in `{@link
* Game#defineactions}`.
*/
prompt?: string,
/**
* Description of taking the action from a 3rd person perspective,
* e.g. "choosing a card". The string will be automatically prefixed with the
* player name and appropriate verb ("is/are"). If specified, this will be
* used to convey to non-acting players what actions are happening.
*/
description?: string,
/**
* An object containing arguments to be passed to the follow-up action. This
* is useful if there are multiple ways to trigger this follow-up that have
* variations.
*/
args?: Record<string, Argument>
}
type Group = Record<string,
['number', Parameters<Action['chooseNumber']>[1]?] |
['select', Parameters<Action['chooseFrom']>[1], Parameters<Action['chooseFrom']>[2]?] |
['text', Parameters<Action['enterText']>[1]?]
>
type ExpandGroup<A extends Record<string, Argument>, R extends Group> = A & {[K in keyof R]:
R[K][0] extends 'number' ? number :
R[K][0] extends 'text' ? string :
R[K][0] extends 'select' ? (R[K][1] extends Parameters<typeof Action.prototype.chooseFrom<any, infer E extends SingleArgument>>[1] ? E : never) :
never
}
/**
* Actions represent discreet moves players can make. These contain the choices
* needed to take this action and the results of the action. Create Actions
* using the {@link Game#action} function. Actions are evaluated at the time the
* player has the option to perform the action, so any expressions that involve
* game state will reflect the state at the time the player is performing the
* action.
*
* @privateRemarks
* The Action object is responsible for:
* - providing Selection objects to players to aid in supplying appropriate Arguments
* - validating player Arguments and returning any Selections needed to complete
* - accepting player Arguments and altering board state
*
* @category Actions
*/
export default class Action<A extends Record<string, Argument> = NonNullable<unknown>> {
name?: string;
prompt?: string;
description?: string;
selections: Selection[] = [];
moves: ((args: Record<string, Argument>) => any)[] = [];
condition?: ((args: A) => boolean) | boolean;
messages: {text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>), position?: number}[] = [];
order: ('move' | 'message')[] = [];
mutated = false;
gameManager: GameManager;
constructor({ prompt, description, condition }: {
prompt?: string,
description?: string,
condition?: ((args: A) => boolean) | boolean,
}) {
this.prompt = prompt;
this.description = description;
this.condition = condition;
}
isPossible(args: A): boolean {
return typeof this.condition === 'function' ? this.condition(args) : this.condition ?? true;
}
// given a set of args, return sub-selections possible trying each possible next arg
// return undefined if these args are impossible
// return 0-length if these args are submittable
// return array of follow-up selections if incomplete
// skipping/expanding is very complex and this method runs all the rules for what should/must be combined, either as additional selections or as forced args
// skippable options will still appear in order to present the choices to the user to select that tree. This will be the final selection if no other selection turned skipping off
// TODO memoize
_getPendingMoves(args: Record<string, Argument>, debug?: ActionDebug): PendingMove[] | undefined {
if (debug) {
debug[this.name!] = { args: {} };
for (const arg of Object.keys(args)) debug[this.name!].args[arg] = 'sel';
}
const moves = this._getPendingMovesInner(args, debug);
// resolve any combined selections now with only args up until first choice
if (moves?.length) {
for (const move of moves) {
if (debug) {
debug[move.name].args[move.selections[0].name] = 'ask';
}
const combineWith = move.selections[0].clientContext?.combineWith; // guaranteed single selection
let confirm: Selection['confirm'] | undefined = move.selections[0].confirm;
let validation: Selection['validation'] | undefined = move.selections[0].validation;
// look ahead for any selections that can/should be combined
for (let i = this.selections.findIndex(s => s.name === move.selections[0].name) + 1; i !== this.selections.length; i++) {
if (confirm) break; // do not skip an explicit confirm
let selection: Selection | ResolvedSelection = this.selections[i];
if (combineWith?.includes(selection.name)) selection = selection.resolve(move.args);
if (!selection.isResolved()) break;
const arg = selection.isForced();
if (arg !== undefined) { // forced future args are added here to shorten the form and pre-prompt any confirmation
move.args[selection.name] = arg;
if (debug) {
debug[move.name].args[selection.name] = 'forced';
}
} else if (combineWith?.includes(selection.name)) { // future combined selections are added as well
move.selections.push(selection);
if (debug) {
debug[move.name].args[selection.name] = 'ask';
}
} else {
break;
}
confirm = selection.confirm ?? confirm; // find latest confirm for the overall combination
validation = selection.validation ?? validation;
}
if (confirm) move.selections[0].confirm = confirm; // and put it on top
if (validation) move.selections[move.selections.length - 1].validation = validation; // on bottom
}
}
return moves;
}
_getPendingMovesInner(args: Record<string, Argument>, debug?: ActionDebug): PendingMove[] | undefined {
let selection = this._nextSelection(args);
if (!selection) return [];
const move = {
name: this.name!,
prompt: this.prompt,
description: this.description,
args,
selections: [selection]
};
if (!selection.isPossible()) {
if (debug) {
debug[this.name!].args[selection.name] ??= 'imp';
}
return;
}
if (!selection.isUnbounded()) {
let possibleOptions: { choice: SingleArgument, error?: string, label?: string }[] = [];
let anyValidOption = false;
let pruned = false;
let pendingMoves: PendingMove[] = [];
let hasCompleteMove = false
for (const option of selection.options()) {
const allArgs = {...args, [selection.name]: option.choice};
if (selection.validation && !selection.isMulti()) {
const error = this._withDecoratedArgs(allArgs as A, args => selection!.error(args))
if (error) {
pruned = true;
option.error = error;
possibleOptions.push(option as { choice: SingleArgument, error?: string, label?: string })
continue;
}
}
const submoves = this._getPendingMovesInner(allArgs, debug);
if (submoves === undefined) {
pruned = true;
} else {
if (!selection.isMulti()) possibleOptions.push(option as { choice: SingleArgument, error?: string, label?: string });
anyValidOption ||= true;
hasCompleteMove ||= submoves.length === 0;
pendingMoves = pendingMoves.concat(submoves);
}
}
if (!anyValidOption) {
if (debug) {
debug[this.name!].args[selection.name] = 'tree';
}
return undefined;
}
if (pruned && !selection.isMulti()) {
selection.resolvedChoices = possibleOptions;
}
// return the next selection(s) if skipIf, provided it exists for all possible choices
// special case: do not skip "apparent" choices in group even if they are ultimately forced, in order to best present the limited options
if (pendingMoves.length && (
((selection.skipIf === 'always' || selection.skipIf === true) && !hasCompleteMove) ||
selection.skipIf === 'only-one' && possibleOptions.length === 1 && (!selection.clientContext?.combineWith || selection.options().length <= 1)
)) {
if (debug) {
debug[this.name!].args[selection.name] = selection.skipIf === true ? 'skip' : selection.skipIf;
}
return pendingMoves;
}
}
if (debug && (debug[this.name!].args[selection.name] ?? 'imp') === 'imp') {
debug[this.name!].args[selection.name] ??= 'future';
}
return [move];
}
/**
* given a partial arg list, returns a selection object for continuation if one exists.
* @internal
*/
_nextSelection(args: Record<string, Argument>): ResolvedSelection | undefined {
let nextSelection: ResolvedSelection | undefined = undefined;
for (const s of this.selections) {
const selection = s.resolve(args);
if (selection.skipIf === true) continue;
if (!(s.name in args)) {
nextSelection = selection;
break;
}
}
return nextSelection;
}
/**
* process this action with supplied args. returns error if any
* @internal
*/
_process(player: Player, args: Record<string, Argument>): string | undefined {
// truncate invalid args - is this needed?
let error: string | undefined = undefined;
if (!this.isPossible(args as A)) return `${this.name} action not possible`;
for (const selection of this.selections) {
if (args[selection.name] === undefined) {
const arg = selection.resolve(args).isForced()
if (arg) args[selection.name] = arg;
}
error = this._withDecoratedArgs(args as A, args => selection.error(args))
if (error) {
console.error(`Invalid choice for ${selection.name}. Got "${args[selection.name]}" ${error}`);
break;
}
}
if (error) return error;
// revalidate on server. quite expensive. easier way? I think this might just be counting the args since the validation already passed ^^
if (!globalThis.window) {
const pendingMoves = this._getPendingMoves(args);
if (!pendingMoves) {
console.error('attempted to process invalid args', this.name, args);
return error || 'unknown error during action._process';
}
if (pendingMoves.length) {
return error || 'incomplete action';
}
}
let moveIndex = 0;
let messageIndex = 0;
for (const seq of this.order) {
if (seq === 'move') {
this.moves[moveIndex++](args);
} else {
const message = this.messages[messageIndex++];
const messageArgs = ((typeof message.args === 'function') ? message.args(args as A) : message.args);
if (message.position) {
this.gameManager.game.messageTo(message.position, message.text, {...args, player, ...messageArgs});
} else {
this.gameManager.game.message(message.text, {...args, player, ...messageArgs});
}
}
}
}
_addSelection(selection: Selection) {
if (this.selections.find(s => s.name === selection.name)) throw Error(`Duplicate selection name on action: ${selection.name}`);
if (this.mutated) console.warn(`Adding a choice ("${selection.name}") after behavior in action is valid but players will need to perform the choices before the behavior.`);
this.selections.push(selection);
return selection;
}
// fn must be idempotent
_withDecoratedArgs(args: A, fn: (args: A) => any) {
if (args['__placement__']) {
const placementSelection = this.selections.find(s => s.name === '__placement__');
if (placementSelection && args[placementSelection.placePiece!]) {
args = {...args};
// temporarily set piece to place to access position properties
const placePiece = (args[placementSelection.placePiece!] as Piece<Game>);
const { row, column, _rotation } = placePiece;
const [newColumn, newRow, newRotation] = args['__placement__'] as [number, number, number?];
placePiece.column = newColumn;
placePiece.row = newRow;
placePiece.rotation = newRotation ?? 0;
const result = fn(args);
placePiece.column = column;
placePiece.row = row;
placePiece._rotation = _rotation;
return result;
}
}
return fn(args);
}
_getError(selection: ResolvedSelection, args: A) {
return this._withDecoratedArgs(args, args => selection.error(args));
}
_getConfirmation(selection: ResolvedSelection, args: A) {
if (!selection.confirm) return;
const argList = selection.confirm[1];
return n(
selection.confirm[0],
{...args, ...(typeof argList === 'function' ? this._withDecoratedArgs(args, argList) : argList)}
);
}
/**
* Add behaviour to this action to alter game state. After adding the choices
* to an action, calling `do` causes Boardzilla to use the player choices to
* actually do something with those choices. Call this method after all the
* methods for player choices so that the choices are properly available to
* the `do` function.
*
* @param move - The action to perform. This function accepts one argument
* with key-value pairs for each choice added to the action using the provided
* names.
*
* @example
* player => action({
* prompt: 'Take resources',
* }).chooseFrom({
* 'resource', ['lumber', 'steel'],
* { prompt: 'Select resource' }
* }).chooseNumber(
* 'amount', {
* prompt: 'Select amount',
* max: 3
* }).do(({ resource, amount }) => {
* // the choices are automatically passed in with their proper type
* game.firstN(amount, Resource, {resource}).putInto(
* player.my('stockPile')
* );
* })
* @category Behaviour
*/
do(move: (args: A) => any): Action<A> {
this.mutated = true;
this.moves.push(move);
this.order.push('move');
return this;
}
/**
* Add a message to this action that will be broadcast in the chat. Call this
* method after all the methods for player choices so that the choices are
* properly available to the `message` function. However the message should be
* called before or after any `do` behaviour depending on whether you want the
* message to reflect the game state before or after the move is performs. The
* action's `message` and `do` functions can be intermixed in this way to
* generate messages at different points int the execution of a move.
*
* @param text - The text of the message to send. This can contain interpolated
* strings with double braces just as when calling {@link Game#message}
* directly. However when using this method, the player performing the action,
* plus any choices made in the action are automatically made available.
*
* @param args - If additional strings are needed in the message besides
* 'player' and the player choices, these can be specified here. This can also
* be specified as a function that accepts the player choices and returns
* key-value pairs of strings for interpolation.
*
* @example
* action({
* prompt: 'Say something',
* }).enterText({
* 'message',
* }).message(
* '{{player}} said {{message}}' // no args needed
* ).message(
* "I said, {{player}} said {{loudMessage}}",
* ({ message }) => ({ loudMessage: message.toUpperCase() })
* )
* @category Behaviour
*/
message(text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>)) {
this.messages.push({text, args});
this.order.push('message');
return this;
}
/**
* Add a message to this action that will be broadcast in the chat to the
* specified player(s). Call this method after all the methods for player
* choices so that the choices are properly available to the `message`
* function. However the message should be called before or after any `do`
* behaviour depending on whether you want the message to reflect the game
* state before or after the move is performs. The action's `message` and `do`
* functions can be intermixed in this way to generate messages at different
* points int the execution of a move.
*
* @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 just as when calling {@link Game#message}
* directly. However when using this method, the player performing the action,
* plus any choices made in the action are automatically made available.
*
* @param args - If additional strings are needed in the message besides
* 'player' and the player choices, these can be specified here. This can also
* be specified as a function that accepts the player choices and returns
* key-value pairs of strings for interpolation.
*
* @example
* action({
* prompt: 'Say something',
* }).enterText({
* 'message',
* }).message(
* '{{player}} said {{message}}' // no args needed
* ).message(
* "I said, {{player}} said {{loudMessage}}",
* ({ message }) => ({ loudMessage: message.toUpperCase() })
* )
* @category Behaviour
*/
messageTo(player: (Player | number) | (Player | number)[], text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>)) {
if (!(player instanceof Array)) player = [player];
for (const p of player) {
this.messages.push({position: typeof p === 'number' ? p : p.position, text, args});
this.order.push('message');
}
return this;
}
/**
* Add a choice to this action from a list of options. These choices will be
* displayed as buttons in the UI.
*
* @param name - The name of this choice. This name will be used in all
* functions that accept the player's choices
*
* @param choices - An array of choices. This may be an array of simple values
* or an array of objects in the form: `{ label: string, choice: value }`
* where value is the actual choice that will be passed to the rest of the
* action, but label is the text presented to the player that they will be
* prompted to click. Use the object style when you want player text to
* contain additional logic or differ in some way from the choice, similiar to
* `<option value="key">Some text</option>` in HTML. This can also be a
* function that returns the choice array. This function will accept arguments
* for each choice the player has made up to this point in the action.
*
* @param {Object} options
* @param options.prompt - Prompt displayed to the user for this choice.
* @param options.skipIf - One of 'always', 'never' or 'only-one' or a
* function returning a boolean. (Default 'only-one').
*
* <ul>
* <li>only-one: If there is only valid choice in the choices given, the game
* will skip this choice, prompting the player for subsequent choices, if any,
* or completing the action otherwise.
* <li>always: Rather than present this choice directly, the player will be
* prompted with choices from the *next choice* in the action for each
* possible choice here, essentially expanding the choices ahead of time to
* save the player a step. This option only has relevance if there are
* subsequent choices in the action.
* <li>never: Always present this choice, even if the choice is forced
* <li>function: A function that accepts all player choices up to this point
* and returns a boolean. If returning true, this choice will be skipped.
* This form is useful in the rare situations where the choice at the time may
* be meaningless, e.g. selecting from a set of identical tokens. In this case
* the game will make the choice for the player using the first viable option.
* </ul>
*
* @param options.validate - A function that takes an object of key-value
* pairs for all player choices and returns a boolean. If false, the game will
* not allow the player to submit this choice. If a string is returned, this
* will display as the reason for disallowing these selections.
*
* @param options.confirm - A confirmation message that the player will always
* see before commiting this choice. This can be useful to present additional
* information about the consequences of this choice, or simply to force the
* player to hit a button with a clear message. This can be a simple string,
* or a 2-celled array in the same form as {@link message} with a string
* message and a set of key-value pairs for string interpolation, optionally
* being a function that takes an object of key-value pairs for all player
* choices, and returns the interpolation object.
*
* @example
* action({
* prompt: 'Choose color',
* }).chooseFrom(
* 'color', ['white', 'blue', 'red'],
* ).do(
* ({ color }) => ... color will be equal to the player-selected color ...
* )
*
* // a more complex example:
* action({
* prompt: 'Take resources',
* }).chooseFrom(
* 'resource', ['lumber', 'steel', 'oil'],
* { prompt: 'Select resource' }
* ).chooseFrom(
* // Use the functional style to include the resource choice in the text
* // Also use object style to have the value simply be "high" or "low"
* 'grade', ({ resource }) => [
* { choice: 'high', label: `High grade ${resource}` }
* { choice: 'low', label: `Low grade ${resource}` }
* ],
* {
* // A follow-up choice that doesn't apply to "oil"
* skipIf: ({ resource }) => resource === 'oil',
* // Add an 'are you sure?' message
* confirm: ['Buy {{grade}} grade {{resource}}?', ({ grade }) = ({ grade: grade.toUpperCase() })]
* }
* ).do (
* ({ resource, grade }) => {
* // resource will equal 'lumber', 'steel' or 'oil'
* // grade will equal 'high' or 'low'
* }
* )
* @category Choices
*/
chooseFrom<N extends string, T extends SingleArgument>(
name: N,
choices: (T & (string | number | boolean))[] | { label: string, choice: T }[] | ((args: A) => (T & (string | number | boolean))[] | { label: string, choice: T }[]),
options?: {
prompt?: string | ((args: A) => string)
confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T}) => Record<string, Argument>) | undefined]
validate?: ((args: A & {[key in N]: T}) => string | boolean | undefined)
// initial?: T | ((...arg: A) => T), // needed for select-boxes?
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
}
): Action<A & {[key in N]: T}> {
this._addSelection(new Selection(name, {
prompt: options?.prompt,
validation: options?.validate,
confirm: options?.confirm,
skipIf: options?.skipIf,
selectFromChoices: { choices }
}));
return this as unknown as Action<A & {[key in N]: T}>;
}
/**
* Prompt the user for text entry. Use this in games where players submit
* text, like word-guessing games.
*
* @param name - The name of this text input. This name will be used in all
* functions that accept the player's choices
*
* @param {Object} options
* @param options.initial - Default text that can appear initially before a
* user types.
* @param options.prompt - Prompt displayed to the user for entering this
* text.
*
* @param options.validate - A function that takes an object of key-value
* pairs for all player choices and returns a boolean. If false, the game will
* not allow the player to submit this text. If a string is returned, this
* will display as the reason for disallowing this text.
*
* @example
* action({
* prompt: 'Guess a word',
* }).enterText({
* 'guess',
* { prompt: 'Your guess', }
* }).message(
* guess => `{{player}} guessed ${guess}`
* })
* @category Choices
*/
enterText<N extends string>(name: N, options?: {
prompt?: string | ((args: A) => string),
validate?: ((args: A & {[key in N]: string}) => string | boolean | undefined),
regexp?: RegExp,
initial?: string | ((args: A) => string)
}): Action<A & {[key in N]: string}> {
const { prompt, validate, regexp, initial } = options || {}
this._addSelection(new Selection(name, { prompt, validation: validate, enterText: { regexp, initial }}));
return this as unknown as Action<A & {[key in N]: string}>;
}
/**
* Add a numerical choice for this action. This will be presented with a
* number picker.
*
* @param name - The name of this choice. This name will be used in all
* functions that accept the player's choices
*
* @param {Object} options
*
* @param options.prompt - Prompt displayed to the user for entering this
* number.
*
* @param options.min - Minimum allowed. Default 1.
*
* @param options.max - Maximum allowed. Default Infinity
*
* @param options.initial - Initial value to display in the picker
*
* @param options.skipIf - One of 'always', 'never' or 'only-one' or a
* function returning a boolean. (Default 'only-one').
*
* <ul>
* <li>only-one: If there is only valid choice in the choices given, the game
* will skip this choice, prompting the player for subsequent choices, if any,
* or completing the action otherwise.
* <li>always: Rather than present this choice directly, the player will be
* prompted with choices from the *next choice* in the action for each
* possible choice here, essentially expanding the choices ahead of time to
* save the player a step. This option only has relevance if there are
* subsequent choices in the action.
* <li>never: Always present this choice, even if the choice is forced
* <li>function: A function that accepts all player choices up to this point
* and returns a boolean. If returning true, this choice will be skipped.
* This form is useful in the rare situations where the choice at the time may
* be meaningless, e.g. selecting from a set of identical tokens. In this case
* the game will make the choice for the player using the first viable option.
* </ul>
*
* @param options.validate - A function that takes an object of key-value
* pairs for all player choices and returns a boolean. If false, the game will
* not allow the player to submit this choice. If a string is returned, this
* will display as the reason for disallowing these selections.
*
* @param options.confirm - A confirmation message that the player will always
* see before commiting this choice. This can be useful to present additional
* information about the consequences of this choice, or simply to force the
* player to hit a button with a clear message. This can be a simple string,
* or a 2-celled array in the same form as {@link message} with a string
* message and a set of key-value pairs for string interpolation, optionally
* being a function that takes an object of key-value pairs for all player
* choices, and returns the interpolation object.
*
* @example
* player => action({
* prompt: 'Buy resources',
* }).chooseNumber(
* 'amount', {
* min: 5,
* max: 10 // select from 5 - 10
* }).do(
* ({ amount }) => player.resource += amount
* );
* @category Choices
*/
chooseNumber<N extends string>(name: N, options: {
min?: number | ((args: A) => number),
max?: number | ((args: A) => number),
prompt?: string | ((args: A) => string),
confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: number}) => Record<string, Argument>) | undefined]
validate?: ((args: A & {[key in N]: number}) => string | boolean | undefined),
initial?: number | ((args: A) => number),
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
} = {}): Action<A & {[key in N]: number}> {
const { min, max, prompt, confirm, validate, initial, skipIf } = options;
this._addSelection(new Selection(name, { prompt, confirm, validation: validate, skipIf, selectNumber: { min, max, initial } }));
return this as unknown as Action<A & {[key in N]: number}>;
}
/**
* Add a choice of game elements to this action. Users will click on the
* playing area to make their choice.
*
* @param {Object} options
* @param name - The name of this choice. This name will be used in all
* functions that accept the player's choices
* @param choices - Elements that may be chosen. This can either be an array
* of elements or a function returning an array, if the choices depend on
* previous choices. If using a function, it will accept arguments for each
* choice the player has made up to this point in the action.
*
* @param options.prompt - Prompt displayed to the user for this choice.
*
* @param options.number - If supplied, the choice is for a *set* of exactly
* `number` elements. For example, if the player is being asked to pass 3
* cards from their hand, the `choices` should be to the cards in their hand
* and the `number` to 3.
*
* @param options.min - If supplied, the choice is for a *set* of
* elements and the minimum required is `min`.
*
* @param options.max - If supplied, the choice is for a *set* of
* elements and the maximum allowed is `max`.
*
* @param options.initial - Optional list of game elements to be preselected
*
* @param options.skipIf - One of 'always', 'never' or 'only-one' or a
* function returning a boolean. (Default 'only-one').
*
* <ul>
* <li>only-one: If there is only valid choice in the choices given, the game
* will skip this choice, prompting the player for subsequent choices, if any,
* or completing the action otherwise.
* <li>always: Rather than present this choice directly, the player will be
* prompted with choices from the *next choice* in the action for each
* possible choice here, essentially expanding the choices ahead of time to
* save the player a step. This option only has relevance if there are
* subsequent choices in the action.
* <li>never: Always present this choice, even if the choice is forced
* <li>function: A function that accepts all player choices up to this point
* and returns a boolean. If returning true, this choice will be skipped.
* This form is useful in the rare situations where the choice at the time may
* be meaningless, e.g. selecting from a set of identical tokens. In this case
* the game will make the choice for the player using the first viable option.
* </ul>
*
* @param options.validate - A function that takes an object of key-value
* pairs for all player choices and returns a boolean. If false, the game will
* not allow the player to submit this choice. If a string is returned, this
* will display as the reason for disallowing these selections.
*
* @param options.confirm - A confirmation message that the player will always
* see before commiting this choice. This can be useful to present additional
* information about the consequences of this choice, or simply to force the
* player to hit a button with a clear message. This can be a simple string,
* or a 2-celled array in the same form as {@link message} with a string
* message and a set of key-value pairs for string interpolation, optionally
* being a function that takes an object of key-value pairs for all player
* choices up to this point, including this one, and returns the interpolation
* object.
*
* @example
* player => action({
* prompt: 'Mulligan',
* }).chooseOnBoard(
* 'cards', player.allMy(Card), {
* prompt: 'Mulligan 1-3 cards',
* // select 1-3 cards from hand
* min: 1,
* max: 3
* }).do(
* ({ cards }) => {
* // `cards` is an ElementCollection of the cards selected
* cards.putInto($.discard);
* $.deck.firstN(cards.length, Card).putInto(player.my('hand')!);
* }
* )
* @category Choices
*/
chooseOnBoard<T extends GameElement, N extends string>(name: N, choices: BoardQueryMulti<T, A>, options?: {
prompt?: string | ((args: A) => string);
confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T}) => Record<string, Argument>) | undefined]
validate?: ((args: A & {[key in N]: T}) => string | boolean | undefined);
initial?: never;
min?: never;
max?: never;
number?: never;
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
}): Action<A & {[key in N]: T}>;
chooseOnBoard<T extends GameElement, N extends string>(name: N, choices: BoardQueryMulti<T, A>, options?: {
prompt?: string | ((args: A) => string);
confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T[]}) => Record<string, Argument>) | undefined]
validate?: ((args: A & {[key in N]: T[]}) => string | boolean | undefined);
initial?: T[] | ((args: A) => T[]);
min?: number | ((args: A) => number);
max?: number | ((args: A) => number);
number?: number | ((args: A) => number);
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
}): Action<A & {[key in N]: T[]}>;
chooseOnBoard<T extends GameElement, N extends string>(name: N, choices: BoardQueryMulti<T, A>, options?: {
prompt?: string | ((args: A) => string);
confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T | T[]}) => Record<string, Argument>) | undefined]
validate?: ((args: A & {[key in N]: T | T[]}) => string | boolean | undefined);
initial?: T[] | ((args: A) => T[]);
min?: number | ((args: A) => number);
max?: number | ((args: A) => number);
number?: number | ((args: A) => number);
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
}): Action<A & {[key in N]: T | T[]}> {
const { prompt, confirm, validate, initial, min, max, number, skipIf } = options || {};
this._addSelection(new Selection(
name, { prompt, confirm, validation: validate, skipIf, selectOnBoard: { chooseFrom: choices, min, max, number, initial } }
));
if (min !== undefined || max !== undefined || number !== undefined) {
return this as unknown as Action<A & {[key in N]: T[]}>;
}
return this as unknown as Action<A & {[key in N]: T}>;
}
choose<N extends string, S extends 'number'>(
name: N,
type: S,
options?: Parameters<this['chooseNumber']>[1]
): Action<A & {[key in N]: number}>;
choose<N extends string, S extends 'text'>(
name: N,
type: S,
options?: Parameters<this['enterText']>[1]
): Action<A & {[key in N]: string}>;
choose<N extends string, S extends 'select', T extends SingleArgument>(
name: N,
type: S,
choices: T[] | Record<string, T> | ((args: A) => T[] | Record<string, T>),
options?: Parameters<this['chooseFrom']>[2]
): Action<A & {[key in N]: T}>;
choose<N extends string, S extends 'board', T extends GameElement>(
name: N,
type: S,
choices: BoardQueryMulti<T, A>,
options?: Parameters<this['chooseOnBoard']>[2] & { min: never, max: never, number: never }
): Action<A & {[key in N]: T}>;
choose<N extends string, S extends 'board', T extends GameElement>(
name: N,
type: S,
choices: BoardQueryMulti<T, A>,
options?: Parameters<this['chooseOnBoard']>[2]
): Action<A & {[key in N]: T[]}>;
choose<N extends string, S extends 'select' | 'number' | 'text' | 'board'>(
name: N,
type: S,
choices?: any,
options?: Record<string, any>
): Action<A & {[key in N]: Argument}> {
if (type === 'number') return this.chooseNumber(name, choices as Parameters<this['chooseNumber']>[1]);
if (type === 'text') return this.enterText(name, choices as Parameters<this['enterText']>[1]);
if (type === 'select') return this.chooseFrom(name, choices as Parameters<this['chooseFrom']>[1], options as Parameters<this['chooseFrom']>[2]);
return this.chooseOnBoard(name, choices as Parameters<this['chooseOnBoard']>[1], options as Parameters<this['chooseOnBoard']>[2]);
}
/**
* Create a multi-selection choice. These selections will be presented all at
* once as a form. This is used for form-like choices that have a number of
* choices that are not board choices, i.e. chooseFrom, chooseNumber and
* enterText
*
* @param choices - An object containing the selections. This is a set of
* key-value pairs where each key is the name of the selection and each value
* is an array of options where the first array element is a string indicating
* the type of choice ('number', 'select', 'text') and subsequent elements
* contain the options for the appropriate choice function (`chooseNumber`,
* `chooseFrom` or `enterText`).
*
* @param options.validate - A function that takes an object of key-value
* pairs for all player choices and returns a boolean. If false, the game will
* not allow the player to submit these choices. If a string is returned, this
* will display as the reason for disallowing these selections.
*
* @param options.confirm - A confirmation message that the player will always
* see before commiting this choice. This can be useful to present additional
* information about the consequences of this choice, or simply to force the
* player to hit a button with a clear message. This can be a simple string,
* or a 2-celled array in the same form as {@link message} with a string
* message and a set of key-value pairs for string interpolation, optionally
* being a function that takes an object of key-value pairs for all player
* choices, and returns the interpolation object.
*
* @example
* action({
* prompt: 'purchase'
* }).chooseGroup({
* lumber: ['number', { min: 2 }],
* steel: ['number', { min: 2 }]
* }, {
* // may not purchase more than 10 total resources
* validate: ({ lumber, steel }) => lumber + steel <= 10
* });
* @category Choices
*/
chooseGroup<R extends Group>(
choices: R,
options?: {
validate?: (args: ExpandGroup<A, R>) => string | boolean | undefined,
confirm?: string | [string, Record<string, Argument> | ((args: ExpandGroup<A, R>) => Record<string, Argument>) | undefined]
}
): Action<ExpandGroup<A, R>> {
for (const [name, choice] of Object.entries(choices)) {
if (choice[0] === 'number') this.chooseNumber(name, choice[1]);
if (choice[0] === 'select') this.chooseFrom(name, choice[1], choice[2]);
if (choice[0] === 'text') this.enterText(name, choice[1]);
}
if (options?.confirm) this.selections[this.selections.length - 1].confirm = typeof options.confirm === 'string' ? [options.confirm, undefined] : options.confirm;
if (options?.validate) this.selections[this.selections.length - 1].validation = options.validate
for (let i = 1; i < Object.values(choices).length; i++) {
this.selections[this.selections.length - 1 - i].clientContext = {combineWith: this.selections.slice(-i).map(s => s.name)};
}
return this as unknown as Action<ExpandGroup<A, R>>;
}
/**
* Add a confirmtation step to this action. This can be useful if you want to
* present additional information to the player related to the consequences of
* their choice, like a cost incurred. Or this can simply be used to force the
* user to click an additional button on a particular important choice.
*
* @param prompt - Button text for the confirmation step. This can be a
* function returning the text which accepts each choice the player has made
* up till now as an argument.
*
* @example
* action({
* prompt: "Buy resources",
* }).chooseNumber({
* 'amount', {
* prompt: "Amount",
* max: Math.floor(player.coins / 5)
* }).confirm(
* ({ amount }) => `Spend ${amount * 5} coins`
* }).do(({ amount }) => {
* player.resource += amount;
* player.coins -= amount * 5;
* });
*/
confirm(prompt: string | ((args: A) => string)): Action<A> {
this._addSelection(new Selection('__confirm__', {
prompt,
confirm: typeof prompt === 'string' ? prompt : ['{{__message__}}', (args: A) => ({__message__: prompt(args)})],
value: true
}));
return this;
}
/**
* Perform a move with the selected element(s) into a selected
* Space/Piece. This is almost the equivalent of calling Action#do and adding
* a putInto command, except that the game will also permit the UI to allow a
* mouse drag for the move.
*
* @param piece - A {@link Piece} to move or the name of the piece selection in this action
* @param into - A {@link GameElement} to move into or the name of the
* destination selection in this action.
*
* player => action({
* prompt: 'Discard a card from hand'
* }).chooseOnBoard(
* 'card', player.my(Card)
* ).move(
* 'card', $.discard
* )
* @category Behaviour
*/
move(piece: keyof A | Piece<Game>, into: keyof A | GameElement) {
this.do((args: A) => {
const selectedPiece = piece instanceof Piece ? piece : args[piece] as Piece<Game> | Piece<Game>[];
const selectedInto = into instanceof GameElement ? into : args[into] as GameElement;
if (selectedPiece instanceof Array) {
new ElementCollection(...selectedPiece).putInto(selectedInto);
} else {
selectedPiece.putInto(selectedInto);
}
});
const pieceSelection = typeof piece === 'string' ? this.selections.find(s => s.name === piece) : undefined;
const intoSelection = typeof into === 'string' ? this.selections.find(s => s.name === into) : undefined;
if (intoSelection && intoSelection.type !== 'board') throw Error(`Invalid move: "${into as string}" must be the name of a previous chooseOnBoard`);
if (pieceSelection && pieceSelection.type !== 'board') throw Error(`Invalid move: "${piece as string}" must be the name of a previous chooseOnBoard`);
if (intoSelection?.isMulti()) throw Error("Invalid move: May not move into a multiple choice selection");
if (pieceSelection && !pieceSelection.isMulti()) pieceSelection.clientContext = { dragInto: intoSelection ?? into };
if (intoSelection) intoSelection.clientContext = { dragFrom: pieceSelection ?? piece };
return this;
}
/**
* Swap the location of two Pieces. Each of the two pieces can either be the
* name of a previous `chooseOnBoard`, or a simply provide a piece if it is
* not a player choice. The game will also allow a mouse drag for the swap.
*
* @param piece1 - A {@link Piece} to swap or the name of the piece selection in this action
* @param piece2 - A {@link Piece} to swap or the name of the piece selection in this action
*
* player => action({
* prompt: 'Exchange a card from hand with the top of the deck'
* }).chooseOnBoard(
* 'card', player.my(Card)
* ).swap(
* 'card', $.deck.first(Card)!
* )
* @category Behaviour
*/
swap(piece1: keyof A | Piece<Game>, piece2: keyof A | Piece<Game>) {
this.do((args: A) => {
const p1 = piece1 instanceof Piece ? piece1 : args[piece1] as Piece<Game>;
const p2 = piece2 instanceof Piece ? piece2 : args[piece2] as Piece<Game>;
const parent1 = p1._t.parent!;
const parent2 = p2._t.parent!;
const pos1 = p1.position();
const pos2 = p2.position();
const row1 = p1.row;
const column1 = p1.column;
const row2 = p2.row;
const column2 = p2.column;
p1.putInto(parent2, { position: pos2, row: row2, column: column2 });
p2.putInto(parent1, { position: pos1, row: row1, column: column1 });
});
const piece1Selection = typeof piece1 === 'string' ? this.selections.find(s => s.name === piece1) : undefined;
const piece2Selection = typeof piece2 === 'string' ? this.selections.find(s => s.name === piece2) : undefined;
if (piece1Selection && piece1Selection.type !== 'board') throw Error(`Invalid swap: "${piece1 as string}" must be the name of a previous chooseOnBoard`);
if (piece2Selection && piece2Selection.type !== 'board') throw Error(`Invalid swap: "${piece2 as string}" must be the name of a previous chooseOnBoard`);
if (piece1Selection) piece1Selection.clientContext = { dragInto: piece2Selection ?? piece2 };
return this;
}
/**
* Have the player select one of the Pieces in the collection and select a new
* position within the collection while keeping everything else in the same
* order. The game will also permit a mouse drag for the reorder.
*
* @param collection - A collection of {@link Piece}s to reorder
*
* @param options.prompt - Prompt displayed to the user for this reorder
* choice.
*
* player => action({
* prompt: 'Reorder cards in hand'
* }).reorder(
* player.my(Card)
* )
* @category Behaviour
*/
reorder(collection: Piece<Game>[], options?: {
prompt?: string | ((args: A) => string),
}) {
const { prompt } = options || {};
if (this.selections.some(s => s.name === '__reorder_from__')) throw Error(`Invalid reorder: only one reorder allowed`);
if (collection.some(c => c._t.parent !== collection[0]._t.parent)) throw Error(`Invalid reorder: all elements must belong to the same parent`);
const pieceSelection = this._addSelection(new Selection(
'__reorder_from__', { prompt, selectOnBoard: { chooseFrom: collection }}
));
const intoSelection = this._addSelection(new Selection(
'__reorder_to__', { prompt, selectOnBoard: { chooseFrom: ({ __reorder_from__ }) => collection.filter(e => e !== __reorder_from__) }}
));
pieceSelection.clientContext = { dragInto: intoSelection };
intoSelection.clientContext = { dragFrom: pieceSelection };
this.do((args: A) => {
const reorderFrom = args['__reorder_from__'] as Piece<Game>;
const reorderTo = args['__reorder_to__'] as Piece<Game>;
let position = reorderTo.position();
reorderFrom.putInto(reorderFrom._t.parent!, { position });
});
return this as unknown as Action<A & {__reorder_to__: Piece<Game>, __reorder_from__: number}>;
}
/**
* Add a placement selection to this action. This will be presented as a piece
* that players can move into the desired location, snapping to the grid of
* the destination as the player moves.
*
* @param piece - The name of the piece selection in this action from a
* `chooseOnBoard` prior to this
* @param into - A {@link GameElement} to move into
*
* @param options.prompt - Prompt displayed to the user for this placement
* choice.
*
* @param options.validate - A function that takes an object of key-value
* pairs for all player choices and returns a boolean. The position selected
* during the piece placement can be checked by reading the 'column', 'row'
* and `rotation` properties of the `piece` as provided in the first
* argument. If false, the game will not allow the player to submit these
* choices. If a string is returned, this will display as the reason for
* disallowing these selections.
*
* @param options.confirm - A confirmation message that the player will always
* see before commiting this choice. This can be useful to present additional
* information about the consequences of this choice, or simply to force the
* player to hit a button with a clear message. This can be a simple string,
* or a 2-celled array in the same form as {@link message} with a string
* message and a set of key-value pairs for string interpolation, optionally
* being a function that takes an object of key-value pairs for all player
* choices, and returns the interpolation object.
*
* @param options.rotationChoices = An array of valid rotations in
* degrees. These choices must be normalized to numbers between 0-359°. If
* supplied the piece will be given rotation handles for the player to set the
* rotation and position together.
*
* player => action({
* prompt: 'Place your tile'
* }).chooseOnBoard(
* 'tile', player.my(Tile)
* ).placePiece(
* 'tile', $.map, {
* confirm: ({ tile }) => [
* 'Place tile into row {{row}} and column {{column}}?',
* tile
* ]
* })
* @category Choices
*/
placePiece<T extends keyof A & string>(piece: T, into: PieceGrid<Game>, options?: {
prompt?: string | ((args: A) => string),
confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in T]: { column: number, row: number }}) => Record<string, Argument>) | undefined]
validate?: ((args: A & {[key in T]: { column: number, row: number }}) => string | boolean | undefined),
rotationChoices?: number[],
}) {
const { prompt, confirm, validate } = options || {};
if (this.selections.some(s => s.name === '__placement__')) throw Error(`Invalid placePiece: only one placePiece allowed`);
const pieceSelection = this.selections.find(s => s.name === piece);
if (!pieceSelection) throw (`No selection named ${String(piece)} for placePiece`)
const positionSelection = this._addSelection(new Selection(
'__placement__', { prompt, confirm, validation: validate, selectPlaceOnBoard: {piece, rotationChoices: options?.rotationChoices} }
));
positionSelection.clientContext = { placement: { piece, into } };
this.do((args: A & {__placement__: number[]}) => {
const selectedPiece = args[piece];
if (!(selectedPiece instanceof Piece)) throw Error(`Cannot place piece selection named ${String(piece)}. Returned ${selectedPiece} instead of a piece`);
selectedPiece.putInto(into, { column: args['__placement__'][0], row: args['__placement__'][1] });
selectedPiece.rotation = args['__placement__'][2];
});
if (pieceSelection) pieceSelection.clientContext = { dragInto: into };
return this as unknown as Action<A & {__placement__: number[]} & {[key in T]: { column: number, row: number }}>;
}
}
================================================
FILE: src/action/index.ts
================================================
export {default as Action} from './action.js';
export {default as Selection} from './selection.js';
export type { Argument, ActionStub } from './action.js';
export {
serializeArg,
deserializeArg
} from './utils.js';
================================================
FILE: src/action/selection.ts
================================================
import { range } from '../utils.js';
import { combinations } from './utils.js';
import GameElement from '../board/element.js';
import Player from '../player/player.js';
import type { SingleArgument, Argument } from './action.js';
export type BoardQuerySingle<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = T | undefined | ((args: A) => T | undefined)
export type BoardQueryMulti<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = T[] | ((args: A) => T[])
export type BoardQuery<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = BoardQuerySingle<T, A> | BoardQueryMulti<T, A>
export type BoardSelection<T extends GameElement, A extends Record<string, Argument> = Record<string, Argument>> = {
chooseFrom: BoardQueryMulti<T, A>;
min?: number | ((args: A) => number);
max?: number | ((args: A) => number);
number?: number | ((args: A) => number);
initial?: T[] | ((args: A) => T[]);
}
export type ChoiceSelection<A extends Record<string, Argument> = Record<string, Argument>> = {
choices: SingleArgument[] | { label: string, choice: SingleArgument }[] | ((args: A) => SingleArgument[] | { label: string, choice: SingleArgument }[]);
initial?: Argument | ((args: A) => Argument);
// min?: number | ((args: A) => number);
// max?: number | ((args: A) => number);
// number?: number | ((args: A) => number);
}
export type NumberSelection<A extends Record<string, Argument> = Record<string, Argument>> = {
min?: number | ((args: A) => number);
max?: number | ((args: A) => number);
initial?: number | ((args: A) => number);
}
export type TextSelection<A extends Record<string, Argument> = Record<string, Argument>> = {
regexp?: RegExp;
initial?: string | ((args: A) => string);
}
export type ButtonSelection = Argument;
export type SelectionDefinition<A extends Record<string, Argument> = Record<string, Argument>> = {
prompt?: string | ((args: A) => string);
confirm?: string | [string, Record<string, Argument> | ((args: A) => Record<string, Argument>) | undefined]
validation?: ((args: A) => string | boolean | undefined);
clientContext?: Record<any, any>; // additional meta info that describes the context for this selection
} & ({
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
selectOnBoard: BoardSelection<GameElement>;
selectPlaceOnBoard?: never;
selectFromChoices?: never;
selectNumber?: never;
enterText?: never;
value?: never;
} | {
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
selectOnBoard?: never;
selectPlaceOnBoard?: never;
selectFromChoices: ChoiceSelection;
selectNumber?: never;
enterText?: never;
value?: never;
} | {
skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean);
selectOnBoard?: never;
selectPlaceOnBoard?: never;
selectFromChoices?: never;
selectNumber: NumberSelection;
enterText?: never;
value?: never;
} | {
selectOnBoard?: never;
selectPlaceOnBoard?: never;
selectFromChoices?: never;
selectNumber?: never;
enterText: TextSelection;
value?: never;
} | {
selectOnBoard?: never;
selectPlaceOnBoard?: never;
selectFromChoices?: never;
selectNumber?: never;
enterText?: never;
value: ButtonSelection;
} | {
selectOnBoard?: never;
selectPlaceOnBoard: {piece: string, rotationChoices?: number[]};
selectFromChoices?: never;
selectNumber?: never;
enterText?: never;
value?: never;
});
// any lambdas have been resolved to actual values
export type ResolvedSelection = Omit<Selection, 'prompt' | 'min' | 'max' | 'initial' | 'skipIf'> & {
prompt?: string;
resolvedChoices?: { label?: string, choice: SingleArgument, error?: string }[]; // selection.choices or selection.boardChoices resolve to this array
min?: number;
max?: number;
initial?: Argument;
skipIf?: 'never' | 'always' | 'only-one' | boolean;
}
/**
* Selection objects represent player choices. They either specify the options
* or provide enough information for the client to contextually show options to
* players at runtime
* @internal
*/
export default class Selection {
type: 'board' | 'choices' | 'text' | 'number' | 'button' | 'place';
name: string;
prompt?: string | ((args: Record<string, Argument>) => string);
confirm?: [string, Record<string, Argument> | ((args: Record<string, Argument>) => Record<string, Argument>) | undefined]
validation?: ((args: Record<string, Argument>) => string | boolean | undefined);
clientContext: Record<any, any> = {}; // additional meta info that describes the context for this selection
skipIf?: 'never' | 'always' | 'only-one' | ((args: Record<string, Argument>) => boolean);
choices?: SingleArgument[] | { label: string, choice: SingleArgument }[] | ((args: Record<string, Argument>) => SingleArgument[] | { label: string, choice: SingleArgument }[]);
boardChoices?: BoardQueryMulti<GameElement>
min?: number | ((args: Record<string, Argument>) => number);
max?: number | ((args: Record<string, Argument>) => number);
initial?: Argument | ((args: Record<string, Argument>) => Argument);
regexp?: RegExp;
placePiece?: string;
rotationChoices?: number[];
value?: Argument;
constructor(name: string, s: SelectionDefinition | Selection) {
this.name = name;
if (s instanceof Selection) {
Object.assign(this, s);
} else {
if (s.selectFromChoices) {
this.type = 'choices';
this.choices = s.selectFromChoices.choices;
//this.min = s.selectFromChoices.min;
//this.max = s.selectFromChoices.max;
this.initial = s.selectFromChoices.initial;
} else if (s.selectOnBoard) {
this.type = 'board';
this.boardChoices = s.selectOnBoard.chooseFrom;
if (s.selectOnBoard.number !== undefined) {
this.min = s.selectOnBoard.number;
this.max = s.selectOnBoard.number;
}
this.min ??= s.selectOnBoard.min;
this.max ??= s.selectOnBoard.max;
this.initial ??= s.selectOnBoard.initial;
} else if (s.selectNumber) {
this.type = 'number';
this.min = s.selectNumber.min;
this.max = s.selectNumber.max;
this.initial = s.selectNumber.initial ?? s.selectNumber.min ?? 1;
} else if (s.enterText) {
this.type = 'text';
this.regexp = s.enterText.regexp;
this.initial = s.enterText.initial;
} else if (s.selectPlaceOnBoard) {
this.type = 'place';
this.placePiece = s.selectPlaceOnBoard.piece;
this.rotationChoices = s.selectPlaceOnBoard.rotationChoices;
} else {
this.type = 'button';
this.value = s.value;
this.skipIf ??= 'only-one';
}
}
this.prompt = s.prompt;
this.confirm = typeof s.confirm === 'string' ? [s.confirm, undefined] : s.confirm;
this.validation = s.validation;
this.skipIf = ('skipIf' in s && s.skipIf) || 'only-one';
this.clientContext = s.clientContext ?? {};
}
/**
* check specific selection with a given arg. evaluates within the context of
* previous args, so any selection elements that have previous-arg-function
* forms are here evaluated with the previous args. returns new selection and
* error if any
*/
error(args: Record<string, Argument>): string | undefined {
const arg = args[this.name];
const s = this.resolve(args);
if (s.validation) {
const error = s.validation(args);
if (error !== undefined && error !== true) return error || 'Invalid selection';
}
if (s.type === 'choices' && s.resolvedChoices) {
if (arg instanceof Array) return "multi-choice stil unsupported"; // TODO
return s.resolvedChoices.find(c => c.choice === arg) ? undefined : "Not a valid choice";
}
if (s.type === 'board' && s.resolvedChoices) {
const results = s.resolvedChoices.map(c => c.choice);
if (!results) console.warn('Attempted to validate an impossible move', s);
if (this.isMulti()) {
if (!(arg instanceof Array)) throw Error("Required multi select");
if (results && arg.some(a => !results.includes(a as GameElement))) return "Selected elements are not valid";
if (s.min !== undefined && arg.length < s.min) return "Below minimum";
if (s.max !== undefined && arg.length > s.max) return "Above maximum";
} else {
return (results && results.includes(arg as GameElement)) ? undefined : "Selected element is not valid";
}
}
if (s.type === 'text') {
return (typeof arg === 'string' && (!s.regexp || arg.match(s.regexp))) ? undefined : "Invalid text entered";
}
if (s.type === 'number') {
if (typeof arg !== 'number') return "Not a number";
if (s.min !== undefined && arg < s.min) return "Below minimum";
if (s.max !== undefined && arg > s.max) return "Above maximum";
return undefined;
}
return undefined;
}
// All possible valid Arguments to this selection. Have to make some assumptions here to tree shake possible moves
// Argument to handle array of combo selections arrays
options(this: ResolvedSelection): {choice: Argument, error?: string, label?: string}[] {
if (this.isUnbounded()) return [];
if (this.type === 'number') return range(this.min ?? 1, this.max!).map(choice => ({ choice }));
if (this.isMulti() && this.resolvedChoices) {
return combinations(this.resolvedChoices.map(c => c.choice), this.min ?? 1, this.max ?? Infinity).map(choice => ({ choice }));
}
if (this.resolvedChoices) return this.resolvedChoices;
return [];
}
isUnbounded(this: ResolvedSelection): boolean {
if (this.type === 'number') return this.max === undefined || this.max - (this.min ?? 1) > 100;
return this.type === 'text' || this.type === 'button' || this.type === 'place';
}
isResolved(): this is ResolvedSelection {
return typeof this.prompt !== 'function' &&
typeof this.min !== 'function' &&
typeof this.max !== 'function' &&
typeof this.initial !== 'function' &&
typeof this.skipIf !== 'function' &&
typeof this.choices !== 'function' &&
typeof this.boardChoices !== 'function' &&
(!this.choices && !this.boardChoices || 'resolvedChoices' in this);
}
isMulti() {
return (this.type === 'choices' || this.type === 'board') && (this.min !== undefined || this.max !== undefined);
}
isBoardChoice() {
return this.type === 'board' || this.type ==='place';
}
resolve(args: Record<string, Argument>): ResolvedSelection {
const resolved = new Selection(this.name, this) as ResolvedSelection;
if (this.choices) {
const choices = typeof this.choices === 'function' ? this.choices(args) : this.choices;
if (choices instanceof Array && typeof choices[0] === 'object' && !(choices[0] instanceof GameElement) && !(choices[0] instanceof Player)) {
resolved.resolvedChoices = choices as { label: string, choice: SingleArgument }[];
} else {
resolved.resolvedChoices = (choices as SingleArgument[]).map(choice => ({ choice }));
}
}
if (typeof this.prompt === 'function') resolved.prompt = this.prompt(args);
if (typeof this.min === 'function') resolved.min = this.min(args)
if (typeof this.max === 'function') resolved.max = this.max(args)
if (typeof this.initial === 'function') resolved.initial = this.initial(args)
if (typeof this.skipIf === 'function') resolved.skipIf = this.skipIf(args)
if (this.boardChoices) {
const choices = typeof this.boardChoices === 'function' ? this.boardChoices(args) : this.boardChoices;
resolved.resolvedChoices = choices.map(choice => ({ choice }));
}
return resolved;
}
isPossible(this: ResolvedSelection): boolean {
if (this.type === 'choices' && this.resolvedChoices) return this.resolvedChoices.length > 0
const isInBounds = this.max !== undefined ? (this.min ?? 1) <= this.max : true;
if (this.type === 'board' && this.resolvedChoices) return isInBounds && this.resolvedChoices.length >= (this.min ?? 1);
if (this.type === 'number') return isInBounds;
return true;
}
isForced(this: ResolvedSelection): Argument | undefined {
if (this.skipIf === 'never') return;
if (this.type === 'button') {
return this.value;
} else if (this.type === 'board') {
if (this.resolvedChoices && (this.skipIf === true || this.resolvedChoices?.length === 1) && !this.isMulti()) {
return this.resolvedChoices[0].choice;
} else if (this.resolvedChoices && this.isMulti() && (this.skipIf === true || (this.resolvedChoices.length === (this.min ?? 1)) || this.max === 0)) {
return this.resolvedChoices.slice(0, this.min).map(c => c.choice);
}
} else if (this.type === 'number' && this.min !== undefined && this.min === this.max) {
return this.min;
} else if (this.type === 'choices' && this.resolvedChoices) {
if (this.resolvedChoices.length === 1 || this.skipIf === true) return this.resolvedChoices[0].choice
}
}
toString(): string {
if (!this.isResolved()) return `unresolved selection ${this.type}`;
return `${this.type === 'board' ? `click ${this.resolvedChoices![0]?.choice.constructor.name || 'board element'}` : `pick ${this.type}`}${(this.choices || this.boardChoices) ? ` (${(this.choices || this.boardChoices)!.length} choices)` : ''}`;
}
}
================================================
FILE: src/action/utils.ts
================================================
import type { Argument, SingleArgument } from './action.js';
import type { Player } from '../player/index.js';
import type { BaseGame } from '../board/game.js';
import type GameElement from '../board/element.js';
export type SerializedSingleArg = string | number | boolean;
export type SerializedArg = SerializedSingleArg | SerializedSingleArg[];
export type Serializable = SingleArgument | null | undefined | Serializable[] | { [key: string]: Serializable };
export const serialize = (arg: Serializable, forPlayer=true, name?: string): any => {
if (arg === undefined) return undefined;
if (arg === null) return null;
if (arg instanceof Array) return arg.map(a => serialize(a, forPlayer));
if (typeof arg === 'object' && 'constructor' in arg && ('isPlayer' in arg.constructor || 'isGameElement' in arg.constructor)) {
return serializeSingleArg(arg as GameElement | Player, forPlayer);
}
if (typeof arg === 'object') return serializeObject(arg, forPlayer);
if (typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'boolean') return serializeSingleArg(arg, forPlayer);
throw Error(`Unable to serialize the property ${name ? '"' + name + '": ' : ''} ${arg}. Only primitives, Player's, GameElement's or arrays/objects containing such can be used.`);
}
export const serializeArg = (arg: Argument, forPlayer=true): SerializedArg => {
if (arg instanceof Array) return arg.map(a => serializeSingleArg(a, forPlayer));
return serializeSingleArg(arg, forPlayer);
}
export const serializeSingleArg = (arg: SingleArgument, forPlayer=true): SerializedSingleArg => {
if (typeof arg === 'object' && 'constructor' in arg) {
if ('isPlayer' in arg.constructor) return `$p[${(arg as Player).position}]`;
if ('isGameElement' in arg.constructor) return forPlayer ? `$el[${(arg as GameElement).branch()}]` : `$eid[${(arg as GameElement)._t.id}]`;
}
return arg as SerializedSingleArg;
}
export const serializeObject = (obj: Record<string, any>, forPlayer=true) => {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, serialize(v, forPlayer, k)]));
}
export const escapeArgument = (arg: Argument): string => {
if (arg instanceof Array) {
const escapees = arg.map(escapeArgument);
return escapees.slice(0, -1).join(', ') + (escapees.length > 1 ? ' and ' : '') + (escapees[escapees.length - 1] || '');
}
if (typeof arg === 'object') return `[[${serializeSingleArg(arg)}|${arg.toString()}]]`;
return String(arg);
}
export const deserializeArg = (arg: SerializedArg, game: BaseGame): Argument => {
if (arg instanceof Array) return arg.map(a => deserializeSingleArg(a, game)) as GameElement[];
return deserializeSingleArg(arg, game);
}
export const deserializeSingleArg = (arg: SerializedSingleArg, game: BaseGame): SingleArgument => {
if (typeof arg === 'number' || typeof arg === 'boolean') return arg;
let deser: SingleArgument | undefined;
if (arg.slice(0, 3) === '$p[') {
deser = game.players.atPosition(parseInt(arg.slice(3, -1)));
} else if (arg.slice(0, 4) === '$el[') {
deser = game.atBranch(arg.slice(4, -1));
} else if (arg.slice(0, 5) === '$eid[') {
deser = game.atID(parseInt(arg.slice(5, -1)));
} else {
return arg;
}
if (!deser) throw Error(`Unable to find arg: ${arg}`);
return deser;
}
export const deserializeObject = (obj: Record<string, any>, game: BaseGame) => {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, deserialize(v, game)]));
}
export const deserialize = (arg: any, game: BaseGame): Serializable => {
if (arg === undefined) return undefined;
if (arg === null) return null;
if (arg instanceof Array) return arg.map(a => deserialize(a, game));
if (typeof arg === 'object') return deserializeObject(arg, game);
if (typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'boolean') return deserializeSingleArg(arg, game);
throw Error(`unable to deserialize ${arg}`);
}
export const combinations = <T>(set: T[], min: number, max: number): T[][] => {
const combos = [] as T[][];
const poss = (curr: T[], i: number) => {
if (set.length - i < min - curr.length) return;
if (curr.length >= min) combos.push(curr);
if (curr.length < max) {
for (let j = i; j !== set.length; j++) {
poss(curr.concat([set[j]]), j + 1);
}
}
}
poss([], 0);
return combos;
}
================================================
FILE: src/board/adjacency-space.ts
================================================
import GameElement from './element.js';
import type { BaseGame } from './game.js';
import type { ElementUI, LayoutAttributes } from './element.js';
import SingleLayout from './single-layout.js';
/**
* Abstract base class for all adjacency spaces
*/
export default abstract class AdjacencySpace<G extends BaseGame> extends SingleLayout<G> {
_ui: ElementUI<this> = {
layouts: [],
appearance: {},
getBaseLayout: () => ({
sticky: true,
alignment: 'center',
direction: 'square'
})
};
isAdjacent(_el1: GameElement, _el2: GameElement): boolean {
throw Error("Abstract AdjacencySpace has no implementation");
}
_positionOf(element: GameElement) {
const positionedParent = this._positionedParentOf(element);
return {column: positionedParent.column, row: positionedParent.row};
}
_positionedParentOf(element: GameElement): GameElement {
if (!element._t.parent) throw Error(`Element not found within adjacency space "${this.name}"`);
return element._t.parent === this ? element : this._positionedParentOf(element._t.parent);
}
/**
* Change the layout attributes for this space's layout.
* @category UI
*/
configureLayout(layoutConfiguration: Partial<LayoutAttributes>) {
const keys = Object.keys(layoutConfiguration);
if (keys.includes('scaling') || keys.includes('alignment')) {
throw Error("Layouts for grids cannot have alignment, scaling");
}
super.configureLayout(layoutConfiguration);
}
}
================================================
FILE: src/board/connected-space-map.ts
================================================
import AdjacencySpace from './adjacency-space.js';
import graphology, { DirectedGraph } from 'graphology';
import { dijkstra, edgePathFromNodePath } from 'graphology-shortest-path';
import Piece from './piece.js';
import GameElement from './element.js';
import { bfsFromNode } from 'graphology-traversal';
import ElementCollection from './element-collection.js';
import type { BaseGame } from './game.js';
import type Space from './space.js';
import type { ElementContext, ElementClass } from './element.js';
import type { ElementFinder } from './element-collection.js';
/**
* Space element that has child Space elements with an adjacency relationship
* with each other. Only Spaces can be directly added to an AdjacencySpace. No
* adjacency is automically created with this class. Instead, each space
* adjacency is created manually with {@link ConnectedSpaceMap#connect}. This is
* useful for arbitrary adjacencies. See also {@link SquareGrid}, {@link
* HexGrid} for standard adjacency layouts.
* @category Board
*/
export default class ConnectedSpaceMap<G extends BaseGame> extends AdjacencySpace<G> {
_graph: DirectedGraph;
static unserializableAttributes = [...AdjacencySpace.unserializableAttributes, '_graph'];
constructor(ctx: ElementContext) {
super(ctx);
this._graph = new graphology.DirectedGraph<{space: Space<G>}, {distance: number}>();
this.onEnter(Piece, () => { throw Error(`Only spaces can be added to space ${this.name}`); });
}
/**
* Returns whether 2 elements contained within this space have an adjacency to
* each other. The elements are considered adjacent if they are child Spaces
* that have been connected, or if the provided elements are placed inside
* such connected Spaces.
* @category Adjacency
*/
isAdjacent(el1: GameElement, el2: GameElement) {
const n1 = this._positionedParentOf(el1);
const n2 = this._positionedParentOf(el2);
return this._graph.areNeighbors(n1._t.ref, n2._t.ref);
}
/**
* Make these two Spaces adjacent. This creates a two-way adjacency
* relationship. If called twice with the Spaces reversed, different distances
* can be created for the adjacency in each direction.
* @category Adjacency
*
* @param space1 - {@link Space} to connect
* @param space2 - {@link Space} to connect
* @param distance - Add a custom distance to this connection for the purposes
* of distance-measuring. This distance is when measuring from space1 to space2.
*/
connect(space1: Space<G>, space2: Space<G>, distance: number = 1) {
this.connectOneWay(space1, space2, distance);
// assume bidirectional unless directly called in reverse
if (!this._graph.hasDirectedEdge(space2._t.ref, space1._t.ref)) this._graph.addDirectedEdge(space2._t.ref, space1._t.ref, {distance});
}
// @internal
connectOneWay(space1: Space<G>, space2: Space<G>, distance: number = 1) {
if (this !== space1._t.parent || this !== space2._t.parent) throw Error("Both spaces must be children of the space to be connected");
if (!this._graph.hasNode(space1._t.ref)) this._graph.addNode(space1._t.ref, {space: space1});
if (!this._graph.hasNode(space2._t.ref)) this._graph.addNode(space2._t.ref, {space: space2});
this._graph.mergeEdge(space1._t.ref, space2._t.ref, {distance});
}
/**
* Finds the shortest distance between two elements using this space. Elements
* must be connected Spaces of this element or be elements inside such spaces.
* @category Adjacency
*
* @param el1 - {@link GameElement} to measure distance from
* @param el2 - {@link GameElement} to measure distance to
* @returns shortest distance measured by the `distance` values added to each
* connection in {@link connectTo}
*/
distanceBetween(el1: GameElement, el2: GameElement) {
const n1 = this._positionedParentOf(el1);
const n2 = this._positionedParentOf(el2);
return this._distanceBetweenNodes(String(n1._t.ref), String(n2._t.ref));
}
_distanceBetweenNodes(n1: string, n2: string): number {
try {
const path = dijkstra.bidirectional(this._graph, n1, n2, 'distance');
const edgePath = edgePathFromNodePath(this._graph, path);
return edgePath.reduce((distance, edge) => distance + this._graph.getEdgeAttribute(edge, 'distance'), 0);
} catch(e) {
return Infinity;
}
}
/**
* Finds all elements of the query type given that are adjacent to the
* provided element, searching recursively through the adjacent Spaces. Uses
* the same query parameters as {@link all}.
* @category Adjacency
*
* @param element - {@link GameElement} to measure distance from
* @param {class} className - Optionally provide a class as the first argument
* as a class filter. This will only match elements which are instances of the
* provided class
* @param finders - All other parameters are filters. See {@link
* ElementFinder} for more information.
*/
allAdjacentTo<F extends GameElement>(element: GameElement, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
allAdjacentTo(element: GameElement, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): ElementCollection;
allAdjacentTo(element: GameElement, className?: any, ...finders: ElementFinder[]) {
const source = this._positionedParentOf(element);
return this._t.children.filter(c => this.isAdjacent(source, c)).all(className, ...finders);
}
/**
* Finds all elements of the query type given that are within the provided
* distance from the provided element, searching recursively through the
* connected Spaces. This does *not* include the supplied element. Uses the
* same query parameters as {@link all}.
* @category Adjacency
*
* @param element - {@link GameElement} to measure distance from
* @param distance - Distance to measure using the adjacency distances
* @param {class} className - Optionally provide a class as the first argument
* as a class filter. This will only match elements which are instances of the
* provided class
* @param finders - All other parameters are filters. See {@link
* ElementFinder} for more information.
*/
allWithinDistanceOf<F extends GameElement>(element: GameElement, distance: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
allWithinDistanceOf(element: GameElement, distance: number, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): ElementCollection;
allWithinDistanceOf(element: GameElement, distance: number, className?: any, ...finders: ElementFinder[]) {
const source = String(this._positionedParentOf(element)._t.ref);
const nodes = new ElementCollection();
bfsFromNode(this._graph, source, target => {
const d = this._distanceBetweenNodes(source, target);
if (d > distance) return true;
nodes.push(this._graph.getNodeAttributes(target).space);
});
return nodes.all(className, (el: GameElement) => el !== element, ...finders);
}
/**
* Finds all elements of the query type that are connected to the provided
* element by any path, searching recursively through the connected
* spaces. This includes the supplied element. This is useful for determining
* the size of a contiguous connected area. Uses the same query parameters as
* {@link all}.
* @category Adjacency
*
* @param element - {@link GameElement} to measure distance from
* @param {class} className - Optionally provide a class as the first argument
* as a class filter. This will only match elements which are instances of the
* provided class
* @param finders - All other parameters are filters. See {@link
* ElementFinder} for more information.
*/
allConnectedTo<F extends GameElement>(element: GameElement, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
allConnectedTo(element: GameElement, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): ElementCollection;
allConnectedTo(element: GameElement, className?: any, ...finders: ElementFinder[]) {
const source = String(this._positionedParentOf(element)._t.ref);
const nodes = new ElementCollection();
bfsFromNode(this._graph, source, target => {
nodes.push(this._graph.getNodeAttributes(target).space);
});
return nodes.all(className, ...finders);
}
/**
* Finds the nearest element of the query type given to the provided element,
* searching recursively through the connected Spaces.
* @category Adjacency
*
* @param element - {@link GameElement} to measure distance from
* @param {class} className - Optionally provide a class as the first argument
* as a class filter. This will only match elements which are instances of the
* provided class
* @param finders - All other parameters are filters. See {@link
* ElementFinder} for more information.
*/
closestTo<F extends GameElement>(element: GameElement, className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
closestTo(element: GameElement, className?: ElementFinder<GameElement>, ...finders: ElementFinder<GameElement>[]): GameElement | undefined;
closestTo<F extends GameElement>(element: GameElement, className?: any, ...finders: ElementFinder[]): F | GameElement | undefined {
const source = this._positionedParentOf(element);
let collection: ElementCollection;
collection = this._t.children.all(className, (el: GameElement) => el !== element, ...finders);
return collection.sortBy(el => this.distanceBetween(source, el))[0];
}
}
================================================
FILE: src/board/element-collection.ts
================================================
import type {
ElementClass,
ElementUI,
ElementAttributes,
} from './element.js';
import type Piece from './piece.js';
import type Game from './game.js';
import type { GameElement } from './index.js'
/**
* Either the name of a property of the object that can be lexically sorted, or
* a function that will be called with the object to sort and must return a
* lexically sortable value.
* @category Board
*/
export type Sorter<T> = keyof T | ((e: T) => number | string)
import type { Player } from '../player/index.js';
import { BaseGame } from './game.js';
/**
* A query filter can be one of 3 different forms:
* - *string*: will match elements with this name
* - *function*: A function that accept an element as its argument and returns a
* boolean indicating whether it is a match, similar to `Array#filter`.
* - *object*: will match elements whose properties match the provided
* properties. For example, `deck.all(Card, {suit: 'H'})` would match all
* `Card` elements in `deck` with a `suit` property equal to `"H"`. There are
* some special property names allowed here:
* - *mine*: true/false whether this element belongs to the player in whose context the query is made
* - *empty* true/false whether this element is empty
* - *adjacent* true/false whether this element is adjacent by a connection to the
* element on which the query method was
* called. E.g. `france.other(Country, {adjacent: true})` will match
* `Country` elements that are connected to `france` by {@link
* Space#connectTo}
* - *withinDistance* Similar to adjacent but uses the provided number to
* determine if a connection is possible between elements whose cost is
* not greater than the provided value
* @category Board
*/
export type ElementFinder<T extends GameElement = GameElement> = (
((e: T) => boolean) |
(ElementAttributes<T> & {mine?: boolean, owner?: T['player'], empty?: boolean}) |
string
);
/**
* Operations that return groups of {@link GameElement}'s return
* this Array-like class.
* @noInheritDoc
* @category Board
*/
export default class ElementCollection<T extends GameElement = GameElement> extends Array<T> {
slice(...a: Parameters<Array<T>['slice']>):ElementCollection<T> {return super.slice(...a) as ElementCollection<T>}
filter(...a: Parameters<Array<T>['filter']>):ElementCollection<T> {return super.filter(...a) as ElementCollection<T>}
/**
* As {@link GameElement#all}, but finds all elements within this collection
* and its contained elements recursively.
* @category Queries
*
* @param {class} className - Optionally provide a class as the first argument
* as a class filter. This will only match elements which are instances of the
* provided class
*
* @param finders - All other parameters are filters. See {@link
* ElementFinder} for more information.
*
* @returns An {@link ElementCollection} of as many matching elements as can be
* found. The collection is typed to `ElementCollection<className>` if one was
* provided.
*/
all<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
all(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;
all(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder(undefined, {}, ...finders);
}
return this._finder(className, {}, ...finders);
}
_finder<F extends GameElement>(
className: ElementClass<F> | undefined,
options: {limit?: number, order?: 'asc' | 'desc', noRecursive?: boolean},
...finders: ElementFinder<F>[]
): ElementCollection<F> {
const coll = new ElementCollection<F>();
if (options.limit !== undefined && options.limit <= 0) return coll;
const fns: ((e: F) => boolean)[] = finders.map(finder => {
if (typeof finder === 'object') {
const attrs = finder;
return el => Object.entries(attrs).every(([k1, v1]) => (
(k1 === 'empty' ? el.isEmpty() : el[k1 as keyof typeof el]) === v1
))
}
if (typeof finder === 'string') {
const name = finder;
return el => el.name === name;
}
return finder;
})
const finderFn = (el: T, order: 'asc' | 'desc') => {
if ((!className || el instanceof className) && fns.every(fn => fn(el as unknown as F))) {
if (order === 'asc') {
coll.push(el as unknown as F);
} else {
coll.unshift(el as unknown as F);
}
}
if (!options.noRecursive) {
if (options.limit !== undefined) {
coll.push(...el._t.children._finder(className, {limit: options.limit - coll.length, order: options.order}, ...finders));
} else {
coll.push(...el._t.children._finder(className, {}, ...finders));
}
}
};
if (options.order === 'desc') {
for (let e = this.length - 1; e >= 0; e--) {
const el = this[e];
if (options.limit !== undefined && coll.length >= options.limit) break;
finderFn(el, 'desc');
}
} else {
for (const el of this) {
if (options.limit !== undefined && coll.length >= options.limit) break;
finderFn(el, 'asc');
}
}
return coll;
}
/**
* As {@link GameElement#first}, except finds the first element within this
* collection and its contained elements recursively that matches the
* arguments provided. See {@link GameElement#all} for parameter details.
* @category Queries
* @returns A matching element, if found
*/
first<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
first(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;
first(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement | undefined {
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder(undefined, {limit: 1}, ...finders)[0];
}
return this._finder(className, {limit: 1}, ...finders)[0];
}
/**
* As {@link GameElement#firstn}, except finds the first `n` elements within
* this collection and its contained elements recursively that match the
* arguments provided. See {@link all} for parameter details.
* @category Queries
* @param n - number of matches
*
* @returns An {@link ElementCollection} of as many matching elements as can be
* found, up to `n`. The collection is typed to `ElementCollection<className>`
* if one was provided.
*/
firstN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
firstN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;
firstN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {
if (typeof n !== 'number') throw Error('first argument must be number of matches');
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: n}, ...finders);
}
return this._finder(className, {limit: n}, ...finders);
}
/**
* As {@link GameElement#last}, expect finds the last element within this
* collection and its contained elements recursively that matches the
* arguments provided. See {@link all} for parameter details.
* @category Queries
* @returns A matching element, if found
*/
last<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
last(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;
last(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement | undefined {
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: 1, order: 'desc'}, ...finders)[0];
}
return this._finder(className, {limit: 1, order: 'desc'}, ...finders)[0];
}
/**
* As {@link GameElement#lastn}, expect finds the last n elements within this
* collection and its contained elements recursively that match the arguments
* provided. See {@link all} for parameter details.
* @category Queries
* @param n - number of matches
*
* @returns An {@link ElementCollection} of as many matching elements as can be
* found, up to `n`. The collection is typed to `ElementCollection<className>`
* if one was provided.
*/
lastN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
lastN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;
lastN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {
if (typeof n !== 'number') throw Error('first argument must be number of matches');
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: n, order: 'desc'}, ...finders);
}
return this._finder(className, {limit: n, order: 'desc'}, ...finders);
}
/**
* Alias for {@link first}
* @category Queries
*/
top<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
top(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;
top(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement | undefined {
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: 1}, ...finders)[0];
}
return this._finder(className, {limit: 1}, ...finders)[0];
}
/**
* Alias for {@link firstN}
* @category Queries
*/
topN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
topN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;
topN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {
if (typeof n !== 'number') throw Error('first argument must be number of matches');
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: n}, ...finders);
}
return this._finder(className, {limit: n}, ...finders);
}
/**
* Alias for {@link last}
* @category Queries
*/
bottom<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
bottom(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined;
bottom(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): GameElement<any> | undefined {
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: 1, order: 'desc'}, ...finders)[0];
}
return this._finder(className, {limit: 1, order: 'desc'}, ...finders)[0];
}
/**
* Alias for {@link lastN}
* @category Queries
*/
bottomN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
bottomN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<T>;
bottomN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection<any> {
if (typeof n !== 'number') throw Error('first argument must be number of matches');
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return this._finder<GameElement>(undefined, {limit: n, order: 'desc'}, ...finders);
}
return this._finder(className, {limit: n, order: 'desc'}, ...finders);
}
/**
* Show these elements to all players
* @category Visibility
*/
showToAll(this: ElementCollection<Piece<BaseGame>>) {
for (const el of this) {
delete(el._visible);
}
}
/**
* Show these elements only to the given player
* @category Visibility
*/
showOnlyTo(this: ElementCollection<Piece<BaseGame>>, player: Player | number) {
if (typeof player !== 'number') player = player.position;
for (const el of this) {
el._visible = {
default: false,
except: [player]
};
}
}
/**
* Show these elements to the given players without changing it's visibility to
* any other players.
* @category Visibility
*/
showTo(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] | number[]) {
if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position);
for (const el of this) {
if (el._visible === undefined) continue;
if (el._visible.default) {
if (!el._visible.except) continue;
el._visible.except = el._visible.except.filter(i => !(player as number[]).includes(i));
} else {
el._visible.except = Array.from(new Set([...(el._visible.except instanceof Array ? el._visible.except : []), ...(player as number[])]))
}
}
}
/**
* Hide this element from all players
* @category Visibility
*/
hideFromAll(this: ElementCollection<Piece<BaseGame>>) {
for (const el of this) {
el._visible = {default: false};
}
}
/**
* Hide these elements from the given players without changing it's visibility to
* any other players.
* @category Visibility
*/
hideFrom(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] | number[]) {
if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position);
for (const el of this) {
if (el._visible?.default === false && !el._visible.except) continue;
if (el._visible === undefined || el._visible.default === true) {
el._visible = {
default: true,
except: Array.from(new Set([...(el._visible?.except instanceof Array ? el._visible.except : []), ...(player as number[])]))
};
} else {
if (!el._visible.except) continue;
el._visible.except = el._visible.except.filter(i => !(player as number[]).includes(i));
}
}
}
/**
* Sorts this collection by some {@link Sorter}.
* @category Structure
*/
sortBy<E extends T>(key: Sorter<E> | Sorter<E>[], direction?: "asc" | "desc") {
const rank = (e: E, k: Sorter<E>) => typeof k === 'function' ? k(e) : e[k as keyof E]
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 as E, k);
const r2 = rank(b as E, k);
if (r1 > r2) return up;
if (r1 < r2) return down;
}
return 0;
});
}
/**
* Returns a copy of this collection sorted by some {@link Sorter}.
* @category Structure
*/
sortedBy(key: Sorter<T> | (Sorter<T>)[], direction: "asc" | "desc" = "asc") {
return (this.slice(0, this.length) as this).sortBy(key, direction);
}
/**
* Returns the sum of all elements in this collection measured by a provided key
* @category Queries
*
* @example
* deck.create(Card, '2', { pips: 2 });
* deck.create(Card, '3', { pips: 3 });
* deck.all(Card).sum('pips'); // => 5
*/
sum(key: ((e: T) => number) | (keyof {[K in keyof T]: T[K] extends number ? never: K})) {
return this.reduce((sum, n) => sum + (typeof key === 'function' ? key(n) : n[key] as unknown as number), 0);
}
/**
* Returns the element in this collection with the highest value of the
* provided key(s).
* @category Queries
*
* @param attributes - any number of {@link Sorter | Sorter's} used for
* comparing. If multiple are provided, subsequent ones are used to break ties
* on earlier ones.
*
* @example
* army.create(Soldier, 'a', { strength: 2, initiative: 3 });
* army.create(Soldier, 'b', { strength: 3, initiative: 1 });
* army.create(Soldier, 'c', { strength: 3, initiative: 2 });
* army.all(Solider).withHighest('strength', 'initiative'); // => Soldier 'c'
*/
withHighest(...attributes: Sorter<T>[]): T | undefined {
return this.sortedBy(attributes, 'desc')[0];
}
/**
* Returns the element in this collection with the lowest value of the
* provided key(s).
* @category Queries
*
* @param attributes - any number of {@link Sorter | Sorter's} used for
* comparing. If multiple are provided, subsequent ones are used to break ties
* on earlier ones.
*
* @example
* army.create(Soldier, 'a', { strength: 2, initiative: 3 });
* army.create(Soldier, 'b', { strength: 3, initiative: 1 });
* army.create(Soldier, 'c', { strength: 2, initiative: 2 });
* army.all(Solider).withLowest('strength', 'initiative'); // => Soldier 'c'
*/
withLowest(...attributes: Sorter<T>[]): T | undefined {
return this.sortedBy(attributes, 'asc')[0];
}
/**
* Returns the highest value of the provided key(s) found on any element in
* this collection.
* @category Queries
*
* @param key - a {@link Sorter | Sorter's} used for comparing and extracting
* the max.
*
* @example
* army.create(Soldier, 'a', { strength: 2, initiative: 3 });
* army.create(Soldier, 'b', { strength: 3, initiative: 1 });
* army.create(Soldier, 'c', { strength: 2, initiative: 2 });
* army.all(Solider).max('strength'); // => 3
*/
max<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ? K2 : never}[keyof T] | ((t: T) => K)): K | undefined {
const el = this.sortedBy(key, 'desc')[0];
if (!el) return;
return typeof key === 'function' ? key(el) : el[key] as K;
}
/**
* Returns the lowest value of the provided key(s) found on any element in
* this collection.
* @category Queries
*
* @param key - a {@link Sorter | Sorter's} used for comparing and extracting
* the minimum.
*
* @example
* army.create(Soldier, 'a', { strength: 2, initiative: 3 });
* army.create(Soldier, 'b', { strength: 3, initiative: 1 });
* army.create(Soldier, 'c', { strength: 2, initiative: 2 });
* army.all(Solider).min('initiative'); // => 1
*/
min<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ? K2 : never}[keyof T] | ((t: T) => K)): K | undefined {
const el = this.sortedBy(key, 'asc')[0]
if (!el) return;
return typeof key === 'function' ? key(el) : el[key] as K;
}
/**
* Returns whether all elements in this collection have the same value for key.
* @category Queries
*/
areAllEqual(key: keyof T): boolean {
if (this.length === 0) return true;
return this.every(el => el[key] === this[0][key]);
}
/**
* Remove all elements in this collection from the playing area and place them
* into {@link Game#pile}
* @category Structure
*/
remove() {
for (const el of this) {
if ('isSpace' in el) throw Error('cannot move Space');
(el as unknown as Piece<Game>).remove();
}
}
/**
* Move all pieces in this collection into another element. See {@link Piece#putInto}.
* @category Structure
*/
putInto(to: GameElement, options?: {position?: number, fromTop?: number, fromBottom?: number}) {
if (this.some(el => el.hasMoved()) || to.hasMoved()) to.game.addDelay();
for (const el of this) {
if ('isSpace' in el) throw Error('cannot move Space');
(el as unknown as Piece<Game>).putInto(to, options);
}
}
// UI
/**
* Apply a layout to some of the elements directly contained within the elements
* in this collection. See {@link GameElement#layout}
* @category UI
*/
layout(
applyTo: T['_ui']['layouts'][number]['applyTo'],
attributes: Partial<GameElement['_ui']['layouts'][number]['attributes']>
) {
for (const el of this) el.layout(applyTo, attributes);
}
/**
* Configure the layout for all elements contained within this collection. See
* {@link GameElement#configureLayout}
* @category UI
*/
configureLayout(
attributes: Partial<GameElement['_ui']['layouts'][number]['attributes']>
) {
for (const el of this) el.configureLayout(attributes);
}
/**
* Define the appearance of the elements in this collection. Any values
* provided override previous ones. See {@link GameElement#appearance}.
* @category UI
*/
appearance(appearance: ElementUI<T>['appearance']) {
for (const el of this) el.appearance(appearance);
}
}
================================================
FILE: src/board/element.ts
================================================
import ElementCollection from './element-collection.js';
import { shuffleArray, times } from '../utils.js';
import { serializeObject, deserializeObject } from '../action/utils.js';
import uuid from 'uuid-random';
import type GameManager from '../game-manager.js';
import type { default as Player, BasePlayer } from '../player/player.js';
import type { default as Game, BaseGame } from './game.js';
import type Space from './space.js';
import type ConnectedSpaceMap from './connected-space-map.js';
import type { ElementFinder, Sorter } from './element-collection.js';
import type AdjacencySpace from './adjacency-space.js';
import type { Argument } from '../action/action.js';
export type ElementJSON = ({className: string, children?: ElementJSON[]} & Record<string, any>);
export type ElementClass<T extends GameElement = GameElement> = {
new(ctx: Partial<ElementContext>): T;
isGameElement: boolean; // here to help enforce types
visibleAttributes?: string[];
}
/**
* Either the name of a property of the object that can be lexically sorted, or
* a function that will be called with the object to sort and must return a
* lexically sortable value.
* @category Board
*/
export type GenericSorter = string | ((e: GameElement) => number | string)
/**
* The attributes of this class that inherits GameElement, excluding internal
* ones from the base GameElement
*/
export type ElementAttributes<T extends GameElement> =
Partial<Pick<T, {[K in keyof T]: K extends keyof GameElement ? never : (T[K] extends (...a:any[]) => any ? never : K)}[keyof T] | 'name' | 'player' | 'row' | 'column' | 'rotation'>>
export type ElementContext = {
gameManager: GameManager;
top: GameElement;
namedSpaces: Record<string, Space<Game>>
uniqueNames: Record<string, boolean>
removed: GameElement;
sequence: number;
player?: Player;
classRegistry: ElementClass[];
moves: Record<string, string>;
trackMovement: boolean;
};
/**
* A Box size and position relative to a container
* @category UI
*/
export type Box = { left: number, top: number, width: number, height: number };
/**
* An (x, y) Vector
* @category UI
*/
export type Vector = { x: number, y: number };
export type Direction = 'up' | 'down' | 'left' | 'right'
export type DirectionWithDiagonals = Direction | 'upleft' | 'upright' | 'downleft' | 'downright';
export type ElementUI<T extends GameElement> = {
layouts: {
applyTo: ElementClass | GameElement | ElementCollection | string,
attributes: LayoutAttributes
}[],
appearance: {
className?: string,
render?: ((el: T) => JSX.Element | null) | false,
aspectRatio?: number,
effects?: { trigger: (element: T, oldAttributes: ElementAttributes<T>) => boolean, name: string }[],
info?: ((el: T) => JSX.Element | null | boolean) | boolean,
connections?: {
thickness?: number,
style?: 'solid' | 'double',
color?: string,
fill?: string,
label?: ({distance, to, from}: {distance: number, to: Space<Game>, from: Space<Game> }) => React.ReactNode,
labelScale?: number,
},
},
getBaseLayout: () => LayoutAttributes,
ghost?: boolean,
};
/**
* List of attributes used to create a new layout in {@link GameElement#layout}.
* @category UI
*/
export type LayoutAttributes = {
/**
* Instead of providing `area`, providing a `margin` defines the bounding box
* in terms of a margin around the edges of this element. This value is an
* absolute percentage of the board's size so that margins specified on
* different layouts with the same value will exactly match.
*/
margin?: number | { top: number, bottom: number, left: number, right: number },
/**
* A box defining the layout's bounds within this element. Unless `size` is
* set too large, no elements will ever overflow this area. If unspecified,
* the entire area is used, i.e. `{ left: 0, top: 0, width: 100, height: 100
* }`
*/
area?: Box,
/**
* The number of rows to allot for placing elements in this layout. If a
* number is provided, this is fixed. If min/max values are provided, the
* layout will allot at least `min` and up to `max` as needed. If `min` is
* omitted, a minimum of 1 is implied. If `max` is omitted, as many are used
* as needed. Default is no limits on either.
*/
rows?: number | {min: number, max?: number} | {min?: number, max: number},
/**
* Columns, as per `rows`
*/
columns?: number | {min: number, max?: number} | {min?: number, max: number},
/**
* If supplied, this overrides all other attributes to define a set of
* strictly defined boxes for placing each element. Any elements that exceed
* the number of slots provided are not displayed.
*/
slots?: Box[],
/**
* Size alloted for each element placed in this layout. Overrides `scaling`
* and all defined aspect ratios for these elements, fixing the size for each
* element at the specified size.
*/
size?: { width: number, height: number },
/**
* Aspect ratio for each element placed in this layout. This value is a ratio
* of width over height. Elements will adhere to this ratio unless they have
* their own specified `aspectRatio` in their {@link
* GameElement#appearance}. This value is ignored if `size` is provided.
*/
aspectRatio?: number, // w / h
/**
* Scaling strategy for the elements placed in this layout.
* - *fit*: Elements scale up or down to fit within the area alloted without
* squshing
* - *fill*: Elements scale up or down to completely fill the area, squishing
* themselves together as needed along one dimension.
*/
scaling?: 'fit' | 'fill'
/**
* If provided, this places a gap between elements. If scaling is 'fill', this
* is considered a maximum but may shrink or even become negative in order to
* fill the area. This value is an absolute percentage of the board's size so
* that gaps specified on different layouts with the same value will exactly
* match
*/
gap?: number | { x: number, y: number },
/**
* If more room is provided than needed, this determines how the elements will
* align themselves within the area.
*/
alignment: 'top' | 'bottom' | 'left' | 'right' | 'top left' | 'bottom left' | 'top right' | 'bottom right' | 'center',
/**
* Instead of `gap`, providing an `offsetColumn`/`offsetRow` specifies that
* the contained elements must offset one another by a specified amount as a
* percentage of the elements size, i.e. `offsetColumn=100` is equivalent to a
* `gap` of 0. This allows non-orthogonal grids like hex or diamond. If one of
* `offsetColumn`/`offsetRow` is provided but not the other, the unspecified
* one will be 90° to the one specified. Like `gap`, if `scaling` is set to
* `fill`, these offsets may squish to fill space.
*/
offsetColumn?: Vector | number,
/**
* As `offsetColumn`
*/
offsetRow?: Vector | number,
/**
* Specifies the direction in which elements placed here should fill up the
* rows and columns of the layout. Rows or columns will increase to their
* specified maximum as needed. Therefore if, for example, `direction` is
* `"ltr"` and `columns` has no maximum, there will never be a second row
* added. Values are:
* - *square*: fill rows and columns equally to maintain as square a grid as possible (default)
* - *ltr*: fill columns left to right, then rows top to bottom once maximum columns reached
* - *rtl*: fill columns right to left, then rows top to bottom once maximum columns reached
* - *ltr-btt*: fill columns left to right, then rows bottom to top once maximum columns reached
* - *rtl-btt*: fill columns right to left, then rows bottom to top once maximum columns reached
* - *ttb*: fill rows top to bottom, then columns left to right once maximum rows reached
* - *btt*: fill rows bottom to top, then columns left to right once maximum rows reached
* - *ttb-rtl*: fill rows top to bottom, then columns right to left once maximum rows reached
* - *btt-rtl*: fill rows bottom to top, then columns right to left once maximum rows reached
*/
direction: 'square' | 'ltr' | 'rtl' | 'rtl-btt' | 'ltr-btt' | 'ttb' | 'ttb-rtl' | 'btt' | 'btt-rtl',
/**
* If specified, no more than `limit` items will be visible. This is useful
* for displaying e.g. decks of cards where showing only 2 or 3 cards provides
* a deck-like appearance without needed to render more cards underneath that
* aren't visible.
*/
limit?: number,
/**
* If `scaling` is `"fill"`, this will limit the total amount of overlap if
* elements are squished together in their space before they will start to
* shrink to fit. This is useful for e.g. cards that can overlap but that must
* leave a certain amount visible to clearly identify the card.
*/
maxOverlap?: number,
/**
* A number specifying an amount of randomness added to the layout to provide
* a more natural looking placement
*/
haphazardly?: number,
/**
* Set to true to prevent these elements from automatically changing position
* within the container grid.
*/
sticky?: boolean,
/**
* Set to true for debugging. Creates a visible box on screen around the
* defined `area`, tagged with the provided string.
*/
showBoundingBox?: string | boolean,
__container__?: {
type: 'drawer' | 'popout' | 'tabs',
attributes: Record<string, any>,
id?: string,
key?: string,
}
};
/**
* Abstract base class for all Game elements. Do not subclass this
* directly. Instead use {@link Space} or {@link Piece} as the base for
* subclassing your own elements.
* @category Board
*/
export default class GameElement<G extends BaseGame = BaseGame, P extends BasePlayer = BasePlayer> {
/**
* Element name, used to distinguish elements. Elements with the same name are
* generally considered indistibuishable. Names are also used for easy
* searching of elements.
* @category Queries
*/
name: string;
/**
* Player with which this element is identified. This does not affect
* behaviour but will mark the element as `mine` in queries in the context of
* this player (during an action taken by a player or while the game is
* viewed by a given player.).
* @category Queries
*/
player?: P;
/**
* Row of element within its layout grid if specified directly or by a
* "sticky" layout.
* @category Structure
*/
row?: number;
/**
* Column of element within its layout grid if specified directly or by a
* "sticky" layout.
* @category Structure
*/
column?: number;
_rotation?: number; // degrees
/**
* The {@link Game} to which this element belongs
* @category Structure
*/
game: G;
/**
* ctx shared for all elements in the tree
* @internal
*/
_ctx: ElementContext
/**
* tree info
* @internal
*/
_t: {
children: ElementCollection<GameElement>,
parent?: GameElement,
id: number, // unique and immuatable
ref: number, // unique and may change to hide moves
wasRef?: number, // previous ref to track changes, only populated if reorder during trackMovement
moved?: boolean, // track if already moved (changed parent)
order?: 'normal' | 'stacking',
setId: (id: number) => void,
} = {
children: new ElementCollection<GameElement>(),
id: 0,
ref: 0,
setId: () => {}
};
_size?: {
width: number,
height: number,
shape: string[],
edges?: Record<string, Partial<Record<Direction, string>>>
}
static isGameElement = true;
static unserializableAttributes = ['_ctx', '_t', '_ui', 'game'];
static visibleAttributes: string[] | undefined;
/**
* Do not use the constructor directly. Instead Call {@link
* GameElement#create} or {@link GameElement#createMany} on the element in
* which you want to create a new element.
* @category Structure
*/
constructor(ctx: Partial<ElementContext>) {
this._ctx = ctx as ElementContext;
this._ctx.classRegistry ??= [];
if (!ctx.top) {
this._ctx.top = this as unknown as GameElement;
this._ctx.sequence = 0;
}
if (!this._ctx.namedSpaces) {
this._ctx.uniqueNames = {};
this._ctx.namedSpaces = {};
}
this._t = {
children: new ElementCollection(),
id: this._ctx.sequence,
ref: this._ctx.sequence,
setId: (id?: number) => {
if (id !== undefined) {
this._t.id = id;
if (this._ctx.sequence < id) this._ctx.sequence = id;
}
},
};
this._ctx.sequence += 1;
}
/**
* String used for representng this element in game messages when the object
* is passed directly, e.g. when taking the choice directly from a
* chooseOnBoard choice.
* @category Structure
*/
toString() {
return this.name || this.constructor.name.replace(/([a-z0-9])([A-Z])/g, "$1 $2");
}
isVisibleTo(_player: Player | number) {
return true;
}
isVisible() {
return true;
}
/**
* Finds all elements within this element recursively that match the arguments
* provided.
* @category Queries
*
* @param {class} className - Optionally provide a class as the first argument
* as a class filter. This will only match elements which are instances of the
* provided class
*
* @param finders - All other parameters are filters. See {@link
* ElementFinder} for more information.
*
* @returns An {@link ElementCollection} of as many matching elements as can be
* found. The collection is typed to `ElementCollection<className>` if one was
* provided.
*/
all<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
all(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
all(className?: any, ...finders: ElementFinder[]) {
return this._t.children.all(className, ...finders);
}
/**
* Finds the first element within this element recursively that matches the arguments
* provided. See {@link all} for parameter details.
* @category Queries
* @returns A matching element, if found
*/
first<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
first(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;
first(className?: any, ...finders: ElementFinder[]) {
return this._t.children.first(className, ...finders);
}
/**
* Finds the first `n` elements within this element recursively that match the arguments
* provided. See {@link all} for parameter details.
* @category Queries
* @param n - number of matches
*
* @returns An {@link ElementCollection} of as many matching elements as can be
* found, up to `n`. The collection is typed to `ElementCollection<className>`
* if one was provided.
*/
firstN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
firstN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
firstN(n: number, className?: any, ...finders: ElementFinder[]) {
return this._t.children.firstN(n, className, ...finders);
}
/**
* Finds the last element within this element recursively that matches the arguments
* provided. See {@link all} for parameter details.
* @category Queries
* @returns A matching element, if found
*/
last<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
last(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;
last(className?: any, ...finders: ElementFinder[]) {
return this._t.children.last(className, ...finders);
}
/**
* Finds the last `n` elements within this element recursively that match the arguments
* provided. See {@link all} for parameter details.
* @category Queries
* @param n - number of matches
*
* @returns An {@link ElementCollection} of as many matching elements as can be
* found, up to `n`. The collection is typed to `ElementCollection<className>`
* if one was provided.
*/
lastN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
lastN(n: number, className: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
lastN(n: number, className: any, ...finders: ElementFinder[]) {
return this._t.children.lastN(n, className, ...finders);
}
/**
* Alias for {@link first}
* @category Queries
*/
top<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
top(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;
top(className?: any, ...finders: ElementFinder[]) {
return this._t.children.top(className, ...finders);
}
/**
* Alias for {@link firstN}
* @category Queries
*/
topN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
topN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
topN(n: number, className?: any, ...finders: ElementFinder[]) {
return this._t.children.topN(n, className, ...finders);
}
/**
* Alias for {@link last}
* @category Queries
*/
bottom<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): F | undefined;
bottom(className?: ElementFinder, ...finders: ElementFinder[]): GameElement<G, P> | undefined;
bottom(className?: any, ...finders: ElementFinder[]) {
return this._t.children.bottom(className, ...finders);
}
/**
* Alias for {@link lastN}
* @category Queries
*/
bottomN<F extends GameElement>(n: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
bottomN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
bottomN(n: number, className?: any, ...finders: ElementFinder[]) {
return this._t.children.bottomN(n, className, ...finders);
}
/**
* Finds next element in this element's Space of the same class that matches
* the arguments provided, e.g. the next card after this one in the same
* pile.
* @param finders - any number of {@link ElementFinder} arguments to filter
* @category Queries
*/
next<F extends GameElement>(this: F, ...finders: ElementFinder<F>[]): F | undefined {
if (!this._t.parent) return undefined;
const thisIndex = this._t.parent!._t.children.indexOf(this);
return this._t.parent!._t.children.slice(thisIndex + 1).first(this.constructor as ElementClass<F>, ...finders);
}
/**
* Finds previous element in this element's Space of the same class that
* matches the arguments provided, e.g. the previous card before this one in
* the same pile.
* @param finders - any number of {@link ElementFinder} arguments to filter
* @category Queries
*/
previous<F extends GameElement>(this: F, ...finders: ElementFinder<F>[]): F | undefined {
if (!this._t.parent) return undefined;
const thisIndex = this._t.parent!._t.children.indexOf(this);
return this._t.parent!._t.children.slice(0, thisIndex - 1).last(this.constructor as ElementClass<F>, ...finders);
}
/**
* Finds "sibling" elements (elements that are directly inside the parent of this element) that match the arguments
* provided. See {@link all} for parameter details.
* @category Queries
*/
others<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
others(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
others(className?: any, ...finders: ElementFinder[]) {
if (!this._t.parent) return new ElementCollection();
return this._t.parent!._t.children.all(className, (el: GameElement) => el !== this, ...finders);
}
/**
* Return whether any element within this element recursively matches the arguments
* provided. See {@link all} for parameter details.
* @category Queries
*/
has<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): boolean;
has(className?: ElementFinder, ...finders: ElementFinder[]): boolean;
has(className?: any, ...finders: ElementFinder[]) {
if ((typeof className !== 'function') || !('isGameElement' in className)) {
if (className) finders = [className, ...finders];
return !!this.first(GameElement, ...finders);
}
return !!this.first(className, ...finders);
}
/**
* If this element is adjacent to some other element, using the nearest
* containing space that has an adjacency map.
* @category Adjacency
*/
isAdjacentTo(element: GameElement): boolean {
const graph = this.containerWithProperty('isAdjacent');
if (!graph) return false;
return (graph as AdjacencySpace<G>).isAdjacent(this, element);
}
/**
* Finds the shortest distance between two spaces
* @category Adjacency
*
* @param element - {@link element} to measure distance to
*/
distanceTo(element: GameElement): number {
const graph = this.containerWithProperty('distanceBetween');
if (!graph) return Infinity;
return (graph as ConnectedSpaceMap<G>).distanceBetween(this, element);
}
/**
* Find all elements adjacent based on row/column placement or based on this
* element having connections created by Space#connectTo. Uses the same
* parameters as {@link GameElement#all}
* @category Adjacency
*/
adjacencies<F extends GameElement>(className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
adjacencies(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
adjacencies(className?: any, ...finders: ElementFinder[]) {
const graph = this.containerWithProperty('isAdjacent') as AdjacencySpace<G> | undefined;
if (!graph) return false;
return (graph as ConnectedSpaceMap<G>).allAdjacentTo(this, className, ...finders);
}
/**
* Finds all spaces connected to this space by a distance no more than
* `distance`
*
* @category Adjacency
*/
withinDistance<F extends GameElement>(distance: number, className: ElementClass<F>, ...finders: ElementFinder<F>[]): ElementCollection<F>;
withinDistance(distance: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection<GameElement<G, P>>;
withinDistance(distance: number, className?: any, ...finders: ElementFinder[]) {
const graph = this.containerWithProperty('allWithinDistanceOf');
if (!graph) return new ElementCollection();
return (graph as ConnectedSpaceMap<G>).allWithinDistanceOf(this, distance, className, ...finders);
}
/**
* Set this class to use a different ordering style.
* @category Structure
* @param order - ordering style
* - "normal": Elements placed into this element are put at the end of the
* list (default)
* - "stacking": Used primarily for stacks of cards. Elements placed into this
* element are put at the beginning of the list. E.g. if a stack of cards
* has `order` set to `stacking` the {@link first} method will return the
* last card placed in the stack, rather than the first one placed in the
* stack. Hidden items in the stack are not tracked or animated while
* reordered to prevent their identity from being exposed as they move
*/
setOrder(order: typeof this._t.order) {
this._t.order = order;
}
/**
* Returns this elements parent.
* @category Queries
* @param className - If provided, searches up the parent tree to find the first
* matching element. E.g. if a Token is placed on a Card in a players
* Tableau. calling `token.container(Tableau)` can be used to find the
* grandparent.
*/
container<T extends GameElement>(className?: ElementClass<T>): T | undefined {
if (!className) return this._t.parent as T;
if (this._t.parent) return this._t.parent instanceof className ?
this._t.parent as T:
this._t.parent.container(className);
}
/**
* Returns this elements containing element that also has a given property.
* @category Queries
*/
containerWithProperty(property: string, value?: any): GameElement | undefined {
const parent = this._t.parent;
if (parent) return property in parent && (value === undefined || parent[property as keyof typeof parent] === value) ?
parent:
parent.containerWithProperty(property, value);
}
/**
* Returns whether this element has no elements placed within it.
* @category Structure
*/
isEmpty() {
return !this._t.children.length;
}
/**
* Sorts the elements directly contained within this element by some {@link Sorter}.
* @category Structure
*/
sortBy(key: GenericSorter | GenericSorter[], direction?: "asc" | "desc"): ElementCollection<GameElement<G, P>> {
return this._t.children.sortBy(key as Sorter<GameElement> | Sorter<GameElement>[], direction) as ElementCollection<GameElement<G, P>>
}
/**
* re-orders the elements directly contained within this element randomly.
* @category Structure
*/
shuffle() {
const refs = this.childRefsIfObscured();
shuffleArray(this._t.children, this._ctx.gameManager?.random || Math.random);
if (refs) this.assignChildRefs(refs);
}
/**
* The player that owns this element, or the first element that contains this
* element searching up through the parent hierarchy. This is related to, but
* different than {@link player}. E.g. if a standard playing card is in a
* player's hand, typically the `hand.player` will be assigned to that player
* but the card itself would not have a `player`. In this case the
* card.owner() will equal the player in whose hand the card is placed.
* @category Structure
*/
get owner(): P | undefined {
return this.player !== undefined ? this.player as P : this._t.parent?.owner as P;
}
/**
* Whether this element belongs to the player viewing the game. A player is
* considered to be currently viewing the game if this is called in the
* context of an action taken by a given player (during an action taken by a
* player or while the game is viewed by a given player.) It is an error to
* call this method when not in the context of a player action. When querying
* for elements using {@link ElementFinder} such as {@link all} and {@link
* first}, {@link mine} is available as a search key that accepts a value of
* true/false
@category Queries
*/
get mine() {
if (!this._ctx.player) return false; // throw?
return this.owner === this._ctx.player;
}
/**
* Create an element inside this element. This can only be called during the
* game setup (see {@link createGame}. Any game elements that are required
* must be created before the game starts. Elements that only appear later in
* the game can be created inside the {@link Game#pile} or made invisible.
* @category Structure
*
* @param className - Class to create. This class must be included in the `elementClasses` in {@link createGame}.
* @param name - Sets {@link GameElement#name | name}
* @param attributes - Sets any attributes of the class that are defined in
* your own class that extend {@link Space}, {@link Piece}, or {@link
* Game}. Can also include {@link player}.
*
* @example
* deck.create(Card, 'ace-of-hearts', { suit: 'H', value: '1' });
*/
create<T extends GameElement>(className: ElementClass<T>, name: string, attributes?: ElementAttributes<T>): T {
if (this._ctx.gameManager?.phase === 'started') throw Error('Game elements cannot be created once game has started.');
const el = this.createElement(className, name, attributes);
el._t.parent = this;
const firstPiece = this._t.children.findIndex(c => !('isSpace' in c));
if (this._t.order === 'stacking' && !('isSpace' in el)) {
if (firstPiece > 0) {
this._t.children.splice(firstPiece, 0, el);
} else {
this._t.children.unshift(el);
}
} else {
if ('isSpace' in el && firstPiece !== -1) {
this._t.children.splice(firstPiece, 0, el)
} else {
this._t.children.push(el);
}
}
if ('isSpace' in el && name) {
if (name in this._ctx.uniqueNames) { // no longer unique
delete this._ctx.namedSpaces[name];
this._ctx.uniqueNames[name] = false
} else {
this._ctx.namedSpaces[name] = el as unknown as Space<Game>;
this._ctx.uniqueNames[name] = true;
}
}
return el as T;
}
/**
* Create n elements inside this element of the same class. This can only be
* called during the game setup (see {@link createGame}. Any game elements
* that are required must be created before the game starts. Elements that
* only appear later in the game can be created inside the {@link Game#pile}
* or made invisible.
* @category Structure
*
* @param n - Number to create
* @param className - Class to create. This class must be included in the `elementClasses` in {@link createGame}.
* @param name - Sets {@link GameElement#name | name}
* @param attributes - Sets any attributes of the class that are defined in
* your own class that extend {@link Space}, {@link Piece}, or {@link
* Game}. Can also include {@link player}. If a function is supplied here, a
* single number argument will be passed with the number of the added element,
* starting with 1.
*/
createMany<T extends GameElement>(n: number, className: ElementClass<T>, name: string, attributes?: ElementAttributes<T> | ((n: number) => ElementAttributes<T>)): ElementCollection<T> {
return new ElementCollection<T>(...times(n, i => this.create(className, name, typeof attributes === 'function' ? attributes(i) : attributes)));
}
/**
* Base element creation method
* @internal
*/
createElement<T extends GameElement>(className: ElementClass<T>, name: string, attrs?: ElementAttributes<T>): T {
if (!this._ctx.classRegistry.includes(className)) {
this._ctx.classRegistry.push(className);
}
const el = new className(this._ctx);
el.game = this.game;
el.name = name;
Object.assign(el, attrs);
if ('afterCreation' in el) (el.afterCreation as () => void).bind(el)();
return el;
}
/**
* Permanently remove an element. This can only be done while defining the
* game, and is usually only useful when creating groups of elements, such as
* {@link createMany} or {@link createGrid} where some of the created elements
* are not needed.
* @category Structure
*/
destroy() {
if (this._ctx.gameManager?.phase === 'started') throw Error('Game elements cannot be destroy once game has started.');
const position = this.position();
this._t.parent?._t.children.splice(position, 1);
}
/**
* Rotation of element if set, normalized to 0-359 degrees
* @category Structure
*/
get rotation() {
if (this._rotation === undefined) return 0;
return (this._rotation % 360 + 360) % 360;
}
set rotation(r: number) {
this._rotation = r;
}
/**
* Returns the index of this element within its parent, starting at zero
* @category Structure
*/
position() {
return this._t.parent?._t.children.indexOf(this) ?? -1;
}
/**
* Returns a string identifying the tree position of the element suitable for
* anonymous reference
* @internal
*/
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 the element at the given position returned by {@link branch}
* @internal
*/
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 for the given id
* @internal
*/
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 ref
* @internal
*/
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;
}
}
_cellAt(pos: Vector): string | undefined {
if (!this._size) return pos.x === 0 && pos.y === 0 ? '.' : undefined;
if (this.rotation === 0) return this._size.shape[pos.y]?.[pos.x];
if (this.rotation === 90) return this._size.shape[this._size.height - 1 - pos.x]?.[pos.y];
if (this.rotation === 180) return this._size.shape[this._size.height - 1 - pos.y]?.[this._size.width - 1 - pos.x];
if (this.rotation === 270) return this._size.shape[pos.x]?.[this._size.width - 1 - pos.y];
}
_sizeNeededFor(_element: GameElement) {
return {width: 1, height: 1};
}
/**
* 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'
* );
*/
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 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'
* }
* });
*/
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}};
}
}
/**
* Whether this element has the given element in its parent hierarchy
* @category Structure
*/
isDescendantOf(el: GameElement): boolean {
return this._t.parent === el || !!this._t.parent?.isDescendantOf(el)
}
attributeList<T extends GameElement>(this: T): ElementAttributes<T> {
let attrs: Record<string, any>;
({ ...attrs } = this);
for (const attr of (this.constructor as typeof GameElement).unserializableAttributes as string[]) delete attrs[attr];
// remove methods
return Object.fromEntries(Object.entries(attrs).filter(
([, value]) => typeof value !== 'function'
)) as ElementAttributes<T>;
}
/**
* JSON representation
* @param seenBy - optional player position viewing the game
* @internal
*/
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' &&
gitextract_pasq2vds/ ├── .eslintrc ├── .github/ │ └── workflows/ │ ├── check.yml │ └── test.yml ├── .gitignore ├── .mocharc.json.ignore ├── .npmignore ├── CHANGELOG.md ├── CLA.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── decl.d.ts ├── esbuild.mjs ├── package.json ├── scripts/ │ ├── postpack │ └── prepack ├── src/ │ ├── action/ │ │ ├── action.ts │ │ ├── index.ts │ │ ├── selection.ts │ │ └── utils.ts │ ├── board/ │ │ ├── adjacency-space.ts │ │ ├── connected-space-map.ts │ │ ├── element-collection.ts │ │ ├── element.ts │ │ ├── fixed-grid.ts │ │ ├── game.ts │ │ ├── hex-grid.ts │ │ ├── index.ts │ │ ├── piece-grid.ts │ │ ├── piece.ts │ │ ├── single-layout.ts │ │ ├── space.ts │ │ ├── square-grid.ts │ │ ├── stack.ts │ │ └── utils.ts │ ├── components/ │ │ ├── d6/ │ │ │ ├── assets/ │ │ │ │ ├── dice.ogg │ │ │ │ └── index.scss │ │ │ ├── d6.ts │ │ │ ├── index.ts │ │ │ └── useD6.tsx │ │ ├── flippable/ │ │ │ ├── Flippable.tsx │ │ │ ├── assets/ │ │ │ │ └── index.scss │ │ │ └── index.ts │ │ └── index.ts │ ├── flow/ │ │ ├── action-step.ts │ │ ├── each-player.ts │ │ ├── enums.ts │ │ ├── every-player.ts │ │ ├── flow.ts │ │ ├── for-each.ts │ │ ├── for-loop.ts │ │ ├── if-else.ts │ │ ├── index.ts │ │ ├── switch-case.ts │ │ └── while-loop.ts │ ├── game-creator.ts │ ├── game-manager.ts │ ├── index.ts │ ├── interface.ts │ ├── player/ │ │ ├── collection.ts │ │ ├── index.ts │ │ └── player.ts │ ├── test/ │ │ ├── actions_test.ts │ │ ├── compiler.cjs │ │ ├── fixtures/ │ │ │ └── games.ts │ │ ├── flow_test.ts │ │ ├── game_manager_test.ts │ │ ├── game_test.ts │ │ ├── render_test.ts │ │ ├── setup-debug.js │ │ ├── setup.js │ │ └── ui_test.ts │ ├── test-runner.ts │ ├── ui/ │ │ ├── Main.tsx │ │ ├── assets/ │ │ │ ├── click.ogg.ts │ │ │ ├── click_004.ogg │ │ │ └── index.scss │ │ ├── game/ │ │ │ ├── Game.tsx │ │ │ └── components/ │ │ │ ├── ActionForm.tsx │ │ │ ├── AnnouncementOverlay.tsx │ │ │ ├── BoardDebug.tsx.wip │ │ │ ├── Debug.tsx │ │ │ ├── DebugArgument.tsx │ │ │ ├── DebugChoices.tsx │ │ │ ├── Drawer.tsx │ │ │ ├── Element.tsx │ │ │ ├── FlowDebug.tsx │ │ │ ├── InfoOverlay.tsx │ │ │ ├── PlayerControls.tsx │ │ │ ├── Popout.tsx │ │ │ ├── ProfileBadge.tsx │ │ │ ├── Selection.tsx │ │ │ └── Tabs.tsx │ │ ├── index.tsx │ │ ├── lib.ts │ │ ├── queue.ts │ │ ├── render.ts │ │ ├── setup/ │ │ │ ├── Setup.tsx │ │ │ └── components/ │ │ │ ├── Seating.tsx │ │ │ └── settingComponents.tsx │ │ └── store.ts │ └── utils.ts ├── tsconfig.json └── tsfmt.json
SYMBOL INDEX (537 symbols across 47 files)
FILE: src/action/action.ts
type SingleArgument (line 16) | type SingleArgument = string | number | boolean | GameElement | Player;
type Argument (line 29) | type Argument = SingleArgument | SingleArgument[];
type ActionStub (line 35) | type ActionStub = {
type Group (line 64) | type Group = Record<string,
type ExpandGroup (line 70) | type ExpandGroup<A extends Record<string, Argument>, R extends Group> = ...
class Action (line 93) | class Action<A extends Record<string, Argument> = NonNullable<unknown>> {
method constructor (line 106) | constructor({ prompt, description, condition }: {
method isPossible (line 116) | isPossible(args: A): boolean {
method _getPendingMoves (line 127) | _getPendingMoves(args: Record<string, Argument>, debug?: ActionDebug):...
method _getPendingMovesInner (line 172) | _getPendingMovesInner(args: Record<string, Argument>, debug?: ActionDe...
method _nextSelection (line 250) | _nextSelection(args: Record<string, Argument>): ResolvedSelection | un...
method _process (line 267) | _process(player: Player, args: Record<string, Argument>): string | und...
method _addSelection (line 314) | _addSelection(selection: Selection) {
method _withDecoratedArgs (line 322) | _withDecoratedArgs(args: A, fn: (args: A) => any) {
method _getError (line 344) | _getError(selection: ResolvedSelection, args: A) {
method _getConfirmation (line 348) | _getConfirmation(selection: ResolvedSelection, args: A) {
method do (line 386) | do(move: (args: A) => any): Action<A> {
method message (line 425) | message(text: string, args?: Record<string, Argument> | ((a: A) => Rec...
method messageTo (line 466) | messageTo(player: (Player | number) | (Player | number)[], text: strin...
method chooseFrom (line 564) | chooseFrom<N extends string, T extends SingleArgument>(
method enterText (line 614) | enterText<N extends string>(name: N, options?: {
method chooseNumber (line 689) | chooseNumber<N extends string>(name: N, options: {
method chooseOnBoard (line 805) | chooseOnBoard<T extends GameElement, N extends string>(name: N, choice...
method choose (line 853) | choose<N extends string, S extends 'select' | 'number' | 'text' | 'boa...
method chooseGroup (line 904) | chooseGroup<R extends Group>(
method confirm (line 948) | confirm(prompt: string | ((args: A) => string)): Action<A> {
method move (line 976) | move(piece: keyof A | Piece<Game>, into: keyof A | GameElement) {
method swap (line 1013) | swap(piece1: keyof A | Piece<Game>, piece2: keyof A | Piece<Game>) {
method reorder (line 1053) | reorder(collection: Piece<Game>[], options?: {
method placePiece (line 1123) | placePiece<T extends keyof A & string>(piece: T, into: PieceGrid<Game>...
FILE: src/action/selection.ts
type BoardQuerySingle (line 8) | type BoardQuerySingle<T extends GameElement, A extends Record<string, Ar...
type BoardQueryMulti (line 9) | type BoardQueryMulti<T extends GameElement, A extends Record<string, Arg...
type BoardQuery (line 10) | type BoardQuery<T extends GameElement, A extends Record<string, Argument...
type BoardSelection (line 12) | type BoardSelection<T extends GameElement, A extends Record<string, Argu...
type ChoiceSelection (line 20) | type ChoiceSelection<A extends Record<string, Argument> = Record<string,...
type NumberSelection (line 28) | type NumberSelection<A extends Record<string, Argument> = Record<string,...
type TextSelection (line 34) | type TextSelection<A extends Record<string, Argument> = Record<string, A...
type ButtonSelection (line 39) | type ButtonSelection = Argument;
type SelectionDefinition (line 41) | type SelectionDefinition<A extends Record<string, Argument> = Record<str...
type ResolvedSelection (line 94) | type ResolvedSelection = Omit<Selection, 'prompt' | 'min' | 'max' | 'ini...
class Selection (line 109) | class Selection {
method constructor (line 127) | constructor(name: string, s: SelectionDefinition | Selection) {
method error (line 180) | error(args: Record<string, Argument>): string | undefined {
method options (line 223) | options(this: ResolvedSelection): {choice: Argument, error?: string, l...
method isUnbounded (line 233) | isUnbounded(this: ResolvedSelection): boolean {
method isResolved (line 238) | isResolved(): this is ResolvedSelection {
method isMulti (line 249) | isMulti() {
method isBoardChoice (line 253) | isBoardChoice() {
method resolve (line 257) | resolve(args: Record<string, Argument>): ResolvedSelection {
method isPossible (line 279) | isPossible(this: ResolvedSelection): boolean {
method isForced (line 289) | isForced(this: ResolvedSelection): Argument | undefined {
method toString (line 306) | toString(): string {
FILE: src/action/utils.ts
type SerializedSingleArg (line 6) | type SerializedSingleArg = string | number | boolean;
type SerializedArg (line 7) | type SerializedArg = SerializedSingleArg | SerializedSingleArg[];
type Serializable (line 8) | type Serializable = SingleArgument | null | undefined | Serializable[] |...
FILE: src/board/adjacency-space.ts
method isAdjacent (line 22) | isAdjacent(_el1: GameElement, _el2: GameElement): boolean {
method _positionOf (line 26) | _positionOf(element: GameElement) {
method _positionedParentOf (line 31) | _positionedParentOf(element: GameElement): GameElement {
method configureLayout (line 40) | configureLayout(layoutConfiguration: Partial<LayoutAttributes>) {
FILE: src/board/connected-space-map.ts
class ConnectedSpaceMap (line 23) | class ConnectedSpaceMap<G extends BaseGame> extends AdjacencySpace<G> {
method constructor (line 28) | constructor(ctx: ElementContext) {
method isAdjacent (line 41) | isAdjacent(el1: GameElement, el2: GameElement) {
method connect (line 58) | connect(space1: Space<G>, space2: Space<G>, distance: number = 1) {
method connectOneWay (line 65) | connectOneWay(space1: Space<G>, space2: Space<G>, distance: number = 1) {
method distanceBetween (line 84) | distanceBetween(el1: GameElement, el2: GameElement) {
method _distanceBetweenNodes (line 90) | _distanceBetweenNodes(n1: string, n2: string): number {
method allAdjacentTo (line 115) | allAdjacentTo(element: GameElement, className?: any, ...finders: Eleme...
method allWithinDistanceOf (line 137) | allWithinDistanceOf(element: GameElement, distance: number, className?...
method allConnectedTo (line 165) | allConnectedTo(element: GameElement, className?: any, ...finders: Elem...
method closestTo (line 188) | closestTo<F extends GameElement>(element: GameElement, className?: any...
FILE: src/board/element-collection.ts
type Sorter (line 16) | type Sorter<T> = keyof T | ((e: T) => number | string)
type ElementFinder (line 42) | type ElementFinder<T extends GameElement = GameElement> = (
class ElementCollection (line 54) | class ElementCollection<T extends GameElement = GameElement> extends Arr...
method slice (line 56) | slice(...a: Parameters<Array<T>['slice']>):ElementCollection<T> {retur...
method filter (line 57) | filter(...a: Parameters<Array<T>['filter']>):ElementCollection<T> {ret...
method all (line 77) | all(className?: ElementFinder | ElementClass, ...finders: ElementFinde...
method _finder (line 85) | _finder<F extends GameElement>(
method first (line 149) | first(className?: ElementFinder | ElementClass, ...finders: ElementFin...
method firstN (line 170) | firstN(n: number, className?: ElementFinder | ElementClass, ...finders...
method last (line 188) | last(className?: ElementFinder | ElementClass, ...finders: ElementFind...
method lastN (line 209) | lastN(n: number, className?: ElementFinder | ElementClass, ...finders:...
method top (line 224) | top(className?: ElementFinder | ElementClass, ...finders: ElementFinde...
method topN (line 238) | topN(n: number, className?: ElementFinder | ElementClass, ...finders: ...
method bottom (line 253) | bottom(className?: ElementFinder | ElementClass, ...finders: ElementFi...
method bottomN (line 267) | bottomN(n: number, className?: ElementFinder | ElementClass, ...finder...
method showToAll (line 280) | showToAll(this: ElementCollection<Piece<BaseGame>>) {
method showOnlyTo (line 290) | showOnlyTo(this: ElementCollection<Piece<BaseGame>>, player: Player | ...
method showTo (line 305) | showTo(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] |...
method hideFromAll (line 322) | hideFromAll(this: ElementCollection<Piece<BaseGame>>) {
method hideFrom (line 333) | hideFrom(this: ElementCollection<Piece<BaseGame>>, ...player: Player[]...
method sortBy (line 353) | sortBy<E extends T>(key: Sorter<E> | Sorter<E>[], direction?: "asc" | ...
method sortedBy (line 372) | sortedBy(key: Sorter<T> | (Sorter<T>)[], direction: "asc" | "desc" = "...
method sum (line 385) | sum(key: ((e: T) => number) | (keyof {[K in keyof T]: T[K] extends num...
method withHighest (line 404) | withHighest(...attributes: Sorter<T>[]): T | undefined {
method withLowest (line 423) | withLowest(...attributes: Sorter<T>[]): T | undefined {
method max (line 441) | max<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ...
method min (line 461) | min<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ...
method areAllEqual (line 471) | areAllEqual(key: keyof T): boolean {
method remove (line 481) | remove() {
method putInto (line 492) | putInto(to: GameElement, options?: {position?: number, fromTop?: numbe...
method layout (line 507) | layout(
method configureLayout (line 520) | configureLayout(
method appearance (line 531) | appearance(appearance: ElementUI<T>['appearance']) {
FILE: src/board/element.ts
type ElementJSON (line 15) | type ElementJSON = ({className: string, children?: ElementJSON[]} & Reco...
type ElementClass (line 17) | type ElementClass<T extends GameElement = GameElement> = {
type GenericSorter (line 29) | type GenericSorter = string | ((e: GameElement) => number | string)
type ElementAttributes (line 35) | type ElementAttributes<T extends GameElement> =
type ElementContext (line 38) | type ElementContext = {
type Box (line 55) | type Box = { left: number, top: number, width: number, height: number };
type Vector (line 60) | type Vector = { x: number, y: number };
type Direction (line 62) | type Direction = 'up' | 'down' | 'left' | 'right'
type DirectionWithDiagonals (line 63) | type DirectionWithDiagonals = Direction | 'upleft' | 'upright' | 'downle...
type ElementUI (line 65) | type ElementUI<T extends GameElement> = {
type LayoutAttributes (line 93) | type LayoutAttributes = {
class GameElement (line 234) | class GameElement<G extends BaseGame = BaseGame, P extends BasePlayer = ...
method constructor (line 319) | constructor(ctx: Partial<ElementContext>) {
method toString (line 351) | toString() {
method isVisibleTo (line 355) | isVisibleTo(_player: Player | number) {
method isVisible (line 359) | isVisible() {
method all (line 381) | all(className?: any, ...finders: ElementFinder[]) {
method first (line 393) | first(className?: any, ...finders: ElementFinder[]) {
method firstN (line 409) | firstN(n: number, className?: any, ...finders: ElementFinder[]) {
method last (line 421) | last(className?: any, ...finders: ElementFinder[]) {
method lastN (line 437) | lastN(n: number, className: any, ...finders: ElementFinder[]) {
method top (line 448) | top(className?: any, ...finders: ElementFinder[]) {
method topN (line 458) | topN(n: number, className?: any, ...finders: ElementFinder[]) {
method bottom (line 468) | bottom(className?: any, ...finders: ElementFinder[]) {
method bottomN (line 478) | bottomN(n: number, className?: any, ...finders: ElementFinder[]) {
method next (line 489) | next<F extends GameElement>(this: F, ...finders: ElementFinder<F>[]): ...
method previous (line 502) | previous<F extends GameElement>(this: F, ...finders: ElementFinder<F>[...
method others (line 515) | others(className?: any, ...finders: ElementFinder[]) {
method has (line 527) | has(className?: any, ...finders: ElementFinder[]) {
method isAdjacentTo (line 540) | isAdjacentTo(element: GameElement): boolean {
method distanceTo (line 552) | distanceTo(element: GameElement): number {
method adjacencies (line 566) | adjacencies(className?: any, ...finders: ElementFinder[]) {
method withinDistance (line 580) | withinDistance(distance: number, className?: any, ...finders: ElementF...
method setOrder (line 599) | setOrder(order: typeof this._t.order) {
method container (line 611) | container<T extends GameElement>(className?: ElementClass<T>): T | und...
method containerWithProperty (line 622) | containerWithProperty(property: string, value?: any): GameElement | un...
method isEmpty (line 633) | isEmpty() {
method sortBy (line 641) | sortBy(key: GenericSorter | GenericSorter[], direction?: "asc" | "desc...
method shuffle (line 649) | shuffle() {
method owner (line 664) | get owner(): P | undefined {
method mine (line 679) | get mine() {
method create (line 700) | create<T extends GameElement>(className: ElementClass<T>, name: string...
method createMany (line 747) | createMany<T extends GameElement>(n: number, className: ElementClass<T...
method createElement (line 755) | createElement<T extends GameElement>(className: ElementClass<T>, name:...
method destroy (line 774) | destroy() {
method rotation (line 784) | get rotation() {
method rotation (line 789) | set rotation(r: number) {
method position (line 797) | position() {
method branch (line 806) | branch() {
method atBranch (line 823) | atBranch(b: string) {
method atID (line 839) | atID(id: number): GameElement | undefined {
method atRef (line 852) | atRef(ref: number): GameElement | undefined {
method _cellAt (line 861) | _cellAt(pos: Vector): string | undefined {
method _sizeNeededFor (line 869) | _sizeNeededFor(_element: GameElement) {
method setShape (line 902) | setShape(...shape: string[]) {
method setEdges (line 947) | setEdges(edges: Record<string, Partial<Record<Direction, string>>> | P...
method isDescendantOf (line 963) | isDescendantOf(el: GameElement): boolean {
method attributeList (line 967) | attributeList<T extends GameElement>(this: T): ElementAttributes<T> {
method toJSON (line 983) | toJSON(seenBy?: number) {
method createChildrenFromJSON (line 1018) | createChildrenFromJSON(childrenJSON: ElementJSON[], branch: string) {
method assignAttributesFromJSON (line 1052) | assignAttributesFromJSON(childrenJSON: ElementJSON[], branch: string) {
method resetUI (line 1077) | resetUI() {
method layout (line 1105) | layout(
method layoutAsDrawer (line 1157) | layoutAsDrawer(applyTo: Space<G, P> | string, attributes: {
method layoutAsTabs (line 1185) | layoutAsTabs(tabs: Record<string, Space<G, P> | string>, attributes: {
method layoutAsPopout (line 1213) | layoutAsPopout(applyTo: Space<G, P> | string, attributes: {
method configureLayout (line 1226) | configureLayout(layoutConfiguration: Partial<LayoutAttributes>) {
method appearance (line 1267) | appearance(appearance: ElementUI<this>['appearance']) {
method childRefsIfObscured (line 1271) | childRefsIfObscured() {
method assignChildRefs (line 1281) | assignChildRefs(refs: number[]) {
method hasMoved (line 1287) | hasMoved(): boolean {
method resetMovementTracking (line 1291) | resetMovementTracking() {
method resetRefTracking (line 1296) | resetRefTracking() {
FILE: src/board/fixed-grid.ts
method afterCreation (line 31) | afterCreation() {
method create (line 50) | create<T extends GameElement>(_className: ElementClass, _name: string): T {
method _adjacentGridPositionsTo (line 54) | _adjacentGridPositionsTo(_column: number, _row: number): [number, number...
method _gridPositions (line 58) | _gridPositions(): [number, number][] {
FILE: src/board/game.ts
type ActionLayout (line 35) | type ActionLayout = {
type BoardSize (line 95) | type BoardSize = {
type BoardSizeMatcher (line 105) | type BoardSizeMatcher = {
type BaseGame (line 114) | interface BaseGame extends Game<BaseGame, BasePlayer> {}
class Game (line 124) | class Game<G extends BaseGame = BaseGame, P extends BasePlayer = BasePla...
method constructor (line 151) | constructor(ctx: Partial<ElementContext>) {
method registerClasses (line 161) | registerClasses(...classList: ElementClass[]) {
method defineFlow (line 178) | defineFlow(...flow: FlowStep[]) {
method defineSubflow (line 190) | defineSubflow(name: string, ...flow: FlowStep[]) {
method defineActions (line 204) | defineActions(actions: Record<string, (player: P) => Action<Record<str...
method setting (line 214) | setting(key: string) {
method action (line 268) | action<A extends Record<string, Argument> = NonNullable<unknown>>(defi...
method followUp (line 303) | followUp(action: ActionStub) {
method finish (line 348) | finish(winner?: P | P[], announcement?: string) {
method getWinners (line 358) | getWinners() {
method addDelay (line 369) | addDelay() {
method message (line 402) | message(text: string, args?: Record<string, Argument>) {
method messageTo (line 429) | messageTo(player: (BasePlayer | number) | (BasePlayer | number)[], tex...
method announce (line 453) | announce(announcement: string) {
method allJSON (line 460) | allJSON(seenBy?: number): ElementJSON[] {
method fromJSON (line 467) | fromJSON(boardJSON: ElementJSON[]) {
method resetUI (line 515) | resetUI() {
method setBoardSize (line 520) | setBoardSize(boardSize: BoardSize) {
method getBoardSize (line 526) | getBoardSize(screenX: number, screenY: number, mobile: boolean) {
method layoutControls (line 543) | layoutControls(attributes: ActionLayout) {
method layoutStep (line 556) | layoutStep(step: string, attributes: ActionLayout) {
method layoutAction (line 570) | layoutAction(action: string, attributes: ActionLayout) {
method disableDefaultAppearance (line 580) | disableDefaultAppearance() {
method showLayoutBoundingBoxes (line 589) | showLayoutBoundingBoxes() {
FILE: src/board/hex-grid.ts
class HexGrid (line 16) | class HexGrid<G extends Game> extends FixedGrid<G> {
method _adjacentGridPositionsTo (line 67) | _adjacentGridPositionsTo(column: number, row: number): [number, number...
method _gridPositions (line 92) | _gridPositions(): [number, number][] {
method _cornerPositions (line 118) | _cornerPositions(): [number, number][] {
FILE: src/board/index.ts
function union (line 24) | function union<T extends GameElement>(...queries: (T | ElementCollection...
FILE: src/board/piece-grid.ts
class PieceGrid (line 19) | class PieceGrid<G extends Game> extends AdjacencySpace<G> {
method constructor (line 58) | constructor(ctx: ElementContext) {
method isAdjacent (line 63) | isAdjacent(el1: GameElement, el2: GameElement): boolean {
method _sizeNeededFor (line 67) | _sizeNeededFor(element: GameElement) {
method cellsAround (line 80) | cellsAround(piece: Piece<G>, pos: Vector) {
method isOverlapping (line 97) | isOverlapping(piece: Piece<G>, other?: Piece<G>): boolean {
method _fitPieceInFreePlace (line 127) | _fitPieceInFreePlace(piece: Piece<G>, rows: number, columns: number, o...
method adjacenciesByCell (line 201) | adjacenciesByCell(piece: Piece<G>, other?: Piece<G>): {piece: Piece<G>...
method adjacenciesByEdge (line 287) | adjacenciesByEdge(piece: Piece<G>, other?: Piece<G>): {piece: Piece<G>...
FILE: src/board/piece.ts
class Piece (line 13) | class Piece<G extends Game, P extends Player = NonNullable<G['player']>>...
method createElement (line 20) | createElement<T extends GameElement>(className: ElementClass<T>, name:...
method showToAll (line 31) | showToAll() {
method showOnlyTo (line 39) | showOnlyTo(player: Player | number) {
method showTo (line 52) | showTo(...player: Player[] | number[]) {
method hideFromAll (line 67) | hideFromAll() {
method hideFrom (line 76) | hideFrom(...player: Player[] | number[]) {
method isVisibleTo (line 94) | isVisibleTo(player: Player | number) {
method isVisible (line 110) | isVisible() {
method revealWhenHidden (line 126) | static revealWhenHidden<T extends Piece<BaseGame>>(this: ElementClass<...
method putInto (line 144) | putInto(to: GameElement, options?: {position?: number, row?: number, c...
method cloneInto (line 170) | cloneInto<T extends GameElement>(this: T, into: GameElement): T {
method remove (line 192) | remove() {
FILE: src/board/single-layout.ts
method layout (line 26) | layout() {
method resetUI (line 30) | resetUI() {
FILE: src/board/space.ts
type ElementEventHandler (line 8) | type ElementEventHandler<T extends GameElement> = {callback: (el: T) => ...
class Space (line 15) | class Space<G extends BaseGame, P extends Player = NonNullable<G['player...
method contentsWillBeShown (line 35) | contentsWillBeShown() {
method contentsWillBeShownToOwner (line 43) | contentsWillBeShownToOwner() {
method contentsWillBeShownTo (line 51) | contentsWillBeShownTo(...players: P[]) {
method contentsWillBeHidden (line 59) | contentsWillBeHidden() {
method contentsWillBeHiddenFrom (line 67) | contentsWillBeHiddenFrom(...players: P[]) {
method blockViewFor (line 80) | blockViewFor(players: 'all' | 'none' | 'all-but-owner' | Player[]) {
method isSpace (line 84) | isSpace() { return true; }
method create (line 86) | create<T extends GameElement>(className: ElementClass<T>, name: string...
method addEventHandler (line 92) | addEventHandler<T extends GameElement>(type: keyof Space<G>['_eventHan...
method onEnter (line 109) | onEnter<T extends GameElement>(type: ElementClass<T>, callback: (el: T...
method onExit (line 125) | onExit<T extends GameElement>(type: ElementClass<T>, callback: (el: T)...
method triggerEvent (line 129) | triggerEvent(event: keyof Space<G>['_eventHandlers'], element: Piece<G...
FILE: src/board/square-grid.ts
class SquareGrid (line 14) | class SquareGrid<G extends Game> extends FixedGrid<G> {
method _adjacentGridPositionsTo (line 22) | _adjacentGridPositionsTo(column: number, row: number): [number, number...
method _gridPositions (line 43) | _gridPositions(): [number, number][] {
FILE: src/board/stack.ts
class Stack (line 14) | class Stack<G extends BaseGame> extends SingleLayout<G> {
method afterCreation (line 28) | afterCreation() {
FILE: src/board/utils.ts
function rotateDirection (line 3) | function rotateDirection(dir: Direction, rotation: number) {
FILE: src/components/d6/d6.ts
class D6 (line 14) | class D6<G extends Game = Game> extends Piece<G> {
method roll (line 28) | roll() {
FILE: src/flow/action-step.ts
type ActionStepPosition (line 10) | type ActionStepPosition = { // turn taken by `player`
class ActionStep (line 16) | class ActionStep extends Flow {
method constructor (line 33) | constructor({ name, player, players, actions, prompt, description, opt...
method reset (line 67) | reset() {
method thisStepArgs (line 71) | thisStepArgs() {
method setPosition (line 78) | setPosition(position: ActionStepPosition, sequence?: number) {
method getPlayers (line 86) | getPlayers() {
method awaitingAction (line 93) | awaitingAction() {
method currentBlock (line 97) | currentBlock() {
method allowedActions (line 106) | allowedActions(): string[] {
method actionNeeded (line 110) | actionNeeded(player?: Player): {
method processMove (line 137) | processMove(move: {
method playOneStep (line 185) | playOneStep(): InterruptSignal[] | FlowControl | Flow {
method advance (line 189) | advance() {
method toJSON (line 195) | toJSON(forPlayer=true) {
method fromJSON (line 207) | fromJSON(position: any) {
method allSteps (line 215) | allSteps() {
method toString (line 219) | toString(): string {
method visualize (line 223) | visualize(top: Flow) {
FILE: src/flow/each-player.ts
class EachPlayer (line 8) | class EachPlayer<P extends Player> extends ForLoop<P> {
method constructor (line 12) | constructor({ name, startingPlayer, nextPlayer, turns, continueUntil, ...
method setPosition (line 40) | setPosition(position: typeof this.position, sequence?: number, reset=t...
method toJSON (line 47) | toJSON() {
method fromJSON (line 54) | fromJSON(position: any) {
method allSteps (line 61) | allSteps() {
method toString (line 65) | toString(): string {
method visualize (line 69) | visualize(top: Flow) {
FILE: src/flow/enums.ts
type LoopInterruptSignal (line 63) | type LoopInterruptSignal = { signal: InterruptControl.repeat | Interrupt...
type SubflowSignal (line 64) | type SubflowSignal = { signal: InterruptControl.subflow, data: {name: st...
type InterruptSignal (line 65) | type InterruptSignal = LoopInterruptSignal | SubflowSignal
function interrupt (line 70) | function interrupt({ signal, data }: InterruptSignal) {
type InterruptControl (line 83) | enum InterruptControl {
type FlowControl (line 91) | enum FlowControl {
FILE: src/flow/every-player.ts
type EveryPlayerPosition (line 9) | type EveryPlayerPosition = {positions: FlowBranchJSON[][], sequences: nu...
class EveryPlayer (line 11) | class EveryPlayer<P extends Player> extends Flow {
method constructor (line 19) | constructor({ players, do: block, name }: {
method reset (line 28) | reset() {
method thisStepArgs (line 34) | thisStepArgs() {
method withPlayer (line 43) | withPlayer<T>(value: number, fn: () => T, mutate=false): T {
method getPlayers (line 59) | getPlayers(): P[] {
method branchJSON (line 64) | branchJSON(forPlayer=true): FlowBranchJSON[] {
method setPosition (line 81) | setPosition(positionJSON: any, sequence?: number) {
method currentBlock (line 101) | currentBlock() {
method actionNeeded (line 107) | actionNeeded(player?: Player) {
method processMove (line 113) | processMove(move: {
method playOneStep (line 128) | playOneStep(): InterruptSignal[] | FlowControl | Flow {
method toString (line 147) | toString(): string {
method visualize (line 151) | visualize(top: Flow) {
FILE: src/flow/flow.ts
type FlowArguments (line 45) | type FlowArguments = Record<string, any>;
type FlowStep (line 54) | type FlowStep = Flow | ((args: FlowArguments) => any);
type FlowDefinition (line 64) | type FlowDefinition = FlowStep | FlowStep[]
type FlowBranchNode (line 66) | type FlowBranchNode = ({
type FlowBranchJSON (line 88) | type FlowBranchJSON = ({
type Position (line 96) | type Position = (
type FlowVisualization (line 100) | type FlowVisualization = {
class Flow (line 112) | class Flow {
method constructor (line 124) | constructor({ name, do: block }: { name?: string, do?: FlowDefinition ...
method validateNoDuplicate (line 131) | validateNoDuplicate() {
method flowStepArgs (line 138) | flowStepArgs(): FlowArguments {
method thisStepArgs (line 148) | thisStepArgs() {
method branchJSON (line 154) | branchJSON(forPlayer=true): FlowBranchJSON[] {
method setBranchFromJSON (line 166) | setBranchFromJSON(branch: FlowBranchJSON[]) {
method setPosition (line 178) | setPosition(position: any, sequence?: number, reset=true) {
method setPositionFromJSON (line 200) | setPositionFromJSON(positionJSON: any, sequence?: number) {
method currentLoop (line 204) | currentLoop(name?: string): WhileLoop | undefined {
method currentProcessor (line 209) | currentProcessor(): Flow | undefined {
method actionNeeded (line 214) | actionNeeded(player?: Player): {
method processMove (line 225) | processMove(move: NonNullable<ActionStepPosition>): string | SubflowSi...
method getStep (line 232) | getStep(name: string): Flow | undefined {
method playOneStep (line 253) | playOneStep(): InterruptSignal[] | FlowControl | Flow {
method play (line 283) | play() {
method reset (line 301) | reset() {
method currentBlock (line 306) | currentBlock(): FlowDefinition | undefined {
method toJSON (line 311) | toJSON(_forPlayer=true): any {
method fromJSON (line 316) | fromJSON(json: any): typeof this.position {
method advance (line 321) | advance(): FlowControl {
method allSteps (line 326) | allSteps(): FlowDefinition | undefined {
method toString (line 330) | toString() {
method stacktrace (line 334) | stacktrace(indent=0) {
method visualize (line 340) | visualize(top: Flow) {
method visualizeBlocks (line 351) | visualizeBlocks({ type, blocks, name, top, block, position }: {
FILE: src/flow/for-each.ts
type ForEachPosition (line 9) | type ForEachPosition<T> = ForLoopPosition<T> & { collection: T[] };
class ForEach (line 11) | class ForEach<T extends Serializable> extends ForLoop<T> {
method constructor (line 17) | constructor({ name, collection, do: block }: {
method reset (line 33) | reset() {
method toJSON (line 38) | toJSON(forPlayer=true) {
method fromJSON (line 46) | fromJSON(position: any) {
method toString (line 54) | toString(): string {
method visualize (line 58) | visualize(top: Flow) {
FILE: src/flow/for-loop.ts
type ForLoopPosition (line 7) | type ForLoopPosition<T> = { index: number, value: T };
class ForLoop (line 9) | class ForLoop<T = Serializable> extends WhileLoop {
method constructor (line 17) | constructor({ name, initial, next, do: block, while: whileCondition }: {
method currentBlock (line 31) | currentBlock() {
method toString (line 35) | toString(): string {
method visualize (line 39) | visualize(top: Flow) {
FILE: src/flow/if-else.ts
class If (line 6) | class If extends SwitchCase<boolean> {
method constructor (line 7) | constructor({ name, if: test, do: doExpr, else: elseExpr }: {
method toString (line 16) | toString(): string {
method visualize (line 20) | visualize(top: Flow) {
FILE: src/flow/switch-case.ts
type SwitchCasePostion (line 8) | type SwitchCasePostion<T> = { index?: number, value?: T, default?: boole...
type SwitchCaseCases (line 9) | type SwitchCaseCases<T> = ({eq: T, do: FlowDefinition} | {test: (a: T) =...
class SwitchCase (line 11) | class SwitchCase<T extends Serializable> extends Flow {
method constructor (line 18) | constructor({ name, switch: switchExpr, cases, default: def }: {
method reset (line 30) | reset() {
method currentBlock (line 44) | currentBlock() {
method toJSON (line 51) | toJSON(forPlayer=true) {
method fromJSON (line 59) | fromJSON(position: any) {
method allSteps (line 67) | allSteps(): FlowDefinition {
method toString (line 73) | toString(): string {
method visualize (line 77) | visualize(top: Flow) {
FILE: src/flow/while-loop.ts
type WhileLoopPosition (line 7) | type WhileLoopPosition = { index: number, value?: any };
class WhileLoop (line 9) | class WhileLoop extends Flow {
method constructor (line 17) | constructor({ do: block, while: whileCondition }: {
method reset (line 25) | reset() {
method currentBlock (line 36) | currentBlock() {
method advance (line 40) | advance() {
method repeat (line 52) | repeat() {
method exit (line 58) | exit(): FlowControl.complete {
method interrupt (line 63) | interrupt(signal: InterruptControl) {
method allSteps (line 69) | allSteps() {
method toString (line 73) | toString(): string {
method visualize (line 77) | visualize(top: Flow) {
FILE: src/game-creator.ts
type SetupFunction (line 8) | type SetupFunction<G extends Game = Game> = (
FILE: src/game-manager.ts
type PlayerAttributes (line 24) | type PlayerAttributes<T extends Player = Player> = {
type Move (line 32) | type Move = {
type PendingMove (line 38) | type PendingMove = {
type SerializedMove (line 45) | type SerializedMove = {
type Message (line 50) | type Message = {
type ActionDebug (line 55) | type ActionDebug = Record<string, {
type FlowStackJSON (line 61) | type FlowStackJSON = {
class GameManager (line 73) | class GameManager<G extends BaseGame = BaseGame, P extends BasePlayer = ...
method constructor (line 103) | constructor(playerClass: {new(...a: any[]): P}, gameClass: ElementClas...
method setSettings (line 114) | setSettings(settings: Record<string, any>) {
method setRandomSeed (line 118) | setRandomSeed(rseed: string) {
method start (line 130) | start() {
method play (line 141) | play(): void {
method flow (line 175) | flow() {
method getFlowStep (line 179) | getFlowStep(name: string) {
method beginSubflow (line 186) | beginSubflow(flow: SubflowSignal['data']) {
method setFlowFromJSON (line 209) | setFlowFromJSON(json: FlowStackJSON[]) {
method startFlow (line 216) | startFlow(flowState: FlowStackJSON) {
method flowJSON (line 236) | flowJSON(player: boolean = false) {
method getState (line 254) | getState(player?: P): GameState {
method getPlayerStates (line 267) | getPlayerStates(): PlayerState[] {
method getUpdate (line 276) | getUpdate(): GameUpdate {
method contextualizeBoardToPlayer (line 303) | contextualizeBoardToPlayer(player?: Player) {
method inContextOfPlayer (line 309) | inContextOfPlayer<T>(player: Player, fn: () => T): T {
method trackMovement (line 316) | trackMovement(track=true) {
method getAction (line 327) | getAction(name: string, player: P) {
method godModeActions (line 348) | godModeActions(): Record<string, Action> {
method processMove (line 389) | processMove({ player, name, args }: Move): string | undefined {
method allowedActions (line 411) | allowedActions(player: P, debug?: ActionDebug): {
method getPendingMoves (line 453) | getPendingMoves(player: P, name?: string, args?: Record<string, Argume...
FILE: src/interface.ts
type SetupState (line 12) | type SetupState = {
type GameState (line 18) | type GameState = {
type GameStartedState (line 29) | type GameStartedState = {
type GameFinishedState (line 35) | type GameFinishedState = {
type PlayerState (line 41) | type PlayerState = {
type GameUpdate (line 48) | type GameUpdate = {
type ReprocessHistoryResult (line 54) | type ReprocessHistoryResult = {
type SerializedInterfaceMove (line 60) | type SerializedInterfaceMove = {
type GameInterface (line 65) | type GameInterface = {
function advanceRseed (line 79) | function advanceRseed(rseed?: string) {
method reprocessHistory (line 157) | reprocessHistory(state: SetupState, moves: SerializedInterfaceMove[]): R...
FILE: src/player/collection.ts
class PlayerCollection (line 18) | class PlayerCollection<P extends Player> extends Array<P> {
method addPlayer (line 29) | addPlayer(attrs: PlayerAttributes & Record<string, any>) {
method atPosition (line 41) | atPosition(position: number) {
method current (line 49) | current(): P | undefined {
method allCurrent (line 57) | allCurrent(): P[] {
method host (line 64) | host(): P {
method notCurrent (line 71) | notCurrent() {
method inPositionOrder (line 79) | inPositionOrder() {
method setCurrent (line 89) | setCurrent(players: number | P | number[] | P[]) {
method next (line 98) | next() {
method after (line 110) | after(player: number | P) {
method seatedNext (line 118) | seatedNext(player: P, steps = 1) {
method turnOrderOf (line 127) | turnOrderOf(player: number | P) {
method sortBy (line 141) | sortBy(key: Sorter<P> | (Sorter<P>)[], direction?: "asc" | "desc") {
method sortedBy (line 159) | sortedBy(key: Sorter<P> | (Sorter<P>)[], direction: "asc" | "desc" = "...
method sum (line 163) | sum(key: ((e: P) => number) | (keyof {[K in keyof P]: P[K] extends num...
method withHighest (line 167) | withHighest(...attributes: Sorter<P>[]) {
method withLowest (line 171) | withLowest(...attributes: Sorter<P>[]) {
method shuffle (line 175) | shuffle() {
method max (line 179) | max<K extends keyof P>(key: K): P[K] {
method min (line 183) | min<K extends keyof P>(key: K): P[K] {
method fromJSON (line 187) | fromJSON(players: Record<string, any>[]) {
method assignAttributesFromJSON (line 196) | assignAttributesFromJSON(players: PlayerAttributes[]) {
FILE: src/player/player.ts
type BasePlayer (line 9) | interface BasePlayer extends Player<BaseGame, BasePlayer> {}
class Player (line 18) | class Player<G extends BaseGame = BaseGame, P extends BasePlayer = BaseP...
method hide (line 59) | static hide<P extends BasePlayer>(this: {new(): P; hiddenAttributes: s...
method isCurrent (line 65) | isCurrent() {
method setCurrent (line 72) | setCurrent(this: P) {
method others (line 79) | others(): P[] {
method other (line 86) | other(): P {
method allMy (line 98) | allMy(className?: any, ...finders: ElementFinder[]) {
method my (line 109) | my(className?: any, ...finders: ElementFinder[]) {
method has (line 120) | has(className?: any, ...finders: ElementFinder[]): boolean {
method toJSON (line 124) | toJSON(player?: Player) {
method toString (line 148) | toString() {
FILE: src/test-runner.ts
type Window (line 12) | interface Window {
class TestRunnerPlayer (line 17) | class TestRunnerPlayer<G extends BaseGame> {
method constructor (line 25) | constructor(runner: TestRunner<G>, position: number, store: ReturnType...
method move (line 33) | move(name: string, args: Record<string, Argument>) {
method actions (line 49) | actions() {
class TestRunner (line 56) | class TestRunner<G extends BaseGame> {
method constructor (line 68) | constructor(private setup: SetupFunction, mocks?: (game: G) => void) {
method start (line 100) | start({players, settings}: {
method getCurrentGame (line 130) | getCurrentGame() {
method updatePlayers (line 135) | updatePlayers() {
method updatePlayersFromState (line 140) | updatePlayersFromState() {
FILE: src/test/fixtures/games.ts
class TestPlayer (line 9) | class TestPlayer extends Player<TestGame, TestPlayer> {
class TestGame (line 13) | class TestGame extends Game<TestGame, TestPlayer> {
class Token (line 17) | class Token extends Piece<TestGame> {
FILE: src/test/game_manager_test.ts
class TestPlayer (line 22) | class TestPlayer extends Player<TestGame, TestPlayer> {
class TestGame (line 28) | class TestGame extends Game<TestGame, TestPlayer> {
class Card (line 32) | class Card extends Piece<TestGame> {
class Country (line 38) | class Country extends Space<TestGame> {
class General (line 42) | class General extends Piece<TestGame> {
FILE: src/test/game_test.ts
class Country (line 150) | class Country extends Space<Game> {
class Country (line 167) | class Country extends Space<Game> {
class General (line 170) | class General extends Piece<Game> {
class Card (line 229) | class Card extends Piece<Game> {
class Cell (line 746) | class Cell extends Space<Game> { color: string }
FILE: src/test/render_test.ts
class Country (line 326) | class Country extends Space<Game> { }
FILE: src/test/ui_test.ts
function getGameStore (line 271) | function getGameStore(gameCreator: (game: Game) => void) {
function updateStore (line 278) | function updateStore(store: ReturnType<typeof createGameStore>, players:...
FILE: src/ui/Main.tsx
type User (line 10) | type User = {
type UsersEvent (line 23) | type UsersEvent = {
type UserOnlineEvent (line 28) | type UserOnlineEvent = {
type GameSettings (line 34) | type GameSettings = Record<string, any>
type SettingsUpdateEvent (line 37) | type SettingsUpdateEvent = {
type GameUpdateEvent (line 43) | type GameUpdateEvent = {
type GameFinishedEvent (line 50) | type GameFinishedEvent = {
type MessageProcessedEvent (line 58) | type MessageProcessedEvent = {
type SeatOperation (line 64) | type SeatOperation = {
type UnseatOperation (line 73) | type UnseatOperation = {
type UpdateOperation (line 78) | type UpdateOperation = {
type PlayerOperation (line 87) | type PlayerOperation = SeatOperation | UnseatOperation | UpdateOperation
type UpdatePlayersMessage (line 89) | type UpdatePlayersMessage = {
type UpdateSettingsMessage (line 95) | type UpdateSettingsMessage = {
type StartMessage (line 103) | type StartMessage = {
type ReadyMessage (line 109) | type ReadyMessage = {
type SwitchPlayerMessage (line 113) | type SwitchPlayerMessage = {
FILE: src/ui/game/components/ProfileBadge.tsx
function ProfileBadge (line 14) | function ProfileBadge({player}: {player: Player}) {
FILE: src/ui/lib.ts
type GamePendingMoves (line 16) | type GamePendingMoves = ReturnType<GameManager['getPendingMoves']>;
type UIMove (line 18) | type UIMove = PendingMove & {
type MoveMessage (line 23) | type MoveMessage = {
class NoRandomAllowed (line 35) | class NoRandomAllowed extends Error {}
function updateSelections (line 45) | function updateSelections(store: GameStore): GameStore {
function updateControls (line 261) | function updateControls(store: GameStore): Pick<GameStore, "controls"> {
function updateBoardSelections (line 376) | function updateBoardSelections(store: GameStore): Pick<GameStore, "board...
function updatePrompts (line 421) | function updatePrompts(store: GameStore): Partial<GameStore> {
function removePlacementPiece (line 450) | function removePlacementPiece(placement: NonNullable<GameStore['placemen...
function decorateUIMove (line 455) | function decorateUIMove(move: PendingMove | UIMove): UIMove {
function clearMove (line 468) | function clearMove(): Partial<GameStore> {
FILE: src/ui/queue.ts
class Queue (line 1) | class Queue {
method constructor (line 7) | constructor(
method schedule (line 12) | schedule(update: () => any, waitIfProcessing = false) {
method pump (line 19) | pump() {
method pause (line 32) | pause() {
method resume (line 36) | resume() {
FILE: src/ui/render.ts
type UIRender (line 11) | type UIRender = {
type UI (line 51) | type UI = {
function applyLayouts (line 64) | function applyLayouts(game: Game, base?: (b: Game) => void): UI {
function applyDOMKeys (line 100) | function applyDOMKeys(render: UIRender, ui: UI, oldUI: UI) {
function applyDiff (line 118) | function applyDiff(render: UIRender, ui: UI, oldUI: UI): boolean {
function calcLayouts (line 263) | function calcLayouts(el: GameElement, ui: UI): UIRender['layouts'] {
function applyBaseStyles (line 843) | function applyBaseStyles(render: UIRender, element: GameElement) {
function getLayoutItems (line 875) | function getLayoutItems(el: GameElement) {
function getArea (line 920) | function getArea(absolutePosition: Box, margin?: number | { top: number,...
function translate (line 944) | function translate(original: Box, transform: Box): Box {
function cellBoxRC (line 953) | function cellBoxRC(
function cellSizeForArea (line 985) | function cellSizeForArea(
function getTotalArea (line 1016) | function getTotalArea(
FILE: src/ui/setup/components/settingComponents.tsx
type SetupComponentProps (line 5) | type SetupComponentProps = {
FILE: src/ui/store.ts
type GameStore (line 33) | type GameStore = {
type SetupComponentProps (line 398) | type SetupComponentProps = {
Condensed preview — 104 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (802K chars).
[
{
"path": ".eslintrc",
"chars": 968,
"preview": "{\n \"root\": true,\n \"parser\": \"@typescript-eslint/parser\",\n \"plugins\": [\n \"@typescript-eslint\",\n ],\n \"extends\": [\n"
},
{
"path": ".github/workflows/check.yml",
"chars": 346,
"preview": "on:\n push:\n branches:\n - main\n pull_request:\n branches:\n - main\nname: Check\njobs:\n check:\n runs-on: ub"
},
{
"path": ".github/workflows/test.yml",
"chars": 369,
"preview": "on:\n push:\n branches:\n - main\n pull_request:\n branches:\n - main\nname: Check\njobs:\n check:\n runs-on: ub"
},
{
"path": ".gitignore",
"chars": 132,
"preview": "# temp files\n.DS_Store\n\\#*\n.\\#*\n\n# npm\nnode_modules\nyarn-error.log\n\n# build artifacts\n/dist\n/docs\n\ntodos.txt\nnotes.txt\n*"
},
{
"path": ".mocharc.json.ignore",
"chars": 133,
"preview": "{\n \"require\": [ \"ts-node/register\" ],\n \"loader\": \"ts-node/esm\",\n \"extensions\": [\"ts\", \"tsx\"],\n \"spec\": [\n \"src/te"
},
{
"path": ".npmignore",
"chars": 6,
"preview": "!/dist"
},
{
"path": "CHANGELOG.md",
"chars": 4745,
"preview": "# v0.2.14\n* Game elements now have next/previous selectors to find adjacent elements in\n the same space.\n* Invalid opti"
},
{
"path": "CLA.md",
"chars": 9648,
"preview": "# Contributor Agreement\n\n# Individual Contributor Exclusive License Agreement\n\nThank you for your interest in contributi"
},
{
"path": "CONTRIBUTING.md",
"chars": 1124,
"preview": "# Contributing\n\nAny open source product is only as good as the community behind it. You can\nparticipate by sharing code,"
},
{
"path": "LICENSE",
"chars": 34522,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 317,
"preview": "👋 This is Boardzilla, a framework to make writing a digital board game easy. Boardzilla takes care of\n\n- player manageme"
},
{
"path": "decl.d.ts",
"chars": 24,
"preview": "declare module \"*.ogg\";\n"
},
{
"path": "esbuild.mjs",
"chars": 846,
"preview": "import * as esbuild from 'esbuild'\nimport {sassPlugin} from 'esbuild-sass-plugin'\n\nawait esbuild.build({\n entryPoints: "
},
{
"path": "package.json",
"chars": 2837,
"preview": "{\n \"name\": \"@boardzilla/core\",\n \"version\": \"0.2.14\",\n \"author\": \"Andrew Hull <aghull@gmail.com>\",\n \"license\": \"AGPL-"
},
{
"path": "scripts/postpack",
"chars": 48,
"preview": "#!/bin/bash\nset -e\n\nrm -r entry\nln -s src entry\n"
},
{
"path": "scripts/prepack",
"chars": 68,
"preview": "#!/bin/bash\nset -e\n\nyarn clean\nyarn build\nrm -r entry\nmv dist entry\n"
},
{
"path": "src/action/action.ts",
"chars": 51494,
"preview": "import Selection from './selection.js';\nimport GameElement from '../board/element.js';\nimport Piece from '../board/piece"
},
{
"path": "src/action/index.ts",
"chars": 222,
"preview": "export {default as Action} from './action.js';\nexport {default as Selection} from './selection.js';\n\nexport type { Argum"
},
{
"path": "src/action/selection.ts",
"chars": 13440,
"preview": "import { range } from '../utils.js';\nimport { combinations } from './utils.js';\nimport GameElement from '../board/elemen"
},
{
"path": "src/action/utils.ts",
"chars": 4372,
"preview": "import type { Argument, SingleArgument } from './action.js';\nimport type { Player } from '../player/index.js';\nimport ty"
},
{
"path": "src/board/adjacency-space.ts",
"chars": 1500,
"preview": "import GameElement from './element.js';\n\nimport type { BaseGame } from './game.js';\nimport type { ElementUI, LayoutAttri"
},
{
"path": "src/board/connected-space-map.ts",
"chars": 9693,
"preview": "import AdjacencySpace from './adjacency-space.js';\nimport graphology, { DirectedGraph } from 'graphology';\nimport { dijk"
},
{
"path": "src/board/element-collection.ts",
"chars": 21267,
"preview": "import type {\n ElementClass,\n ElementUI,\n ElementAttributes,\n} from './element.js';\nimport type Piece from './piece.j"
},
{
"path": "src/board/element.ts",
"chars": 50942,
"preview": "import ElementCollection from './element-collection.js';\nimport { shuffleArray, times } from '../utils.js';\nimport { ser"
},
{
"path": "src/board/fixed-grid.ts",
"chars": 2000,
"preview": "import ConnectedSpaceMap from \"./connected-space-map.js\";\nimport Space from './space.js';\n\nimport type Game from './game"
},
{
"path": "src/board/game.ts",
"chars": 20767,
"preview": "import Space from './space.js'\nimport { Action, Argument, ActionStub } from '../action/index.js';\nimport { deserializeOb"
},
{
"path": "src/board/hex-grid.ts",
"chars": 6748,
"preview": "import FixedGrid from \"./fixed-grid.js\";\nimport { times } from '../utils.js';\n\nimport type Game from './game.js';\nimport"
},
{
"path": "src/board/index.ts",
"chars": 1388,
"preview": "import GameElement from './element.js';\nimport ElementCollection from './element-collection.js';\nexport { GameElement, E"
},
{
"path": "src/board/piece-grid.ts",
"chars": 13722,
"preview": "import AdjacencySpace from \"./adjacency-space.js\";\nimport { rotateDirection } from './utils.js';\nimport Space from '../b"
},
{
"path": "src/board/piece.ts",
"chars": 7386,
"preview": "import GameElement from './element.js'\nimport Space from './space.js'\n\nimport type { ElementAttributes, ElementClass } f"
},
{
"path": "src/board/single-layout.ts",
"chars": 991,
"preview": "import Space from './space.js';\n\nimport type { BaseGame } from './game.js';\nimport type { ElementUI } from './element.js"
},
{
"path": "src/board/space.ts",
"chars": 4954,
"preview": "import GameElement from './element.js'\n\nimport type { BaseGame } from './game.js';\nimport type Player from '../player/pl"
},
{
"path": "src/board/square-grid.ts",
"chars": 1604,
"preview": "import FixedGrid from \"./fixed-grid.js\";\nimport { times } from '../utils.js';\n\nimport type Game from './game.js';\n\n/**\n "
},
{
"path": "src/board/stack.ts",
"chars": 949,
"preview": "import SingleLayout from './single-layout.js';\n\nimport type { BaseGame } from './game.js';\nimport type { ElementUI } fro"
},
{
"path": "src/board/utils.ts",
"chars": 603,
"preview": "import type { Direction } from './element.js';\n\nexport function rotateDirection(dir: Direction, rotation: number) {\n ro"
},
{
"path": "src/components/d6/assets/index.scss",
"chars": 4675,
"preview": ".D6 {\n > ol {\n display: grid;\n grid-template-columns: 1fr;\n grid-template-rows: 1fr;\n list-style-type: none"
},
{
"path": "src/components/d6/d6.ts",
"chars": 711,
"preview": "import Piece from '../../board/piece.js';\n\nimport type Game from '../../board/game.js';\n\n/**\n * Specialized piece for re"
},
{
"path": "src/components/d6/index.ts",
"chars": 84,
"preview": "export {default as D6} from './d6.js';\nexport {default as useD6} from './useD6.js';\n"
},
{
"path": "src/components/d6/useD6.tsx",
"chars": 1472,
"preview": "import React, { useEffect, useRef, useState } from 'react';\n\nimport dice from './assets/dice.ogg';\nimport { times } from"
},
{
"path": "src/components/flippable/Flippable.tsx",
"chars": 1640,
"preview": "import React from 'react';\n\nimport './assets/index.scss';\n\n/**\n * A Piece with two sides: front and back. When the Piece"
},
{
"path": "src/components/flippable/assets/index.scss",
"chars": 588,
"preview": ".bz-flippable {\n #game:not(.browser-firefox) & {\n perspective: 40vw;\n }\n\n width: 100%;\n height: 100%;\n transitio"
},
{
"path": "src/components/flippable/index.ts",
"chars": 53,
"preview": "export {default as Flippable} from './Flippable.js';\n"
},
{
"path": "src/components/index.ts",
"chars": 93,
"preview": "export { D6, useD6 } from './d6/index.js';\nexport { Flippable } from './flippable/index.js';\n"
},
{
"path": "src/flow/action-step.ts",
"chars": 9014,
"preview": "import Flow from './flow.js';\nimport { deserializeObject, serializeObject } from '../action/utils.js';\nimport { FlowCont"
},
{
"path": "src/flow/each-player.ts",
"chars": 2466,
"preview": "import ForLoop from './for-loop.js';\nimport { Player } from '../player/index.js';\nimport { serializeSingleArg, deseriali"
},
{
"path": "src/flow/enums.ts",
"chars": 3705,
"preview": "/**\n * Functions for interrupting flows\n *\n * These functions all interrupt the flow in some. Upon calling one, the flow"
},
{
"path": "src/flow/every-player.ts",
"chars": 5808,
"preview": "import Flow from './flow.js';\nimport { FlowControl } from './enums.js';\n\nimport type { FlowDefinition, FlowBranchNode, F"
},
{
"path": "src/flow/flow.ts",
"chars": 12809,
"preview": "import { InterruptControl, interruptSignal, FlowControl } from './enums.js';\nimport { Do } from './enums.js';\n\nimport ty"
},
{
"path": "src/flow/for-each.ts",
"chars": 2334,
"preview": "import ForLoop from './for-loop.js';\nimport { serialize, deserialize } from '../action/utils.js';\n\nimport type { FlowArg"
},
{
"path": "src/flow/for-loop.ts",
"chars": 1525,
"preview": "import type { Serializable } from '../action/utils.js';\nimport type { FlowArguments, FlowDefinition, FlowBranchNode } fr"
},
{
"path": "src/flow/if-else.ts",
"chars": 1127,
"preview": "import SwitchCase from './switch-case.js';\n\nimport type { FlowDefinition, FlowStep } from './flow.js';\nimport type Flow "
},
{
"path": "src/flow/index.ts",
"chars": 13927,
"preview": "import ActionStep from './action-step.js';\nimport WhileLoop from './while-loop.js';\nimport ForLoop from './for-loop.js';"
},
{
"path": "src/flow/switch-case.ts",
"chars": 3314,
"preview": "import Flow from './flow.js';\n\nimport { serialize, deserialize } from '../action/utils.js';\n\nimport type { FlowArguments"
},
{
"path": "src/flow/while-loop.ts",
"chars": 2835,
"preview": "import Flow from './flow.js';\nimport { FlowControl } from './enums.js';\nimport { InterruptControl } from './enums.js';\n\n"
},
{
"path": "src/game-creator.ts",
"chars": 2728,
"preview": "import GameManager from './game-manager.js';\n\nimport type { Game } from './board/index.js';\nimport type { SetupState, Ga"
},
{
"path": "src/game-manager.ts",
"chars": 17339,
"preview": "import {\n Space,\n Piece,\n GameElement\n} from './board/index.js';\nimport { Action, Selection } from './action/index.js"
},
{
"path": "src/index.ts",
"chars": 1172,
"preview": "import GameManager from './game-manager.js';\nimport { Game, Space } from './board/index.js';\nimport { Player } from './p"
},
{
"path": "src/interface.ts",
"chars": 6501,
"preview": "import { deserializeArg } from './action/utils.js';\nimport { range } from './utils.js';\nimport random from 'random-seed'"
},
{
"path": "src/player/collection.ts",
"chars": 6034,
"preview": "import Player from './player.js';\n\nimport { shuffleArray } from '../utils.js';\nimport { deserializeObject } from '../act"
},
{
"path": "src/player/index.ts",
"chars": 112,
"preview": "export { default as Player } from './player.js';\nexport { default as PlayerCollection } from './collection.js';\n"
},
{
"path": "src/player/player.ts",
"chars": 4822,
"preview": "import { serializeObject } from '../action/utils.js';\n\nimport type PlayerCollection from './collection.js';\nimport type "
},
{
"path": "src/test/actions_test.ts",
"chars": 16531,
"preview": "/* global describe, it, beforeEach */\n/* eslint-disable no-unused-expressions */\nimport chai from 'chai';\nimport spies f"
},
{
"path": "src/test/compiler.cjs",
"chars": 122,
"preview": "const tsNode = require('ts-node');\n\ntsNode.register({\n project: './tsconfig.json',\n ignore: ['.*\\.scss', '.*\\.ogg']\n})"
},
{
"path": "src/test/fixtures/games.ts",
"chars": 3830,
"preview": "import Player from '../../player/player.js';\nimport {\n Game,\n Space,\n Piece,\n PieceGrid,\n} from '../../board/index.j"
},
{
"path": "src/test/flow_test.ts",
"chars": 29334,
"preview": "import chai from 'chai';\nimport spies from 'chai-spies';\n\nimport Flow from '../flow/flow.js';\nimport {\n playerActions,\n"
},
{
"path": "src/test/game_manager_test.ts",
"chars": 48715,
"preview": "import chai from 'chai';\nimport spies from 'chai-spies';\n\nimport GameManager, { PlayerAttributes } from '../game-manager"
},
{
"path": "src/test/game_test.ts",
"chars": 44586,
"preview": "import chai from 'chai';\nimport spies from 'chai-spies';\nimport random from 'random-seed';\n\nimport {\n Game,\n Space,\n "
},
{
"path": "src/test/render_test.ts",
"chars": 25550,
"preview": "import chai from 'chai';\nimport spies from 'chai-spies';\n\nimport {\n Game,\n Space,\n Piece,\n GameElement,\n} from '../b"
},
{
"path": "src/test/setup-debug.js",
"chars": 138,
"preview": "globalThis.document={\n createElement:() => {},\n createTextNode: ()=>{},\n head: {\n appendChild:() => ({appendChild:"
},
{
"path": "src/test/setup.js",
"chars": 210,
"preview": "globalThis.console.debug = () => {}\nglobalThis.console.warn = () => {}\n\nglobalThis.document={\n createElement:() => {},\n"
},
{
"path": "src/test/ui_test.ts",
"chars": 10732,
"preview": "import chai from 'chai';\n\nimport Game from '../board/game.js';\nimport Player from '../player/player.js';\nimport { times "
},
{
"path": "src/test-runner.ts",
"chars": 5295,
"preview": "import { createGameStore } from './ui/store.js';\nimport { createInterface } from './interface.js';\nimport { times } from"
},
{
"path": "src/ui/Main.tsx",
"chars": 6568,
"preview": "import React, { useState, useEffect, useCallback, useMemo } from 'react';\nimport { gameStore } from './store.js';\nimport"
},
{
"path": "src/ui/assets/click.ogg.ts",
"chars": 6031,
"preview": "export default \"data:application/ogg;base64,T2dnUwACAAAAAAAAAAAISQAAAAAAAFRKKQUBHgF2b3JiaXMAAAAAAUSsAAAAAAAAAHcBAAAAAAC4"
},
{
"path": "src/ui/assets/index.scss",
"chars": 26546,
"preview": "@keyframes fade-in-prompt {\n 0% { opacity: 0; filter: blur(2em); transform: translate(-40vw, 0) }\n 50% { opacity: 0; f"
},
{
"path": "src/ui/game/Game.tsx",
"chars": 8749,
"preview": "import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';\nimport { gameStore } from '../store.js"
},
{
"path": "src/ui/game/components/ActionForm.tsx",
"chars": 5315,
"preview": "import React, { useState, useMemo, useCallback, useEffect } from 'react';\nimport { gameStore } from '../../store.js';\nim"
},
{
"path": "src/ui/game/components/AnnouncementOverlay.tsx",
"chars": 1549,
"preview": "import React, { useEffect, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nconst AnnouncementOverl"
},
{
"path": "src/ui/game/components/BoardDebug.tsx.wip",
"chars": 1469,
"preview": "import React, { useState } from 'react';\nimport { gameStore } from '../../';\n\nimport {\n GameElement,\n ElementCollectio"
},
{
"path": "src/ui/game/components/Debug.tsx",
"chars": 5838,
"preview": "import React, { useCallback, useEffect, useMemo } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport Flow"
},
{
"path": "src/ui/game/components/DebugArgument.tsx",
"chars": 635,
"preview": "import React from 'react';\nimport { gameStore } from '../../store.js';\n\nimport type { Argument } from '../../../action/a"
},
{
"path": "src/ui/game/components/DebugChoices.tsx",
"chars": 601,
"preview": "import React from 'react';\nimport DebugArgument from './DebugArgument.js';\n\nimport type { Argument } from '../../../acti"
},
{
"path": "src/ui/game/components/Drawer.tsx",
"chars": 3678,
"preview": "import React, { useEffect, useMemo, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport type { "
},
{
"path": "src/ui/game/components/Element.tsx",
"chars": 22457,
"preview": "import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';\nimport classNames from 'classnames';\ni"
},
{
"path": "src/ui/game/components/FlowDebug.tsx",
"chars": 1451,
"preview": "import React from 'react';\nimport type { FlowVisualization } from '../../../flow/flow.js';\n\nconst colors = ['#900', '#06"
},
{
"path": "src/ui/game/components/InfoOverlay.tsx",
"chars": 6085,
"preview": "import React, { useMemo, useState, useEffect, useCallback } from 'react';\nimport { gameStore } from '../../store.js';\nim"
},
{
"path": "src/ui/game/components/PlayerControls.tsx",
"chars": 1863,
"preview": "import React from 'react';\nimport { gameStore } from '../../store.js';\nimport ActionForm from './ActionForm.js';\n\nimport"
},
{
"path": "src/ui/game/components/Popout.tsx",
"chars": 2256,
"preview": "import React, { ReactNode, useEffect, useMemo, useState } from 'react';\n\nimport type { UIRender } from '../../render.js'"
},
{
"path": "src/ui/game/components/ProfileBadge.tsx",
"chars": 872,
"preview": "import React from 'react';\n\nimport Player from '../../../player/player.js';\nimport { gameStore } from '../../store.js';\n"
},
{
"path": "src/ui/game/components/Selection.tsx",
"chars": 1751,
"preview": "import React from 'react';\n\nimport type { ResolvedSelection } from '../../../action/selection.js';\nimport type { Argumen"
},
{
"path": "src/ui/game/components/Tabs.tsx",
"chars": 3261,
"preview": "import React, { useEffect, useMemo, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport type { "
},
{
"path": "src/ui/index.tsx",
"chars": 9014,
"preview": "import React from 'react'\nimport { createRoot } from 'react-dom/client';\nimport { gameStore } from './store.js';\nimport "
},
{
"path": "src/ui/lib.ts",
"chars": 19373,
"preview": "import { SerializedArg, serializeArg } from '../action/utils.js';\nimport Selection from '../action/selection.js'\nimport "
},
{
"path": "src/ui/queue.ts",
"chars": 869,
"preview": "class Queue {\n updates: (() => any)[] = [];\n justProcessed: boolean = false; // queue was just processed\n timeout: nu"
},
{
"path": "src/ui/render.ts",
"chars": 38845,
"preview": "import GameElement from '../board/element.js';\nimport ElementCollection from '../board/element-collection.js';\nimport ra"
},
{
"path": "src/ui/setup/Setup.tsx",
"chars": 3094,
"preview": "import React, { useCallback, useMemo } from 'react';\nimport Seating from './components/Seating.js';\nimport { gameStore }"
},
{
"path": "src/ui/setup/components/Seating.tsx",
"chars": 12986,
"preview": "import React, { useCallback, useState } from 'react';\nimport { gameStore } from '../../store.js';\n\nimport { times } from"
},
{
"path": "src/ui/setup/components/settingComponents.tsx",
"chars": 3219,
"preview": "import React, { useEffect } from 'react';\n\nimport type { User } from '../../Main.js'\n\nexport type SetupComponentProps = "
},
{
"path": "src/ui/store.ts",
"chars": 14970,
"preview": "import React from 'react'\nimport { createWithEqualityFn } from \"zustand/traditional\";\nimport { shallow } from 'zustand/s"
},
{
"path": "src/utils.ts",
"chars": 2220,
"preview": "import type { Argument } from './action/action.js';\nimport { escapeArgument } from './action/utils.js';\n\nexport const sh"
},
{
"path": "tsconfig.json",
"chars": 532,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"es2020\",\n \"module\": \"nodenext\",\n \"resolveJsonModule\": true,\n \"outDir\": "
},
{
"path": "tsfmt.json",
"chars": 69,
"preview": "{\n \"tabSize\": 2,\n \"indentSize\": 2,\n \"convertTabsToSpaces\": true\n}\n"
}
]
// ... and 2 more files (download for full content)
About this extraction
This page contains the full source code of the boardzilla/boardzilla-core GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 104 files (756.1 KB), approximately 204.2k tokens, and a symbol index with 537 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.