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. 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. Copyright (C) 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 . 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 . ================================================ 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 ", "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 } type Group = Record[1]?] | ['select', Parameters[1], Parameters[2]?] | ['text', Parameters[1]?] > type ExpandGroup, 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>[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 = NonNullable> { name?: string; prompt?: string; description?: string; selections: Selection[] = []; moves: ((args: Record) => any)[] = []; condition?: ((args: A) => boolean) | boolean; messages: {text: string, args?: Record | ((a: A) => Record), 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, 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, 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): 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 | 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); 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 { 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 | ((a: A) => Record)) { 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 | ((a: A) => Record)) { 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 * `` 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'). * *
    *
  • 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. *
  • 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. *
  • never: Always present this choice, even if the choice is forced *
  • 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. *
* * @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( 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 | ((args: A & {[key in N]: T}) => Record) | 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
{ 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; } /** * 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(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 { const { prompt, validate, regexp, initial } = options || {} this._addSelection(new Selection(name, { prompt, validation: validate, enterText: { regexp, initial }})); return this as unknown as Action; } /** * 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'). * *
    *
  • 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. *
  • 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. *
  • never: Always present this choice, even if the choice is forced *
  • 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. *
* * @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(name: N, options: { min?: number | ((args: A) => number), max?: number | ((args: A) => number), prompt?: string | ((args: A) => string), confirm?: string | [string, Record | ((args: A & {[key in N]: number}) => Record) | 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
{ 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; } /** * 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'). * *
    *
  • 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. *
  • 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. *
  • never: Always present this choice, even if the choice is forced *
  • 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. *
* * @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(name: N, choices: BoardQueryMulti, options?: { prompt?: string | ((args: A) => string); confirm?: string | [string, Record | ((args: A & {[key in N]: T}) => Record) | 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
; chooseOnBoard(name: N, choices: BoardQueryMulti, options?: { prompt?: string | ((args: A) => string); confirm?: string | [string, Record | ((args: A & {[key in N]: T[]}) => Record) | 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; chooseOnBoard(name: N, choices: BoardQueryMulti, options?: { prompt?: string | ((args: A) => string); confirm?: string | [string, Record | ((args: A & {[key in N]: T | T[]}) => Record) | 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 { 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; } return this as unknown as Action; } choose( name: N, type: S, options?: Parameters[1] ): Action; choose( name: N, type: S, options?: Parameters[1] ): Action; choose( name: N, type: S, choices: T[] | Record | ((args: A) => T[] | Record), options?: Parameters[2] ): Action; choose( name: N, type: S, choices: BoardQueryMulti, options?: Parameters[2] & { min: never, max: never, number: never } ): Action; choose( name: N, type: S, choices: BoardQueryMulti, options?: Parameters[2] ): Action; choose( name: N, type: S, choices?: any, options?: Record ): Action { if (type === 'number') return this.chooseNumber(name, choices as Parameters[1]); if (type === 'text') return this.enterText(name, choices as Parameters[1]); if (type === 'select') return this.chooseFrom(name, choices as Parameters[1], options as Parameters[2]); return this.chooseOnBoard(name, choices as Parameters[1], options as Parameters[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( choices: R, options?: { validate?: (args: ExpandGroup) => string | boolean | undefined, confirm?: string | [string, Record | ((args: ExpandGroup) => Record) | undefined] } ): Action> { 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>; } /** * 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 { 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, into: keyof A | GameElement) { this.do((args: A) => { const selectedPiece = piece instanceof Piece ? piece : args[piece] as Piece | Piece[]; 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, piece2: keyof A | Piece) { this.do((args: A) => { const p1 = piece1 instanceof Piece ? piece1 : args[piece1] as Piece; const p2 = piece2 instanceof Piece ? piece2 : args[piece2] as Piece; 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[], 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; const reorderTo = args['__reorder_to__'] as Piece; let position = reorderTo.position(); reorderFrom.putInto(reorderFrom._t.parent!, { position }); }); return this as unknown as Action, __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(piece: T, into: PieceGrid, options?: { prompt?: string | ((args: A) => string), confirm?: string | [string, Record | ((args: A & {[key in T]: { column: number, row: number }}) => Record) | 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; } } ================================================ 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 = Record> = T | undefined | ((args: A) => T | undefined) export type BoardQueryMulti = Record> = T[] | ((args: A) => T[]) export type BoardQuery = Record> = BoardQuerySingle | BoardQueryMulti export type BoardSelection = Record> = { chooseFrom: BoardQueryMulti; min?: number | ((args: A) => number); max?: number | ((args: A) => number); number?: number | ((args: A) => number); initial?: T[] | ((args: A) => T[]); } export type ChoiceSelection = Record> = { 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 = Record> = { min?: number | ((args: A) => number); max?: number | ((args: A) => number); initial?: number | ((args: A) => number); } export type TextSelection = Record> = { regexp?: RegExp; initial?: string | ((args: A) => string); } export type ButtonSelection = Argument; export type SelectionDefinition = Record> = { prompt?: string | ((args: A) => string); confirm?: string | [string, Record | ((args: A) => Record) | undefined] validation?: ((args: A) => string | boolean | undefined); clientContext?: Record; // additional meta info that describes the context for this selection } & ({ skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean); selectOnBoard: BoardSelection; 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 & { 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); confirm?: [string, Record | ((args: Record) => Record) | undefined] validation?: ((args: Record) => string | boolean | undefined); clientContext: Record = {}; // additional meta info that describes the context for this selection skipIf?: 'never' | 'always' | 'only-one' | ((args: Record) => boolean); choices?: SingleArgument[] | { label: string, choice: SingleArgument }[] | ((args: Record) => SingleArgument[] | { label: string, choice: SingleArgument }[]); boardChoices?: BoardQueryMulti min?: number | ((args: Record) => number); max?: number | ((args: Record) => number); initial?: Argument | ((args: Record) => 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 | 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): 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, 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, 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 = (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 extends SingleLayout { _ui: ElementUI = { 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) { 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 extends AdjacencySpace { _graph: DirectedGraph; static unserializableAttributes = [...AdjacencySpace.unserializableAttributes, '_graph']; constructor(ctx: ElementContext) { super(ctx); this._graph = new graphology.DirectedGraph<{space: Space}, {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, space2: Space, 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, space2: Space, 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(element: GameElement, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; allAdjacentTo(element: GameElement, className?: ElementFinder, ...finders: ElementFinder[]): 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(element: GameElement, distance: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; allWithinDistanceOf(element: GameElement, distance: number, className?: ElementFinder, ...finders: ElementFinder[]): 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(element: GameElement, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; allConnectedTo(element: GameElement, className?: ElementFinder, ...finders: ElementFinder[]): 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(element: GameElement, className: ElementClass, ...finders: ElementFinder[]): F | undefined; closestTo(element: GameElement, className?: ElementFinder, ...finders: ElementFinder[]): GameElement | undefined; closestTo(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 = 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 = ( ((e: T) => boolean) | (ElementAttributes & {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 extends Array { slice(...a: Parameters['slice']>):ElementCollection {return super.slice(...a) as ElementCollection} filter(...a: Parameters['filter']>):ElementCollection {return super.filter(...a) as ElementCollection} /** * 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` if one was * provided. */ all(className: ElementClass, ...finders: ElementFinder[]): ElementCollection; all(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection; all(className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection { if ((typeof className !== 'function') || !('isGameElement' in className)) { if (className) finders = [className, ...finders]; return this._finder(undefined, {}, ...finders); } return this._finder(className, {}, ...finders); } _finder( className: ElementClass | undefined, options: {limit?: number, order?: 'asc' | 'desc', noRecursive?: boolean}, ...finders: ElementFinder[] ): ElementCollection { const coll = new ElementCollection(); 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(className: ElementClass, ...finders: ElementFinder[]): 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` * if one was provided. */ firstN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; firstN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection; firstN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection { 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(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(className: ElementClass, ...finders: ElementFinder[]): 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(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` * if one was provided. */ lastN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; lastN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection; lastN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection { 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(undefined, {limit: n, order: 'desc'}, ...finders); } return this._finder(className, {limit: n, order: 'desc'}, ...finders); } /** * Alias for {@link first} * @category Queries */ top(className: ElementClass, ...finders: ElementFinder[]): 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(undefined, {limit: 1}, ...finders)[0]; } return this._finder(className, {limit: 1}, ...finders)[0]; } /** * Alias for {@link firstN} * @category Queries */ topN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; topN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection; topN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection { 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(undefined, {limit: n}, ...finders); } return this._finder(className, {limit: n}, ...finders); } /** * Alias for {@link last} * @category Queries */ bottom(className: ElementClass, ...finders: ElementFinder[]): F | undefined; bottom(className?: ElementFinder, ...finders: ElementFinder[]): T | undefined; bottom(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, order: 'desc'}, ...finders)[0]; } return this._finder(className, {limit: 1, order: 'desc'}, ...finders)[0]; } /** * Alias for {@link lastN} * @category Queries */ bottomN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; bottomN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection; bottomN(n: number, className?: ElementFinder | ElementClass, ...finders: ElementFinder[]): ElementCollection { 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(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>) { for (const el of this) { delete(el._visible); } } /** * Show these elements only to the given player * @category Visibility */ showOnlyTo(this: ElementCollection>, 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>, ...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>) { 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>, ...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(key: Sorter | Sorter[], direction?: "asc" | "desc") { const rank = (e: E, k: Sorter) => 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 | (Sorter)[], 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 | 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 | 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(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(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).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).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 ) { 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 ) { 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['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); export type ElementClass = { new(ctx: Partial): 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 = Partial any ? never : K)}[keyof T] | 'name' | 'player' | 'row' | 'column' | 'rotation'>> export type ElementContext = { gameManager: GameManager; top: GameElement; namedSpaces: Record> uniqueNames: Record removed: GameElement; sequence: number; player?: Player; classRegistry: ElementClass[]; moves: Record; 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 = { 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) => 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, from: Space }) => 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, 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 { /** * 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, 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(), id: 0, ref: 0, setId: () => {} }; _size?: { width: number, height: number, shape: string[], edges?: Record>> } 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) { 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` if one was * provided. */ all(className: ElementClass, ...finders: ElementFinder[]): ElementCollection; all(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; 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(className: ElementClass, ...finders: ElementFinder[]): F | undefined; first(className?: ElementFinder, ...finders: ElementFinder[]): GameElement | 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` * if one was provided. */ firstN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; firstN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; 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(className: ElementClass, ...finders: ElementFinder[]): F | undefined; last(className?: ElementFinder, ...finders: ElementFinder[]): GameElement | 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` * if one was provided. */ lastN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; lastN(n: number, className: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; lastN(n: number, className: any, ...finders: ElementFinder[]) { return this._t.children.lastN(n, className, ...finders); } /** * Alias for {@link first} * @category Queries */ top(className: ElementClass, ...finders: ElementFinder[]): F | undefined; top(className?: ElementFinder, ...finders: ElementFinder[]): GameElement | undefined; top(className?: any, ...finders: ElementFinder[]) { return this._t.children.top(className, ...finders); } /** * Alias for {@link firstN} * @category Queries */ topN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; topN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; topN(n: number, className?: any, ...finders: ElementFinder[]) { return this._t.children.topN(n, className, ...finders); } /** * Alias for {@link last} * @category Queries */ bottom(className: ElementClass, ...finders: ElementFinder[]): F | undefined; bottom(className?: ElementFinder, ...finders: ElementFinder[]): GameElement | undefined; bottom(className?: any, ...finders: ElementFinder[]) { return this._t.children.bottom(className, ...finders); } /** * Alias for {@link lastN} * @category Queries */ bottomN(n: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; bottomN(n: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; 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(this: F, ...finders: ElementFinder[]): 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, ...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(this: F, ...finders: ElementFinder[]): 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, ...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(className: ElementClass, ...finders: ElementFinder[]): ElementCollection; others(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; 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(className: ElementClass, ...finders: ElementFinder[]): 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).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).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(className: ElementClass, ...finders: ElementFinder[]): ElementCollection; adjacencies(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; adjacencies(className?: any, ...finders: ElementFinder[]) { const graph = this.containerWithProperty('isAdjacent') as AdjacencySpace | undefined; if (!graph) return false; return (graph as ConnectedSpaceMap).allAdjacentTo(this, className, ...finders); } /** * Finds all spaces connected to this space by a distance no more than * `distance` * * @category Adjacency */ withinDistance(distance: number, className: ElementClass, ...finders: ElementFinder[]): ElementCollection; withinDistance(distance: number, className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; withinDistance(distance: number, className?: any, ...finders: ElementFinder[]) { const graph = this.containerWithProperty('allWithinDistanceOf'); if (!graph) return new ElementCollection(); return (graph as ConnectedSpaceMap).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(className?: ElementClass): 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> { return this._t.children.sortBy(key as Sorter | Sorter[], direction) as ElementCollection> } /** * 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(className: ElementClass, name: string, attributes?: ElementAttributes): 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; 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(n: number, className: ElementClass, name: string, attributes?: ElementAttributes | ((n: number) => ElementAttributes)): ElementCollection { return new ElementCollection(...times(n, i => this.create(className, name, typeof attributes === 'function' ? attributes(i) : attributes))); } /** * Base element creation method * @internal */ createElement(className: ElementClass, name: string, attrs?: ElementAttributes): 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>> | Partial>) { 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>; } 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(this: T): ElementAttributes { let attrs: Record; ({ ...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; } /** * 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' && this.owner?.position === seenBy) || (this._screen instanceof Array && this._screen.includes(this.owner?.position)) )) { json.children = Array.from(this._t.children.map(c => c.toJSON(seenBy))); } if (globalThis.window) { // guard-rail in dev try { structuredClone(json); } catch (e) { console.error(`invalid properties on ${this}:\n${JSON.stringify(json, undefined, 2)}`); throw(e); } } return json; } createChildrenFromJSON(childrenJSON: ElementJSON[], branch: string) { // preserve previous children references const childrenRefs = [...this._t.children]; this._t.children = new ElementCollection>(); for (let i = 0; i !== childrenJSON.length; i++) { const json = childrenJSON[i]; const childBranch = branch + '/' + i; let { className, children, _id, _ref, _wasRef, name, order } = json; // try to match and preserve the object and any references. let child = childrenRefs.find(c => _id !== undefined ? (c._t.id === _id) : (c._t.ref === (_wasRef ?? _ref))); if (!child) { const elementClass = this._ctx.classRegistry.find(c => c.name === className); if (!elementClass) throw Error(`No class found ${className}. Declare any classes in \`game.registerClasses\``); child = this.createElement(elementClass, name); child._t.setId(_id); child._t.parent = this; child._t.order = order; child._t.ref = _ref ?? _id; } else { // remove absent attributes const emptyAttrs = Object.keys(child).filter(k => !(k in json) && !['_rotation', 'column', 'row'].includes(k) && !(child!.constructor as typeof GameElement).unserializableAttributes.includes(k)); if (emptyAttrs.length) { const blank = Reflect.construct(child.constructor, [{}]); for (const attr of emptyAttrs) Object.assign(child, {[attr]: blank[attr]}); } } if (_id !== undefined) child._t.ref = _ref ?? _id; if (_wasRef !== undefined && !this._ctx.trackMovement) child._t.wasRef = _wasRef; this._t.children.push(child); child.createChildrenFromJSON(children || [], childBranch); } } assignAttributesFromJSON(childrenJSON: ElementJSON[], branch: string) { for (let i = 0; i !== childrenJSON.length; i++) { const json = childrenJSON[i]; let { className: _cn, children, _ref, _wasRef, _id, order: _o, ...rest } = json; rest = deserializeObject({...rest}, this.game); let child = this._t.children[i]; Object.assign(child, rest); child.assignAttributesFromJSON(children || [], branch + '/' + i); } } /** * UI * @internal */ _ui: ElementUI = { layouts: [], appearance: {}, getBaseLayout: () => ({ alignment: 'center', direction: 'square' }), }; resetUI() { this._ui.layouts = [{ applyTo: GameElement, attributes: this._ui.getBaseLayout() }]; this._ui.appearance = {}; for (const child of this._t.children) child.resetUI(); } /** * Apply a layout to some of the elements directly contained within this * element. See also {@link ElementCollection#layout} * @category UI * * @param applyTo - Which elements this layout applies to. Provided value can be: * - A specific {@link GameElement} * - The name of an element * - A specific set of elements ({@link ElementCollection}) * - A class of elements * * If multiple layout declarations would apply to the same element, only one * will be used. The order of specificity is as above. If a class is used and * mutiple apply, the more specific class will be used. * * @param {Object} attributes - A list of attributes describing the * layout. All units of measurement are percentages of this elements width and * height from 0-100, unless otherwise noted (See `margin` and `gap`) */ layout( applyTo: typeof this._ui.layouts[number]['applyTo'], attributes: Partial ) { let {slots, area, size, aspectRatio, scaling, gap, margin, offsetColumn, offsetRow} = attributes if (slots && (area || margin || scaling || gap || margin || offsetColumn || offsetRow)) { console.warn('Layout has `slots` which overrides supplied grid parameters'); delete attributes.area; delete attributes.margin; delete attributes.gap; delete attributes.scaling; delete attributes.offsetRow; delete attributes.offsetColumn; } if (area && margin) { console.warn('Both `area` and `margin` supplied in layout. `margin` is ignored'); delete attributes.margin; } if (size && aspectRatio) { console.warn('Both `size` and `aspectRatio` supplied in layout. `aspectRatio` is ignored'); delete attributes.aspectRatio; } if (size && scaling) { console.warn('Both `size` and `scaling` supplied in layout. `scaling` is ignored'); delete attributes.scaling; } if (gap && (offsetColumn || offsetRow)) { console.warn('Both `gap` and `offset` supplied in layout. `gap` is ignored'); delete attributes.gap; } this._ui.layouts.push({ applyTo, attributes: { alignment: 'center', direction: 'square', ...attributes} }); } /** * Creates a collapsible drawer layout for a Space within this Element. This * is like {@link GameElement#layout} except for one specific Space, with * additional parameters that set the behaviour/appearance of the drawer. A * tab will be attached the drawer that will allow it be opened/closed. * * @param applyTo - The Space for the drawer. Either the Space itself or its * name. * @param area - The area for the drawer when opened expressed in percentage * sizes of this element. * @param openDirection - the direction the drawer will open * @param tab - JSX for the appearance of the tab * @param closedTab - JSX for the appearance of the tab when closed if * different * @param openIf - A function that will be checked at each game state. If it * returns true, the drawer will automatically open. * @param closeIf - A function that will be checked at each game state. If it * returns true, the drawer will automatically close. */ layoutAsDrawer(applyTo: Space | string, attributes: { area?: Box, openDirection: 'left' | 'right' | 'down' | 'up', tab?: React.ReactNode, closedTab?: React.ReactNode, openIf?: (actions: { name: string, args: Record }[]) => boolean, closeIf?: (actions: { name: string, args: Record }[]) => boolean, }) { const { area, ...container } = attributes; this.layout(applyTo, { area, __container__: { type: 'drawer', attributes: container }}); } /** * Creates a tabbed layout for a set of Space's within this Element. This is * like {@link GameElement#layout} except for a set of Spaces, with additional * parameters that set the behaviour/appearance of the tabs. Each Space will * be laid out into the same area, with a set of tabs attached to allow the * Player or the game rules to select which tab is shown. * * @param applyTo - The Spaces for the drawer as a set of key-value * pairs. Each value is a Space or a name of a Space. * @param area - The area for the tabs expressed in percentage sizes of this * element. * @param tabDirection - the side on which the tabs will be placed * @param tabs - JSX for the appearance of the tabs as a set of key-value pairs * @param setTabTo - A function that will be checked at each game state. If it * returns a string, the tab with the matching key will be shown. */ layoutAsTabs(tabs: Record | string>, attributes: { area?: Box, tabDirection: 'left' | 'right' | 'down' | 'up', tabs?: Record, setTabTo?: (actions: { name: string, args: Record }[]) => string, }) { const { area, ...container } = attributes; const id = uuid(); for (const [key, tab] of Object.entries(tabs)) { this.layout(tab, { area, __container__: { type: 'tabs', id, key, attributes: container }}); } } /** * Hides a Space within this element and replaces it with popout * button. Clicking on the button opens this Space in a full-board modal. This * is like {@link GameElement#layout} except for one Space, with additional * parameters that set the behaviour/appearance of the popout modal. * * @param applyTo - The Space for the popout. Either a Space or the name of a * Space. * @param area - The area for the tabs expressed in percentage sizes of this * element. * @param button - JSX for the appearance of the popout button * @param popoutMargin - Alter the default margin around the opened * popout. Takes a percentage or an object with percentages for top, bottom, * left and right. */ layoutAsPopout(applyTo: Space | string, attributes: { area?: Box, button: React.ReactNode, popoutMargin?: number | { top: number, bottom: number, left: number, right: number }, }) { const { area, ...container } = attributes; this.layout(applyTo, { area, __container__: { type: 'popout', attributes: container }}); } /** * Change the layout attributes for this space's layout. * @category UI */ configureLayout(layoutConfiguration: Partial) { this._ui.layouts[0] = { applyTo: GameElement, attributes: { ...this._ui.getBaseLayout(), ...layoutConfiguration, } }; } /** * Define the appearance of this element. Any values provided override * previous ones. See also {@link ElementCollection#appearance} * @category UI * * @param appearance - Possible values are: * @param appearance.className - A class name to add to the dom element * * @param appearance.render - A function that takes this element as its only * argument and returns JSX for the element. See {@link ../ui/appearance} for * more on usage. * * @param appearance.aspectRatio - The aspect ratio for this element. This * value is a ratio of width over height. All layouts defined in {@link * layout} will respect this aspect ratio. * * @param appearance.info - Return JSX for more info on this element. If * returning true, an info modal will be available for this element but with * only the rendered element and no text * * @param appearance.connections - If the elements immediately within this * element are connected using {@link Space#connectTo}, this makes those * connections visible as connecting lines. Providing a `label` will place a * label over top of this line by calling the provided function with the * distance of the connection specified in {@link Space#connectTo} and using * the retured JSX. If `labelScale` is provided, the label is scaled by this * amount. * * @param appearance.effects - Provides a CSS class that will be applied to * this element if its attributes change to match the provided ones. */ appearance(appearance: ElementUI['appearance']) { Object.assign(this._ui.appearance, appearance); } childRefsIfObscured() { if (this._t.order !== 'stacking') return; const refs = []; for (const child of this._t.children) { if (this._ctx.trackMovement) child._t.wasRef ??= child._t.ref; refs.push(child._t.ref); } return refs; } assignChildRefs(refs: number[]) { for (let i = 0; i != refs.length; i++) { this._t.children[i]._t.ref = refs[i]; } } hasMoved(): boolean { return this._t.moved || !!this._t.parent?.hasMoved(); } resetMovementTracking() { this._t.moved = false for (const child of this._t.children) child.resetMovementTracking(); } resetRefTracking() { delete this._t.wasRef; for (const child of this._t.children) child.resetRefTracking(); } } ================================================ FILE: src/board/fixed-grid.ts ================================================ import ConnectedSpaceMap from "./connected-space-map.js"; import Space from './space.js'; import type Game from './game.js'; import type { default as GameElement, ElementClass, ElementUI } from "./element.js"; /** * Abstract base class for {@link SquareGrid} and {@link HexGrid} * @category Board */ export default abstract class FixedGrid extends ConnectedSpaceMap { rows: number = 1; columns: number = 1; space: ElementClass> = Space; _ui: ElementUI = { layouts: [], appearance: {}, getBaseLayout: () => ({ rows: this.rows, columns: this.columns, sticky: true, alignment: 'center', direction: 'square' }) }; static unserializableAttributes = [...ConnectedSpaceMap.unserializableAttributes, 'space']; afterCreation() { const name = this.name + '-' + this.space.name.toLowerCase(); const grid: Space[][] = []; for (const [column, row] of this._gridPositions()) { const space = this.createElement(this.space, name, {column, row}); space._t.parent = this; this._t.children.push(space); this._graph.addNode(space._t.id, {space}); grid[column] ??= []; grid[column][row] = space; } for (const space of this._t.children) { for (const [column, row, distance] of this._adjacentGridPositionsTo(space.column!, space.row!)) { if (grid[column]?.[row]) this._graph.addDirectedEdge(space._t.id, grid[column][row]._t.id, {distance: distance ?? 1}); } } this.configureLayout({ rows: this.rows, columns: this.columns }); } create(_className: ElementClass, _name: string): T { throw Error("Fixed grids automatically create it's own spaces. Spaces can be destroyed but not created"); } _adjacentGridPositionsTo(_column: number, _row: number): [number, number, number?][] { return []; // unimplemented } _gridPositions(): [number, number][] { return []; // unimplemented } } ================================================ FILE: src/board/game.ts ================================================ import Space from './space.js' import { Action, Argument, ActionStub } from '../action/index.js'; import { deserializeObject } from '../action/utils.js'; import Flow from '../flow/flow.js'; import { n } from '../utils.js'; import { PlayerCollection } from '../player/index.js'; import { ActionStep, WhileLoop, ForEach, ForLoop, EachPlayer, EveryPlayer, IfElse, SwitchCase, Do, } from '../flow/index.js'; import type { BasePlayer } from '../player/player.js'; import type { default as GameElement, ElementJSON, ElementClass, ElementContext, Box, ElementUI, } from './element.js'; import type { FlowStep } from '../flow/flow.js'; import type { Serializable } from '../action/utils.js'; /** * Type for layout of player controls * @category UI */ export type ActionLayout = { /** * The element to which the controls will anchor themselves */ element: GameElement, /** * Maximum width of the controls as a percentage of the anchor element */ width?: number, /** * Maximum height of the controls as a percentage of the anchor element */ height?: number, /** * Boardzilla will automatically anchor the controls to {@link GameElement}'s * selected as part of the action. Include the name of the selection here to * prevent that behaviour. */ noAnchor?: string[], /** * Position of the controls *
    *
  • inset: Inside the element *
  • beside: To the left or right of the element *
  • stack: Above or below the element *
*/ position?: 'inset' | 'beside' | 'stack' /** * Distance from the left edge of the anchor element as a percentage of the * element's width */ left?: number, /** * Distance from the right edge of the anchor element as a percentage of the * element's width */ right?: number, /** * Distance from the top edge of the anchor element as a percentage of the * element's height */ center?: number, /** * Distance from the left edge of the anchor element to the center of the * controls as a percentage of the element's width */ top?: number, /** * Distance from the bottom edge of the anchor element as a percentage of the * element's height */ bottom?: number, /** * For `'beside'` or `'stack'`, `gap` is the distance between the controls and * the element as a percentage of the entire board's size. */ gap?: number, }; export type BoardSize = { name: string, aspectRatio: number, orientation?: 'landscape' | 'portrait', scaling?: 'fit' | 'scroll', flipped?: boolean, frame: { x: number, y: number }, screen: { x: number, y: number }, }; export type BoardSizeMatcher = { name: string, aspectRatio: number | { min: number, max: number }, mobile?: boolean, desktop?: boolean, orientation?: 'landscape' | 'portrait', scaling?: 'fit' | 'scroll' }; export interface BaseGame extends Game {} /** * Base class for the game. Represents the current state of the game and * contains all game elements (spaces and pieces). All games contain a single * Game class that inherits from this class and on which custom properties and * methods for a specific game can be added. * * @category Board */ export default class Game extends Space { /** * An element containing all game elements that are not currently in * play. When elements are removed from the game, they go here, and can be * retrieved, using * e.g. `game.pile.first('removed-element').putInto('destination-area')`. * @category Structure */ pile: GameElement; /** * The players in this game. See {@link Player} * @category Definition */ players: PlayerCollection

= new PlayerCollection

; player?: P; /** * Use instead of Math.random to ensure random number seed is consistent when * replaying from history. * @category Definition */ random: () => number; static unserializableAttributes = [...Space.unserializableAttributes, 'pile', 'flowCommands', 'flowGuard', 'players', 'random']; constructor(ctx: Partial) { super({ ...ctx, trackMovement: false }); this.game = this as unknown as G; this.random = ctx.gameManager?.random || Math.random; if (ctx.gameManager) this.players = ctx.gameManager.players as unknown as PlayerCollection

; this._ctx.removed = this.createElement(Space, 'removed'), this.pile = this._ctx.removed; } // no longer needed - remove in next minor release registerClasses(...classList: ElementClass[]) { this._ctx.classRegistry = this._ctx.classRegistry.concat(classList); } /** * Define your game's main flow. May contain any of the following: * - {@link playerActions} * - {@link loop} * - {@link whileLoop} * - {@link forEach} * - {@link forLoop} * - {@link eachPlayer} * - {@link everyPlayer} * - {@link ifElse} * - {@link switchCase} * @category Definition */ defineFlow(...flow: FlowStep[]) { this.defineSubflow('__main__', ...flow); } /** * Define an addtional flow that the main flow can enter. A subflow has a * unique name and can be entered at any point by calling {@link * Do|Do.subflow}. * * @param name - Unique name of flow * @param flow - Steps of the flow */ defineSubflow(name: string, ...flow: FlowStep[]) { if (this._ctx.gameManager.phase !== 'new') throw Error('cannot call defineFlow once started'); this._ctx.gameManager.flows[name] = new Flow({ name, do: flow }); this._ctx.gameManager.flows[name].gameManager = this._ctx.gameManager; } /** * Define your game's actions. * @param actions - An object consisting of actions where the key is the name * of the action and value is a function that accepts a player taking the * action and returns the result of calling {@link action} and chaining * choices, results and messages onto the result * @category Definition */ defineActions(actions: Record Action>>) { if (this._ctx.gameManager.phase !== 'new') throw Error('cannot call defineActions once started'); this._ctx.gameManager.actions = actions; } /** * Retrieve the selected setting value for a setting defined in {@link * render}. * @category Definition */ setting(key: string) { return this._ctx.gameManager.settings[key]; } /** * Create an {@link Action}. An action is a single move that a player can * take. Some actions require choices, sometimes several, before they can be * executed. Some don't have any choices, like if a player can simply * 'pass'. What defines where one action ends and another begins is how much * you as a player can decide before you "commit". For example, in chess you * select a piece to move and then a place to put it. These are a single move, * not separate. (Unless playing touch-move, which is rarely done in digital * chess.) In hearts, you pass 3 cards to another players. These are a single * move, not 3. You can change your mind as you select the cards, rather than * have to commit to each one. Similarly, other players do not see any * information about your choices until you actually commit the entire move. * * This function is called for each action in the game `actions` you define in * {@link defineActions}. These actions are initially declared with an optional * prompt and condition. Further information is added to the action by chaining * methods that add choices and behaviour. See {@link Action}. * * If this action accepts prior arguments besides the ones chosen by the * player during the execution of this action (especially common for {@link * followUp} actions) then a generic can be added for these arguments to help * Typescript type these parameters, e.g.: * `player => action<{ cards: number}>(...)` * * @param definition.prompt - The prompt that will appear for the player to * explain what the action does. Further prompts can be defined for each choice * they subsequently make to complete the action. * * @param definition.condition - A boolean or a function returning a boolean * that determines whether the action is currently allowed. Note that the * choices you define for your action will further determine if the action is * allowed. E.g. if you have a play card action and you add a choice for cards * in your hand, Boardzilla will automatically disallow this action if there * are no cards in your hand based on the face that there are no valid choices * to complete the action. You do not need to specify a `condition` for these * types of limitations. If using the function form, the function will receive * an object with any arguments passed to this action, e.g. from {@link * followUp}. * * @example * action({ * prompt: 'Flip one of your cards' * }).chooseOnBoard({ * choices: game.all(Card, {mine: true}) * }).do( * card => card.hideFromAll() * ) * * @category Definition */ action = NonNullable>(definition: { prompt?: string, description?: string, condition?: Action['condition'], } = {}) { return new Action(definition); } /** * Queue up a follow-up action while processing an action. If called during * the processing of a game action, the follow-up action given will be added * as a new action immediately following the current one, before the game's * flow can resume normally. This is common for card games where the play of a * certain card may require more actions be taken. * * @param {Object} action - The action added to the follow-up queue. * * @example * defineAction({ * ... * playCard: player => action() * .chooseOnBoard('card', cards) * .do( * ({ card }) => { * if (card.damage) { * // this card allows another action to do damage to another Card * game.followUp({ * name: 'doDamage', * args: { amount: card.damage } * }); * } * } * ) * @category Game Management */ followUp(action: ActionStub) { Do.subflow('__followup__', action); } flowGuard = (name: string): true => { if (this._ctx.gameManager.phase !== 'new') { throw Error(`Cannot use "${name}" once game has started. It is likely that this function is in the wrong place and must be called directly in defineFlow as a FlowDefinition`); } return true; }; /** * The flow commands available for this game. See: * - {@link playerActions} * - {@link loop} * - {@link whileLoop} * - {@link forEach} * - {@link forLoop} * - {@link eachPlayer} * - {@link everyPlayer} * - {@link ifElse} * - {@link switchCase} * @category Definition */ flowCommands = { playerActions: (options: ConstructorParameters[0]) => this.flowGuard('playerActions') && new ActionStep(options), loop: (...block: FlowStep[]) => this.flowGuard('loop') && new WhileLoop({do: block, while: () => true}), whileLoop: (options: ConstructorParameters[0]) => this.flowGuard('whileloop') && new WhileLoop(options), forEach: (options: ConstructorParameters>[0]) => this.flowGuard('forEach') && new ForEach(options), forLoop: (options: ConstructorParameters>[0]) => this.flowGuard('forloop') && new ForLoop(options), eachPlayer: (options: ConstructorParameters>[0]) => this.flowGuard('eachPlayer') && new EachPlayer

(options), everyPlayer: (options: ConstructorParameters>[0]) => this.flowGuard('everyplayer') && new EveryPlayer

(options), ifElse: (options: ConstructorParameters[0]) => this.flowGuard('ifelse') && new IfElse(options), switchCase: (options: ConstructorParameters>[0]) => this.flowGuard('switchCase') && new SwitchCase(options), }; /** * End the game * * @param winner - a player or players that are the winners of the game. In a * solo game if no winner is provided, this is considered a loss. * @param announcement - an optional announcement from {@link render} to * replace the standard boardzilla announcement. * @category Game Management */ finish(winner?: P | P[], announcement?: string) { this._ctx.gameManager.phase = 'finished'; if (winner) this._ctx.gameManager.winner = winner instanceof Array ? winner : [winner]; this._ctx.gameManager.announcements.push(announcement ?? '__finish__'); } /** * Return array of game winners, or undefined if game is not yet finished * @category Game Management */ getWinners() { let winner = this._ctx.gameManager.winner; if (!(winner instanceof Array)) winner = [winner]; return this._ctx.gameManager.phase === 'finished' ? winner : undefined; } /** * Add a delay in the animation of the state change at this point for player * as they receive game updates. * @category Game Management */ addDelay() { this.resetMovementTracking(); if (this.game._ctx.trackMovement) { this._ctx.gameManager.sequence += 1; } else if (this._ctx.gameManager.intermediateUpdates.length) { return; // even if not tracking, record one intermediate to allow UI to extract proper state to animate towards } this._ctx.gameManager.intermediateUpdates.push(this.players.map( p => this._ctx.gameManager.getState(p) // TODO unnecessary for all players if in context of player )); } /** * Add a message that will be broadcast in the chat at the next game update, * based on the current state of the game. * * @param text - The text of the message to send. This can contain interpolated strings * with double braces, i.e. {{player}} that are defined in args. Of course, * strings can be interpolated normally using template literals. However game * objects (e.g. players or pieces) passed in as args will be displayed * specially by Boardzilla. * * @param args - An object of key-value pairs of strings for interpolation in * the message. * * @example * game.message( * '{{player}} has a score of {{score}}', * { player, score: player.score() } * ); * * @category Game Management */ message(text: string, args?: Record) { this._ctx.gameManager.messages.push({body: n(text, args, true)}); } /** * Add a message that will be broadcast to the given player(s) in the chat at * the next game update, based on the current state of the game. * * @param player - Player or players to receive the message * * @param text - The text of the message to send. This can contain interpolated strings * with double braces, i.e. {{player}} that are defined in args. Of course, * strings can be interpolated normally using template literals. However game * objects (e.g. players or pieces) passed in as args will be displayed * specially by Boardzilla. * * @param args - An object of key-value pairs of strings for interpolation in * the message. * * @example * game.message( * '{{player}} has a score of {{score}}', * { player, score: player.score() } * ); * * @category Game Management */ messageTo(player: (BasePlayer | number) | (BasePlayer | number)[], text: string, args?: Record) { if (!(player instanceof Array)) player = [player]; for (const p of player) { this._ctx.gameManager.messages.push({ body: n(text, args, true), position: typeof p === 'number' ? p : p.position }); } } /** * Broadcast a message to all players that interrupts the game and requires * dismissal before actions can be taken. * * @param announcement - The modal name to announce, as provided in {@link render}. * * @example * game.message( * '{{player}} has a score of {{score}}', * { player, score: player.score() } * ); * * @category Game Management */ announce(announcement: string) { this._ctx.gameManager.announcements.push(announcement); this.addDelay(); this._ctx.gameManager.announcements = []; } // also gets removed elements allJSON(seenBy?: number): ElementJSON[] { return [this.toJSON(seenBy)].concat( this._ctx.removed._t.children.map(el => el.toJSON(seenBy)) ); } // hydrate from json, and assign all attrs. requires that players be hydrated first fromJSON(boardJSON: ElementJSON[]) { let { className, children, _id, order, ...rest } = boardJSON[0]; if (this.constructor.name !== className) throw Error(`Cannot create board from JSON. ${className} must equal ${this.constructor.name}`); // reset all on self - think this is unnecessary? if it is, need to figure out how to use unserializableAttributes for (const key of Object.keys(this)) { if (!Game.unserializableAttributes.includes(key) && !(key in rest)) rest[key] = undefined; } this.createChildrenFromJSON(children || [], '0'); this._ctx.removed.createChildrenFromJSON(boardJSON.slice(1), '1'); if (order) this._t.order = order; if (this._ctx.gameManager) rest = deserializeObject({...rest}, this); Object.assign(this, {...rest}); this.assignAttributesFromJSON(children || [], '0'); this._ctx.removed.assignAttributesFromJSON(boardJSON.slice(1), '1'); } // UI _ui: ElementUI & { boardSize?: BoardSize, boardSizes?: (screenX: number, screenY: number, mobile: boolean) => BoardSize setupLayout?: (game: G, player: P, boardSize: string) => void; frame?: Box; // size of the board in abs coords disabledDefaultAppearance?: boolean; boundingBoxes?: boolean; stepLayouts: Record; announcements: Record JSX.Element>; infoModals: { title: string, condition?: (game: G) => boolean, modal: (game: G) => JSX.Element }[]; } = { layouts: [], appearance: {}, stepLayouts: {}, announcements: {}, infoModals: [], getBaseLayout: () => ({ alignment: 'center', direction: 'square' }) }; // restore default layout rules before running setupLayout resetUI() { super.resetUI(); this._ui.stepLayouts = {}; } setBoardSize(boardSize: BoardSize) { if (boardSize.name !== this._ui.boardSize?.name || boardSize.aspectRatio !== this._ui.boardSize?.aspectRatio) { this._ui.boardSize = boardSize; } } getBoardSize(screenX: number, screenY: number, mobile: boolean) { return this._ui.boardSizes?.(screenX, screenY, mobile) ?? { name: '_default', aspectRatio: 1, frame: {x:100, y:100}, screen: {x:100, y:100} }; } /** * Apply default layout rules for all the placement of all player prompts and * choices, in relation to the playing area * * @param attributes - see {@link ActionLayout} * * @category UI */ layoutControls(attributes: ActionLayout) { this._ui.stepLayouts["*"] = attributes; } /** * Apply layout rules to a particular step in the flow, controlling where * player prompts and choices appear in relation to the playing area * * @param step - the name of the step as defined in {@link playerActions} * @param attributes - see {@link ActionLayout} * * @category UI */ layoutStep(step: string, attributes: ActionLayout) { if (!this._ctx.gameManager.getFlowStep(step)) throw Error(`No such step: ${step}`); this._ui.stepLayouts["step:" + step] = attributes; } /** * Apply layout rules to a particular action, controlling where player prompts * and choices appear in relation to the playing area * * @param action - the name of the action as defined in {@link game#defineActions} * @param attributes - see {@link ActionLayout} * * @category UI */ layoutAction(action: string, attributes: ActionLayout) { this._ui.stepLayouts["action:" + action] = attributes; } /** * Remove all built-in default appearance. If any elements have not been given a * custom appearance, this causes them to be hidden. * * @category UI */ disableDefaultAppearance() { this._ui.disabledDefaultAppearance = true; } /** * Show bounding boxes around every layout * * @category UI */ showLayoutBoundingBoxes() { this._ui.boundingBoxes = true; } } ================================================ FILE: src/board/hex-grid.ts ================================================ import FixedGrid from "./fixed-grid.js"; import { times } from '../utils.js'; import type Game from './game.js'; import type { ElementUI } from "./element.js"; /** * A Hex grid. Create the HexGrid with 'rows' and 'columns' values to * automatically create the spaces. Optionally use {@link shape} and {@link * axes} to customize the type of hex. * @category Board * * @example * game.create(HexGrid, 'catan-board', { rows: 5, columns: 5, shape: 'hex' }) */ export default class HexGrid extends FixedGrid { /** * Determines which direction the rows and columns go within the * hex. E.g. with east-by-southwest axes, The cell at {row: 1, column: 2} is * directly east of {row: 1, column: 1}. The cell at {row: 2, column: 1} is * directly southwest of {row: 1, column: 1}. * @category Adjacency */ axes: 'east-by-southwest' | 'east-by-southeast' | 'southeast-by-south' | 'northeast-by-south' = 'east-by-southwest'; /** * Determines the overall shape of the spaces created. * * rhomboid - A rhomboid shape. This means a cell will exist at every row and * column combination. A 3x3 rhomboid hex contains 9 cells. * * hex - A hex shape. This means the hex will be at most row x columns but * will be missing cells at the corners. A 3x3 hex shape contains 7 cells. * * square - A square shape. This means the hex will be at most row x columns * but will be shaped to keep a square shape. Some cells will therefore have a * column value outside the range of columns. A 3x3 square hex contains 8 * cells, 3 on each side, and two in the middle. * @category Adjacency */ shape: 'square' | 'hex' | 'rhomboid' = 'rhomboid'; _ui: ElementUI = { layouts: [], appearance: {}, getBaseLayout: () => ({ rows: this.rows, columns: this.columns, sticky: true, alignment: 'center', direction: 'square', offsetColumn: { 'east-by-southwest': {x: 100, y: 0}, 'east-by-southeast': {x: 100, y: 0}, 'southeast-by-south': {x: 100, y: 50}, 'northeast-by-south': {x: 100, y: -50} }[this.axes], offsetRow: { 'east-by-southwest': {x: -50, y: 100}, 'east-by-southeast': {x: 50, y: 100}, 'southeast-by-south': {x: 0, y: 100}, 'northeast-by-south': {x: 0, y: 100} }[this.axes] }) }; _adjacentGridPositionsTo(column: number, row: number): [number, number][] { const positions: [number, number][] = []; if (column > 1) { positions.push([column - 1, row]); if (['east-by-southwest', 'northeast-by-south'].includes(this.axes)) { positions.push([column - 1, row - 1]); } if (['east-by-southeast', 'southeast-by-south'].includes(this.axes)) { positions.push([column - 1, row + 1]); } } if (column < this.columns) { positions.push([column + 1, row]); if (['east-by-southeast', 'southeast-by-south'].includes(this.axes)) { positions.push([column + 1, row - 1]); } if (['east-by-southwest', 'northeast-by-south'].includes(this.axes)) { positions.push([column + 1, row + 1]); } } if (row > 1) positions.push([column, row - 1]); if (row < this.rows) positions.push([column, row + 1]); return positions; } _gridPositions(): [number, number][] { const positions: [number, number][] = []; if (this.shape === 'hex') { const topCorner = Math.ceil((Math.min(this.rows, this.columns) - 1) / 2); const bottomCorner = Math.floor((Math.min(this.rows, this.columns) - 1) / 2); const topRight = ['east-by-southwest', 'northeast-by-south'].includes(this.axes); times(this.rows, row => times(this.columns - Math.max(topCorner + 1 - row, 0) - Math.max(row - this.rows + bottomCorner, 0), col => { positions.push([col + Math.max(topRight ? bottomCorner + row - this.rows : topCorner - row + 1, 0), row]); })); } else if (this.shape === 'square') { const squished = ['east-by-southeast', 'southeast-by-south'].includes(this.axes); if (['east-by-southwest', 'east-by-southeast'].includes(this.axes)) { times(this.rows, row => times(this.columns - (row % 2 ? 0 : 1), col => { positions.push([col + (squished ? 1 - Math.ceil(row / 2) : Math.floor(row / 2)), row]) })); } else { times(this.columns, col => times(this.rows - (col % 2 ? 0 : 1), row => { positions.push([col, row + (squished ? Math.floor(col / 2) : 1 - Math.ceil(col / 2))]) })); } } else { times(this.rows, row => times(this.columns, col => positions.push([col, row]))); } return positions; } _cornerPositions(): [number, number][] { if (this.shape === 'hex') { const topCorner = Math.ceil((Math.min(this.rows, this.columns) - 1) / 2); const bottomCorner = Math.floor((Math.min(this.rows, this.columns) - 1) / 2); if (['east-by-southwest', 'northeast-by-south'].includes(this.axes)) { return [ [1, 1], [this.columns - topCorner, 1], [1, Math.floor(this.rows / 2) + 1], [this.columns, Math.floor(this.rows / 2) + 1], [1 + bottomCorner, this.rows], [this.columns, this.rows], ]; } else { return [ [1 + topCorner, 1], [this.columns, 1], [1, Math.floor(this.rows / 2) + 1], [this.columns, Math.floor(this.rows / 2) + 1], [1, this.rows], [this.columns - bottomCorner, this.rows], ]; } } else if (this.shape === 'square') { if (['east-by-southwest'].includes(this.axes)) { return [ [1, 1], [this.columns, 1], [1 + Math.floor(this.rows / 2), this.rows], [this.columns - 1 + Math.ceil(this.rows / 2), this.rows], ]; } else if (['east-by-southeast'].includes(this.axes)) { return [ [1, 1], [this.columns, 1], [2 - Math.ceil(this.rows / 2), this.rows], [this.columns - Math.floor(this.rows / 2), this.rows], ]; } else if (['southeast-by-south'].includes(this.axes)) { return [ [1, 1], [1, this.rows], [this.columns, 2 - Math.ceil(this.columns / 2)], [this.columns, this.rows - Math.floor(this.columns / 2)], ]; } else { return [ [1, 1], [1, this.rows], [this.columns, 1 + Math.floor(this.columns / 2)], [this.columns, this.rows - 1 + Math.ceil(this.columns / 2)], ]; } } return [ [1, 1], [this.columns, 1], [1, this.rows], [this.columns, this.rows], ]; } } ================================================ FILE: src/board/index.ts ================================================ import GameElement from './element.js'; import ElementCollection from './element-collection.js'; export { GameElement, ElementCollection }; export { default as Space } from './space.js'; export { default as Piece } from './piece.js'; export { default as Stack } from './stack.js'; export { default as AdjacencySpace } from './adjacency-space.js'; export { default as ConnectedSpaceMap } from './connected-space-map.js'; export { default as FixedGrid } from './fixed-grid.js'; export { default as SquareGrid } from './square-grid.js'; export { default as HexGrid } from './hex-grid.js'; export { default as PieceGrid } from './piece-grid.js'; export { default as Game } from './game.js'; export type { ActionLayout } from './game.js'; export type { LayoutAttributes, Box, Vector } from './element.js'; export type { ElementFinder, Sorter } from './element-collection.js'; /** * Returns an {@link ElementCollection} by combining a list of {@link * GameElement}'s or {@link ElementCollection}'s, * @category Flow */ export function union(...queries: (T | ElementCollection | undefined)[]): ElementCollection { let c = new ElementCollection(); for (const q of queries) { if (q) { if ('forEach' in q) { q.forEach(e => c.includes(e) || c.push(e)); } else if (!c.includes(q)) { c.push(q); } } } return c; } ================================================ FILE: src/board/piece-grid.ts ================================================ import AdjacencySpace from "./adjacency-space.js"; import { rotateDirection } from './utils.js'; import Space from '../board/space.js'; import type Game from './game.js' import type Piece from './piece.js' import type { default as GameElement, Vector, Direction, DirectionWithDiagonals } from "./element.js"; import type { ElementContext, ElementUI } from './element.js'; /** * A grid that tracks adjacency for pieces placed within it. This is useful for * tile placement games, e.g. dominoes. Only pieces can be placed in a PieceGrid * and each must have a column and row. Pieces that have been assigned irregular * shapes using {@link Piece#setShape} will be rendered as taking up more than a * single cell in the grid, depending on their shape. Adjacency is calculated * for the entire shape. * @category Board */ export default class PieceGrid extends AdjacencySpace { /** * If true, the space will be automatically enlarged when new places are added * using {@link Action#placePiece}. * @category Adjacency */ extendableGrid: boolean = true; /** * Initial number of rows to render, but this can increase if {@link * extendableGrid} is true. * @category Adjacency */ rows: number = 1; /** * Initial number of columns to render, but this can increase if {@link * extendableGrid} is true. * @category Adjacency */ columns: number = 1; /** * Whether to consider tiles that touch at the corners to be adjacent when * using adjacenciesByCell. * @category Adjacency */ diagonalAdjacency: boolean = false _ui: ElementUI = { layouts: [], appearance: {}, getBaseLayout: () => ({ rows: this.rows, columns: this.columns, aspectRatio: 1, alignment: 'center', direction: 'square' }) }; constructor(ctx: ElementContext) { super(ctx); this.onEnter(Space, () => { throw Error(`Only pieces can be added to the PieceGrid ${this.name}`) }); } isAdjacent(el1: GameElement, el2: GameElement): boolean { return this.adjacenciesByCell(el1 as Piece, el2 as Piece).length > 0; } _sizeNeededFor(element: GameElement) { if (!element._size) return {width: 1, height: 1}; if (element.rotation % 180 === 90) return { width: element._size.height, height: element._size.width } return { width: element._size.width, height: element._size.height } } // internal cellsAround(piece: Piece, pos: Vector) { const adjacencies: Partial> = { up: piece._cellAt({y: pos.y - 1, x: pos.x}), down: piece._cellAt({y: pos.y + 1, x: pos.x}), left: piece._cellAt({y: pos.y, x: pos.x - 1}), right: piece._cellAt({y: pos.y, x: pos.x + 1}) }; if (this.diagonalAdjacency) { adjacencies.upleft = piece._cellAt({y: pos.y - 1, x: pos.x - 1}); adjacencies.upright = piece._cellAt({y: pos.y - 1, x: pos.x + 1}); adjacencies.downleft = piece._cellAt({y: pos.y + 1, x: pos.x - 1}); adjacencies.downright = piece._cellAt({y: pos.y + 1, x: pos.x + 1}); } return adjacencies; } // internal isOverlapping(piece: Piece, other?: Piece): boolean { if (!other) { return this._t.children.some(p => p !== piece && this.isOverlapping(piece, p as Piece)); } const p1: Vector = {x: piece.column!, y: piece.row!}; const p2: Vector = {x: other.column!, y: other.row!}; if (!piece._size && !other._size) return p2.y === p1.y && p2.x === p1.x; if (piece.rotation % 90 !== 0 || other.rotation % 90 !== 0) return false; // unsupported to calculate for irregular shapes at non-orthoganal orientations if (!piece._size) return (other._cellAt({y: p1.y - p2.y, x: p1.x - p2.x}) ?? ' ') !== ' '; if (!other._size) return (piece._cellAt({y: p2.y - p1.y, x: p2.x - p1.x}) ?? ' ') !== ' '; const gridSize1 = this._sizeNeededFor(piece); const gridSize2 = this._sizeNeededFor(other); if ( p2.y >= p1.y + gridSize1.height || p2.y + gridSize2.height <= p1.y || p2.x >= p1.x + gridSize1.width || p2.x + gridSize2.width <= p1.x ) return false; const size = Math.max(piece._size.height, piece._size.width); for (let x = 0; x !== size; x += 1) { for (let y = 0; y !== size; y += 1) { if ((piece._cellAt({x, y}) ?? ' ') !== ' ' && (other._cellAt({x: x + p1.x - p2.x, y: y + p1.y - p2.y}) ?? ' ') !== ' ') { return true; } } } return false; } // internal _fitPieceInFreePlace(piece: Piece, rows: number, columns: number, origin: {column: number, row: number}) { const tryLaterally = (vertical: boolean, d: number): boolean => { for (let lateral = 0; lateral < d + (vertical ? 0 : 1); lateral = -lateral + (lateral < 1 ? 1 : 0)) { if (vertical) { if (row + lateral <= 0 || row + lateral + gridSize.height - 1 > rows) continue; piece.row = row + lateral + origin.row - 1; } else { if (column + lateral <= 0 || column + lateral + gridSize.width - 1 > columns) continue; piece.column = column + lateral + origin.column - 1; } if (!this.isOverlapping(piece)) return true; } return false; } let gridSize = this._sizeNeededFor(piece); piece._rotation ??= 0; const row = piece.row === undefined ? Math.floor((rows - gridSize.height) / 2) : piece.row - origin.row + 1; const column = piece.column === undefined ? Math.floor((columns - gridSize.width) / 2) : piece.column - origin.column + 1; let possibleRotations = [piece._rotation, ...(piece._size ? [piece._rotation + 90, piece._rotation + 180, piece._rotation + 270] : [])]; while (possibleRotations.length) { piece._rotation = possibleRotations.shift()!; gridSize = this._sizeNeededFor(piece); for (let distance = 0; distance < rows || distance < columns; distance += 1) { if (column - distance > 0 && column - distance + gridSize.width - 1 <= columns) { piece.column = column - distance + origin.column - 1; if (tryLaterally(true, distance || 1)) return; } if (distance && column + distance > 0 && column + distance + gridSize.width - 1 <= columns) { piece.column = column + distance + origin.column - 1; if (tryLaterally(true, distance)) return; } if (distance && row - distance > 0 && row - distance + gridSize.height - 1 <= rows) { piece.row = row - distance + origin.row - 1; if (tryLaterally(false, distance)) return; } if (distance && row + distance > 0 && row + distance + gridSize.height - 1 <= rows) { piece.row = row + distance + origin.row - 1; if (tryLaterally(false, distance)) return; } } } piece.row = undefined; piece.column = undefined; } /** * Returns a list of other Pieces in the grid that have a touching edge (or * touching corner if {@link diagonalAdjacency} is true} with this shape. Each * item in the list contains the adjacent Piece, as well as the string * representation of cells in both pieces, as provided in {@link * Piece#setShape}. * @category Adjacency * * @param piece - The piece to check for adjacency * @param other - An optional other piece to check against. If undefined, it * will check for all pieces against the first argument * * @example * * A domino named "domino12" is adjacent to a domino named "domino34" with the * 2 touching the 3: * * domino12.setShape('12'); * domino34.setShape('34'); * board.adjacenciesByCell(domino12) => * [ * { * piece: domino34, * from: '2', * to: '3' * } * ] */ adjacenciesByCell(piece: Piece, other?: Piece): {piece: Piece, from: string, to: string}[] { if (!other) { return this._t.children.reduce( (all, p) => all.concat(p !== piece ? this.adjacenciesByCell(piece, p as Piece) : []), [] as {piece: Piece, from: string, to: string}[] ); } const p1: Vector = {x: piece.column!, y: piece.row!}; const p2: Vector = {x: other.column!, y: other.row!}; // unsupported to calculate at non-orthoganal orientations if (p1.y === undefined || p1.x === undefined || piece.rotation % 90 !== 0 || p2.y === undefined || p2.x === undefined || other.rotation % 90 !== 0) return []; if (!piece._size) { return Object.values(this.cellsAround(other, {x: p1.x - p2.x, y: p1.y - p2.y})).reduce( (all, adj) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: '.', to: adj}] : []), [] as {piece: Piece, from: string, to: string}[] ); } if (!other._size) { return Object.values(this.cellsAround(piece, {x: p2.x - p1.x, y: p2.y - p1.y})).reduce( (all, adj) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: adj, to: '.'}] : []), [] as {piece: Piece, from: string, to: string}[] ); } const gridSize1 = this._sizeNeededFor(piece); const gridSize2 = this._sizeNeededFor(other); if ( p2.y >= p1.y + 1 + gridSize1.height || p2.y + 1 + gridSize2.height <= p1.y || p2.x >= p1.x + 1 + gridSize1.width || p2.x + 1 + gridSize2.width <= p1.x ) return []; const size = Math.max(piece._size.height, piece._size.width); const adjacencies = [] as {piece: Piece, from: string, to: string}[]; for (let x = 0; x !== size; x += 1) { for (let y = 0; y !== size; y += 1) { const thisCell = piece._cellAt({x, y}); if (thisCell === undefined || thisCell === ' ') continue; for (const cell of Object.values(this.cellsAround(other, {x: x + p1.x - p2.x, y: y + p1.y - p2.y}))) { if (cell !== undefined && cell !== ' ') { adjacencies.push({piece: other, from: thisCell, to: cell}); } } } } return adjacencies; } /** * Returns a list of other Pieces in the grid that have a touching edge with * this shape. Each item in the list contains the adjacent Piece, as well as * the string representation of the edges in both pieces, as provided in * {@link Piece#setEdges}. * @category Adjacency * * @param piece - The piece to check for adjacency * @param other - An optional other piece to check against. If undefined, it * will check for all pieces against the first argument * * @example * * A tile named "corner" is adjacent directly to the left of a tile named * "bridge". * * corner.setEdges({ * up: 'road', * right: 'road' * }); * * bridge.setEdges({ * up: 'river', * down: 'river', * left: 'road' * right: 'road' * }); * * board.adjacenciesByCell(corner) => * [ * { * piece: bridge, * from: 'road', * to: 'road' * } * ] */ adjacenciesByEdge(piece: Piece, other?: Piece): {piece: Piece, from?: string, to?: string}[] { if (!other) { const children = this._t.children; return children.reduce( (all, p) => all.concat(p !== piece ? this.adjacenciesByEdge(piece, p as Piece) : []), [] as {piece: Piece, from?: string, to?: string}[] ); } const p1: Vector = {x: piece.column!, y: piece.row!}; const p2: Vector = {x: other.column!, y: other.row!}; if (p2.y === undefined || p2.x === undefined || other.rotation % 90 !== 0) return []; if (piece.rotation % 90 !== 0 || other.rotation % 90 !== 0) return []; // unsupported to calculate at non-orthoganal orientations if (!piece._size) { return (Object.entries(this.cellsAround(other, {x: p1.x - p2.x, y: p1.y - p2.y})) as [Direction, string][]).reduce( (all, [dir, adj]) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: undefined, to: other._size?.edges?.[adj][rotateDirection(dir, 180 - other.rotation)]}] : []), [] as {piece: Piece, from?: string, to?: string}[] ); } if (!other._size) { return (Object.entries(this.cellsAround(piece, {x: p2.x - p1.x, y: p2.y - p1.y})) as [Direction, string][]).reduce( (all, [dir, adj]) => all.concat(adj !== undefined && adj !== ' ' ? [{piece: other, from: piece._size?.edges?.[adj][rotateDirection(dir, 180 - piece.rotation)], to: undefined}] : []), [] as {piece: Piece, from?: string, to?: string}[] ); } const gridSize1 = this._sizeNeededFor(piece); const gridSize2 = this._sizeNeededFor(other); if ( p2.y >= p1.y + 1 + gridSize1.height || p2.y + 1 + gridSize2.height <= p1.y || p2.x >= p1.x + 1 + gridSize1.width || p2.x + 1 + gridSize2.width <= p1.x ) return []; const size = Math.max(piece._size.height, piece._size.width); const adjacencies = [] as {piece: Piece, from?: string, to?: string}[]; for (let x = 0; x !== size; x += 1) { for (let y = 0; y !== size; y += 1) { const thisCell = piece._cellAt({x, y}); if (thisCell === undefined || thisCell === ' ') continue; for (const [dir, cell] of Object.entries(this.cellsAround(other, {x: x + p1.x - p2.x, y: y + p1.y - p2.y})) as [Direction, string][]) { if (cell !== undefined && cell !== ' ') { adjacencies.push({ piece: other, from: piece._size?.edges?.[thisCell][rotateDirection(dir, -piece.rotation)], to: other._size?.edges?.[cell][rotateDirection(dir, 180 - other.rotation)] }); } } } } return adjacencies; } } ================================================ FILE: src/board/piece.ts ================================================ import GameElement from './element.js' import Space from './space.js' import type { ElementAttributes, ElementClass } from './element.js' import type Game from './game.js' import type Player from '../player/player.js'; import type { BaseGame } from './game.js'; /** * Pieces are game elements that can move during play * @category Board */ export default class Piece> extends GameElement { _visible?: { default: boolean, except?: number[] } createElement(className: ElementClass, name: string, attrs?: ElementAttributes): T { if (className === Space as unknown as ElementClass || Object.prototype.isPrototypeOf.call(Space, className)) { throw Error(`May not create Space "${name}" in Piece "${this.name}"`); } return super.createElement(className, name, attrs); } /** * Show this piece to all players * @category Visibility */ showToAll() { delete(this._visible); } /** * Show this piece only to the given player * @category Visibility */ showOnlyTo(player: Player | number) { if (typeof player !== 'number') player = player.position; this._visible = { default: false, except: [player] }; } /** * Show this piece to the given players without changing it's visibility to * any other players. * @category Visibility */ showTo(...player: Player[] | number[]) { if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position); if (this._visible === undefined) return; if (this._visible.default) { if (!this._visible.except) return; this._visible.except = this._visible.except.filter(i => !(player as number[]).includes(i)); } else { this._visible.except = Array.from(new Set([...(this._visible.except instanceof Array ? this._visible.except : []), ...(player as number[])])) } } /** * Hide this piece from all players * @category Visibility */ hideFromAll() { this._visible = {default: false}; } /** * Hide this piece from the given players without changing it's visibility to * any other players. * @category Visibility */ hideFrom(...player: Player[] | number[]) { if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position); if (this._visible?.default === false && !this._visible.except) return; if (this._visible === undefined || this._visible.default === true) { this._visible = { default: true, except: Array.from(new Set([...(this._visible?.except instanceof Array ? this._visible.except : []), ...(player as number[])])) }; } else { if (!this._visible.except) return; this._visible.except = this._visible.except.filter(i => !(player as number[]).includes(i)); } } /** * Returns whether this piece is visible to the given player * @category Visibility */ isVisibleTo(player: Player | number) { if (typeof player !== 'number') player = player.position; if (this._visible === undefined) return true; if (this._visible.default) { return !this._visible.except || !(this._visible.except.includes(player)); } else { return this._visible.except?.includes(player) || false; } } /** * Returns whether this piece is visible to all players, or to the current * player if called when in a player context (during an action taken by a * player or while the game is viewed by a given player.) * @category Visibility */ isVisible() { if (this._ctx.player) return this.isVisibleTo(this._ctx.player.position); return this._visible?.default !== false && (this._visible?.except ?? []).length === 0; } /** * Provide list of attributes that remain visible even when these pieces are * not visible to players. E.g. In a game with multiple card decks with * different backs, identified by Card#deck, the identity of the card when * face-down is hidden, but the deck it belongs to is not, since the card art * on the back would identify the deck. In this case calling * `Card.revealWhenHidden('deck')` will cause all attributes other than 'deck' * to be hidden when the card is face down, while still revealing which deck * it is. * @category Visibility */ static revealWhenHidden>(this: ElementClass, ...attrs: (string & keyof T)[]): void { this.visibleAttributes = attrs; } /** * Move this piece into another element. This triggers any {@link * Space#onEnter | onEnter} callbacks in the destination. * @category Structure * * @param to - Destination element * @param options.position - Place the piece into a specific numbered position * relative to the other elements in this space. Positive numbers count from * the beginning. Negative numbers count from the end. * @param options.fromTop - Place the piece into a specific numbered position counting * from the first element * @param options.fromBottom - Place the piece into a specific numbered position * counting from the last element */ putInto(to: GameElement, options?: {position?: number, row?: number, column?: number, fromTop?: number, fromBottom?: number}) { if (to.isDescendantOf(this)) throw Error(`Cannot put ${this} into itself`); let pos: number = to._t.order === 'stacking' ? 0 : to._t.children.length; if (options?.position !== undefined) pos = options.position >= 0 ? options.position : to._t.children.length + options.position + 1; if (options?.fromTop !== undefined) pos = options.fromTop; if (options?.fromBottom !== undefined) pos = to._t.children.length - options.fromBottom; const previousParent = this._t.parent; const position = this.position(); if (this.hasMoved() || to.hasMoved()) this.game.addDelay(); const refs = previousParent === to && options?.row === undefined && options?.column === undefined && to.childRefsIfObscured(); this._t.parent!._t.children.splice(position, 1); this._t.parent = to; to._t.children.splice(pos, 0, this); if (refs) to.assignChildRefs(refs); if (previousParent !== to && previousParent instanceof Space) previousParent.triggerEvent("exit", this); if (previousParent !== to && this._ctx.trackMovement) this._t.moved = true; delete this.column; delete this.row; if (options?.row !== undefined) this.row = options.row; if (options?.column !== undefined) this.column = options.column; if (previousParent !== to && to instanceof Space) to.triggerEvent("enter", this); } cloneInto(this: T, into: GameElement): T { let attrs = this.attributeList(); delete attrs.column; delete attrs.row; const clone = into.createElement(this.constructor as ElementClass, this.name, attrs); if (into._t.order === 'stacking') { into._t.children.unshift(clone); } else { into._t.children.push(clone); } clone._t.parent = into; clone._t.order = this._t.order; for (const child of this._t.children) if (child instanceof Piece) child.cloneInto(clone); return clone; } /** * Remove this piece from the playing area and place it into {@link * Game#pile} * @category Structure */ remove() { return this.putInto(this._ctx.removed); } } ================================================ FILE: src/board/single-layout.ts ================================================ import Space from './space.js'; import type { BaseGame } from './game.js'; import type { ElementUI } from './element.js'; /** * Abstract base class for all adjacency spaces */ export default abstract class SingleLayout extends Space { _ui: ElementUI = { layouts: [], appearance: {}, getBaseLayout: () => ({ alignment: 'center', direction: 'square' }) }; /** * Single layout space can only contain elements of a certain type. Rather * than adding multiple, overlapping layouts for different elements, there is * a single layout that can be modified using {@link configureLayout}. * @category UI */ layout() { throw Error("Space cannot have additional layouts added. The layout can instead be configured with configureLayout."); } resetUI() { if (!this._ui.layouts.length) this.configureLayout({}); this._ui.appearance = {}; for (const child of this._t.children) child.resetUI(); } } ================================================ FILE: src/board/space.ts ================================================ import GameElement from './element.js' import type { BaseGame } from './game.js'; import type Player from '../player/player.js'; import type { ElementClass, ElementAttributes } from './element.js'; import { Piece } from '../index.js'; export type ElementEventHandler = {callback: (el: T) => void} & Record; /** * Spaces are areas of the game. The spaces of your game are declared during * setup in {@link createGame} and never change during play. * @category Board */ export default class Space> extends GameElement { static unserializableAttributes = [...GameElement.unserializableAttributes, '_eventHandlers', '_visOnEnter', '_screen']; _eventHandlers: { enter: ElementEventHandler[], exit: ElementEventHandler[], } = { enter: [], exit: [] }; _visOnEnter?: { default: boolean, except?: number[] | 'owner' } _screen?: 'all' | 'all-but-owner' | number[]; /** * Show pieces to all players when they enter this space * @category Visibility */ contentsWillBeShown() { this._visOnEnter = {default: true}; } /** * Show pieces when they enter this space to its owner * @category Visibility */ contentsWillBeShownToOwner() { this._visOnEnter = {default: false, except: 'owner'}; } /** * Show piece to these players when they enter this space * @category Visibility */ contentsWillBeShownTo(...players: P[]) { this._visOnEnter = {default: false, except: players.map(p => p.position)}; } /** * Hide pieces to all players when they enter this space * @category Visibility */ contentsWillBeHidden() { this._visOnEnter = {default: false}; } /** * Hide piece to these players when they enter this space * @category Visibility */ contentsWillBeHiddenFrom(...players: P[]) { this._visOnEnter = {default: true, except: players.map(p => p.position)}; } /** * Call this to screen view completely from players. Blocked spaces completely * hide their contents, like a physical screen. No information about the * number, type or movement of contents inside this Space will be revealed to * the specified players * * @param players = Players for whom the view is blocked * @category Visibility */ blockViewFor(players: 'all' | 'none' | 'all-but-owner' | Player[]) { this._screen = players === 'none' ? undefined : players instanceof Array ? players.map(p => p.position) : players } isSpace() { return true; } create(className: ElementClass, name: string, attributes?: ElementAttributes): T { const el = super.create(className, name, attributes); if ('showTo' in el) this.triggerEvent("enter", el as unknown as Piece); return el; } addEventHandler(type: keyof Space['_eventHandlers'], handler: ElementEventHandler) { if (this._ctx.gameManager?.phase === 'started') throw Error('Event handlers cannot be added once game has started.'); this._eventHandlers[type].push(handler); } /** * Attach a callback to this space for every element that enters or is created * within. * @category Structure * * @param type - the class of element that will trigger this callback * @param callback - Callback will be called each time an element enters, with * the entering element as the only argument. * * @example * deck.onEnter(Card, card => card.hideFromAll()) // card placed in the deck are automatically turned face down */ onEnter(type: ElementClass, callback: (el: T) => void) { this.addEventHandler("enter", { callback, type }); } /** * Attach a callback to this space for every element that is moved out of this * space. * @category Structure * * @param type - the class of element that will trigger this callback * @param callback - Callback will be called each time an element exits, with * the exiting element as the only argument. * * @example * deck.onExit(Card, card => card.showToAll()) // cards drawn from the deck are automatically turned face up */ onExit(type: ElementClass, callback: (el: T) => void) { this.addEventHandler("exit", { callback, type }); } triggerEvent(event: keyof Space['_eventHandlers'], element: Piece) { if (this._visOnEnter) { element._visible = { default: this._visOnEnter.default, except: this._visOnEnter.except === 'owner' ? (this.owner ? [this.owner.position] : undefined) : this._visOnEnter.except } } for (const handler of this._eventHandlers[event]) { if (event === 'enter' && !(element instanceof handler.type)) continue; if (event === 'exit' && !(element instanceof handler.type)) continue; handler.callback(element); } } } ================================================ FILE: src/board/square-grid.ts ================================================ import FixedGrid from "./fixed-grid.js"; import { times } from '../utils.js'; import type Game from './game.js'; /** * A Square grid. Create the SquareGrid with 'rows' and 'columns' values to * automatically create the spaces. * @category Board * * @example * game.create(SquareGrid, 'chess-board', { rows: 8, columns: 8 }) */ export default class SquareGrid extends FixedGrid { /** * Optionally add a measurement for diagonal adjacencies on this grid. If * undefined, diagonals are not considered directly adjacent. * @category Adjacency */ diagonalDistance?: number; _adjacentGridPositionsTo(column: number, row: number): [number, number, number?][] { const positions: [number, number, number?][] = []; if (column > 1) { positions.push([column - 1, row]); if (this.diagonalDistance !== undefined) { positions.push([column - 1, row - 1, this.diagonalDistance]); positions.push([column - 1, row + 1, this.diagonalDistance]); } } if (column < this.columns) { positions.push([column + 1, row]); if (this.diagonalDistance !== undefined) { positions.push([column + 1, row - 1, this.diagonalDistance]); positions.push([column + 1, row + 1, this.diagonalDistance]); } } positions.push([column, row - 1]); positions.push([column, row + 1]); return positions; } _gridPositions(): [number, number][] { const positions: [number, number][] = []; times(this.rows, row => times(this.columns, col => positions.push([col, row]))); return positions; } } ================================================ FILE: src/board/stack.ts ================================================ import SingleLayout from './single-layout.js'; import type { BaseGame } from './game.js'; import type { ElementUI } from './element.js'; /** * A Stack hides all movement information within to avoid exposing the identity * of pieces inside the stack. Useful for decks of cards where calling * `shuffle()` should prevent players from knowing the order of the cards. By * default elements in a stack are hidden and are rendered as a stack with a * small offset and a limited number of items. Use configureLayout to change * this. */ export default class Stack extends SingleLayout { _ui: ElementUI = { layouts: [], appearance: {}, getBaseLayout: () => ({ columns: 1, offsetRow: { x: 2, y: 2 }, scaling: 'fit', alignment: 'center', direction: 'ltr', limit: 10, }) }; afterCreation() { this._t.order = 'stacking'; this.contentsWillBeHidden(); } } ================================================ FILE: src/board/utils.ts ================================================ import type { Direction } from './element.js'; export function rotateDirection(dir: Direction, rotation: number) { rotation = (rotation % 360 + 360) % 360; if (rotation === 0) return dir; let angle: number; if (dir === 'up') { angle = rotation; } else if (dir === 'down') { angle = (rotation + 180) % 360; } else if (dir === 'right') { angle = (rotation + 90) % 360; } else { angle = (rotation + 270) % 360; } if (angle === 0) { return 'up'; } else if (angle === 90) { return 'right'; } else if (angle === 180) { return 'down'; } return 'left'; } ================================================ FILE: src/components/d6/assets/index.scss ================================================ .D6 { > ol { display: grid; grid-template-columns: 1fr; grid-template-rows: 1fr; list-style-type: none; transform-style: preserve-3d; width: 100%; height: 100%; margin: 0; padding: 0; &[data-spin="up"] { transition: transform 2s ease-out; } &[data-spin="down"] { transition: transform 2s ease-out; } .die-face { background: #eee; box-shadow: inset 0 0 0.4em rgba(0, 0, 0, 0.4); border-radius: .3em; display: grid; grid-column: 1; grid-row: 1; grid-template-areas: "one two three" "four five six" "sup eight nine"; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); height: 100%; padding: .7em; width: 100%; outline: .01em solid #333; .dot { align-self: center; background-color: #333; border-radius: 50%; box-shadow: inset -0.12em 0.12em 0.25em rgba(255, 255, 255, 0.3); display: block; height: 1.25em; justify-self: center; width: 1.25em; } &[data-face="1"] { transform: rotate3d(0, 0, 0, 90deg) translateZ(3.1em); } &[data-face="2"] { transform: rotate3d(-1, 0, 0, 90deg) translateZ(3.1em); } &[data-face="3"] { transform: rotate3d(0, 1, 0, 90deg) translateZ(3.1em); } &[data-face="4"] { transform: rotate3d(0, -1, 0, 90deg) translateZ(3.1em); } &[data-face="5"] { transform: rotate3d(1, 0, 0, 90deg) translateZ(3.1em); } &[data-face="6"] { transform: rotate3d(0, 1, 0, 180deg) translateZ(3.1em); } &[data-face="1"] .dot:nth-of-type(1) { grid-area: five; } &[data-face="2"] .dot:nth-of-type(1) { grid-area: one; } &[data-face="2"] .dot:nth-of-type(2) { grid-area: nine; } &[data-face="3"] .dot:nth-of-type(1) { grid-area: one; } &[data-face="3"] .dot:nth-of-type(2) { grid-area: five; } &[data-face="3"] .dot:nth-of-type(3) { grid-area: nine; } &[data-face="4"] .dot:nth-of-type(1) { grid-area: one; } &[data-face="4"] .dot:nth-of-type(2) { grid-area: three; } &[data-face="4"] .dot:nth-of-type(3) { grid-area: sup; } &[data-face="4"] .dot:nth-of-type(4) { grid-area: nine; } &[data-face="5"] .dot:nth-of-type(1) { grid-area: one; } &[data-face="5"] .dot:nth-of-type(2) { grid-area: three; } &[data-face="5"] .dot:nth-of-type(3) { grid-area: five; } &[data-face="5"] .dot:nth-of-type(4) { grid-area: sup; } &[data-face="5"] .dot:nth-of-type(5) { grid-area: nine; } &[data-face="6"] .dot:nth-of-type(1) { grid-area: one; } &[data-face="6"] .dot:nth-of-type(2) { grid-area: three; } &[data-face="6"] .dot:nth-of-type(3) { grid-area: four; } &[data-face="6"] .dot:nth-of-type(4) { grid-area: six; } &[data-face="6"] .dot:nth-of-type(5) { grid-area: sup; } &[data-face="6"] .dot:nth-of-type(6) { grid-area: nine; } } } &[data-current="1"] [data-spin="up"] { transform: rotateX(360deg) rotateY(720deg) rotateZ(360deg); } &[data-current="2"] [data-spin="up"] { transform: rotateX(450deg) rotateY(720deg) rotateZ(360deg); } &[data-current="3"] [data-spin="up"] { transform: rotateX(360deg) rotateY(630deg) rotateZ(360deg); } &[data-current="4"] [data-spin="up"] { transform: rotateX(360deg) rotateY(810deg) rotateZ(360deg); } &[data-current="5"] [data-spin="up"] { transform: rotateX(270deg) rotateY(720deg) rotateZ(360deg); } &[data-current="6"] [data-spin="up"] { transform: rotateX(360deg) rotateY(900deg) rotateZ(360deg); } &[data-current="1"] [data-spin="down"] { transform: rotateX(-360deg) rotateY(-720deg) rotateZ(-360deg); } &[data-current="2"] [data-spin="down"] { transform: rotateX(-270deg) rotateY(-720deg) rotateZ(-360deg); } &[data-current="3"] [data-spin="down"] { transform: rotateX(-360deg) rotateY(-810deg) rotateZ(-360deg); } &[data-current="4"] [data-spin="down"] { transform: rotateX(-360deg) rotateY(-630deg) rotateZ(-360deg); } &[data-current="5"] [data-spin="down"] { transform: rotateX(-450deg) rotateY(-720deg) rotateZ(-360deg); } &[data-current="6"] [data-spin="down"] { transform: rotateX(-360deg) rotateY(-900deg) rotateZ(-360deg); } } ================================================ FILE: src/components/d6/d6.ts ================================================ import Piece from '../../board/piece.js'; import type Game from '../../board/game.js'; /** * Specialized piece for representing 6-sided dice * * @example * import { D6 } from '@boardzilla/core/components'; * ... * game.create(D6, 'my-die'); * @category Board */ export default class D6 extends Piece { sides: number = 6; /** * Currently shown face * @category D6 */ current: number = 1; rollSequence: number = 0; /** * Randomly choose a new face, causing the roll animation * @category D6 */ roll() { this.current = Math.ceil((this.game.random || Math.random)() * this.sides); this.rollSequence = this._ctx.gameManager.sequence; } } ================================================ FILE: src/components/d6/index.ts ================================================ export {default as D6} from './d6.js'; export {default as useD6} from './useD6.js'; ================================================ FILE: src/components/d6/useD6.tsx ================================================ import React, { useEffect, useRef, useState } from 'react'; import dice from './assets/dice.ogg'; import { times } from '../../utils.js'; import D6 from './d6.js'; import './assets/index.scss'; import type { BaseGame } from '../../board/game.js'; /** * Adds an animated spinning appearance to the {@link D6} class * * @example * import { useD6 } from '@boardzilla/core/components'; * * // then in the layout() method * useD6(game); */ const D6Component = ({ die }: { die: D6 }) => { const diceAudio = useRef(null); const lastRollSequence = useRef(); const [flip, setFlip] = useState(false); useEffect(() => { if (die.rollSequence === Math.ceil(die._ctx.gameManager.sequence - 1) && lastRollSequence.current !== undefined && lastRollSequence.current !== die.rollSequence) { diceAudio.current?.play(); setFlip(!flip); } lastRollSequence.current = die.rollSequence; }, [die, die.rollSequence, flip, setFlip]); return ( <>

    {[1,2,3,4,5,6].map(dots => (
  1. {times(dots, d => )}
  2. ))}
); } export default (game: BaseGame) => { game.all(D6).appearance({ render: (die: D6) => , aspectRatio: 1, }); } ================================================ FILE: src/components/flippable/Flippable.tsx ================================================ import React from 'react'; import './assets/index.scss'; /** * A Piece with two sides: front and back. When the Piece is hidden, the back is * shown. When visible, the front is shown. When the visibility changes, the CSS * animates a 3d flip. * * @example * import { Flippable } from '@boardzilla/core/components'; * ... * Piece.appearance({ * render: piece => ( * * {piece.name} * * * ); * }); * // The DOM structure inside the Piece element will be: *
*
{piece.name}
*
*
*/ const Flippable = ({ children }: { children?: React.ReactNode, }) => { let frontContent: React.ReactNode = null; let backContent: React.ReactNode = null; React.Children.forEach(children, child => { if (!React.isValidElement(child)) return; if (child.type === Flippable.Front) { frontContent = child; } else if (child.type === Flippable.Back) { backContent = child; } else { throw Error("Flippable must contain only and "); } }); return (
{frontContent}
{backContent}
); } export default Flippable; const Front = ({ children }: { children: React.ReactNode }) => children; Flippable.Front = Front; const Back = ({ children }: { children: React.ReactNode }) => children; Flippable.Back = Back; ================================================ FILE: src/components/flippable/assets/index.scss ================================================ .bz-flippable { #game:not(.browser-firefox) & { perspective: 40vw; } width: 100%; height: 100%; transition: transform 0.6s; transform-style: preserve-3d; #game:not(.browser-firefox) & { transform-style: preserve-3d; } position: relative; .front, .back { position: absolute; top: 0; left: 0; width: 100%; height: 100%; backface-visibility: hidden; } /* back, initially hidden pane */ .back { transform: rotateY(180deg); } /* flip the pane when hovered */ :not([data-name]) > & { transform: rotateY(180deg); } } ================================================ FILE: src/components/flippable/index.ts ================================================ export {default as Flippable} from './Flippable.js'; ================================================ FILE: src/components/index.ts ================================================ export { D6, useD6 } from './d6/index.js'; export { Flippable } from './flippable/index.js'; ================================================ FILE: src/flow/action-step.ts ================================================ import Flow from './flow.js'; import { deserializeObject, serializeObject } from '../action/utils.js'; import { FlowControl, InterruptControl, interruptSignal } from './enums.js'; import type { FlowBranchNode, FlowDefinition, FlowStep } from './flow.js'; import type { Player } from '../player/index.js'; import type { Argument, ActionStub } from '../action/action.js'; import type { InterruptSignal, SubflowSignal } from './enums.js'; export type ActionStepPosition = { // turn taken by `player` player: number, name: string, args: Record, } | undefined // waiting; export default class ActionStep extends Flow { players?: Player | Player[] | ((args: Record) => Player | Player[]); // if restricted to a particular player list. otherwise uses current player position: ActionStepPosition; actions: { name: string, prompt?: string | ((args: Record) => string), args?: Record | ((args: Record) => Record), do?: FlowDefinition }[]; type: FlowBranchNode['type'] = "action"; prompt?: string | ((args: Record) => string); // needed if multiple board actions condition?: (args: Record) => boolean; continueIfImpossible?: boolean; repeatUntil?: boolean; description?: string; skipIf: 'always' | 'never' | 'only-one'; constructor({ name, player, players, actions, prompt, description, optional, condition, continueIfImpossible, repeatUntil, skipIf }: { name?: string, players?: Player[] | ((args: Record) => Player[]), player?: Player | ((args: Record) => Player), actions: (string | { name: string, prompt?: string | ((args: Record) => string), args?: Record | ((args: Record) => Record), do?: FlowDefinition })[], prompt?: string | ((args: Record) => string), condition?: (args: Record) => boolean; continueIfImpossible?: boolean; repeatUntil?: string | ((args: Record) => string); description?: string, optional?: string | ((args: Record) => string), skipIf?: 'always' | 'never' | 'only-one', }) { super({ name }); this.actions = actions.map(a => typeof a === 'string' ? {name: a} : a); this.prompt = prompt; if (repeatUntil) { this.repeatUntil = true; this.actions.push({name: '__pass__', prompt: typeof repeatUntil === 'function' ? repeatUntil(this.flowStepArgs()) : repeatUntil}); } else if (optional) { this.actions.push({name: '__pass__', prompt: typeof optional === 'function' ? optional(this.flowStepArgs()) : optional}); } this.description = description; this.condition = condition; this.continueIfImpossible = continueIfImpossible ?? false; this.skipIf = skipIf ?? 'always'; this.players = players ?? player; } reset() { this.setPosition(undefined); } thisStepArgs() { if (this.position?.name && this.position?.args) { // want to remove return {[this.position.name]: this.position.args}; } } setPosition(position: ActionStepPosition, sequence?: number) { super.setPosition(position, sequence); if (this.awaitingAction()) { const players = this.getPlayers(); if (players) this.gameManager.players.setCurrent(players); } } getPlayers() { if (this.players) { const players = typeof this.players === 'function' ? this.players(this.flowStepArgs()) : this.players; return (players instanceof Array ? players : [players]).map(p => p.position); } } awaitingAction() { return !this.position && (!this.condition || this.condition(this.flowStepArgs())); } currentBlock() { if (this.position) { const actionName = (this.position as { player: number, name: string, args: Record }).name; // turn taken by `player` const step = this.actions.find(a => a.name === actionName)?.do; if (step) return step; } } // current actions that can process. does not check player allowedActions(): string[] { return this.position ? [] : this.actions.map(a => a.name); } actionNeeded(player?: Player): { step?: string, prompt?: string, description?: string, actions: ActionStub[], continueIfImpossible?: boolean, skipIf: 'always' | 'never' | 'only-one'; } | undefined { if (!this.position) { if (!player || player.isCurrent()) { return { prompt: typeof this.prompt === 'function' ? this.prompt(this.flowStepArgs()) : this.prompt, description: this.description, step: this.name, actions: this.actions.map(action => ({ name: action.name, prompt: typeof action.prompt === 'function' ? action.prompt(this.flowStepArgs()) : action.prompt, args: typeof action.args === 'function' ? action.args(this.flowStepArgs()) : action.args, })), continueIfImpossible: this.continueIfImpossible, skipIf: this.skipIf, } } } } // returns error (string) or subflow {args, name} or ok (undefined) processMove(move: { player: number, name: string, args: Record, }): string | SubflowSignal['data'][] | undefined { if ((move.name !== '__continue__' || !this.continueIfImpossible) && !this.allowedActions().includes(move.name)) { throw Error(`No action ${move.name} available at this point. Waiting for ${this.allowedActions().join(", ")}`); } const gameManager = this.gameManager; if (!gameManager.players.currentPosition.includes(move.player)) { throw Error(`Move ${move.name} from player #${move.player} not allowed. Current players: #${gameManager.players.currentPosition.join('; ')}`); } const player = gameManager.players.atPosition(move.player); if (!player) return `No such player position: ${move.player}`; if (move.name === '__pass__' || move.name === '__continue__') { this.setPosition(move); return; } const gameAction = gameManager.getAction(move.name, player); const error = gameAction._process(player, move.args); if (error) { // failed with a selection required return error; } else { // succeeded this.setPosition(this.position ? {...this.position} : move); if (interruptSignal[0]) { const interrupt = interruptSignal.splice(0); if (interrupt[0].signal === InterruptControl.subflow) return (interrupt as SubflowSignal[]).map(s => s.data); const loop = this.currentLoop(interrupt[0].data); if (!loop) { if (interrupt[0].data) throw Error(`No loop found "${interrupt[0].data}" for interrupt`); if (interrupt[0].signal === InterruptControl.continue) throw Error("Cannot use Do.continue when not in a loop"); if (interrupt[0].signal === InterruptControl.repeat) throw Error("Cannot use Do.repeat when not in a loop"); throw Error("Cannot use Do.break when not in a loop"); } else { loop.interrupt(interrupt[0].signal); return; } } } } playOneStep(): InterruptSignal[] | FlowControl | Flow { return this.awaitingAction() ? this : super.playOneStep(); } advance() { if (!this.repeatUntil || this.position?.name === '__pass__') return FlowControl.complete; this.reset(); return FlowControl.ok; } toJSON(forPlayer=true) { if (this.position) { const json: any = { player: this.position.player, name: this.position.name, args: serializeObject(this.position.args, forPlayer), }; return json; } return undefined; } fromJSON(position: any) { if (!position) return undefined; return !('player' in position) ? position : { ...position, args: deserializeObject(position.args ?? {}, this.gameManager.game) as Record, }; } allSteps() { return this.actions.map(a => a.do).reduce((a, f) => f ? a.concat(f) : a, []); } toString(): string { return `player-action${this.name ? ":" + this.name : ""} (player #${this.top.gameManager.players.currentPosition}: ${this.allowedActions().join(", ")}${this.block instanceof Array ? ' item #' + this.sequence : ''})`; } visualize(top: Flow) { const args = this.position && '{' + Object.entries(this.position.args).map(([k, v]) => `${k}: ${v}`).join(', ') + '}' return this.visualizeBlocks({ type: 'playerActions', name: this.position?.name ?? '', top, blocks: Object.fromEntries( this.actions.filter(a => a.name !== '__pass__').map(a => [a.name, a.do ? (a.do instanceof Array ? a.do : [a.do]) : undefined]) ) as Record, block: this.position?.name, position: args ?? top.gameManager.players.allCurrent().map(p => p.name).join(', ') }); } } ================================================ FILE: src/flow/each-player.ts ================================================ import ForLoop from './for-loop.js'; import { Player } from '../player/index.js'; import { serializeSingleArg, deserializeSingleArg } from '../action/utils.js'; import type { FlowArguments, FlowDefinition } from './flow.js'; import type Flow from './flow.js'; export default class EachPlayer

extends ForLoop

{ continueUntil?: (p: P) => boolean; turns?: number; constructor({ name, startingPlayer, nextPlayer, turns, continueUntil, do: block }: { name: string, startingPlayer?: ((a: FlowArguments) => P) | P, nextPlayer?: (p: P) => P, turns?: number, continueUntil?: (p: P) => boolean, do: FlowDefinition, }) { let initial: (r: Record) => P if (startingPlayer) { initial = () => startingPlayer instanceof Function ? startingPlayer(this.flowStepArgs()) : startingPlayer } else { initial = () => this.gameManager.players[0] as P; } let next = (player: P) => (nextPlayer ? nextPlayer(player) : this.gameManager.players.after(player)) as P; super({ name, initial, next, while: () => true, do: block }); this.whileCondition = position => continueUntil !== undefined ? !continueUntil(position.value) : position.index < this.gameManager.players.length * (this.turns || 1) this.turns = turns; } setPosition(position: typeof this.position, sequence?: number, reset=true) { if (position.value && position.value.position !== this.position?.value.position) { this.gameManager.players.setCurrent(position.value); } super.setPosition(position, sequence, reset); } toJSON() { return { index: this.position.index, value: this.position.value ? serializeSingleArg(this.position.value) : undefined }; } fromJSON(position: any) { return { index: position.index, value: position.value ? deserializeSingleArg(position.value, this.gameManager.game) as P: undefined } } allSteps() { return this.block; } toString(): string { return `each-player${this.name ? ":" + this.name : ""} (player #${this.position?.value?.position}${this.block instanceof Array ? ', item #' + this.sequence: ''})`; } visualize(top: Flow) { return this.visualizeBlocks({ type: 'eachPlayer', top, blocks: { do: this.block instanceof Array ? this.block : [this.block] }, block: 'do', position: this.position?.value, }); } } ================================================ FILE: src/flow/enums.ts ================================================ /** * Functions for interrupting flows * * These functions all interrupt the flow in some. Upon calling one, the flow * will complete its current step and then proceed with whatever type of * interrupt was provided. * * Three of these functions are for interrupting loops: `Do.break`, `Do.repeat`, * and `Do.continue`. They can be called from anywhere inside a looping flow * ({@link loop}, {@link whileLoop}, {@link forLoop}, {@link forEach}, {@link * eachPlayer}) to interrupt the flow, with each one resuming the flow * differently. * * `Do.subflow` can be called anywhere and causes the flow to jump to another * subflow. When that subflow completes, the game flow will return to the * current flow, at the step immediately after the one that called `Do.subflow`. * * `Do.break` causes the flow to exit loop and resume after the loop, like the * `break` keyword in Javascript. * * `Do.continue` causes the flow to skip the rest of the current loop iteration * and restart the loop at the next iteration, like the `continue` keyword in * Javascript. * * `Do.repeat` causes the flow to skip the rest of the current loop iteration * and restart the same iteration of the loop. * * @example * // each player can shout as many times as they like * eachPlayer({ name: 'player', do: ( * playerActions({ actions: [ * { name: 'shout', do: Do.repeat }, * 'pass' * ]}), * ]}); * * // each player can decide to shout, and if so, may subsequently apologize * eachPlayer({ name: 'player', do: [ * playerActions({ actions: [ * { name: 'shout', do: Do.continue }, // if shouting, skip to the next player * 'pass' * ]}), * playerActions({ actions: [ 'apologize', 'pass' ] }), * ]}); * * // each player can take a card but if the card is a match, it ends this round * eachPlayer({ name: 'player', do: ( * playerActions({ actions: [ * { name: 'takeCard', do: ({ takeCard }) => if (takeCard.card.isMatch()) Do.break() }, * 'pass' * ]}), * ]}); * * @category Flow */ export const Do = { repeat: (loop?: string | Record) => interrupt({ signal: InterruptControl.repeat, data: typeof loop === 'string' ? loop : undefined }), continue: (loop?: string | Record) => interrupt({ signal: InterruptControl.continue, data: typeof loop === 'string' ? loop : undefined }), break: (loop?: string | Record) => interrupt({ signal: InterruptControl.break, data: typeof loop === 'string' ? loop : undefined }), subflow: (flow: string, args?: Record) => interrupt({ signal: InterruptControl.subflow, data: {name: flow, args} }), } type LoopInterruptSignal = { signal: InterruptControl.repeat | InterruptControl.continue | InterruptControl.break, data?: string } export type SubflowSignal = { signal: InterruptControl.subflow, data: {name: string, args?: Record} } export type InterruptSignal = LoopInterruptSignal | SubflowSignal /** @internal */ export const interruptSignal: InterruptSignal[] = []; function interrupt({ signal, data }: InterruptSignal) { if (signal === InterruptControl.subflow) { if (interruptSignal.every(s => s.signal === InterruptControl.subflow)) { interruptSignal.push({data, signal}); // subflows can be queued but will not override loop interrupt } } else { // loop interrupts cancel other signals interruptSignal.splice(0); interruptSignal[0] = {data, signal}; } } /** @internal */ export enum InterruptControl { repeat = "__REPEAT__", continue = "__CONTINUE__", break = "__BREAK__", subflow = "__SUBFLOW__", } /** @internal */ export enum FlowControl { ok = "__OK__", complete = "__COMPLETE__" } ================================================ FILE: src/flow/every-player.ts ================================================ import Flow from './flow.js'; import { FlowControl } from './enums.js'; import type { FlowDefinition, FlowBranchNode, FlowBranchJSON } from './flow.js'; import type { Player, PlayerCollection } from '../player/index.js'; import type { Argument } from '../action/action.js'; import type { SubflowSignal, InterruptSignal } from './enums.js'; export type EveryPlayerPosition = {positions: FlowBranchJSON[][], sequences: number[], completed: (boolean | undefined)[]}; export default class EveryPlayer

extends Flow { position: EveryPlayerPosition; players?: P[]; value: number; // player temporarily looking at completed: (boolean | undefined)[] = []; block: FlowDefinition; type: FlowBranchNode['type'] = 'parallel'; constructor({ players, do: block, name }: { players?: P[], do: FlowDefinition, name?: string }) { super({ do: block, name }); this.players = players; } reset() { this.value = -1; this.completed = []; this.setPosition({positions: [], sequences: [], completed: []}); } thisStepArgs() { if (this.name) { const currentPlayer = this.getPlayers()[this.value]; if (currentPlayer) return {[this.name]: currentPlayer}; } } // closure wrapper for super's methods that will setPosition temporarily to a // specific player and pretend to be a normal flow with just one subflow withPlayer(value: number, fn: () => T, mutate=false): T { this.value = value; this.sequence = this.position.sequences[this.value]; this.setPosition(this.position, this.sequence); const result = fn(); if (mutate) { const currentPlayer = this.getPlayers()[this.value]; // capture position from existing player before returning to all player mode this.position.sequences[this.value] = this.sequence; if (currentPlayer && this.step instanceof Flow) this.position.positions[this.value] = this.step.branchJSON(); } this.value = -1; this.setPosition(this.position); return result; } getPlayers(): P[] { return this.players || this.gameManager.players as PlayerCollection

} // reimpl ourselves to collect json from all players branchJSON(forPlayer=true): FlowBranchJSON[] { if (this.position === undefined && this.sequence === undefined) return []; // probably invalid let branch: FlowBranchJSON = { type: this.type, position: {positions: [], sequences: this.position.sequences, completed: this.completed} }; if (this.name) branch.name = this.name; for (let i = 0; i !== this.getPlayers().length; i++) { this.withPlayer(i, () => { if (this.step instanceof Flow) branch.position.positions[i] = this.step.branchJSON(forPlayer); }); } return [branch]; } // add player management, hydration of flow for the correct player, sequences[] management setPosition(positionJSON: any, sequence?: number) { const player = this.getPlayers()[this.value]; this.completed = positionJSON.completed; if (player) { player.setCurrent(); positionJSON.sequences[this.value] = sequence; } else { // not looking at an individual player. set game state to accept all players const players: P[] = []; for (let i = 0; i !== this.getPlayers().length; i++) { if (this.completed[i] === false) players.push(this.getPlayers()[i]); } this.gameManager.players.setCurrent(players); } super.setPosition(positionJSON, positionJSON.sequences[this.value]); if (this.step instanceof Flow && this.position.positions[this.value]) { this.step.setBranchFromJSON(this.position.positions[this.value]); } } currentBlock() { // need to override this within flow methods by setting value. branch // set/get should not advance past here, but step function may return this.value >= 0 && this.value < this.getPlayers().length ? this.block : undefined; } actionNeeded(player?: Player) { if (player && this.getPlayers().includes(player as P)) { return this.withPlayer(this.getPlayers().indexOf(player as P), () => super.actionNeeded(player)); } } processMove(move: { player: number, name: string, args: Record, }): string | SubflowSignal['data'][] | undefined { const player = this.getPlayers().findIndex(p => p.position === move.player); if (player < 0) throw Error(`Cannot process action from ${move.player}`); return this.withPlayer(player, () => { this.completed[player] = undefined; return super.processMove(move); }, true); } // intercept super.playOneStep so a single branch doesn't signal complete // without us checking all branches playOneStep(): InterruptSignal[] | FlowControl | Flow { // step through each player over top of the normal super stepping const player = this.getPlayers().findIndex((_, p) => this.completed[p] === undefined); if (player !== -1) { // run for next player without a resolution return this.withPlayer(player, () => { let result = super.playOneStep(); // capture the complete state ourselves, pretend everything is fine if (result instanceof Flow || result === FlowControl.complete) this.completed![player] = result === FlowControl.complete; return FlowControl.ok; }, true); } // no more players to step through. return the all-complete return this.completed.every(r => r) ? FlowControl.complete : this; } toString(): string { return `every-player${this.name ? ":" + this.name : ""}`; } visualize(top: Flow) { return this.visualizeBlocks({ type: 'everyPlayer', top, blocks: { do: this.block instanceof Array ? this.block : [this.block] }, block: 'do', }); } } ================================================ FILE: src/flow/flow.ts ================================================ import { InterruptControl, interruptSignal, FlowControl } from './enums.js'; import { Do } from './enums.js'; import type { InterruptSignal, SubflowSignal } from './enums.js'; import type GameManager from '../game-manager.js'; import type { Player } from '../index.js'; import type { WhileLoopPosition } from './while-loop.js'; import type { ForLoopPosition } from './for-loop.js'; import type { ForEachPosition } from './for-each.js'; import type { SwitchCasePostion } from './switch-case.js'; import type { ActionStepPosition } from './action-step.js'; import type { EveryPlayerPosition } from './every-player.js'; import type { ActionStub } from '../action/action.js'; import type WhileLoop from './while-loop.js'; import type { Serializable } from '../action/utils.js'; /** * Several flow methods accept an argument of this type. This is an object * containing the current values of any loops or actions that the game is in the * middle of. Functions that can add these values are {@link forLoop}, {@link * forEach}, {@link switchCase} and {@link playerActions}. The `name` given to * these functions will be the key used in the FlowArguments and its value will * be the value of the current loop for loops, or the test value for switchCase, * or the arguments to the action taken for playerActions. * * @example * forLoop({ * name: 'x', // x is declared here * initial: 0, * next: x => x + 1, * while: x => x < 3, * do: forLoop({ * name: 'y', // y is declared here * initial: 0, * next: y => y + 1, * while: y => y < 2, * do: ({ x, y }) => { * // x is available here as the value of the outer loop * // and y will be the value of the inner loop * } * }) * }) * @category Flow */ export type FlowArguments = Record; /** * FlowStep's are provided to the game and to all flow function to provide * further flow logic inside the given flow. Any of the follow qualifies: * - a plain function that accepts {@link FlowArguments} * - one of the {@link Game#flowCommands} * @category Flow */ export type FlowStep = Flow | ((args: FlowArguments) => any); /** * FlowDefinition's are provided to the game and to all flow function to provide * further flow logic inside the given flow. Any of the follow qualifies: * - a plain function that accepts {@link FlowArguments} * - one of the {@link Game#flowCommands} * - an array of any combination of the above * @category Flow */ export type FlowDefinition = FlowStep | FlowStep[] export type FlowBranchNode = ({ type: 'main', } | { type: 'action', position: ActionStepPosition } | { type: 'parallel', position: EveryPlayerPosition, } | { type: 'loop', position: WhileLoopPosition | ForLoopPosition } | { type: 'foreach', position: ForEachPosition } | { type: 'switch-case', position: SwitchCasePostion }) & { name?: string, sequence?: number, } export type FlowBranchJSON = ({ type: 'main' | 'action' | 'loop' | 'foreach' | 'switch-case' | 'parallel' position?: any, }) & { name?: string, sequence?: number, } export type Position = ( ActionStepPosition | ForLoopPosition | WhileLoopPosition | ForEachPosition | SwitchCasePostion | EveryPlayerPosition ) export type FlowVisualization = { type: string, name?: string, blocks: Record, current: { block?: string, position?: any, sequence?: number, } } /** internal */ export default class Flow { name?: string; position?: Position; sequence?: number; // if block is an array, indicates the index of execution type: FlowBranchNode['type'] = 'main'; step?: FlowStep; // cached by setPositionFromJSON block?: FlowDefinition; args?: Record; top: Flow; parent?: Flow; gameManager: GameManager; constructor({ name, do: block }: { name?: string, do?: FlowDefinition }) { this.name = name; this.block = block; // each subflow can set itself as top because they will be copied later by each parent as it loads its subflows this.top = this; } validateNoDuplicate() { const name = this.name; this.name = undefined; if (name && this.getStep(name)) throw Error(`Duplicate flow name: ${name}`); this.name = name; } flowStepArgs(): FlowArguments { const args = {...(this.top.args ?? {})}; let flow: FlowStep | undefined = this.top; while (flow instanceof Flow) { Object.assign(args, flow.thisStepArgs()); flow = flow.step; } return args; } thisStepArgs() { if (this.position && 'value' in this.position && this.name) { return {[this.name]: this.position.value}; } } branchJSON(forPlayer=true): FlowBranchJSON[] { let branch: Record = { type: this.type, }; if (this.name) branch.name = this.name; if (this.position !== undefined) branch.position = this.toJSON(forPlayer); if (this.sequence !== undefined && this.currentBlock() instanceof Array) branch.sequence = this.sequence; const thisBranch = branch as FlowBranchJSON; if (this.step instanceof Flow) return [thisBranch].concat(this.step.branchJSON(forPlayer)); return [thisBranch]; } setBranchFromJSON(branch: FlowBranchJSON[]) { const node = branch[0]; if (node === undefined) throw Error(`Insufficient position elements sent to flow for ${this.name}`); if (node.type !== this.type || node.name !== this.name) { throw Error(`Flow mismatch. Trying to set ${node.type}:${node.name} on ${this.type}:${this.name}`); } this.setPositionFromJSON(node.position, node.sequence); if (this.step instanceof Flow) { this.step.setBranchFromJSON(branch.slice(1)); // continue down the hierarchy } } setPosition(position: any, sequence?: number, reset=true) { this.position = position; const block = this.currentBlock(); if (!block) { this.step = undefined; // awaiting action or unreachable step } else if (block instanceof Array) { if (sequence === undefined) sequence = 0; this.sequence = sequence; if (!block[sequence]) throw Error(`Invalid sequence for ${this.type}:${this.name} ${sequence}/${block.length}`); this.step = block[sequence]; } else { this.step = block; } if (this.step instanceof Flow) { this.step.gameManager = this.gameManager; this.step.top = this.top; this.step.parent = this; if (reset) this.step.reset(); } } setPositionFromJSON(positionJSON: any, sequence?: number) { this.setPosition(this.fromJSON(positionJSON), sequence, false); } currentLoop(name?: string): WhileLoop | undefined { if ('interrupt' in this && (!name || name === this.name)) return this as unknown as WhileLoop; return this.parent?.currentLoop(); } currentProcessor(): Flow | undefined { if (this.step instanceof Flow) return this.step.currentProcessor(); if (this.type === 'action' || this.type === 'parallel') return this; } actionNeeded(player?: Player): { step?: string, prompt?: string, description?: string, actions: ActionStub[], continueIfImpossible?: boolean, skipIf: 'always' | 'never' | 'only-one'; } | undefined { return this.currentProcessor()?.actionNeeded(player); } processMove(move: NonNullable): string | SubflowSignal['data'][] | undefined { interruptSignal.splice(0); const step = this.currentProcessor(); if (!step) throw Error(`Cannot process action currently ${JSON.stringify(this.branchJSON())}`); return step.processMove(move); } getStep(name: string): Flow | undefined { if (this.name === name) { this.validateNoDuplicate(); return this; } const steps = this.allSteps(); if (!steps) return; for (const step of steps instanceof Array ? steps : [steps]) { if (step instanceof Flow) { const found = step.getStep(name); if (found) return found; } } } /** * Advance flow one step and return FlowControl.complete if complete, * FlowControl.ok if can continue, Do to interrupt the current loop. Returns * ActionStep if now waiting for player input. override for self-contained * flows that do not have subflows. */ playOneStep(): InterruptSignal[] | FlowControl | Flow { const step = this.step; let result: InterruptSignal[] | FlowControl | Flow = FlowControl.complete; if (step instanceof Function) { if (!interruptSignal[0]) step(this.flowStepArgs()); result = FlowControl.complete; if (interruptSignal[0] && interruptSignal[0].signal !== InterruptControl.subflow) result = interruptSignal.splice(0); } else if (step instanceof Flow) { result = step.playOneStep(); } if (result === FlowControl.ok || result instanceof Flow) return result; if (result !== FlowControl.complete) { if ('interrupt' in this && typeof this.interrupt === 'function' && (!result[0].data || result[0].data === this.name)) return this.interrupt(result[0].signal) return result; } // completed step, advance this block if able const block = this.currentBlock(); if (block instanceof Array) { if ((this.sequence ?? 0) + 1 !== block.length) { this.setPosition(this.position, (this.sequence ?? 0) + 1); return FlowControl.ok; } } // completed block, advance self return this.advance(); } // play until action required (returns ActionStep) or flow complete (undefined) or subflow started {name, args} play() { interruptSignal.splice(0); let step; do { if (this.gameManager.phase !== 'finished') step = this.playOneStep(); if (!(step instanceof Flow)) console.debug(`Advancing flow:\n ${this.stacktrace()}`); } while (step === FlowControl.ok && interruptSignal[0]?.signal !== InterruptControl.subflow && this.gameManager.phase !== 'finished') if (interruptSignal[0]?.signal === InterruptControl.subflow) return interruptSignal.map(s => s.data as {name: string, args: Record}); if (step instanceof Flow) return step; if (step instanceof Array) { if (step[0].signal === InterruptControl.continue) throw Error("Cannot use Do.continue when not in a loop"); if (step[0].signal === InterruptControl.repeat) throw Error("Cannot use Do.repeat when not in a loop"); throw Error("Cannot use Do.break when not in a loop"); } // flow complete } // must override. reset runs any logic needed and call setPosition. Must not modify own state. reset() { this.setPosition(undefined); } // must override. must rely solely on this.position currentBlock(): FlowDefinition | undefined { return this.block; } // override if position contains objects that need serialization toJSON(_forPlayer=true): any { return this.position; } // override if position contains objects that need deserialization fromJSON(json: any): typeof this.position { return json; } // override for steps that advance through their subflows. call setPosition if needed. return ok/complete advance(): FlowControl { return FlowControl.complete; } // override return all subflows allSteps(): FlowDefinition | undefined { return this.block; } toString() { return `flow${this.name ? ":" + this.name.replace(/__/g, '') : ""}${this.block instanceof Array && this.block.length > 1 ? ' (item #' + this.sequence + ')' : ''}`; } stacktrace(indent=0) { let string = this.toString(); if (this.step instanceof Flow) string += '\n ' + ' '.repeat(indent) + '↳ ' + this.step.stacktrace(indent + 2); return string; } visualize(top: Flow) { return this.visualizeBlocks({ type: 'flow', top, blocks: { do: this.block ? (this.block instanceof Array ? this.block : [this.block]) : undefined }, block: 'do' }); } visualizeBlocks({ type, blocks, name, top, block, position }: { type: string, blocks: Record, name?: string, top: Flow, block?: string, position?: any, }): FlowVisualization { const blockViz = Object.fromEntries(Object.entries(blocks). map(([key, block]) => [ key, block?.map(s => { if (s instanceof Flow) return s.visualize(top); if (s === Do.break) return 'Do.break'; if (s === Do.repeat) return 'Do.repeat'; if (s === Do.continue) return 'Do.continue'; return s.toString() }) ]) ); return { type, name: name === undefined ? this.name : name, blocks: blockViz, current: { block, position, sequence: this.sequence } } } } ================================================ FILE: src/flow/for-each.ts ================================================ import ForLoop from './for-loop.js'; import { serialize, deserialize } from '../action/utils.js'; import type { FlowArguments, FlowDefinition, FlowBranchNode } from './flow.js'; import type { ForLoopPosition } from './for-loop.js'; import type { Serializable } from '../action/utils.js'; import type Flow from './flow.js'; export type ForEachPosition = ForLoopPosition & { collection: T[] }; export default class ForEach extends ForLoop { collection: ((a: FlowArguments) => T[]) | T[] position: ForEachPosition; whileCondition: (position: ForEachPosition) => boolean; type: FlowBranchNode['type'] = 'foreach'; constructor({ name, collection, do: block }: { name: string, collection: ((a: FlowArguments) => T[]) | T[], do: FlowDefinition }) { super({ name, initial: () => ((typeof collection === 'function') ? collection(this.flowStepArgs()) : collection)[0], next: () => this.position.collection[this.position.index + 1], while: () => true, do: block }); this.collection = collection; this.whileCondition = position => position.index >= 0 && position.index < position.collection.length; } reset() { const collection = (typeof this.collection === 'function') ? this.collection(this.flowStepArgs()) : this.collection; this.setPosition({ index: collection.length ? 0 : -1, value: collection[0], collection }); } toJSON(forPlayer=true) { return { index: this.position.index, value: serialize(this.position.value, forPlayer), collection: serialize(this.position.collection, forPlayer) }; } fromJSON(position: any) { return { index: position.index, value: deserialize(position.value, this.gameManager.game), collection: deserialize(position.collection, this.gameManager.game) }; } toString(): string { return `foreach${this.name ? ":" + this.name : ""} (index: ${this.position.index}, value: ${this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})`; } visualize(top: Flow) { return this.visualizeBlocks({ type: 'forEach', top, blocks: { do: this.block instanceof Array ? this.block : [this.block] }, block: 'do', position: this.position?.value, }); } } ================================================ FILE: src/flow/for-loop.ts ================================================ import type { Serializable } from '../action/utils.js'; import type { FlowArguments, FlowDefinition, FlowBranchNode } from './flow.js'; import WhileLoop from './while-loop.js'; import type Flow from './flow.js'; export type ForLoopPosition = { index: number, value: T }; export default class ForLoop extends WhileLoop { block: FlowDefinition; position: ForLoopPosition; initial: ((a: FlowArguments) => T) | T; whileCondition: (position: ForLoopPosition) => boolean; next: (a: T) => T; type: FlowBranchNode['type'] = 'loop'; constructor({ name, initial, next, do: block, while: whileCondition }: { name: string, initial: ((a: FlowArguments) => T) | T, next: (a: T) => T, while: (a: T) => boolean, do: FlowDefinition }) { super({ do: block, while: () => true }); this.name = name; this.initial = initial; this.next = next; this.whileCondition = position => whileCondition(position.value) } currentBlock() { if (this.position.index !== -1) return this.block; } toString(): string { return `loop${this.name ? ":" + this.name : ""} (index: ${this.position.index}, value: ${this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})$`; } visualize(top: Flow) { return this.visualizeBlocks({ type: 'forLoop', top, blocks: { do: this.block instanceof Array ? this.block : [this.block] }, block: 'do', position: this.position?.value, }); } } ================================================ FILE: src/flow/if-else.ts ================================================ import SwitchCase from './switch-case.js'; import type { FlowDefinition, FlowStep } from './flow.js'; import type Flow from './flow.js'; export default class If extends SwitchCase { constructor({ name, if: test, do: doExpr, else: elseExpr }: { name?: string, if: (r: Record) => boolean, do: FlowDefinition; else?: FlowDefinition }) { super({ name, switch: test, cases: [{ eq: true, do: doExpr }], default: elseExpr }); } toString(): string { return `if-else${this.name ? ":" + this.name : ""} (${!!this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})`; } visualize(top: Flow) { const blocks = { do: this.cases[0].do instanceof Array ? this.cases[0].do : [this.cases[0].do], } as Record; if (this.default) blocks.else = this.default instanceof Array ? this.default : [this.default]; return this.visualizeBlocks({ type: 'ifElse', top, blocks, block: this.position ? (this.position.default ? 'else' : 'do') : undefined, position: this.position?.value, }); } } ================================================ FILE: src/flow/index.ts ================================================ import ActionStep from './action-step.js'; import WhileLoop from './while-loop.js'; import ForLoop from './for-loop.js'; import ForEach from './for-each.js'; import EachPlayer from './each-player.js'; import SwitchCase from './switch-case.js'; import IfElse from './if-else.js'; import EveryPlayer from './every-player.js'; import type { Serializable } from '../action/utils.js'; import { FlowStep } from './flow.js'; import { Do, FlowControl } from './enums.js'; export { ActionStep, WhileLoop, ForLoop, ForEach, EachPlayer, SwitchCase, IfElse, EveryPlayer, Do, FlowControl }; export type { FlowStep, FlowDefinition, FlowArguments } from './flow.js'; /** * Stop the flow and wait for a player to act. * * @param options.actions - An array of possible actions. Each action can be * either a string or on object. If a string, it is the name of the action as * defined in {@link Game#defineActions}. If an object, it consists of the * following keys: *

    *
  • `name`: the name of the action *
  • `do`: a further {@link FlowDefintion} for the game to run if this action is * taken. This can contain any number of nested Flow functions. *
  • `args`: args to pass to the action, or function returning those args. If * provided this pre-selects arguments to the action that the player does not * select themselves. Also see {@link game#action} and {@link game#followUp}. *
  • `prompt`: a string prompt, or function returning a string. If provided this * overrides the prompt defined in the action. This can be useful if the same * action should prompt differently at different points in the game *
* * @param options.name - A unique name for this player action. If provided, this * can be used for the UI to determine placement of messages for this action in * {@link Game#layoutStep}. * * @param options.prompt - A prompting message for the player to decide between * multiple actions that involve clicking on the board. For example, if a player * can choose between playing a card from hand, or drawing from the deck, this * text can contain a single prompt that indicates this. This is used only if * multiple such selections are available and replaces the individual action * prompts. May be a string or a function accepting {@link FlowArguments}. * * @param options.description - A description of this step from a 3rd person * perspective, e.g. "choosing a card". The string will be automatically * prefixed with the player name and verb. If specified, will be used to convey * to non-acting players what step is happening. * * @param options.player - Which player can perform this action. If not * provided, this defaults to the {@link PlayerCollection#current | current * player} * * @param options.players - Which players can perform this action, if multiple. * * @param options.optional - If a string is passed, this becomes a prompt * players can use to 'pass' this step, performing no action and letting the * flow proceed. May be a string or a function accepting {@link FlowArguments} * * @param options.skipIf - One of 'always', 'never' or 'only-one' (Default * 'always'). * *
    *
  • 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. *
  • always: Rather than present this choice directly, the player will be * prompted with choices from the *next choice* in each action here, essentially * expanding the choices ahead of time to save the player a step. *
  • never: Always present this choice, even if the choice is forced *
* * @param options.repeatUntil - Include this option to make this action * repeatable until the player passes. The pass prompt will be the supplied * string, similar to `optional` * * @param options.condtion - Include this option to make this action * automatically skip if this condition returns false. * * @param options.continueIfImpossible - Include this option to make this action * automatically skip if none of the actions are possible, either due to the * action.condition or due to no valid selections being current available in the * game. * * @category Flow */ export const playerActions = (options: ConstructorParameters[0]) => new ActionStep(options); /** * Create a loop that continues until some condition is true. This functions * like a standard `while` loop. * * @param options.do - The part that gets repeated. This can contain any type of * {@link FlowDefintion}, a list of functions, or more Flow commands. The * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue}, can also be used here to cause the current loop to be * interupted. * * @param options.while - Either a simple boolean value or a condition function * that must return true for the loop to continue. If this evaluates to false * when the loop begins, it will be skipped entirely. The condition will be * evaluated at the start of each loop to determine whether it should continue. * * @example * whileLoop({ while: () => !bag.isEmpty(), do: ( * playerActions({ actions: { * takeOneFromBag: null, * }}), * )}); * * @category Flow */ export const whileLoop = (options: ConstructorParameters[0]) => new WhileLoop(options); /** * Create a loop that continues until {@link Do|Do.break} is called * * @param options.do - The part that gets repeated. This can contain any type of * {@link FlowDefintion}, a list of functions, or more Flow commands. The * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue}, can also be used here to cause the current loop to be * interupted. * * @example * loop(playerActions({ actions: [ * 'takeOneFromBag', * { name: 'done', do: Do.break } * ]})); * * @category Flow */ export const loop = (...block: FlowStep[]) => new WhileLoop({do: block, while: () => true}); /** * Create a loop that sets a value and continues until that value meets some * condition. This functions like a standard `for` loop. * * @param options.do - The part that gets repeated. This can contain any type of * {@link FlowDefintion}, a list of functions, or more Flow commands. The * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue}, can also be used here to cause the current loop to be * interupted. * * @param options.name - The current value of the loop variable will be added to * the {@link FlowArguments} under a key with this name. * * @param options.initial - The initial value of the loop variable * * @param options.next - A function that will be run on each loop and must * return the new value of the loop variable * * @param options.while - A condition function that must return true for the * loop to continue. If this evaluates to false when the loop begins, it will be * skipped entirely. The condition will be evaluates at the start of each loop * to determine whether it should continue. * * @example * forLoop({ * name: 'x', * initial: 0, * next: x => x + 1, * while: x => x < 3, * do: ({ x }) => { * // do something 3 times * } * }) * * @category Flow */ export const forLoop = (options: ConstructorParameters>[0]) => new ForLoop(options); /** * Create a loop that iterates over an array. This functions like a standard * `Array#forEach` method. * * @param options.do - The part that gets repeated. This can contain any type of * {@link FlowDefintion}, a list of functions, or more Flow commands. The * functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue}, can also be used here to cause the current loop to be * interupted. * * @param options.name - The current value of collection will be added to the * {@link FlowArguments} under a key with this name. * * @param options.collection - A collection of values to loop over. This can be * declared as an array or as a method that accept the {@link FlowArguments} * used up to this point in the flow and return the collection Array. This * expression is evaluated *only once* at the start of the loop. * * @example * forEach({ name: 'card', collection: () => deck.all(Card), do: [ * // show each card from the deck to player in turn * ({ card }) => card.showTo(player), * playerActions({ actions: [ * 'chooseCard', * 'pass', * ]}), * ]}); * * @category Flow */ export const forEach = (options: ConstructorParameters>[0]) => new ForEach(options); /** * Create a loop that iterates over each player. This is the same as {@link * forEach} with the additional behaviour of setting the {@link * PlayerCollection#current | current player} on each iteration of the loop. * * @param options.do - The part that gets repeated for each player. This can * contain any type of {@link FlowDefintion}, a list of functions, or more Flow * commands. The functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue}, can also be used here to cause the current loop to be * interupted. * * @param options.name - The current player will be added to the {@link * FlowArguments} under a key with this name. * * @param options.startingPlayer - Declare the player to start the loop. If not * specified, this will be the first player in turn order. * * @param options.nextPlayer - Declare a method to select the next player. If * not specified this will follow turn order. See {@link * PlayerCollection#sortby} for more information. * * @param options.turns - If specified, loop through each play this many * times. Default is 1. * * @param options.continueUntil - If specified, rather than loop through each * player for a certain number of turns, the loop will continue until the * provided condition is true. This function accepts the player for the current * loop as its only argument. * * @example * eachPlayer({ name: 'biddingPlayer', do: // each player in turn has a chance to bid * playerActions({ actions: [ 'bid', 'pass' ] }) * }); * * @category Flow */ export const eachPlayer = (options: ConstructorParameters[0]) => new EachPlayer(options); /** * Provides a branching flow on a condition. This operates like a standard * `if... else` * * @param options.if - Condition to test for true/false. This function accepts all * {@link FlowArguments}. * * @param options.do - The part that gets run if the condition is true. This can * contain any type of {@link FlowDefintion}, a list of functions, or more Flow * commands. The functions {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue}, can also be used here to cause the current loop to be * interupted. * * @param options.else - As `do`, but runs if the condition is false. Optional. * * @category Flow */ export const ifElse = (options: ConstructorParameters[0]) => new IfElse(options); /** * Provides a branching flow on a condition with multiple outcomes. This * operates like a standard `switch... case` * * @param options.switch - Expression to evaluate for determining which case * should run. This function accepts all {@link FlowArguments}. * * @param options.name - If a name is provided, the value that results from * evaluating `switch` will be added to the {@link FlowArguments} under a key * with this name. * * @param options.cases - An array of conditions that will test whether they * meet the conditions based on the evaluated `switch` and execute their `do` * block. The case block can contain an `eq` which will test for equality with a * provided value, or `test` which will test the value using a provided function * that must return a boolean. Only the first one that meets the condition will * run. The `do` can contain any type of {@link FlowDefintion}. * * @param options.default - If no case qualifies, a `default` case can be * provided. * * @example * switchCase({ * name: 'switch', * switch: () => deck.top(Card)?.suit, * cases: [ * { eq: 'D', do: () => { /* ... diamonds *\/ } }, * { eq: 'H', do: () => { /* ... hearts *\/ } }, * { eq: 'S', do: () => { /* ... spades *\/ } }, * { eq: 'C', do: () => { /* ... clubs *\/ } }, * ], * default: () => { /* ... there is no card *\/ } * }) * * @category Flow */ export const switchCase = (options: ConstructorParameters>[0]) => new SwitchCase(options); /** * Create a flow for a set of players that can be done by all players * simulataneously in any order. This is similiar to {@link eachPlayer} except * that the players can act in any order. * * @param options.do - The part that each player can perform. This can contain * any type of {@link FlowDefintion}, a list of functions, or more Flow * commands. Each player will go through the defined flows individually and may * be at difference stages. The flow will complete when all players have * completed this flow. If {@link Do|Do.repeat}, {@link Do|Do.break} or {@link * Do|Do.continue} is called, the current loop can be interupted, *regardless of * what the other players have done*. * * @param options.name - The player acting will be added to the {@link * FlowArguments} under a key with this name for flows within this `do`. * * @param options.players - Declare the players to perform this `do`. If not * specified, this will be all players. * * @example * everyPlayer({ name: 'passCardPlayer', do: ( // each player selects a card from hand or passes * playerActions({ actions: [ 'selectCard', 'pass' ]}), * ]}); * * @category Flow */ export const everyPlayer = (options: ConstructorParameters[0]) => new EveryPlayer(options); ================================================ FILE: src/flow/switch-case.ts ================================================ import Flow from './flow.js'; import { serialize, deserialize } from '../action/utils.js'; import type { FlowArguments, FlowDefinition, FlowBranchNode, FlowStep } from './flow.js'; import type { Serializable } from '../action/utils.js'; export type SwitchCasePostion = { index?: number, value?: T, default?: boolean } export type SwitchCaseCases = ({eq: T, do: FlowDefinition} | {test: (a: T) => boolean, do: FlowDefinition})[]; export default class SwitchCase extends Flow { position: SwitchCasePostion; switch: ((a: FlowArguments) => T) | T; cases: SwitchCaseCases; default?: FlowDefinition; type: FlowBranchNode['type'] = "switch-case"; constructor({ name, switch: switchExpr, cases, default: def }: { name?: string, switch: ((a: FlowArguments) => T) | T, cases: SwitchCaseCases; default?: FlowDefinition }) { super({ name }); this.switch = switchExpr; this.cases = cases; this.default = def; } reset() { const test = (typeof this.switch === 'function') ? this.switch(this.flowStepArgs()) : this.switch; let position: typeof this.position = { index: -1, value: test } for (let c = 0; c != this.cases.length; c += 1) { const ca = this.cases[c]; if ('test' in ca && ca.test(test) || ('eq' in ca && ca.eq === test)) { position.index = c; break; } } if (position.index === -1 && this.default) position.default = true; this.setPosition(position); } currentBlock() { if (this.position.default) return this.default; if (this.position.index !== undefined && this.position.index >= 0) { return this.cases[this.position.index].do; } } toJSON(forPlayer=true) { return { index: this.position.index, value: serialize(this.position.value, forPlayer), default: !!this.position.default }; } fromJSON(position: any) { return { index: position.index, value: deserialize(position.value, this.gameManager.game), default: position.default, }; } allSteps(): FlowDefinition { const cases = this.cases.reduce((a, f) => a.concat(f.do ? ((f.do instanceof Array) ? f.do : [f.do]) : []), []); const defaultExpr = this.default ? ((this.default instanceof Array) ? this.default : [this.default]) : []; return cases.concat(defaultExpr); } toString(): string { return `switch-case${this.name ? ":" + this.name : ""} (${this.position.value}${this.block instanceof Array ? ', item #' + this.sequence: ''})`; } visualize(top: Flow) { let block: string | undefined = undefined; if (this.position.default) { block = 'default' } else if (this.position.index !== undefined && this.position.index >= 0) { const c = this.cases[this.position.index]; block = String('eq' in c ? c.eq : c.test); } return this.visualizeBlocks({ type: 'switchCase', top, blocks: Object.fromEntries( this.cases.map(c => [String('eq' in c ? c.eq : c.test), c.do instanceof Array ? c.do : [c.do]]).concat([ this.default ? ['default', (this.default instanceof Array ? this.default : [this.default])] : [] ]) ) as Record, block, position: this.position?.value, }); } } ================================================ FILE: src/flow/while-loop.ts ================================================ import Flow from './flow.js'; import { FlowControl } from './enums.js'; import { InterruptControl } from './enums.js'; import type { FlowArguments, FlowDefinition, FlowBranchNode } from './flow.js'; export type WhileLoopPosition = { index: number, value?: any }; export default class WhileLoop extends Flow { block: FlowDefinition; position: WhileLoopPosition; whileCondition: (position: WhileLoopPosition) => boolean; type: FlowBranchNode['type'] = 'loop'; next?: (...a: any) => void; initial?: any; constructor({ do: block, while: whileCondition }: { while: (a: FlowArguments) => boolean, do: FlowDefinition, }) { super({ do: block }); this.whileCondition = () => whileCondition(this.flowStepArgs()); } reset() { const position: typeof this.position = { index: 0 }; if (this.initial !== undefined) position.value = this.initial instanceof Function ? this.initial(this.flowStepArgs()) : this.initial if (!this.whileCondition(position)) { this.setPosition({...position, index: -1}); } else { this.setPosition(position); } } currentBlock() { if (this.position.index !== -1) return this.block; } advance() { if (this.position.index > 10000) throw Error(`Endless loop detected: ${this.name}`); if (this.position.index === -1) { return this.exit(); } const position: typeof this.position = { ...this.position, index: this.position.index + 1 }; if (this.next && this.position.value !== undefined) position.value = this.next(this.position.value); if (!this.whileCondition(position)) return this.exit(); this.setPosition(position); return FlowControl.ok; } repeat() { if (!this.whileCondition(this.position)) return this.exit(); this.setPosition(this.position); return FlowControl.ok; } exit(): FlowControl.complete { this.setPosition({...this.position, index: -1}); return FlowControl.complete; } interrupt(signal: InterruptControl) { if (signal === InterruptControl.continue) return this.advance(); if (signal === InterruptControl.repeat) return this.repeat(); if (signal === InterruptControl.break) return this.exit(); } allSteps() { return this.block; } toString(): string { return `loop${this.name ? ":" + this.name : ""} (loop ${this.position.index === -1 ? 'complete' : '#' + this.position.index}${this.block instanceof Array ? ', item #' + this.sequence: ''})`; } visualize(top: Flow) { const isLoop = this.whileCondition.toString() === '() => true'; return this.visualizeBlocks({ type: isLoop ? 'loop' : 'whileLoop', top, blocks: { do: this.block instanceof Array ? this.block : [this.block] }, block: 'do', position: this.position ? this.position.index + 1 : undefined, }); } } ================================================ FILE: src/game-creator.ts ================================================ import GameManager from './game-manager.js'; import type { Game } from './board/index.js'; import type { SetupState, GameState } from './interface.js'; import type { Player } from './player/index.js'; import type { ElementClass } from './board/element.js'; export type SetupFunction = ( state: SetupState | GameState, options?: {rseed?: string, trackMovement?: boolean, mocks?: (game: G) => void} ) => GameManager /** * Create your game * @param playerClass - Your player class. This must extend {@link Player}. If * you do not need any custom Player attributes or behaviour, simply put {@link * Player} here. This becomes the `P` type generic used throughout Boardzilla. * @param gameClass - Your game class. This must extend {@link Game}. If you * do not need any custom Game attributes or behaviour, simply put {@link * Game} here. This becomes the `B` type generic used throughout Boardzilla. * @param options.setup - A function that sets up the game. This function * accepts a single argument which is the instance of {@link Game} for this game. The * function should create all the spaces and pieces you need before your game can * start and will typically call: * - {@link game#registerClasses} to add custom classes for Spaces and Pieces * - {@link game#defineActions} to create the game actions * - {@link game#defineFlow} to define the game's flow * @category Core */ export const createGame = ( playerClass: {new(...a: any[]): Player}, gameClass: ElementClass, gameCreator: (game: G) => void ): SetupFunction => ( state: SetupState | GameState, options?: {rseed?: string, trackMovement?: boolean, mocks?: (game: G) => void} ): GameManager => { const gameManager = new GameManager(playerClass, gameClass); const inSetup = !('board' in state); globalThis.$ = gameManager.game._ctx.namedSpaces; if (options?.rseed) gameManager.setRandomSeed(options.rseed); gameManager.setSettings(state.settings); gameManager.players.fromJSON(state.players); // setup board to get all non-serialized setup (spaces, event handlers, graphs) gameCreator(gameManager.game); if (options?.mocks) options.mocks(gameManager.game); if (options?.trackMovement) gameManager.trackMovement(); if (!inSetup) { gameManager.sequence = state.sequence; gameManager.messages = state.messages; gameManager.announcements = state.announcements; gameManager.game.fromJSON(state.board); gameManager.players.assignAttributesFromJSON(state.players); gameManager.setFlowFromJSON(state.position); } else { gameManager.start(); gameManager.players.assignAttributesFromJSON(state.players); } return gameManager; }; ================================================ FILE: src/game-manager.ts ================================================ import { Space, Piece, GameElement } from './board/index.js'; import { Action, Selection } from './action/index.js'; import { Player, PlayerCollection } from './player/index.js'; import Flow, { FlowBranchJSON } from './flow/flow.js'; import ActionStep from './flow/action-step.js'; import { deserialize, serialize } from './action/utils.js'; import random from 'random-seed'; import type { BaseGame } from './board/game.js'; import type { BasePlayer } from './player/player.js'; import type { ElementClass } from './board/element.js'; import type { PlayerState, GameUpdate, GameState } from './interface.js'; import type { SerializedArg } from './action/utils.js'; import type { Argument, ActionStub } from './action/action.js'; import type { ResolvedSelection } from './action/selection.js'; import type { SubflowSignal } from './flow/enums.js'; // find all non-method non-internal attr's export type PlayerAttributes = { [ K in keyof InstanceType<{new(...args: any[]): T}> as InstanceType<{new(...args: any[]): T}>[K] extends (...args: unknown[]) => unknown ? never : (K extends '_players' | 'game' | 'gameManager' ? never : K) ]: InstanceType<{new(...args: any[]): T}>[K] } // a Move is a request from a particular Player to perform a certain Action with supplied args export type Move = { player: Player, name: string, args: Record }; export type PendingMove = { name: string, prompt?: string, args: Record, selections: ResolvedSelection[], }; export type SerializedMove = { name: string, args: Record } export type Message = { position?: number body: string } export type ActionDebug = Record, // pruned?: Record impossible?: boolean }> export type FlowStackJSON = { name?: string, args?: Record, currentPosition: number[], stack: FlowBranchJSON[] } /** * Game manager is used to coordinate other classes, the {@link Game}, the * {@link Player}'s, the {@link Action}'s and the {@link Flow}. * @category Core */ export default class GameManager { flows: Record = {}; // list of defined flows, including at minimum __main__. includes any __followup[n]__ flowState: FlowStackJSON[] = []; // current state for all flows /** * The players in this game. See {@link Player} */ players: PlayerCollection

= new PlayerCollection

; /** * The game. See {@link Game} */ game: G; settings: Record; actions: Record Action>>; sequence: number = 0; /** * Current game phase */ phase: 'new' | 'started' | 'finished' = 'new'; rseed: string; random: () => number; messages: Message[] = []; announcements: string[] = []; intermediateUpdates: GameState[][] = []; /** * If true, allows any piece to be moved or modified in any way. Used only * during development. */ godMode = false; winner: P[] = []; constructor(playerClass: {new(...a: any[]): P}, gameClass: ElementClass, elementClasses: ElementClass[] = []) { this.players = new PlayerCollection

(); this.players.className = playerClass; this.game = new gameClass({ gameManager: this, classRegistry: [GameElement, Space, Piece, ...elementClasses]}) this.players.game = this.game; } /** * configuration functions */ setSettings(settings: Record) { this.settings = settings; } setRandomSeed(rseed: string) { this.rseed = rseed; this.random = random.create(rseed).random; if (this.game.random) this.game.random = this.random; } /** * flow functions * @internal */ // start the game fresh start() { if (this.phase === 'started') throw Error('cannot call start once started'); if (!this.players.length) { throw Error("No players"); } this.phase = 'started'; this.players.currentPosition = [...this.players].map(p => p.position) this.flowState = [{stack: [], currentPosition: this.players.currentPosition}]; this.startFlow(this.flowState[0]); } play(): void { if (this.phase === 'finished') return; if (this.phase !== 'started') throw Error('cannot call play until started'); const result = this.flow().play(); if (result instanceof Flow) { if ('continueIfImpossible' in result && result.continueIfImpossible) { // check if move is impossible and advance here const possible = this.players.allCurrent().some(player => this.getPendingMoves(player) !== undefined); if (!possible) { console.debug(`Continuing past playerActions "${result.name}" with no possible moves`); this.flow().processMove({ player: this.players.currentPosition[0], name: '__continue__', args: {} }); this.play(); } } // now awaiting action } else if (result) { // proceed to new subflow for (const flow of result.reverse()) this.beginSubflow(flow); this.play(); } else { // completed this flow, go up the stack if (this.flowState.length > 1) { // cede to previous flow console.debug(`Completed "${this.flowState[0].name}" flow. Returning to "${this.flowState[1].name ?? 'main' }" flow`); this.flowState.shift(); this.players.currentPosition = this.flowState[0].currentPosition; this.play(); } else { this.game.finish(); } } } flow() { return this.flows[this.flowState[0].name ?? '__main__']; } getFlowStep(name: string) { for (const flow of Object.values(this.flows)) { const step = flow.getStep(name); if (step) return step; } } beginSubflow(flow: SubflowSignal['data']) { if (flow.name !== '__followup__' && flow.name !== '__main__' && !this.flows[flow.name]) throw Error(`No flow named "${flow.name}"`); console.debug(`Proceeding to "${flow.name}" flow${flow.args ? ` with { ${Object.entries(flow.args).map(([k, v]) => `${k}: ${v}`).join(', ')} }` : ''}`); // freeze current player in flow state this.flowState[0].currentPosition = this.players.currentPosition; // proceed to new flow on top of stack let name = flow.name; if (flow.name === '__followup__') { let counter = 1; do { name = `__followup_${counter}__`; counter += 1; } while(this.flows[name]) } this.flowState.unshift({ name, args: serialize(flow.args), currentPosition: this.players.currentPosition, stack: [] }); this.startFlow(this.flowState[0]); } setFlowFromJSON(json: FlowStackJSON[]) { this.flowState = json; this.phase = 'started'; [...this.flowState].reverse().forEach(s => this.startFlow(s)); } // hydrates flow with supplied json startFlow(flowState: FlowStackJSON) { const {name, args, stack} = flowState; let flow: Flow; const deserializedArgs = deserialize(args, this.game) as Record; if (name?.startsWith('__followup_')) { const actions = deserializedArgs as any as ActionStub; flow = new ActionStep({ name, player: actions.player, actions: [actions] }); flow.gameManager = this; this.flows[name] = flow; } else { flow = this.flows[name ?? '__main__']; } if (stack.length) { flow.setBranchFromJSON(stack); } else { flow.reset(); } if (args) flow.args = deserializedArgs; } flowJSON(player: boolean = false) { return this.flowState.map(flowState => { const currentFlow = this.flows[flowState.name ?? '__main__']; const currentState: FlowStackJSON = { stack: currentFlow.branchJSON(!!player), currentPosition: this.players.currentPosition }; if (flowState.name) currentState.name = flowState.name; if (currentFlow.args) currentState.args = serialize(currentFlow.args); return currentState; }) } /** * state functions * @internal */ getState(player?: P): GameState { return { players: this.players.map(p => p.toJSON() as PlayerAttributes), // TODO scrub for player settings: this.settings, position: this.flowJSON(!!player), board: this.game.allJSON(player?.position), sequence: this.sequence, messages: this.messages.filter(m => player && (!m.position || m.position === player?.position)), announcements: [...this.announcements], rseed: player ? '' : this.rseed, } } getPlayerStates(): PlayerState[] { return this.players.map((p, i) => ({ position: p.position, state: this.intermediateUpdates.length ? this.intermediateUpdates.map(state => state[i]).concat([this.getState(p)]) : this.getState(p) })); } getUpdate(): GameUpdate { this.sequence += 1; if (this.phase === 'started') { return { game: { state: this.getState(), currentPlayers: this.players.currentPosition, phase: this.phase }, players: this.getPlayerStates(), messages: this.messages, } } if (this.phase === 'finished') { return { game: { state: this.getState(), winners: this.winner.map(p => p.position), phase: this.phase }, players: this.getPlayerStates(), messages: this.messages, } } throw Error('unable to initialize game'); } contextualizeBoardToPlayer(player?: Player) { const prev = this.game._ctx.player; this.game._ctx.player = player; return prev; } inContextOfPlayer(player: Player, fn: () => T): T { const prev = this.contextualizeBoardToPlayer(player); const results = fn(); this.contextualizeBoardToPlayer(prev); return results; } trackMovement(track=true) { if (this.game._ctx.trackMovement !== track) { this.game._ctx.trackMovement = track; if (track) this.intermediateUpdates = []; } } /** * action functions */ getAction(name: string, player: P) { if (this.godMode) { const godModeAction = this.godModeActions()[name]; if (godModeAction) { godModeAction.name = name; return godModeAction as Action & {name: string}; } } if (!this.actions[name]) { throw Error(`No action found: "${name}". All actions must be specified in defineActions()`); } return this.inContextOfPlayer(player, () => { const action = this.actions[name](player); action.gameManager = this; action.name = name; return action as Action & {name: string}; }); } godModeActions(): Record { if (this.phase !== 'started') throw Error('cannot call god mode actions until started'); return { _godMove: this.game.action({ prompt: "Move", }).chooseOnBoard( 'piece', this.game.all(Piece), ).chooseOnBoard( 'into', this.game.all(GameElement) ).move( 'piece', 'into' ), _godEdit: this.game.action({ prompt: "Change", }) .chooseOnBoard('element', this.game.all(GameElement)) .chooseFrom<'property', string>( 'property', ({ element }) => Object.keys(element).filter(a => !GameElement.unserializableAttributes.concat(['_visible', 'mine', 'owner']).includes(a)), { prompt: "Change property" } ).enterText('value', { prompt: ({ property }) => `Change ${property}`, initial: ({ element, property }) => String(element[property as keyof GameElement]) }).do(({ element, property, value }) => { let v: any = value if (value === 'true') { v = true; } else if (value === 'false') { v = false; } else if (parseInt(value).toString() === value) { v = parseInt(value); } // @ts-ignore element[property] = v; }) }; } // given a player's move (minimum a selected action), attempts to process // it. if not, returns next selection for that player, plus any implied partial // moves processMove({ player, name, args }: Move): string | undefined { if (this.phase === 'finished') return 'Game is finished'; let result: string | SubflowSignal['data'][] | undefined; return this.inContextOfPlayer(player, () => { if (this.godMode && this.godModeActions()[name]) { const godModeAction = this.godModeActions()[name]; result = godModeAction._process(player, args); } else { result = this.flow().processMove({ name, player: player.position, args }); } console.debug(`Received move from player #${player.position} ${name}({${Object.entries(args).map(([k, v]) => `${k}: ${v}`).join(', ')}}) ${result ? (typeof result === 'string' ? '❌ ' + result : `⮕ ${result[0].name}({${Object.entries(result[0].args || {}).map(([k, v]) => `${k}: ${v}`).join(', ')}})`) : '✅'}`); if (result instanceof Array) { for (const flow of result.reverse()) this.beginSubflow(flow); } return typeof result === 'string' ? result : undefined; }); } allowedActions(player: P, debug?: ActionDebug): { step?: string, prompt?: string, description?: string, skipIf: 'always' | 'never' | 'only-one', continueIfImpossible?: boolean, actions: ActionStub[] } { const actions: ActionStub[] = this.godMode ? Object.keys(this.godModeActions()).map(name => ({ name })) : []; if (!player.isCurrent()) return { actions, skipIf: 'always', }; const actionStep = this.flow().actionNeeded(player); if (actionStep?.actions) { for (const allowedAction of actionStep.actions) { if (allowedAction.name === '__pass__') { actions.push(allowedAction); } else { const gameAction = this.getAction(allowedAction.name, player); if (gameAction.isPossible(allowedAction.args ?? {})) { // step action config take priority over action config actions.push({ ...gameAction, ...allowedAction, player }); } else if (debug) { debug[allowedAction.name] = { impossible: true, args: {} }; } } } return { ...actionStep, actions } } // check any other current players, if no action possible, warn and skip somehow ??? return { skipIf: 'always', actions: [] }; } getPendingMoves(player: P, name?: string, args?: Record, debug?: ActionDebug): {step?: string, prompt?: string, moves: PendingMove[]} | undefined { if (this.phase === 'finished') return; const allowedActions = this.allowedActions(player, debug); let possibleActions: string[] = []; if (allowedActions.actions.length) { const { step, prompt, actions, skipIf } = allowedActions; if (!name) { let pendingMoves: PendingMove[] = []; for (const action of actions) { if (action.name === '__pass__') { possibleActions.push('__pass__'); pendingMoves.push({ name: '__pass__', args: {}, selections: [ new Selection('__action__', { prompt: action.prompt, value: '__pass__' }).resolve({}) ] }); if (debug) { debug['__pass__'] = { args: {} }; } } else { const playerAction = this.getAction(action.name, player) const args = action.args || {} let submoves = playerAction._getPendingMoves(args, debug); if (submoves !== undefined) { possibleActions.push(action.name); // no sub-selections to show so just create a prompt selection of this action // if an explcit confirm is required, this would be where to add the logic for it, e.g. playerAction.explicit? => selection[0].confirm if (submoves.length === 0 || skipIf === 'never' || (skipIf === 'only-one' && actions.length > 1)) { submoves = [{ name: action.name, prompt: action.prompt, args, selections: [ new Selection('__action__', { prompt: action.prompt ?? playerAction.prompt, value: action.name, skipIf }).resolve({}) ] }]; } pendingMoves = pendingMoves.concat(submoves); } else { console.debug(`Action ${action.name} not allowed because no valid selections exist`); } } } if (possibleActions.length) return { step, prompt, moves: pendingMoves}; } else { // action provided if (name === '__pass__') return { step, prompt, moves: [] }; const moves = this.getAction(name, player)?._getPendingMoves(args || {}, debug); if (moves) return { step, prompt, moves }; } } return undefined; } } ================================================ FILE: src/index.ts ================================================ import GameManager from './game-manager.js'; import { Game, Space } from './board/index.js'; import { Player } from './player/index.js'; export { Game, Space }; export { union } from './board/index.js'; export { Piece, Stack, ConnectedSpaceMap, AdjacencySpace, FixedGrid, SquareGrid, HexGrid, PieceGrid, GameElement } from './board/index.js'; export { Do } from './flow/index.js'; export { createInterface, colors } from './interface.js'; export { times, range, shuffleArray } from './utils.js'; export { Player }; export { createGame } from './game-creator.js'; export { render, ProfileBadge, toggleSetting, numberSetting, textSetting, choiceSetting, } from './ui/index.js'; export { TestRunner } from './test-runner.js'; import type { ElementClass } from './board/element.js'; import type Action from './action/action.js'; export type { GameManager, Action, ElementClass }; declare global { /** * Global reference to all unique named spaces * * @example * game.create(Space, 'deck'); * ... * $.deck // => equals the Space just created */ var $: Record>; // eslint-disable-line no-var } ================================================ FILE: src/interface.ts ================================================ import { deserializeArg } from './action/utils.js'; import { range } from './utils.js'; import random from 'random-seed'; import type { ElementJSON } from './board/element.js'; import type { PlayerAttributes, Message, SerializedMove } from './game-manager.js'; import type Player from './player/player.js'; import type { FlowBranchJSON } from './flow/flow.js'; import type { SetupFunction } from './game-creator.js'; import type { SerializedArg } from './action/utils.js'; export type SetupState = { players: (PlayerAttributes & Record)[], settings: Record, randomSeed: string, } export type GameState = { players: PlayerAttributes[], settings: Record, position: {name?: string, args?: Record, currentPosition: number[], stack: FlowBranchJSON[]}[], board: ElementJSON[], sequence: number, rseed: string, messages: Message[], announcements: string[], } type GameStartedState = { phase: 'started', currentPlayers: number[], state: GameState, } type GameFinishedState = { phase: 'finished', winners: number[], state: GameState, } export type PlayerState = { position: number state: GameState | GameState[] // Game state, scrubbed summary?: string score?: number } export type GameUpdate = { game: GameStartedState | GameFinishedState players: PlayerState[] messages: Message[] } type ReprocessHistoryResult = { initialState: GameUpdate updates: GameUpdate[] error?: string } type SerializedInterfaceMove = { position: number data: SerializedMove | SerializedMove[] } export type GameInterface = { initialState: (state: SetupState) => GameUpdate processMove: (previousState: GameStartedState, move: SerializedInterfaceMove) => GameUpdate seatPlayer(players: Player[], seatCount: number): {position: number, color: string, settings: any} | null reprocessHistory(setup: SetupState, moves: SerializedInterfaceMove[]): ReprocessHistoryResult } export const colors = [ '#d50000', '#00695c', '#304ffe', '#ff6f00', '#7c4dff', '#ffa825', '#f2d330', '#43a047', '#004d40', '#795a4f', '#00838f', '#408074', '#448aff', '#1a237e', '#ff4081', '#bf360c', '#4a148c', '#aa00ff', '#455a64', '#600020' ]; function advanceRseed(rseed?: string) { if (!rseed) { rseed = String(Math.random()); } else { rseed = String(random.create(rseed).random()); } return rseed; } export const createInterface = (setup: SetupFunction): GameInterface => { return { initialState: (state: SetupState): GameUpdate => { let rseed = state.randomSeed; if (!rseed) { if (globalThis.window?.sessionStorage) { // web context, use a fixed initial seed for dev let fixedRseed = sessionStorage.getItem('rseed') as string; if (!fixedRseed) { fixedRseed = String(Math.random()); sessionStorage.setItem('rseed', fixedRseed); } rseed = fixedRseed; } if (!rseed) rseed = advanceRseed(); // set the seed first because createGame may call random() } const gameManager = setup(state, {rseed, trackMovement: true}); if (globalThis.window) window.serverGameManager = gameManager; if (gameManager.phase !== 'finished') gameManager.play(); return gameManager.getUpdate(); }, processMove: ( previousState: GameStartedState, move: SerializedInterfaceMove, ): GameUpdate => { const rseed = advanceRseed(previousState.state.rseed); previousState.state.rseed = rseed; const gameManager = setup(previousState.state, {rseed, trackMovement: true}); const player = gameManager.players.atPosition(move.position)!; // @ts-ignore gameManager.messages = []; gameManager.announcements = []; if (!(move.data instanceof Array)) move.data = [move.data]; let error = undefined; for (let i = 0; i !== move.data.length; i++) { error = gameManager.processMove({ player, name: move.data[i].name, args: Object.fromEntries(Object.entries(move.data[i].args).map(([k, v]) => [k, deserializeArg(v as SerializedArg, gameManager.game)])) }); if (error) { throw Error(`Unable to process move: ${error}`); } if (gameManager.phase === 'finished') break; gameManager.play(); } return gameManager.getUpdate(); }, seatPlayer: (players: Player[], seatCount: number): {position: number, color: string, settings: any} | null => { let usedPositions = range(1, seatCount); let usedColors = [...colors]; for (const player of players) { usedPositions = usedPositions.filter(position => position !== player.position); usedColors = usedColors.filter(color => color !== player.color); } if (usedPositions.length) { return { position: usedPositions[0], color: usedColors[0], settings: {} }; } return null; }, reprocessHistory(state: SetupState, moves: SerializedInterfaceMove[]): ReprocessHistoryResult { let rseed = state.randomSeed; const gameManager = setup(state, {rseed, trackMovement: false}); if (gameManager.phase !== 'finished') gameManager.play(); const initialState = gameManager.getUpdate(); let error = undefined; const updates: GameUpdate[] = []; for (const move of moves) { rseed = advanceRseed(rseed); gameManager.setRandomSeed(rseed); gameManager.messages = []; gameManager.announcements = []; gameManager.intermediateUpdates = []; const player = gameManager.players.atPosition(move.position)!; if (!(move.data instanceof Array)) move.data = [move.data]; for (let i = 0; i !== move.data.length; i++) { try { error = gameManager.processMove({ player, name: move.data[i].name, args: Object.fromEntries(Object.entries(move.data[i].args).map(([k, v]) => [k, deserializeArg(v as SerializedArg, gameManager.game)])) }); } catch (e) { error = e.message; } if (error || gameManager.phase === 'finished') break; gameManager.play(); } if (error) break; updates.push(gameManager.getUpdate()); if (gameManager.phase === 'finished') break; } return { initialState, updates, error }; } }; } ================================================ FILE: src/player/collection.ts ================================================ import Player from './player.js'; import { shuffleArray } from '../utils.js'; import { deserializeObject } from '../action/utils.js'; import type { PlayerAttributes } from '../game-manager.js'; import type { Sorter } from '../board/index.js'; /** * An Array-like collection of the game's players, mainly used in {@link * Game#players}. The array is automatically created when the game begins and * can be used to determine or alter play order. The order of the array is the * order of play, i.e. `game.players[1]` takes their turn right after * `game.players[0]`. * @noInheritDoc * @category Core */ export default class PlayerCollection

extends Array

{ /** * An array of table positions that may currently act. */ currentPosition: number[] = []; className: {new(...a: any[]): P}; /** * A reference to the {@link Game} class */ game: P['game'] addPlayer(attrs: PlayerAttributes & Record) { const player = new this.className(attrs); Object.assign(player, attrs, {_players: this}); this.push(player); if (this.game) { player.game = this.game; } } /** * Returns the player at a given table position. */ atPosition(position: number) { return this.find(p => p.position === position); } /** * Returns the player that may currently act. It is an error to call current * when multiple players can act */ current(): P | undefined { if (this.currentPosition.length > 1) throw Error(`Using players.current when ${this.currentPosition.length} players may act`); return this.atPosition(this.currentPosition[0] ?? -1); } /** * Returns the array of all players that may currently act. */ allCurrent(): P[] { return this.currentPosition.map(p => this.atPosition(p)!); } /** * Returns the host player */ host(): P { return this.find(p => p.host)!; } /** * Returns the array of players that may not currently act. */ notCurrent() { return this.filter(p => !this.currentPosition.includes(p.position)); } /** * Returns the array of players in the order of table positions. Does not * alter the actual player order. */ inPositionOrder() { return this.sort((p1, p2) => (p1.position > p2.position ? 1 : -1)); } /** * Set the current player(s). * * @param players - The {@link Player} or table position of the player to act, * or an array of either. */ setCurrent(players: number | P | number[] | P[]) { if (!(players instanceof Array)) players = [players] as number[] | P[]; players = players.map(p => typeof p === 'number' ? p : p.position); this.currentPosition = players; } /** * Advance the current player to act to the next player based on player order. */ next() { if (this.currentPosition.length === 0) { this.currentPosition = [this[0].position]; } else if (this.currentPosition.length === 1) { this.currentPosition = [this.after(this.currentPosition[0]).position]; } return this.current()! } /** * Return the next player to act based on player order. */ after(player: number | P) { return this[(this.turnOrderOf(player) + 1) % this.length]; } /** * Return the player next to this player at the table. * @param steps - 1 = one step to the left, -1 = one step to the right, etc */ seatedNext(player: P, steps = 1) { return this.atPosition((player.position + steps - 1) % this.length + 1)!; } /** * Returns the turn order of the given player, starting with 0. This is * distinct from {@link Player#position}. Turn order can be altered during a * game, whereas table position cannot. */ turnOrderOf(player: number | P) { if (typeof player !== 'number') player = player.position; const index = this.findIndex(p => p.position === player); if (index === -1) throw Error("No such player"); return index; } /** * Sorts the players by some means, changing the turn order. * @param key - A key of function for sorting, or a list of such. See {@link * Sorter} * @param direction - `"asc"` to cause players to be sorted from lowest to * highest, `"desc"` for highest to lower */ sortBy(key: Sorter

| (Sorter

)[], direction?: "asc" | "desc") { const rank = (p: P, k: Sorter

) => typeof k === 'function' ? k(p) : p[k] const [up, down] = direction === 'desc' ? [-1, 1] : [1, -1]; return this.sort((a, b) => { const keys = key instanceof Array ? key : [key]; for (const k of keys) { const r1 = rank(a, k); const r2 = rank(b, k); if (r1 > r2) return up; if (r1 < r2) return down; } return 0; }); } /** * Returns a copy of this collection sorted by some {@link Sorter}. */ sortedBy(key: Sorter

| (Sorter

)[], direction: "asc" | "desc" = "asc") { return (this.slice(0, this.length) as this).sortBy(key, direction); } sum(key: ((e: P) => number) | (keyof {[K in keyof P]: P[K] extends number ? never: K})) { return this.reduce((sum, n) => sum + (typeof key === 'function' ? key(n) : n[key] as unknown as number), 0); } withHighest(...attributes: Sorter

[]) { return this.sortedBy(attributes, 'desc')[0]; } withLowest(...attributes: Sorter

[]) { return this.sortedBy(attributes, 'asc')[0]; } shuffle() { shuffleArray(this, this.game?.random || Math.random); } max(key: K): P[K] { return this.sortedBy(key, 'desc')[0][key]; } min(key: K): P[K] { return this.sortedBy(key, 'asc')[0][key]; } fromJSON(players: Record[]) { // reset all on self this.splice(0); for (const p of players) { this.addPlayer({position: p.position} as unknown as PlayerAttributes); } } assignAttributesFromJSON(players: PlayerAttributes[]) { for (let p = 0; p !== players.length; p++) { Object.assign(this[p], deserializeObject(players[p], this.game)); } } } ================================================ FILE: src/player/index.ts ================================================ export { default as Player } from './player.js'; export { default as PlayerCollection } from './collection.js'; ================================================ FILE: src/player/player.ts ================================================ import { serializeObject } from '../action/utils.js'; import type PlayerCollection from './collection.js'; import type GameElement from '../board/element.js'; import type { BaseGame } from '../board/game.js'; import type { ElementClass } from '../board/element.js'; import type { ElementFinder, default as ElementCollection } from '../board/element-collection.js'; export interface BasePlayer extends Player {} /** * Base player class. Each game must declare a single player class that extends * this to be used for players joining the game. Additional properties and * methods on this class will be available in game, when e.g. a player argument * is passed to an action for the player taking that action. * @category Core */ export default class Player { /** * A player's unique user id */ id: string; /** * A player's chosen name */ name: string; /** * String hex code of the player's chosen color */ color: string; /** * String URL of the avatar image for this player */ avatar: string; /** * Whether this player is the gane's host */ host: boolean; /** * A player's seating position at the table. This is distinct from turn order, * which is the order of `game.players`. Turn order can be altered during a * game, whereas `position` cannot. */ position: number; settings?: any; game: G; _players: PlayerCollection

; static isPlayer = true; /** * Provide list of attributes that are hidden from other players */ static hide

(this: {new(): P; hiddenAttributes: string[]}, ...attrs: (keyof P)[]): void { this.hiddenAttributes = attrs as string[]; } static hiddenAttributes: string[] = []; isCurrent() { return this._players.currentPosition.includes(this.position); } /** * Set this player as the current player */ setCurrent(this: P) { return this._players.setCurrent(this); } /** * Returns an array of all other players. */ others(): P[] { return Array.from(this._players).filter(p => p as Player !== this); } /** * Returns the other player. Only allowed in 2 player games */ other(): P { if (this._players.length !== 2) throw Error('Can only use `other` for 2 player games'); return this._players.find(p => p as Player !== this)!; } /** * Finds all elements of a given type that are owned by this player. This is * equivalent to calling `game.all(...)` with `{owner: this}` as one of the * search terms. Also see {@link GameElement#owner}. */ allMy(className: ElementClass, ...finders: ElementFinder[]): ElementCollection; allMy(className?: ElementFinder, ...finders: ElementFinder[]): ElementCollection>; allMy(className?: any, ...finders: ElementFinder[]) { return this.game.all(className, {owner: this}, ...finders); } /** * Finds the first element of a given type that is owned by this player. This * is equivalent to calling `game.first(...)` with `{owner: this}` as one of * the search terms. Also see {@link GameElement#owner}. */ my(className: ElementClass, ...finders: ElementFinder[]): F | undefined; my(className?: ElementFinder, ...finders: ElementFinder[]): GameElement | undefined; my(className?: any, ...finders: ElementFinder[]) { return this.game.first(className, {owner: this}, ...finders); } /** * Returns true if any element of a given type is owned by this player. This * is equivalent to calling `game.has(...)` with `{owner: this}` as one of * the search terms. Also see {@link GameElement#owner}. */ has(className: ElementClass, ...finders: ElementFinder[]): boolean; has(className?: ElementFinder, ...finders: ElementFinder[]): boolean; has(className?: any, ...finders: ElementFinder[]): boolean { return this.game.has(className, {owner: this}, ...finders); } toJSON(player?: Player) { let {_players, game: _b, ...attrs}: Record = this; // remove methods attrs = serializeObject( Object.fromEntries(Object.entries(attrs).filter( ([key, value]) => ( typeof value !== 'function' && (player === undefined || player === this || !(this.constructor as typeof Player).hiddenAttributes.includes(key as keyof Player)) ) )) ); if (globalThis.window) { // guard-rail in dev try { structuredClone(attrs); } catch (e) { console.error(`invalid properties on player ${this}:\n${JSON.stringify(attrs, undefined, 2)}`); throw(e); } } return attrs; } toString() { return this.name; } } ================================================ FILE: src/test/actions_test.ts ================================================ /* global describe, it, beforeEach */ /* eslint-disable no-unused-expressions */ import chai from 'chai'; import spies from 'chai-spies'; import Action from '../action/action.js'; import Player from '../player/player.js'; import Game from '../board/game.js'; import PieceGrid from '../board/piece-grid.js'; import Space from '../board/space.js'; import Piece from '../board/piece.js'; chai.use(spies); const { expect } = chai; const player = new Player(); describe('Actions', () => { let testAction: Action; const actionSpy = chai.spy(({ n, m }: { n: number, m: number }) => {[n, m]}); beforeEach(() => { testAction = new Action({ prompt: 'add some counters', }).chooseNumber('n', { prompt: 'how many?', min: 0, max: 3, }).chooseNumber('m', { prompt: 'how many more?', min: ({ n }) => n * 1, max: ({ n }) => n * 2, }).do(actionSpy) }); it('returns moves', () => { const error = testAction._process(player, {}); expect(error).to.not.be.undefined; const moves = testAction._getPendingMoves({}); expect(moves![0].selections[0].type).to.equal('number'); expect(moves![0].selections[0].min).to.equal(0); expect(moves![0].selections[0].max).to.equal(3); }); it('resolves dependant selections', () => { const error = testAction._process(player, {n: 1}); expect(error).to.not.be.undefined; const moves = testAction._getPendingMoves({n: 1}); expect(moves![0].selections[0].type).to.equal('number'); expect(moves![0].selections[0].min).to.equal(1); expect(moves![0].selections[0].max).to.equal(2); }); it('processes', () => { testAction._process(player, {n: 1, m: 2}); expect(actionSpy).to.have.been.called.with({n: 1, m: 2}); }); describe('nextSelections', () => { it('skipIf', () => { const testAction = new Action({ prompt: 'pick an even number' }) .chooseFrom('a', [1, 2]) .chooseFrom('b', [3, 4], {skipIf: ({ a }) => a === 1 }) .chooseFrom('c', [5, 6]) expect(testAction._nextSelection({})?.resolvedChoices).to.deep.equal([{choice: 1}, {choice: 2}]); expect(testAction._nextSelection({a: 2})?.resolvedChoices).to.deep.equal([{choice: 3}, {choice: 4}]); expect(testAction._nextSelection({a: 1})?.resolvedChoices).to.deep.equal([{choice: 5},{choice: 6}]); expect(testAction._nextSelection({a: 2, b: 3})?.resolvedChoices).to.deep.equal([{choice: 5},{choice: 6}]); expect(testAction._nextSelection({a: 2, b: 3, c: 5})).to.be.undefined; expect(testAction._nextSelection({a:1, c: 5})).to.be.undefined; }); it('skipIf last', () => { const testAction = new Action({ prompt: 'pick an even number' }) .chooseFrom('a', [1, 2] ) .chooseFrom('b', [5, 6]) .chooseFrom('c', [3, 4], { skipIf: ({ a }) => a === 1 }) expect(testAction._nextSelection({a: 2, b: 5})?.resolvedChoices).to.deep.equal([{choice: 3},{choice: 4}]); expect(testAction._nextSelection({a: 1, b: 5})).to.be.undefined; }); }); describe('getPendingMoves', () => { let options: number[]; it('tests choices', () => { const testAction1 = new Action({ prompt: 'pick an even number' }).chooseFrom('n', []); expect(testAction1._getPendingMoves({})).to.be.undefined; const testAction2 = new Action({ prompt: 'pick an even number' }).chooseFrom('n', [1]); expect(testAction2._getPendingMoves({})?.length).to.equal(1); }); it('tests bounds', () => { const testAction1 = new Action({ prompt: 'pick an even number' }).chooseNumber('n', { min: -1, max: 0 }); expect(testAction1._getPendingMoves({})?.length).to.equal(1); const testAction2 = new Action({ prompt: 'pick an even number' }).chooseNumber('n', { min: 0, max: -1 }); expect(testAction2._getPendingMoves({})).to.be.undefined; }); it('resolves selection to determine viability', () => { const testAction1 = new Action({ prompt: 'pick an even number' }) .chooseFrom('n', () => options.filter(n => n % 2 === 0)) options = [1,2]; expect(testAction1._getPendingMoves({})?.length).to.equal(1); options = [1,3,5]; expect(testAction1._getPendingMoves({})).to.be.undefined; }); it('resolves selection deeply to determine viability', () => { const testAction1 = new Action({ prompt: 'pick an even number' }) .chooseFrom('n', () => options.filter(n => n % 2 === 0)) .chooseNumber('m', { min: ({ n }) => n, max: 4 }); options = [1,8,9,10,11,4]; expect(testAction1._getPendingMoves({})?.length).to.equal(1); options = [1,8,9,10,11]; expect(testAction1._getPendingMoves({})).to.be.undefined; }); it('does not fully resolve unbounded args', () => { const testAction1 = new Action({ prompt: 'pick an even number' }) .chooseNumber('n', { min: 1 }) .chooseNumber('m', { min: ({ n }) => n * 10, max: 4 }); expect(testAction1._getPendingMoves({})?.length).to.equal(1); }); it('combines', () => { testAction = new Action({ prompt: 'purchase' }) .enterText('taunt', { prompt: 'taunt' }) .chooseGroup({ lumber: ['number'], steel: ['number'] }, { validate: ({ lumber, steel }) => lumber + steel < 10 }); const move1 = testAction._getPendingMoves({}); if (!move1) { expect(move1).to.not.be.undefined; } else { expect(move1[0].selections.length).to.equal(1); expect(move1[0].selections[0].name).to.equal('taunt'); } const move2 = testAction._getPendingMoves({taunt: 'fu'}); if (!move2) { expect(move2).to.not.be.undefined; } else { expect(move2[0].selections.length).to.equal(2); expect(move2[0].selections[0].name).to.equal('lumber'); expect(move2[0].selections[1].name).to.equal('steel'); expect(move2[0].selections[1].error({ lumber: 5, steel: 5 })).to.not.be.undefined; expect(move2[0].selections[1].error({ lumber: 5, steel: 4 })).to.be.undefined; } }); it('combines and skips', () => { testAction = new Action({ prompt: 'purchase' }) .chooseGroup({ lumber: ['number', {min: 0, max: 3}], steel: ['number', {min: 0, max: 0}], meat: ['number', {min: 0, max: 3}], plastic: ['number', {min: 0, max: 0}] }, { validate: ({ lumber, steel, meat, plastic }) => lumber + steel + meat + plastic > 0 }); const move = testAction._getPendingMoves({}); expect(move).to.not.be.undefined; expect(move?.[0].selections.length).to.equal(2); expect(move?.[0].selections[0].name).to.equal('lumber'); expect(move?.[0].selections[1].name).to.equal('meat'); const move2 = testAction._getPendingMoves({lumber: 1, meat: 0}); expect(move2).to.not.be.undefined; expect(move2?.[0].selections.length).to.equal(1); // bit odd, returns a forced choice so we can show something, although the UI will skip this ultimately expect(move2?.[0].selections[0].name).to.equal('plastic'); const move3 = testAction._getPendingMoves({lumber: 0, meat: 0}); expect(move3).to.be.undefined; }); it('combines forced', () => { testAction = new Action({ prompt: 'purchase' }) .chooseNumber('lumber', {min: 0, max: 3}) .chooseNumber('steel', {min: 0, max: 0}) .chooseNumber('meat', {min: 0, max: 3}) .chooseNumber('plastic', {min: 0, max: 0, validate: ({ lumber, steel, meat, plastic }) => lumber + steel + meat + plastic > 0 }); const move = testAction._getPendingMoves({}); if (!move) { expect(move).to.not.be.undefined; } else { expect(move[0].selections.length).to.equal(1); expect(move[0].selections[0].name).to.equal('lumber'); expect(move[0].args).to.deep.equal({steel: 0}); } const move2 = testAction._getPendingMoves({lumber: 0, steel: 0}); if (!move2) { expect(move2).to.not.be.undefined; } else { expect(move2[0].selections.length).to.equal(1); expect(move2[0].selections[0].name).to.equal('meat'); expect(move2[0].args).to.deep.equal({lumber: 0, steel: 0, plastic: 0}); } }); }); describe('getPendingMoves with skip strategies', () => { let testAction: Action<{r: string, n: number}>; beforeEach(() => { testAction = new Action({ prompt: 'p' }) .chooseFrom('r', [{ label: 'Oil', choice: 'oil' }, { label: 'Garbage', choice: 'garbage' }]) .chooseNumber('n', { max: ({ r }) => r === 'oil' ? 3 : 1 }) }); it('shows first selection', () => { const moves = testAction._getPendingMoves({}); expect(moves?.length).to.equal(1); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('choices'); expect(moves![0].selections[0].resolvedChoices).to.deep.equal([{ label: 'Oil', choice: 'oil' }, { label: 'Garbage', choice: 'garbage' }]); }); it('expands first selection', () => { testAction.selections[0].skipIf = 'always'; const moves = testAction._getPendingMoves({}); expect(moves?.length).to.equal(2); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('number'); expect(moves![1].selections[0].type).to.equal('number'); }); it('provides next selection', () => { const moves = testAction._getPendingMoves({r: 'oil'}); expect(moves?.length).to.equal(1); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('number'); expect(moves![0].args).to.deep.equal({r: 'oil'}); }); it('skips next selection', () => { const moves = testAction._getPendingMoves({r: 'garbage'}); expect(moves?.length).to.equal(1); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('number'); expect(moves![0].args).to.deep.equal({r: 'garbage'}); }); it('completes', () => { const moves = testAction._getPendingMoves({r: 'oil', n: 2}); expect(moves?.length).to.equal(0); }); it('skips', () => { testAction.selections[0].choices = ['oil']; const moves = testAction._getPendingMoves({}); expect(moves?.length).to.equal(1); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('number'); expect(moves![0].args).to.deep.equal({r: 'oil'}); }); it('prevents skips', () => { testAction.selections[0].choices = ['oil']; testAction.selections[0].skipIf = 'never'; const moves = testAction._getPendingMoves({}); expect(moves?.length).to.equal(1); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('choices'); expect(moves![0].selections[0].resolvedChoices).to.deep.equal([{choice: 'oil'}]); }); }); describe('validation rules', () => { let testAction: Action<{r: string, n: number}>; beforeEach(() => { testAction = new Action({ prompt: 'p' }) .chooseFrom( 'r', ['oil', 'steel', 'garbage'], { validate: ({r}) => r === 'steel' ? 'no steel allowed' : true } ).chooseNumber( 'n', { max: ({ r }) => r === 'oil' ? 3 : 1 } ); }); it('validates choices', () => { const moves = testAction._getPendingMoves({}); expect(moves?.[0].selections[0].resolvedChoices).to.deep.equal([ { choice: 'oil' }, { choice: 'steel', error: 'no steel allowed' }, { choice: 'garbage' }, ]); }); }); describe('_withDecoratedArgs', () => { let game: Game; beforeEach(() => { game = new Game({}); }); it('validates', () => { testAction = new Action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', game.all(Space), ).placePiece( 'token', game as unknown as PieceGrid, { rotationChoices: [0, 90, 180, 270], } ).chooseFrom('a', [1,2], { validate: ({ token, a }) => !!((token.column + token.row + a) % 2) === !!(token.rotation! % 180) || 'twist+color', } ); const args = { token: game.create(Space, 'space'), __placement__: [3, 2, 180], a: 2 }; expect(testAction._getError(testAction.selections[2].resolve(args), args)).to.equal('twist+color'); const args2 = { token: game.create(Space, 'space'), __placement__: [3, 2, 90], a: 2 }; expect(testAction._getError(testAction.selections[1].resolve(args2), args2)).to.be.undefined; }); it('confirms', () => { testAction = new Action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', game.all(Space), ).placePiece( 'token', game as unknown as PieceGrid, { rotationChoices: [0, 90, 180, 270], } ).chooseFrom('a', [1,2], { confirm: [ 'Place tile into row {{row}} and column {{column}} at {{rotation}} degrees for {{a}}?', ({ token }) => ({ row: token.row, column: token.column, rotation: token.rotation! }) ] } ); const args = { token: game.create(Space, 'space'), __placement__: [3, 2, 180], a: 2 } expect(testAction._getConfirmation(testAction.selections[2].resolve(args), args)).to.equal('Place tile into row 2 and column 3 at 180 degrees for 2?'); }); }); describe('board moves', () => { let game: Game; beforeEach(() => { game = new Game({}); const space1 = game.create(Space, 'space-1'); game.create(Space, 'space-2'); space1.create(Piece, 'piece-1'); space1.create(Piece, 'piece-2'); space1.create(Piece, 'piece-3'); space1.create(Piece, 'piece-4'); }); it('chooseOnBoard', () => { const boardAction = new Action({}) .chooseOnBoard('piece', game.all(Piece)); const moves = boardAction._getPendingMoves({}); expect(moves?.length).to.equal(1); expect(moves![0].selections.length).to.equal(1); expect(moves![0].selections[0].type).to.equal('board'); expect(moves![0].selections[0].resolvedChoices?.map(c => c.choice)).to.deep.equal(game.all(Piece)); }); it('moves', () => { const boardAction = new Action({}) .chooseOnBoard('piece', game.all(Piece)) .move('piece', game.first('space-2')!); boardAction._process(player, {piece: game.first('piece-1')!}); expect(game.first('space-1')!.all(Piece).length).to.equal(3); expect(game.first('space-2')!.all(Piece).length).to.equal(1); }); it('swaps', () => { const boardAction = new Action({}) .chooseOnBoard('piece', game.all(Piece)) .chooseOnBoard('piece2', game.all(Piece)) .swap('piece', 'piece2'); boardAction._process(player, {piece: game.first('piece-1')!, piece2: game.first('piece-3')!}); expect(game.first('space-1')!.first(Piece)!.name).to.equal('piece-3'); expect(game.first('space-1')!.firstN(2, Piece)!.last()!.name).to.equal('piece-2'); expect(game.first('space-1')!.firstN(3, Piece)!.last()!.name).to.equal('piece-1'); }); it('reorders', () => { const boardAction = new Action({}).reorder(game.all(Piece)); boardAction._process(player, {__reorder_from__: game.first('piece-1')!, __reorder_to__: game.first('piece-3')!}); expect(game.first('space-1')!.first(Piece)!.name).to.equal('piece-2'); expect(game.first('space-1')!.firstN(2, Piece)!.last()!.name).to.equal('piece-3'); expect(game.first('space-1')!.firstN(3, Piece)!.last()!.name).to.equal('piece-1'); }); it('places', () => { const boardAction = new Action({}) .chooseOnBoard('piece', game.all(Piece)) .placePiece('piece', game.first('space-2') as PieceGrid); boardAction._process(player, {piece: game.first('piece-1')!, "__placement__": [3, 2]}); expect(game.first('space-1')!.all(Piece).length).to.equal(3); expect(game.first('space-2')!.all(Piece).length).to.equal(1); const piece = game.first('piece-1')!; expect(piece.row).to.equal(2); expect(piece.column).to.equal(3); }); }); }); ================================================ FILE: src/test/compiler.cjs ================================================ const tsNode = require('ts-node'); tsNode.register({ project: './tsconfig.json', ignore: ['.*\.scss', '.*\.ogg'] }); ================================================ FILE: src/test/fixtures/games.ts ================================================ import Player from '../../player/player.js'; import { Game, Space, Piece, PieceGrid, } from '../../board/index.js'; export class TestPlayer extends Player { tokens: number = 0; } export class TestGame extends Game { tokens: number = 0; } export class Token extends Piece { color: 'red' | 'blue'; } let tiles: PieceGrid; const gameFactory = (creator: (game: TestGame) => void) => (game: TestGame) => { const { playerActions, loop, eachPlayer } = game.flowCommands; tiles = game.create(PieceGrid, 'tiles', { rows: 3, columns: 3}); for (const player of game.players) { const mat = game.create(Space, 'mat', { player }); mat.onEnter(Token, t => t.showToAll()); } game.create(Space, 'pool'); $.pool.onEnter(Token, t => t.hideFromAll()); $.pool.createMany(game.setting('tokens') - 1, Token, 'blue', { color: 'blue' }); $.pool.create(Token, 'red', { color: 'red' }); game.defineFlow( loop( eachPlayer({ name: 'player', do: playerActions({ actions: ['take'] }), }) ) ); creator(game); } export const starterGame = gameFactory(game => { game.defineActions({ take: player => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), ).move( 'token', player.my('mat')! ).message( `{{player}} drew a {{token}} token.` ).do(({ token }) => { if (token.color === 'red') { game.message("{{player}} wins!", { player }); game.finish(player); } }), }); }); export const starterGameWithConfirm = gameFactory(game => { game.defineActions({ take: player => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), { confirm: 'confirm?' } ).move( 'token', player.my('mat')!, ), }); }); export const starterGameWithValidate = gameFactory(game => { game.defineActions({ take: player => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), { validate: ({ token }) => token.container()!.first(Token) === token ? 'not first' : undefined } ).move( 'token', player.my('mat')!, ), }); }); export const starterGameWithCompoundMove = gameFactory(game => { game.defineActions({ take: player => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), ).chooseFrom( 'a', [1,2] ).move( 'token', player.my('mat')! ), }); }); export const starterGameWithTiles = gameFactory(game => { game.defineActions({ take: () => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), ).placePiece( 'token', tiles ), }); }); export const starterGameWithTilesConfirm = gameFactory(game => { game.defineActions({ take: () => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), ).placePiece( 'token', tiles, { confirm: "confirm placement?" } ), }); }); export const starterGameWithTilesValidate = gameFactory(game => { game.defineActions({ take: () => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), ).placePiece( 'token', tiles, { validate: ({ token }) => (token.column + token.row) % 2 !== 0 ? 'must be black square' : undefined, } ), }); }); export const starterGameWithTilesCompound = gameFactory(game => { game.defineActions({ take: () => game.action({ prompt: 'Choose a token', }).chooseOnBoard( 'token', $.pool.all(Token), ).placePiece( 'token', tiles, ).chooseFrom( 'a', [1,2] ), }); }); ================================================ FILE: src/test/flow_test.ts ================================================ import chai from 'chai'; import spies from 'chai-spies'; import Flow from '../flow/flow.js'; import { playerActions, loop, whileLoop, forLoop, forEach, switchCase, ifElse, } from '../flow/index.js'; import { Do, FlowControl, } from '../flow/enums.js'; import type { FlowBranchJSON } from '../flow/flow.js'; chai.use(spies); const { expect } = chai; describe('Flow', () => { let testFlow: Flow; let stepSpy1: (...a: any[]) => any; let stepSpy2: (...a: any[]) => any; let actionSpy: (...a: any[]) => any; let playSpy: (...a: any[]) => any; beforeEach(() => { stepSpy1 = chai.spy(); stepSpy2 = chai.spy(); actionSpy = chai.spy(() => {}); playSpy = chai.spy((a: string) => {a}); testFlow = new Flow({ name: 'test', do: [ () => stepSpy1(), () => stepSpy2(), () => {}, ifElse({ name: 'step4', if: () => true, do: [ () => {}, playerActions({ name: 'play-or-pass', actions: [ {name: 'play', do: ({ play }) => playSpy(play.a)}, {name: 'pass', do: [ () => {} ]} ] }), () => {} ]}), () => {} ]}); const gameManager = { flow: testFlow, players: { currentPosition: [1], atPosition: () => ({position: 1}), setCurrent: () => {} }, getAction: (a: string) => ({ play: { _process: actionSpy, messages: [] }, pass: { _process: () => {}, messages: [] } }[a]), game: { }, }; // @ts-ignore mock gameManager testFlow.gameManager = gameManager; testFlow.gameManager.game.players = testFlow.gameManager.players; testFlow.reset(); }) it('initial', () => { expect(testFlow.branchJSON()).to.deep.equal([{ type: 'main', name: 'test', sequence: 0 }]); }); it('setPosition', () => { testFlow.setBranchFromJSON([{ type: 'main', name: 'test', sequence: 0 }]); expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 0 }]); }); it('play from initial', () => { testFlow.playOneStep(); expect(stepSpy1).to.have.been.called(); expect(stepSpy2).to.not.have.been.called(); expect(testFlow.branchJSON()).to.deep.equal([{ type: 'main', name: 'test', sequence: 1 }]); }); it('play twice', () => { testFlow.playOneStep(); testFlow.playOneStep(); expect(stepSpy1).to.have.been.called(); expect(stepSpy2).to.have.been.called(); expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 2 }]); }); it('play from state', () => { testFlow.setBranchFromJSON([{ type: 'main', name: 'test', sequence: 1 }]); testFlow.playOneStep(); expect(stepSpy1).not.to.have.been.called(); expect(stepSpy2).to.have.been.called(); expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 2 }]); }); it('nested', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 0 } ]); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 0 } ]); }); it('advances into nested', () => { testFlow.setBranchFromJSON([{ type: 'main', name: 'test', sequence: 2 }]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 0 } ]); }); it('advances out of nested', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 2 } ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([{ type: 'main', name: 'test', sequence: 4 }]); }); it('awaits action', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass' } ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: "main", name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass' } ]); }); it('receives action', () => { testFlow.setBranchFromJSON([ { type: "main", name: "test", sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass' } ]); testFlow.processMove({ name: 'play', args: {a: 'violin'}, player: 1 }); expect(actionSpy).to.have.been.called(); expect(testFlow.branchJSON()).to.deep.equals([ { type: "main", name: "test", sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass', position: { name: 'play', args: {a: 'violin'}, player: 1 }} ]); }); it('rejects actions out of turn', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass' } ]); expect(() => testFlow.processMove({ name: 'play', args: {a: 'violin'}, player: 2 })).to.throw; }); it('plays action', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass', position: { name: 'play', args: {a: 'violin'}, player: 1 }} ]); testFlow.playOneStep(); expect(playSpy).to.have.been.called.with('violin'); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 2 }, ]); }); it('actions continue into other flows', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass' } ]); testFlow.processMove({ name: 'pass', args: {}, player: 1 }); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass', position: { name: 'pass', args: {}, player: 1 }, sequence: 0 }, ]); }); it('plays', () => { testFlow.play(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass' } ]); testFlow.processMove({ name: 'pass', args: {}, player: 1 }); const result = testFlow.play(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 4 } ]); expect(result).to.be.undefined; }); it('serializes', () => { const branch: FlowBranchJSON[] = [ { type: 'main', name: 'test', sequence: 3 }, { type: 'switch-case', name: 'step4', position: { index: 0, value: true, default: false }, sequence: 1 }, { type: 'action', name: 'play-or-pass', position: { name: 'pass', args: {}, player: 1 }, sequence: 0 } ]; testFlow.setBranchFromJSON(branch); expect(testFlow.branchJSON()).to.deep.equals(branch); }); it('finds by name', () => { expect(testFlow.getStep('test')?.name).to.equal('test'); expect(testFlow.getStep('step4')?.name).to.equal('step4'); expect(testFlow.getStep('play-or-pass')?.name).to.equal('play-or-pass'); }); it('disallows duplicate step names',() => { const duplFlow = new Flow({ name: 'test', do: [ () => stepSpy1(), () => stepSpy2(), () => {}, ifElse({ name: 'step4', if: () => true, do: [ () => {}, playerActions({ name: 'test', actions: [ {name: 'play', do: ({ play }) => playSpy(play.a)}, {name: 'pass', do: [ () => {} ]} ] }), () => {} ]}), () => {} ]}); expect(() => duplFlow.getStep('test')).to.throw; }); }); describe('Loop', () => { let stepSpy1: (...a: any[]) => any let stepSpy2: (...a: any[]) => any let counter: number let loop: Flow let nonLoop: Flow let testFlow: Flow; beforeEach(() => { stepSpy1 = chai.spy((x:number) => x); stepSpy2 = chai.spy((x:number) => x); counter = 10; loop = whileLoop({ while: () => counter < 13, do: ( () => { stepSpy1(counter); counter += 1; } )}); nonLoop = forLoop({ name: 'nonloop', initial: 0, next: loop => loop + 1, while: loop => loop < 0, do: ( ({ nonloop }) => stepSpy2(nonloop) )}); testFlow = new Flow({ name: 'test', do: [ () => {}, loop, () => {}, nonLoop, () => {}, ]}); // @ts-ignore testFlow.gameManager = { flow: testFlow, players: { setCurrent: () => {} } }; testFlow.reset(); }) it('enters loop', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 0 } ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 1 }, { type: 'loop', position: { index: 0 } } ]); expect(stepSpy1).to.not.have.been.called; }); it('repeats loop', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 1 }, { type: 'loop', position: { index: 0 } } ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 1 }, { type: 'loop', position: { index: 1 } } ]); expect(stepSpy1).to.have.been.called.with(10); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 1 }, { type: 'loop', position: { index: 2 } } ]); expect(stepSpy1).to.have.been.called.with(11); }); it('exits loop', () => { counter = 12; testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 1 }, { type: 'loop', position: { index: 2 } } ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 2 }, ]); }); it('skips non-loop', () => { testFlow.setBranchFromJSON([ { type: 'main', name: 'test', sequence: 2 }, ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 3 }, { type: 'loop', name: 'nonloop', position: { index: -1, value: 0 } } ]); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'main', name: 'test', sequence: 4 }, ]); expect(stepSpy2).to.not.have.been.called; }); describe('nested', () => { let stepSpy: (...a: any[]) => any; let nestedLoop: Flow; beforeEach(() => { stepSpy = chai.spy((x: number, y: number) => {x; y}); nestedLoop = forLoop({ name: 'x', initial: 0, next: x => x + 1, while: x => x < 3, do: forLoop({ name: 'y', initial: 0, next: y => y + 1, while: y => y < 2, do: ({ x, y }) => stepSpy(x, y) }) }); nestedLoop.reset(); }) it ('resets counters', () => { while(nestedLoop.playOneStep() === FlowControl.ok); expect(stepSpy).to.have.been.called.exactly(6); expect(stepSpy).on.nth(1).be.called.with(0, 0); expect(stepSpy).on.nth(2).be.called.with(0, 1); expect(stepSpy).on.nth(3).be.called.with(1, 0); expect(stepSpy).on.nth(4).be.called.with(1, 1); expect(stepSpy).on.nth(5).be.called.with(2, 0); expect(stepSpy).on.nth(6).be.called.with(2, 1); }); }); describe('foreach', () => { it ('loops', () => { const stepSpy = chai.spy((x:number) => {x}); const loop = forEach({ name: 'foreach', collection: [3, 5, 7], do: ({ foreach }) => stepSpy(foreach) }); loop.reset(); while(loop.playOneStep() === FlowControl.ok); expect(stepSpy).to.have.been.called.exactly(3); expect(stepSpy).on.nth(1).be.called.with(3); expect(stepSpy).on.nth(2).be.called.with(5); expect(stepSpy).on.nth(3).be.called.with(7); }); it ('resumes', () => { const stepSpy = chai.spy((x:number) => {x}); const loop = forEach({ name: 'foreach', collection: [3, 5, 7], do: ({ foreach }) => stepSpy(foreach) }); // @ts-ignore mock gameManager loop.gameManager = {game: {}} loop.reset(); loop.setBranchFromJSON([ { type: 'foreach', name: 'foreach', position: { index: 1, value: 5, collection: [3,5,7] } } ]); loop.playOneStep(); expect(stepSpy).to.have.been.called.with(5); expect(loop.playOneStep()).to.equal(FlowControl.complete); expect(stepSpy).to.have.been.called.with(7); }); it ('allows dynamic collection', () => { const stepSpy = chai.spy((x:number) => {x}); const outerLoop = forLoop({ name: 'loop', initial: 1, next: loop => loop + 1, while: loop => loop != 3, do: ( forEach({ name: 'foreach', collection: ({ loop }) => [10 + loop, 20 + loop], do: ({ foreach }) => stepSpy(foreach) }) )}); outerLoop.reset(); while(outerLoop.playOneStep() === FlowControl.ok); expect(stepSpy).to.have.been.called.exactly(4); expect(stepSpy).on.nth(1).be.called.with(11); expect(stepSpy).on.nth(2).be.called.with(21); expect(stepSpy).on.nth(3).be.called.with(12); expect(stepSpy).on.nth(4).be.called.with(22); }); it ('empty collection', () => { const stepSpy = chai.spy((x:number) => {x}); const empty = forEach({ name: 'foreach', collection: [], do: ({ foreach }) => stepSpy(foreach) }); empty.reset(); while(empty.playOneStep() === FlowControl.ok); expect(stepSpy).not.to.have.been.called; }); }); }); describe('Loop short-circuiting', () => { it('can repeat', () => { const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.repeat() : undefined); const stepSpy2 = chai.spy((_: string, x:number) => {x}); const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [ ({ loop }) => stepSpy2('start', loop), ({ loop }) => stepSpy1(loop), ({ loop }) => stepSpy2('end', loop) ]}); shortLoop.reset(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); expect(stepSpy2).to.have.been.called.with('start', 11); expect(stepSpy2).to.have.been.called.with('end', 11); expect(stepSpy2).to.have.been.called.with('start', 12); expect(stepSpy2).not.to.have.been.called.with('end', 12); expect(stepSpy2).not.to.have.been.called.with('start', 13); }); it('can skip', () => { const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.continue() : undefined); const stepSpy2 = chai.spy((_: string, x:number) => {x}); const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [ ({ loop }) => stepSpy2('start', loop), ({ loop }) => stepSpy1(loop), ({ loop }) => stepSpy2('end', loop) ]}); shortLoop.reset(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); expect(stepSpy2).to.have.been.called.with('start', 11); expect(stepSpy2).to.have.been.called.with('end', 11); expect(stepSpy2).to.have.been.called.with('start', 12); expect(stepSpy2).not.to.have.been.called.with('end', 12); expect(stepSpy2).to.have.been.called.with('start', 13); }); it('can break', () => { const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.break() : undefined); const stepSpy2 = chai.spy((_: string, x:number) => {x}); const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [ ({ loop }) => stepSpy2('start', loop), ({ loop }) => stepSpy1(loop), ({ loop }) => stepSpy2('end', loop) ]}); shortLoop.reset(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); const result = shortLoop.playOneStep(); expect(result).to.equal(FlowControl.complete); expect(stepSpy2).to.have.been.called.with('start', 11); expect(stepSpy2).to.have.been.called.with('end', 11); expect(stepSpy2).to.have.been.called.with('start', 12); expect(stepSpy2).not.to.have.been.called.with('end', 12); expect(stepSpy2).not.to.have.been.called.with('start', 13); }); it('rejects interrupt with no loop', () => { const badLoop = ifElse({ if: () => true, do: Do.break }) // @ts-ignore mock gameManager badLoop.gameManager = {phase: 'started'}; badLoop.reset(); expect(() => badLoop.play()).to.throw(/Do\.break/); }); it('can continue to a named loop', () => { const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.continue('loop') : undefined); const stepSpy2 = chai.spy(); const stepSpy3 = chai.spy(); const shortLoop = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 2, do: [ stepSpy2, forLoop({ name: 'loop2', initial: 10, next: loop2 => loop2 + 1, while: loop2 => loop2 < 20, do: [ ({ loop2 }) => stepSpy1(loop2), ]}), stepSpy3 ]}); shortLoop.reset(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0, loop2: 12 }); expect(stepSpy2).to.have.been.called.exactly(1); expect(stepSpy1).to.have.been.called.exactly(2); expect(stepSpy3).to.have.been.called.exactly(0); shortLoop.playOneStep(); // continue to outer loop expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 1 }); expect(stepSpy1).to.have.been.called.exactly(3); expect(stepSpy2).to.have.been.called.exactly(1); expect(stepSpy3).to.have.been.called.exactly(0); shortLoop.playOneStep(); expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 1, loop2: 10 }); expect(stepSpy1).to.have.been.called.exactly(3); expect(stepSpy2).to.have.been.called.exactly(2); }); it('can break to a named loop', () => { const stepSpy1 = chai.spy((x:number) => x === 12 ? Do.break('loop') : undefined); const stepSpy2 = chai.spy(); const stepSpy3 = chai.spy(); const stepSpy4 = chai.spy(); const shortLoop = loop( forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 2, do: [ stepSpy2, forLoop({ name: 'loop2', initial: 10, next: loop2 => loop2 + 1, while: loop2 => loop2 < 20, do: [ ({ loop2 }) => stepSpy1(loop2), ]}), stepSpy3 ]}), stepSpy4 ) shortLoop.reset(); shortLoop.playOneStep(); shortLoop.playOneStep(); shortLoop.playOneStep(); expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0, loop2: 12 }); expect(stepSpy2).to.have.been.called.exactly(1); expect(stepSpy1).to.have.been.called.exactly(2); expect(stepSpy3).to.have.been.called.exactly(0); expect(stepSpy4).to.have.been.called.exactly(0); shortLoop.playOneStep(); // break out of outer loop shortLoop.playOneStep(); // resume at topmost loop expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0 }); expect(stepSpy2).to.have.been.called.exactly(1); expect(stepSpy1).to.have.been.called.exactly(3); expect(stepSpy3).to.have.been.called.exactly(0); expect(stepSpy4).to.have.been.called.exactly(1); shortLoop.playOneStep(); // all loops starting over expect(shortLoop.flowStepArgs()).to.deep.equal({ loop: 0, loop2: 10 }); expect(stepSpy2).to.have.been.called.exactly(2); }); it('can repeat out of processMove', () => { const stepSpy2 = chai.spy((_: string, x:number) => {x}); const shortLoop = forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [ playerActions({ actions: ['breakAction'] }), ({ loop }) => {console.log('end', loop); stepSpy2('end', loop)} ]}); const gameManager = { flow: shortLoop, players: { currentPosition: [1], atPosition: () => ({position: 1}), setCurrent: () => {} }, getAction: (a: string) => ({ breakAction: { _process: Do.repeat, messages: [] }, }[a]), }; // @ts-ignore mock gameManager shortLoop.gameManager = gameManager; shortLoop.reset(); shortLoop.play(); shortLoop.processMove({ name: 'breakAction', args: {}, player: 1 }); shortLoop.play(); expect(stepSpy2).not.to.have.been.called; expect(shortLoop.position.value).to.equal(10); }); it('can break out of processMove', () => { const stepSpy1 = chai.spy(); const stepSpy2 = chai.spy(); const shortLoop = new Flow({ name: 'main', do: forLoop({ name: 'loop', initial: 10, next: loop => loop + 1, while: loop => loop < 20, do: [ playerActions({ actions: ['breakAction'] }), ({ loop }) => {console.log('end', loop); stepSpy1()} ]}), }); const gameManager = { flow: shortLoop, players: { currentPosition: [1], atPosition: () => ({position: 1}), setCurrent: () => {} }, getAction: (a: string) => ({ breakAction: { _process: Do.break, messages: [] }, }[a]), game: { finish: stepSpy2 }, }; // @ts-ignore mock gameManager shortLoop.gameManager = gameManager; shortLoop.reset(); shortLoop.play(); shortLoop.processMove({ name: 'breakAction', args: {}, player: 1 }); shortLoop.play(); expect(stepSpy1).not.to.have.been.called; expect(stepSpy2).to.have.been.called; }); }); describe('SwitchCase', () => { it('switches', () => { const stepSpy1 = chai.spy((x:number) => {x}); const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: ( switchCase({ name: 'switcher', switch: ({ loop }) => loop, cases: [ { eq: 0, do: ({ switcher }) => stepSpy1(switcher) }, { eq: 1, do: ({ switcher }) => stepSpy1(switcher) }, ]}) )}); // @ts-ignore testFlow.gameManager = { flow: testFlow }; testFlow.reset(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 0, value: 0 } }, { type: 'switch-case', name: 'switcher', position: { index: 0, value: 0, default: false } } ]); expect(stepSpy1).not.to.have.been.called; testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 1, value: 1 } }, { type: 'switch-case', name: 'switcher', position: { index: 1, value: 1, default: false } } ]); expect(stepSpy1).to.have.been.called.with(0); expect(testFlow.playOneStep()).to.equal(FlowControl.ok); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 2, value: 2 } }, { type: 'switch-case', name: 'switcher', position: { index: -1, value: 2, default: false } } ]); expect(stepSpy1).to.have.been.called.with(1); expect(testFlow.playOneStep()).to.equal(FlowControl.complete); expect(stepSpy1).to.have.been.called.exactly(2); }); it('sets position', () => { const stepSpy1 = chai.spy((x:number) => {x}); const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: ( switchCase({ name: 'switch', switch: ({ loop }) => loop, cases: [ { eq: 0, do: () => stepSpy1(0) }, { eq: 1, do: () => stepSpy1(1) }, ]}) )}); // @ts-ignore testFlow.gameManager = { flow: testFlow }; testFlow.reset(); testFlow.setBranchFromJSON([ { type: 'loop', name: 'loop', position: { index: 1, value: 1 } }, { type: 'switch-case', name: 'switch', position: { index: 1, value: 1, default: false } } ]); expect(stepSpy1).not.to.have.been.called; testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 2, value: 2 } }, { type: 'switch-case', name: 'switch', position: { index: -1, value: 2, default: false } } ]); expect(stepSpy1).to.have.been.called.with(1); }); it('defaults', () => { const stepSpy1 = chai.spy((x:number) => {x}); const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: ( switchCase({ name: 'switch', switch: ({ loop }) => loop, cases: [ { eq: 0, do: () => stepSpy1(0) }, { eq: 1, do: () => stepSpy1(1) }, ], default: () => stepSpy1(-1) }) )}); // @ts-ignore testFlow.gameManager = { flow: testFlow }; testFlow.reset(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 0, value: 0 } }, { type: 'switch-case', name: 'switch', position: { index: 0, value: 0, default: false } } ]); expect(stepSpy1).not.to.have.been.called; testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 1, value: 1 } }, { type: 'switch-case', name: 'switch', position: { index: 1, value: 1, default: false } } ]); expect(stepSpy1).to.have.been.called.with(0); expect(testFlow.playOneStep()).to.equal(FlowControl.ok); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 2, value: 2 } }, { type: 'switch-case', name: 'switch', position: { index: -1, value: 2, default: true } } ]); expect(stepSpy1).to.have.been.called.with(1); expect(testFlow.playOneStep()).to.equal(FlowControl.complete); expect(stepSpy1).to.have.been.called.with(-1); expect(stepSpy1).to.have.been.called.exactly(3); }); }); describe('IfElse', () => { it('switches', () => { const stepSpy1 = chai.spy((x:number) => {x}); const testFlow = forLoop({ name: 'loop', initial: 0, next: loop => loop + 1, while: loop => loop < 3, do: ifElse({ name: 'if', if: ({ loop }) => loop === 1, do: () => stepSpy1(0), else: () => stepSpy1(-1) }) }); // @ts-ignore testFlow.gameManager = { flow: testFlow }; testFlow.reset(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 0, value: 0 } }, { type: 'switch-case', name: 'if', position: { index: -1, default: true, value: false } } ]); expect(stepSpy1).not.to.have.been.called; testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 1, value: 1 } }, { type: 'switch-case', name: 'if', position: { index: 0, default: false, value: true } } ]); expect(stepSpy1).to.have.been.called.with(-1); testFlow.playOneStep(); expect(testFlow.branchJSON()).to.deep.equals([ { type: 'loop', name: 'loop', position: { index: 2, value: 2 } }, { type: 'switch-case', name: 'if', position: { index: -1, default: true, value: false } } ]); expect(stepSpy1).to.have.been.called.with(0); testFlow.playOneStep(); expect(stepSpy1).to.have.been.called.exactly(3); expect(stepSpy1).on.nth(1).be.called.with(-1); expect(stepSpy1).on.nth(2).be.called.with(0); expect(stepSpy1).on.nth(3).be.called.with(-1); }); }); ================================================ FILE: src/test/game_manager_test.ts ================================================ import chai from 'chai'; import spies from 'chai-spies'; import GameManager, { PlayerAttributes } from '../game-manager.js' import Player from '../player/player.js'; import { Game, Piece, Space } from '../board/index.js'; import { createGame } from '../game-creator.js'; import { createInterface } from '../interface.js'; import { Do } from '../flow/enums.js'; chai.use(spies); const { expect } = chai; describe('GameManager', () => { const players = [ { id: 'joe', name: 'Joe', color: 'red', position: 1, tokens: 0, avatar: '', host: true, }, { id: 'jane', name: 'Jane', color: 'green', position: 2, tokens: 0, avatar: '', host: false, }, { id: 'jag', name: 'Jag', color: 'yellow', position: 3, tokens: 0, avatar: '', host: false, }, { id: 'jin', name: 'Jin', color: 'purple', position: 4, tokens: 0, avatar: '', host: false, }, ]; class TestPlayer extends Player { tokens: number = 0; rival?: TestPlayer; general?: General; } class TestGame extends Game { tokens: number = 0; } class Card extends Piece { suit: string; value: number; flipped: boolean; } class Country extends Space { general?: General; } class General extends Piece { country?: Country; } let gameManager: GameManager; let game: TestGame; const spendSpy = chai.spy(); beforeEach(() => { gameManager = new GameManager(TestPlayer, TestGame, [ Card, Country, General ]); game = gameManager.game; const { playerActions, whileLoop, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 4; game.message('Starting game with {{tokens}} tokens', {tokens: game.tokens}); }, whileLoop({ while: () => game.tokens < 8, do: ( playerActions({ actions: ['addSome', 'spend']}) )}), whileLoop({ while: () => game.tokens > 0, do: ( eachPlayer({ name: 'player', startingPlayer: gameManager.players[0], do: [ playerActions({ actions: ['takeOne']}), () => { if (game.tokens <= 0) game.finish(gameManager.players.withHighest('tokens')) }, ]}) )}), ); game.defineActions({ addSome: () => game.action({ prompt: 'add some counters', }).chooseNumber('n', { prompt: 'how many?', min: 1, max: 3, }).do( ({ n }) => { game.tokens += n } ).message('{{player}} added {{n}}'), takeOne: player => game.action({ prompt: 'take one counter', }).do(() => { game.tokens --; player.tokens ++; }), spend: () => game.action({ prompt: 'Spend resource', }).chooseFrom('r', ['gold', 'silver'], { prompt: 'which resource', }).chooseNumber('n', { prompt: 'How much?', min: 1, max: 3, }).do(spendSpy), }); gameManager.players.fromJSON(players); gameManager.game.fromJSON([ { className: 'TestGame', tokens: 0 } ]); gameManager.players.assignAttributesFromJSON(players); gameManager.start(); gameManager.setFlowFromJSON([{currentPosition: [1,2,3,4], stack: [ { type: 'main', name: '__main__', sequence: 0 } ]}]); }); it('plays', () => { gameManager.play(); expect(gameManager.flowJSON()).to.deep.equals([ { currentPosition: [1,2,3,4], stack: [ { type: 'main', name: '__main__', sequence: 1 }, { type: "loop", position: { index: 0 } }, { type: "action" } ] } ]); const step = gameManager.flow().actionNeeded(); expect(step?.actions).to.deep.equal([{ name: 'addSome', args: undefined, prompt: undefined }, { name: 'spend', args: undefined, prompt: undefined }]); }); it('messages', () => { gameManager.play(); expect(gameManager.messages).to.deep.equals([ { "body": "Starting game with 4 tokens" } ]); gameManager.processMove({ name: 'addSome', args: {n: 3}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.messages).to.deep.equals([ { "body": "Starting game with 4 tokens" }, { "body": "[[$p[1]|Joe]] added 3" } ]); }); it('messages to players', () => { gameManager.actions.addSome = player => game!.action({ prompt: 'add some counters', }).chooseNumber('n', { prompt: 'how many?', min: 1, max: 3, }).do( ({ n }) => { game.tokens += n } ).messageTo( player, '{{player}} added {{n}}' ).messageTo( player.others(), '{{player}} added some' ); gameManager.play(); expect(gameManager.messages).to.deep.equals([ { "body": "Starting game with 4 tokens" } ]); gameManager.processMove({ name: 'addSome', args: {n: 3}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.messages).to.deep.equals([ { "body": "Starting game with 4 tokens" }, { "body": "[[$p[1]|Joe]] added 3", "position": 1 }, { "body": "[[$p[1]|Joe]] added some", "position": 2 }, { "body": "[[$p[1]|Joe]] added some", "position": 3 }, { "body": "[[$p[1]|Joe]] added some", "position": 4 } ]); }); it('finishes', () => { gameManager.setFlowFromJSON([{ currentPosition: [2], stack: [ { type: 'main', name: '__main__', sequence: 2 }, { type: 'loop', position: { index: 0 } }, { type: 'loop', name: 'player', position: { index: 1, value: '$p[2]' } }, { type: 'action' } ] }]); gameManager.game.fromJSON([ { className: 'TestGame', tokens: 9 } ]); gameManager.players.setCurrent(2); do { gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players.current()! }); gameManager.play(); } while (gameManager.phase === 'started'); expect(gameManager.winner.length).to.equal(1); expect(gameManager.winner[0]).to.equal(gameManager.players[1]); }); describe('state', () => { it('is stateless', () => { gameManager.play(); gameManager.processMove({ name: 'addSome', args: {n: 3}, player: gameManager.players[0] }); gameManager.play(); const boardState = gameManager.game.allJSON(); const flowState = gameManager.flowJSON(); gameManager.game.fromJSON(boardState); gameManager.setFlowFromJSON(flowState); expect(gameManager.game.allJSON()).to.deep.equals(boardState); expect(gameManager.flowJSON()).to.deep.equals(flowState); expect(game.tokens).to.equal(7); }); it("does player turns", () => { gameManager.game.fromJSON([ { className: 'TestGame', tokens: 9 } ]); gameManager.setFlowFromJSON([{ currentPosition: [2], stack: [ { type: 'main', name: '__main__', sequence: 2 }, { type: 'loop', position: { index: 0 } }, { type: 'loop', name: 'player', position: { index: 1, value: '$p[2]' } }, { type: 'action' } ]} ]); gameManager.players.setCurrent([2]); expect(gameManager.players.currentPosition).to.deep.equal([2]); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([3]); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([4]); expect(gameManager.flowJSON()[0].stack[1].position.index).to.equal(0) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1]); expect(gameManager.flowJSON()[0].stack[1].position.index).to.equal(1) }); }); describe('godMode', () => { it("does god mode moves", () => { gameManager.godMode = true; gameManager.phase = 'new'; const space1 = gameManager.game.create(Space, 'area1'); const space2 = gameManager.game.create(Space, 'area2'); const piece = space1.create(Piece, 'piece'); gameManager.start(); gameManager.play(); gameManager.processMove({ player: gameManager.players[0], name: '_godMove', args: { piece, into: space2 } }); expect(space2.first(Piece)).to.equal(piece); }); it("does god mode edits", () => { gameManager.godMode = true; gameManager.phase = 'new'; const card = gameManager.game.create(Card, 'area1', {suit: "H", value: 1, flipped: false}); gameManager.start(); gameManager.processMove({ player: gameManager.players[0], name: '_godEdit', args: { element: card, property: 'suit', value: 'S' } }); expect(card.suit).to.equal('S'); }); it("restricts god mode moves", () => { gameManager.phase = 'new'; const space1 = gameManager.game.create(Space, 'area1'); const space2 = gameManager.game.create(Space, 'area2'); const piece = space1.create(Piece, 'piece'); gameManager.start(); expect(() => gameManager.processMove({ player: gameManager.players[0], name: '_godMove', args: { piece, into: space2 } })).to.throw() }); }); describe('processAction', () => { it('runs actions', async () => { gameManager.play(); gameManager.processMove({ name: 'spend', args: {r: 'gold', n: 2}, player: gameManager.players[0] }); expect(spendSpy).to.have.been.called.with({r: 'gold', n: 2}); expect(gameManager.flowJSON()).to.deep.equals([{ currentPosition: [1,2,3,4], stack: [ { type: 'main', name: '__main__', sequence: 1 }, { type: 'loop', position: { index: 0 } }, { type: 'action', position: { name: "spend", args: {r: "gold", n: 2}, player: 1 }} ] }]); gameManager.play(); expect(gameManager.flowJSON()).to.deep.equals([{ currentPosition: [1,2,3,4], stack: [ { type: 'main', name: '__main__', sequence: 1 }, { type: 'loop', position: { index: 1 } }, { type: "action" } ] }]); }); it('changes state', async () => { gameManager.play(); expect(game.tokens).to.equal(4); gameManager.processMove({ name: 'addSome', args: {n: 2}, player: gameManager.players[0] }); expect(gameManager.flowJSON()).to.deep.equals([{ currentPosition: [1,2,3,4], stack: [ { type: 'main', name: '__main__', sequence: 1 }, { type: 'loop', position: { index: 0 } }, { type: 'action', position: { name: "addSome", args: {n: 2}, player: 1 }} ] }]); expect(game.tokens).to.equal(6); }); }); describe('players', () => { it('sortedBy', () => { expect(gameManager.players.sortedBy('color')[0].color).to.equal('green') expect(gameManager.players.sortedBy('color', 'desc')[0].color).to.equal('yellow') expect(gameManager.players[0].color).to.equal('red') }); it('sortBy', () => { gameManager.players.sortBy('color'); expect(gameManager.players[0].color).to.equal('green') }); it('withHighest', () => { expect(gameManager.players.withHighest('color')).to.equal(gameManager.players[2]) }); it('withLowest', () => { expect(gameManager.players.withLowest('color')).to.equal(gameManager.players[1]) }); it('min', () => { expect(gameManager.players.min('color')).to.equal('green') }); it('max', () => { expect(gameManager.players.max('color')).to.equal('yellow') }); it('shuffles', () => { const player = gameManager.players[0]; gameManager.setRandomSeed('a'); gameManager.players.shuffle(); expect(gameManager.players[0]).to.not.equal(player); }); it('preserves serializable attributes from json', () => { gameManager.players[0].rival = gameManager.players[1]; const json = gameManager.players.map(p => p.toJSON() as PlayerAttributes); gameManager.players.fromJSON(json); gameManager.players.assignAttributesFromJSON(json); expect(gameManager.players.map(p => p.toJSON())).to.deep.equals(json); expect(gameManager.players[0].rival).to.equal(gameManager.players[1]); }); it('handles serializable references from player to board', () => { gameManager.phase = 'new'; const map = game.create(Space, 'map', {}); const france = map.create(Country, 'france'); const england = map.create(Country, 'england'); const napoleon = france.create(General, 'napoleon', { country: france }); gameManager.players[0].general = napoleon; france.general = napoleon; gameManager.start(); const playerJSON = gameManager.players.map(p => p.toJSON() as PlayerAttributes); const boardJSON = game.allJSON(1); napoleon.putInto(england); gameManager.players.fromJSON(playerJSON); game.fromJSON(JSON.parse(JSON.stringify(boardJSON))); gameManager.players.assignAttributesFromJSON(playerJSON); expect(game.allJSON(1)).to.deep.equals(boardJSON); expect(gameManager.players.map(p => p.toJSON())).to.deep.equals(playerJSON); expect(gameManager.players[0].general?.name).to.equal('napoleon'); expect(game.first(Country, 'france')).to.equal(france); expect(game.first(Country, 'france')!.general?.name).to.equal('napoleon'); expect(game.first(Country, 'france')!.general?.country).to.equal(france); }); it('hides attributes', () => { TestPlayer.hide('rival'); gameManager.players[0].rival = gameManager.players[1]; gameManager.players[1].rival = gameManager.players[0]; const json = gameManager.players.map(p => p.toJSON(gameManager.players[0]) as PlayerAttributes); gameManager.players.fromJSON(json); gameManager.players.assignAttributesFromJSON(json); expect(gameManager.players[0].rival).to.equal(gameManager.players[1]); expect(gameManager.players[1].rival).to.be.undefined; }); }); describe('action for multiple players', () => { beforeEach(() => { gameManager = new GameManager(TestPlayer, TestGame, [ Card ]); game = gameManager.game; game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', condition: game.tokens > 0 }).do(() => { game.tokens --; player.tokens ++; }), declare: () => game.action({ prompt: 'declare', }).enterText('d', { prompt: 'declaration' }), pass: () => game.action({ prompt: 'pass' }), }); gameManager.players.fromJSON(players); gameManager.players.assignAttributesFromJSON(players); }); it('accepts move from any', () => { const { playerActions } = game.flowCommands game.defineFlow( () => { game.tokens = 4 }, playerActions({ players: gameManager.players, actions: ['takeOne'] }), ); gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] }); gameManager.play(); expect(gameManager.phase).to.equal('finished'); }); it('prompt in actionStep', () => { const { playerActions, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 1 }, eachPlayer({ name: 'player', do: playerActions({ players: gameManager.players, actions: [{name: 'takeOne', prompt: 'take one!'}] }) }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].selections[0].prompt).to.equal('take one!'); }); it('args in actionStep', () => { const { playerActions, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 1 }, eachPlayer({ name: 'player', do: playerActions({ players: gameManager.players, actions: [{name: 'declare', args: {d: 'hi'}}] }) }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].args).to.deep.equal({d: 'hi'}); }); it('functional args in actionStep', () => { const { playerActions, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 1 }, eachPlayer({ name: 'player', do: playerActions({ players: gameManager.players, actions: [{name: 'declare', args: ({ player }) => ({d: player.name}) }] }) }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].args).to.deep.equal({d: 'Joe'}); }); it('unskippable initial playerAction', () => { const { playerActions } = game.flowCommands game.defineFlow( () => { game.tokens = 1 }, playerActions({ player: gameManager.players[0], actions: ['declare'], skipIf: 'never' }) ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].selections[0].type).to.equal('button'); }); it('skippable initial playerAction', () => { const { playerActions } = game.flowCommands game.defineFlow( () => { game.tokens = 1 }, playerActions({ player: gameManager.players[0], actions: ['declare'], }) ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves[0].selections[0].type).to.equal('text'); }); it('accepts condition', () => { const { playerActions, eachPlayer } = game.flowCommands game.defineFlow( () => { game.tokens = 4 }, eachPlayer({ name: 'player', do: playerActions({ name: 'take-one', condition: ({ player }) => player.position !== 2, actions: ['takeOne'], continueIfImpossible: true, }) }) ); gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1]) gameManager.processMove({ player: gameManager.players[0], name: 'takeOne', args: {} }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([3]) }); it('optional actions', () => { const { playerActions, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 1 }, eachPlayer({ name: 'player', do: playerActions({ optional: 'Pass', actions: ['takeOne'] }) }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves.length).to.equal(2); const move1 = gameManager.processMove({ player: gameManager.players[0], name: '__pass__', args: {} }); expect(move1).to.be.undefined; gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([2]) const move2 = gameManager.processMove({ player: gameManager.players[1], name: 'takeOne', args: {} }); expect(move2).to.be.undefined; gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([3]); expect(gameManager.getPendingMoves(gameManager.players[2])?.moves.length).to.equal(1); const move3 = gameManager.processMove({ player: gameManager.players[2], name: 'takeOne', args: {} }); expect(move3).not.to.be.undefined; }); it('repeatUntil actions', () => { const actionSpy = chai.spy(); const { playerActions, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 8 }, eachPlayer({ name: 'player', do: playerActions({ name: 'repeat', repeatUntil: 'Pass', actions: [ { name: 'takeOne', do: actionSpy }, 'declare' ] }) }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.moves.length).to.equal(3); const move1 = gameManager.processMove({ player: gameManager.players[0], name: '__pass__', args: {} }); expect(move1).to.be.undefined; gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([2]) const move2 = gameManager.processMove({ player: gameManager.players[1], name: 'takeOne', args: {} }); expect(move2).to.be.undefined; gameManager.play(); expect(actionSpy).to.have.been.called.once; expect(gameManager.players.currentPosition).to.deep.equal([2]); expect(gameManager.getPendingMoves(gameManager.players[1])?.moves.length).to.equal(3); const move3 = gameManager.processMove({ player: gameManager.players[1], name: 'declare', args: {d: 'hi'} }); expect(move3).to.be.undefined; gameManager.play(); expect(actionSpy).to.have.been.called.once; expect(gameManager.players.currentPosition).to.deep.equal([2]); expect(gameManager.getPendingMoves(gameManager.players[1])?.moves.length).to.equal(3); const move4 = gameManager.processMove({ player: gameManager.players[1], name: '__pass__', args: {} }); expect(move4).to.be.undefined; gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([3]); }); it('deadlocked if impossible actions', () => { const { playerActions } = game.flowCommands game.defineFlow( () => { game.tokens = 0 }, playerActions({ name: 'take-one', players: gameManager.players, actions: ['takeOne'], }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])).to.be.undefined; expect(gameManager.phase).to.not.equal('finished'); }); it('continue if impossible actions', () => { const { playerActions } = game.flowCommands game.defineFlow( () => { game.tokens = 0 }, playerActions({ name: 'take-one', players: gameManager.players, actions: ['takeOne'], continueIfImpossible: true, }), ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])).to.be.undefined; expect(gameManager.phase).to.equal('finished'); }); it('continue if impossible actions in interface', () => { const { playerActions } = game.flowCommands const iface = createInterface( createGame(TestPlayer, TestGame, game => { game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', condition: game.tokens > 0 }).do(() => { game.tokens --; player.tokens ++; }), }); game.defineFlow( () => { game.tokens = 0 }, playerActions({ name: 'take-one', players: gameManager.players, actions: ['takeOne'], continueIfImpossible: true, }), ); }) ); const initialState = iface.initialState({ players: players, settings: {}, randomSeed: '' }); expect(initialState.game.phase).to.equal('finished'); }); it('action for every player', () => { const { playerActions, everyPlayer } = game.flowCommands game.defineFlow( () => { game.tokens = 4 }, everyPlayer({ do: playerActions({ actions: ['takeOne'] }) }) ); gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); expect(gameManager.phase).to.equal('started'); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.phase).to.equal('started'); expect(gameManager.players.currentPosition).to.deep.equal([1, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.phase).to.equal('started'); expect(gameManager.players.currentPosition).to.deep.equal([4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] }); gameManager.play(); expect(gameManager.phase).to.equal('finished'); }); it('action for every player with blocks', () => { const { playerActions, everyPlayer } = game.flowCommands const actionSpy = chai.spy((_p: Player) => {}); game.defineFlow( () => { game.tokens = 4 }, everyPlayer({ name: 'testEvery', do: [ args => actionSpy(args.testEvery), playerActions({ actions: ['takeOne'] }) ] }) ); gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]); expect(actionSpy).to.have.been.called.exactly(4); expect(actionSpy).to.have.been.called.with(game.players[0]); expect(actionSpy).to.have.been.called.with(game.players[1]); expect(actionSpy).to.have.been.called.with(game.players[2]); expect(actionSpy).to.have.been.called.with(game.players[3]); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); expect(gameManager.phase).to.equal('started'); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.phase).to.equal('started'); expect(gameManager.players.currentPosition).to.deep.equal([1, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.phase).to.equal('started'); expect(gameManager.players.currentPosition).to.deep.equal([4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] }); gameManager.play(); expect(gameManager.phase).to.equal('finished'); }); it('action for every player with followups', () => { const { playerActions, everyPlayer } = game.flowCommands game.defineFlow( () => { game.tokens = 4 }, everyPlayer({ do: playerActions({ name: 'take-1', actions: [ { name: 'takeOne', do: playerActions({ name: 'declare', actions: ['declare'] }), }, 'pass' ] }) }) ); gameManager.start(); gameManager.play(); expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]) expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.getPendingMoves(gameManager.players[2])?.step).to.equal('declare'); gameManager.processMove({ name: 'declare', args: {d: 'well i never'}, player: gameManager.players[2] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4]) expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.getPendingMoves(gameManager.players[2])).to.equal(undefined); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 4]) expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.getPendingMoves(gameManager.players[1])?.step).to.equal('declare'); expect(gameManager.getPendingMoves(gameManager.players[2])).to.equal(undefined); gameManager.processMove({ name: 'declare', args: {d: 'i do'}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 4]) expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.getPendingMoves(gameManager.players[1])).to.equal(undefined); expect(gameManager.getPendingMoves(gameManager.players[2])).to.equal(undefined); expect(gameManager.getPendingMoves(gameManager.players[3])?.step).to.equal('take-1'); }); it('survives ser/deser', () => { const { playerActions, everyPlayer } = game.flowCommands game.defineFlow( () => { game.tokens = 4 }, everyPlayer({ do: playerActions({ name: 'take-1', actions: [ { name: 'takeOne', do: playerActions({ name: 'declare', actions: ['declare'] }) }, 'pass' ] }) }) ); gameManager.start(); gameManager.play(); let boardState = gameManager.game.allJSON(); let flowState = gameManager.flowJSON(); gameManager.phase = 'new'; game.defineFlow( () => { game.tokens = 4 }, everyPlayer({ do: playerActions({ name: 'take-1', actions: [ { name: 'takeOne', do: playerActions({ name: 'declare', actions: ['declare'] }) }, 'pass' ] }) }) ); gameManager.start(); gameManager.game.fromJSON(boardState); gameManager.setFlowFromJSON(flowState); expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); boardState = gameManager.game.allJSON(); flowState = gameManager.flowJSON(); gameManager.game.fromJSON(boardState); gameManager.setFlowFromJSON(flowState); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1, 2, 3, 4]) expect(gameManager.getPendingMoves(gameManager.players[0])?.step).to.equal('take-1'); expect(gameManager.getPendingMoves(gameManager.players[2])?.step).to.equal('declare'); }); }); describe('action followups', () => { const actionSpy = chai.spy(); beforeEach(() => { gameManager = new GameManager(TestPlayer, TestGame, [ Card ]); game = gameManager.game; const { loop, eachPlayer, playerActions } = game.flowCommands game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', }).do(() => { game.tokens --; player.tokens ++; if (game.tokens < 10) game.followUp({ player: gameManager.players[1], name: 'declare', prompt: 'follow', }); }), declare: () => game.action({ prompt: 'declare', }).enterText('d', { prompt: 'declaration' }), }); gameManager.players.fromJSON(players); gameManager.players.assignAttributesFromJSON(players); game.defineFlow(loop(eachPlayer({ name: 'player', do: playerActions({ actions: [{name: 'takeOne', do: actionSpy}] }), }))); }); it('allows followup do', () => { gameManager.game.tokens = 11; gameManager.start(); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(actionSpy).to.have.been.called.once expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(0); expect(gameManager.allowedActions(gameManager.players[1]).actions.length).to.equal(1); // gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); // gameManager.play(); // expect(actionSpy).to.have.been.called.once // expect(gameManager.allowedActions(gameManager.players[1]).actions.length).to.equal(1); // expect(gameManager.allowedActions(gameManager.players[1]).actions[0].name).to.equal('declare'); // expect(gameManager.allowedActions(gameManager.players[1]).actions[0].player).to.equal(gameManager.players[1]); // expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(0); // expect(gameManager.allowedActions(gameManager.players[1]).actions[0].prompt).to.equal('follow'); // gameManager.processMove({ name: 'declare', args: {d: 'follow'}, player: gameManager.players[1] }); // gameManager.play(); // expect(actionSpy).to.have.been.called.twice }); it('allows followup for other player', () => { const { loop, eachPlayer, playerActions } = game.flowCommands gameManager.game.defineFlow(loop(eachPlayer({ name: 'player', do: [ playerActions({ actions: [{name: 'takeOne', do: actionSpy}] }), playerActions({ actions: ['declare'] }), ] }))); gameManager.game.tokens = 12; gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1]); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: 'p1'}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([2]); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: 'p1'}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([3]); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([2]); expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(0); expect(gameManager.allowedActions(gameManager.players[1]).actions.length).to.equal(1); expect(gameManager.allowedActions(gameManager.players[2]).actions.length).to.equal(0); gameManager.processMove({ name: 'declare', args: {d: 'follow'}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([3]); }); it('multi followup', () => { gameManager = new GameManager(TestPlayer, TestGame, [ Card ]); game = gameManager.game; const { loop, eachPlayer, playerActions } = game.flowCommands game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', }).do(() => { game.tokens --; player.tokens ++; if (game.tokens < 15) game.followUp({ name: 'declare' }); if (game.tokens < 10) game.followUp({ name: 'takeOne' }); }), declare: () => game.action({ prompt: 'declare', }).enterText('d', { prompt: 'declaration' }), }); gameManager.players.fromJSON(players); gameManager.players.assignAttributesFromJSON(players); game.defineFlow(loop(eachPlayer({ name: 'player', do: playerActions({ actions: ['takeOne'] }), }))); gameManager.game.tokens = 10; gameManager.start(); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: { d: 'first' }, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); }); }); describe('each player', () => { beforeEach(() => { gameManager = new GameManager(TestPlayer, TestGame, [ Card ]); game = gameManager.game; game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', }).do(() => { game.tokens --; player.tokens ++; }), }); gameManager.players.fromJSON(players.slice(0, 2)); gameManager.players.assignAttributesFromJSON(players.slice(0, 2)); }); it('continuous loop for each player', () => { const { whileLoop, playerActions, eachPlayer } = game.flowCommands game.defineFlow(whileLoop({ while: () => true, do: eachPlayer({ name: 'player', do: playerActions({ actions: ['takeOne'] }), }) })); gameManager.game.tokens = 20; gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([2]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([2]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); }); it('nested each player', () => { const { whileLoop, playerActions, eachPlayer } = game.flowCommands const stepSpy = chai.spy((_p1: number, _p2: number) => {}); game.defineFlow(whileLoop({ while: () => true, do: eachPlayer({ name: 'player1', do: eachPlayer({ name: 'player2', do: playerActions({ actions: [{name: 'takeOne', do: ({ player1, player2 }) => stepSpy(player1.position, player2.position)}] }), }) }) })); gameManager.game.tokens = 20; gameManager.start(); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([1]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(stepSpy).to.have.been.called.with(1, 1); expect(gameManager.players.currentPosition).to.deep.equal([2]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(stepSpy).to.have.been.called.with(1, 2); expect(gameManager.players.currentPosition).to.deep.equal([1]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); expect(stepSpy).to.have.been.called.with(2, 1); expect(gameManager.players.currentPosition).to.deep.equal([2]) gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); expect(stepSpy).to.have.been.called.with(2, 2); }); }); describe("subflows", () => { it("proceeds to subflow", () => { gameManager = new GameManager(TestPlayer, TestGame, [ Card, Country, General ]); game = gameManager.game; const stepSpy = chai.spy(); const { playerActions, whileLoop, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 10; game.message('Starting game with {{tokens}} tokens', {tokens: game.tokens}); }, whileLoop({ while: () => game.tokens > 0, do: ( eachPlayer({ name: 'player', do: [ playerActions({ actions: ['takeOne']}), () => { if (game.tokens <= 6) Do.subflow('token-flow'); if (game.tokens <= 0) game.finish(gameManager.players.withHighest('tokens')) }, stepSpy ]}) )}), ); game.defineSubflow( 'token-flow', eachPlayer({ name: 'player', startingPlayer: () => game.players.current()!, do: [ playerActions({ actions: [ { name: 'declare', do: ({ declare, player }) => { if (declare.d === '!') player.tokens = 0 } } ]}), ]}), () => { game.players.withLowest('tokens').tokens += 2; } ); game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', }).do(() => { game.tokens --; player.tokens ++; }), declare: () => game.action({ prompt: 'declare', }).enterText('d', { prompt: 'declaration' }), pass: () => game.action({ prompt: 'pass' }), }); gameManager.players.fromJSON(players); gameManager.game.fromJSON([ { className: 'TestGame', tokens: 0 } ]); gameManager.players.assignAttributesFromJSON(players); gameManager.start(); gameManager.play(); // start play gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([4]); expect(gameManager.allowedActions(gameManager.players[3]).actions.length).to.equal(1); expect(gameManager.allowedActions(gameManager.players[3]).actions[0].name).to.equal('declare'); expect(stepSpy).to.have.been.called.exactly(3); gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[3] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: '!'}, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[1] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[2] }); gameManager.play(); // cedes to previous flow expect(stepSpy).to.have.been.called.exactly(4); expect(gameManager.players[0].tokens).to.equal(2); expect(gameManager.players.currentPosition).to.deep.equal([1]); expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(1); expect(gameManager.allowedActions(gameManager.players[0]).actions[0].name).to.equal('takeOne'); }); it("proceeds to subflow from action do", () => { gameManager = new GameManager(TestPlayer, TestGame, [ Card, Country, General ]); game = gameManager.game; const { playerActions, whileLoop, eachPlayer, } = game.flowCommands game.defineFlow( () => { game.tokens = 10; game.message('Starting game with {{tokens}} tokens', {tokens: game.tokens}); }, whileLoop({ while: () => game.tokens > 0, do: ( eachPlayer({ name: 'player', do: [ playerActions({ actions: ['takeOne']}), () => { if (game.tokens <= 0) game.finish(gameManager.players.withHighest('tokens')) }, ]}) )}), ); game.defineSubflow( 'token-flow', eachPlayer({ name: 'player', startingPlayer: () => game.players.current()!, do: [ playerActions({ actions: [ { name: 'declare', do: ({ declare, player }) => { if (declare.d === '!') player.tokens = 0 } } ]}), ]}), () => { game.players.withLowest('tokens').tokens += 2; } ); game.defineActions({ takeOne: player => game.action({ prompt: 'take one counter', }).do(() => { game.tokens --; player.tokens ++; if (game.tokens <= 6) Do.subflow('token-flow'); }), declare: () => game.action({ prompt: 'declare', }).enterText('d', { prompt: 'declaration' }), pass: () => game.action({ prompt: 'pass' }), }); gameManager.players.fromJSON(players); gameManager.game.fromJSON([ { className: 'TestGame', tokens: 0 } ]); gameManager.players.assignAttributesFromJSON(players); gameManager.start(); gameManager.play(); // start play gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[1] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[2] }); gameManager.play(); gameManager.processMove({ name: 'takeOne', args: {}, player: gameManager.players[3] }); gameManager.play(); expect(gameManager.players.currentPosition).to.deep.equal([4]); expect(gameManager.allowedActions(gameManager.players[3]).actions.length).to.equal(1); expect(gameManager.allowedActions(gameManager.players[3]).actions[0].name).to.equal('declare'); // starting player set from current which was still last player gameManager.processMove({ name: 'declare', args: {d: '!'}, player: gameManager.players[3] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[0] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[1] }); gameManager.play(); gameManager.processMove({ name: 'declare', args: {d: '?'}, player: gameManager.players[2] }); gameManager.play(); // cedes to previous flow expect(gameManager.players[3].tokens).to.equal(2); expect(gameManager.players.currentPosition).to.deep.equal([1]); expect(gameManager.allowedActions(gameManager.players[0]).actions.length).to.equal(1); expect(gameManager.allowedActions(gameManager.players[0]).actions[0].name).to.equal('takeOne'); }); }); }); ================================================ FILE: src/test/game_test.ts ================================================ import chai from 'chai'; import spies from 'chai-spies'; import random from 'random-seed'; import { Game, Space, Piece, ConnectedSpaceMap, SquareGrid, HexGrid, PieceGrid } from '../board/index.js'; import { Player, PlayerCollection, } from '../player/index.js'; import type { BaseGame } from '../board/game.js'; import { applyLayouts } from '../ui/render.js'; chai.use(spies); const { expect } = chai; describe('Game', () => { let game: BaseGame; const players = new PlayerCollection; players.className = Player; players.addPlayer({ id: 'joe', name: 'Joe', position: 1, color: 'red', avatar: '', host: true }); players.addPlayer({ id: 'jane', name: 'Jane', position: 2, color: 'green', avatar: '', host: false }); beforeEach(() => { game = new Game({ // @ts-ignore gameManager: { players, addDelay: () => {}, random: random.create('a').random }, }); game._ctx.gameManager.game = game; game.setBoardSize({ name: '_default', aspectRatio: 1, frame: {x:100, y:100}, screen: {x:100, y:100} }); }); it('renders', () => { expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0 }, ] ); }); it('creates new spaces', () => { game.create(Space, 'map', {}); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'map', _id: 2 } ]}, ] ); }); it('creates new pieces', () => { game.create(Piece, 'token', { player: players[0] }); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Piece', name: 'token', _id: 2, player: '$p[1]' } ]}, ] ); }); it('destroys pieces', () => { game.create(Piece, 'token', { player: players[1] }); game.create(Piece, 'token', { player: players[0] }); game.first(Piece)!.destroy(); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Piece', name: 'token', _id: 3, player: '$p[1]' } ]}, ] ); }); it('removes pieces', () => { game.create(Piece, 'token', { player: players[1] }); game.create(Piece, 'token', { player: players[0] }); game.first(Piece)!.remove(); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Piece', name: 'token', _id: 3, player: '$p[1]' } ]}, { className: 'Piece', name: 'token', _id: 2, player: '$p[2]' } ] ); }); it('removes all', () => { game.create(Piece, 'token', { player: players[1] }); game.create(Piece, 'token', { player: players[0] }); game.all(Piece).remove(); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0}, { className: 'Piece', name: 'token', _id: 2, player: '$p[2]' }, { className: 'Piece', name: 'token', _id: 3, player: '$p[1]' } ] ); }); it('builds from json', () => { const map = game.create(Space, 'map', {}); const france = map.create(Space, 'france', {}); map.create(Piece, 'token3'); map.create(Space, 'england', {}); game.create(Space, 'play', {}); const piece1 = france.create(Piece, 'token1', { player: players[0] }); const piece2 = france.create(Piece, 'token2', { player: players[1] }); const json = game.allJSON(); game.fromJSON(JSON.parse(JSON.stringify(game.allJSON()))); expect(game.allJSON()).to.deep.equals(json); expect(game.first(Piece, 'token1')!._t.id).to.equal(piece1._t.id); expect(game.first(Piece, 'token1')!.player).to.equal(players[0]); expect(game.first(Piece, 'token2')!._t.id).to.equal(piece2._t.id); expect(game.first(Piece, 'token2')!.player).to.equal(players[1]); expect(game.first(Space, 'france')).to.equal(france); }); it('preserves serializable attributes from json', () => { class Country extends Space { rival: Country; general: Piece; } const map = game.create(Space, 'map', {}); const napolean = map.create(Piece, 'napolean') const england = map.create(Country, 'england', {}); const france = map.create(Country, 'france', { rival: england, general: napolean }); const json = game.allJSON(); game.fromJSON(JSON.parse(JSON.stringify(json))); expect(game.allJSON()).to.deep.equals(json); expect(game.first(Country, 'france')).to.equal(france); expect(game.first(Country, 'france')!.rival).to.equal(england); expect(game.first(Country, 'france')!.general).to.equal(napolean); }); it('handles cyclical serializable attributes', () => { class Country extends Space { general?: General; } class General extends Piece { country?: Country; } const map = game.create(Space, 'map', {}); const france = map.create(Country, 'france'); const napolean = france.create(General, 'napolean', { country: france }); france.general = napolean; const json = game.allJSON(1); game.fromJSON(JSON.parse(JSON.stringify(json))); expect(game.allJSON(1)).to.deep.equals(json); expect(game.first(Country, 'france')).to.equal(france); expect(game.first(Country, 'france')!.general?.name).to.equal('napolean'); expect(game.first(Country, 'france')!.general?.country).to.equal(france); }); it('understands branches', () => { const map = game.create(Space, 'map', {}); const france = map.create(Space, 'france', {}); map.create(Space, 'england', {}); const play = game.create(Space, 'play', {}); const piece1 = france.create(Piece, 'token1', { player: players[0] }); const piece2 = france.create(Piece, 'token2', { player: players[1] }); const piece3 = play.create(Piece, 'token3'); expect(piece1.branch()).to.equal('0/0/0/0'); expect(piece2.branch()).to.equal('0/0/0/1'); expect(piece3.branch()).to.equal('0/1/0'); expect(game.atBranch('0/0/0/0')).to.equal(piece1); expect(game.atBranch('0/0/0/1')).to.equal(piece2); expect(game.atBranch('0/1/0')).to.equal(piece3); }); it('assigns and finds IDs', () => { const map = game.create(Space, 'map', {}); const france = map.create(Space, 'france', {}); map.create(Space, 'england', {}); const play = game.create(Space, 'play', {}); const piece1 = france.create(Piece, 'token1', { player: players[0] }); const piece2 = france.create(Piece, 'token2', { player: players[1] }); const piece3 = play.create(Piece, 'token3'); expect(piece1._t.id).to.equal(6); expect(piece2._t.id).to.equal(7); expect(piece3._t.id).to.equal(8); expect(game.atID(6)).to.equal(piece1); expect(game.atID(7)).to.equal(piece2); expect(game.atID(8)).to.equal(piece3); }); it('clones', () => { const map = game.create(Space, 'map', {}); const france = map.create(Space, 'france', {}); const england = map.create(Space, 'england', {}); const piece1 = france.create(Piece, 'token1', { player: players[0] }); const piece2 = piece1.cloneInto(england); expect(piece1.player).to.equal(piece2.player); expect(piece1.name).to.equal(piece2.name); expect(england._t.children).to.include(piece2); }); describe("Element subclasses", () => { class Card extends Piece { suit: string; pip: number = 1; flipped?: boolean = false; state?: string = 'initial'; } it('takes attrs', () => { game.create(Card, '2H', { suit: 'H', pip: 2 }); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 2 } ]}, ] ); }); it('takes base attrs', () => { game.create(Card, '2H', { player: players[1], suit: 'H', pip: 2 }); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Card', flipped: false, state: 'initial', name: '2H', player: '$p[2]', suit: 'H', pip: 2, _id: 2 } ]}, ] ); }); it('searches', () => { game.create(Card, 'AH', { suit: 'H', pip: 1 }); game.create(Card, '2H', { suit: 'H', pip: 2 }); game.create(Card, '3H', { suit: 'H', pip: 3 }); const card = game.first(Card, {pip: 2}); expect(card!.name).equals('2H'); const card2 = game.first(Card, {pip: 4}); expect(card2).equals(undefined); const card3 = game.first(Card, {pip: 2, suit: 'D'}); expect(card3).equals(undefined); const cards = game.all(Card, c => c.pip >= 2); expect(cards.length).equals(2); expect(cards[0].name).equals('2H'); expect(cards[1].name).equals('3H'); const card4 = game.first("2H"); expect(card4!.name).equals('2H'); }); it('searches undefined', () => { game.create(Card, 'AH', { suit: 'H', pip: 1, player: players[0] }); game.create(Card, '2H', { suit: 'H', pip: 2, player: players[1] }); const h3 = game.create(Card, '3H', { suit: 'H', pip: 3 }); expect(game.first(Card, {player: undefined})).to.equal(h3); }), it('has', () => { game.create(Card, 'AH', { suit: 'H', pip: 1, player: players[0] }); game.create(Card, '2H', { suit: 'H', pip: 2, player: players[1] }); expect(game.has(Card, {pip: 2})).to.equal(true); expect(game.has(Card, {pip: 2, suit: 'C'})).to.equal(false); }), it('modifies', () => { game.create(Card, 'AH', { suit: 'H', pip: 1 }); game.create(Card, '2H', { suit: 'H', pip: 2 }); game.create(Card, '3H', { suit: 'H', pip: 3 }); const card = game.first(Card, {pip: 2})!; card.suit = 'D'; expect(card.suit).equals('D'); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 2 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'D', pip: 2, _id: 3 }, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 4 } ]}, ] ); }); it('takes from pile', () => { game.create(Card, 'AH', { suit: 'H', pip: 1 }); game.create(Card, '2H', { suit: 'H', pip: 2 }); const pile = game._ctx.removed; const h3 = pile.create(Card, '3H', { suit: 'H', pip: 3 }); expect(h3.branch()).to.equal('1/0'); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 2 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 3 }, ]}, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 4 } ] ); expect(game.all(Card).length).to.equal(2); expect(pile.all(Card).length).to.equal(1); }); it('moves', () => { const deck = game.create(Space, 'deck'); const discard = game.create(Space, 'discard'); deck.create(Card, 'AH', { suit: 'H', pip: 1 }); deck.create(Card, '2H', { suit: 'H', pip: 2 }); deck.create(Card, '3H', { suit: 'H', pip: 3 }); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 } ]}, { className: 'Space', name: 'discard', _id: 3} ]}, ] ); deck.lastN(2, Card).putInto(discard); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 } ]}, { className: 'Space', name: 'discard', _id: 3, children: [ { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 } ]} ]}, ] ); }); it('moves with stacking order', () => { const deck = game.create(Space, 'deck'); const discard = game.create(Space, 'discard'); deck.setOrder('stacking'); deck.create(Card, 'AH', { suit: 'H', pip: 1 }); deck.create(Card, '2H', { suit: 'H', pip: 2 }); deck.create(Card, '3H', { suit: 'H', pip: 3 }); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, order: 'stacking', children: [ { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 } ]}, { className: 'Space', name: 'discard', _id: 3} ]}, ] ); deck.lastN(2, Card).putInto(discard); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, order: 'stacking', children: [ { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 } ]}, { className: 'Space', name: 'discard', _id: 3, children: [ { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 } ]} ]}, ] ); discard.all(Card).putInto(deck); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, order: 'stacking', children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 } ]}, { className: 'Space', name: 'discard', _id: 3} ]}, ] ); }); it('moves fromTop', () => { const deck = game.create(Space, 'deck'); const discard = game.create(Space, 'discard'); deck.create(Card, 'AH', { suit: 'H', pip: 1 }); deck.create(Card, '2H', { suit: 'H', pip: 2 }); deck.create(Card, '3H', { suit: 'H', pip: 3 }); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 } ]}, { className: 'Space', name: 'discard', _id: 3} ]}, ] ); deck.lastN(2, Card).putInto(discard, {fromTop: 0}); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 } ]}, { className: 'Space', name: 'discard', _id: 3, children: [ { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 }, { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 } ]} ]}, ] ); }); it('tracks movement', () => { const deck = game.create(Space, 'deck'); const discard = game.create(Space, 'discard'); deck.create(Card, 'AH', { suit: 'H', pip: 1 }); deck.create(Card, '2H', { suit: 'H', pip: 2 }); deck.create(Card, '3H', { suit: 'H', pip: 3 }); const json = game.allJSON(); game._ctx.trackMovement = true; game.fromJSON(json); deck.lastN(2, Card).putInto(discard); expect(game.allJSON()).to.deep.equals( [ { className: 'Game', _id: 0, children: [ { className: 'Space', name: 'deck', _id: 2, children: [ { className: 'Card', flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _id: 4 } ]}, { className: 'Space', name: 'discard', _id: 3, children: [ { className: 'Card', flipped: false, state: 'initial', name: '2H', suit: 'H', pip: 2, _id: 5 }, { className: 'Card', flipped: false, state: 'initial', name: '3H', suit: 'H', pip: 3, _id: 6 } ]} ]}, ] ); }); it("understands players", () => { const players1Mat = game.create(Space, 'mat', {player: players[0]}); game.create(Space, 'mat', {player: players[1]}); players1Mat.create(Card, 'player-1-card', { suit: 'H', pip: 1, player: players[0] }); players1Mat.create(Card, 'player-2-card', { suit: 'H', pip: 1, player: players[1] }); players1Mat.create(Card, 'neutral-card', { suit: 'H', pip: 2 }); players[0].game = game; players[1].game = game; expect(() => game.all(Card, { mine: true })).to.throw; game._ctx.player = players[0]; expect(game.all(Card, { mine: true }).length).to.equal(2); expect(game.all(Card, { mine: false }).length).to.equal(1); expect(game.all(Card, { owner: players[0] }).length).to.equal(2); expect(game.last(Card, { mine: true })!.name).to.equal('neutral-card'); expect(game.first('neutral-card')!.owner).to.equal(players[0]); game._ctx.player = players[1]; expect(game.all(Card, { mine: true }).length).to.equal(1); expect(game.all(Card, { owner: players[1] }).length).to.equal(1); expect(game.all(Card, { mine: false }).length).to.equal(2); expect(players[0].allMy(Card).length).to.equal(2); expect(players[1].allMy(Card).length).to.equal(1); expect(players[0].has(Card, {pip: 1})).to.equal(true); expect(players[0].has(Card, 'player-2-card')).to.equal(false); expect(players[0].has(Card, {pip: 2})).to.equal(true); expect(players[1].has(Card, {pip: 1})).to.equal(true); expect(players[1].has(Card, {pip: 2})).to.equal(false); }); it("sorts", () => { const deck = game.create(Space, 'deck'); deck.create(Card, 'AH', { suit: 'H', pip: 1 }); deck.create(Card, '2C', { suit: 'C', pip: 2 }); deck.create(Card, '3D', { suit: 'D', pip: 3 }); deck.create(Card, '2H', { suit: 'H', pip: 2 }); expect(game.all(Card).withHighest('pip')!.name).to.equal('3D'); expect(game.all(Card).withHighest('suit')!.name).to.equal('AH'); expect(game.all(Card).withHighest('suit', 'pip')!.name).to.equal('2H'); expect(game.all(Card).withHighest(c => c.suit === 'D' ? 100 : 1)!.name).to.equal('3D'); expect(game.all(Card).min('pip')).to.equal(1); expect(game.all(Card).max('pip')).to.equal(3); expect(game.all(Card).min('suit')).to.equal('C'); expect(game.all(Card).max('suit')).to.equal('H'); }); it("shuffles", () => { const deck = game.create(Space, 'deck'); deck.create(Card, 'AH', { suit: 'H', pip: 1 }); deck.create(Card, '2C', { suit: 'C', pip: 2 }); deck.create(Card, '3D', { suit: 'D', pip: 3 }); deck.create(Card, '2H', { suit: 'H', pip: 2 }); deck.shuffle(); expect(deck.first(Card)!.name).to.not.equal('AH'); }); it("isVisibleTo", () => { const card = game.create(Card, 'AH', { suit: 'H', pip: 1 }); expect(card.isVisible()).to.equal(true); card.hideFromAll(); expect(card.isVisible()).to.equal(false); expect(card.isVisibleTo(1)).to.equal(false); expect(card.isVisibleTo(2)).to.equal(false); card.showTo(1); expect(card.isVisibleTo(1)).to.equal(true); expect(card.isVisibleTo(2)).to.equal(false); card.hideFrom(1); expect(card.isVisibleTo(1)).to.equal(false); expect(card.isVisibleTo(2)).to.equal(false); card.showToAll(); expect(card.isVisibleTo(1)).to.equal(true); expect(card.isVisibleTo(2)).to.equal(true); card.hideFrom(1); expect(card.isVisibleTo(1)).to.equal(false); expect(card.isVisibleTo(2)).to.equal(true); card.showTo(1); expect(card.isVisibleTo(1)).to.equal(true); expect(card.isVisibleTo(2)).to.equal(true); }); it("hides", () => { Card.revealWhenHidden('pip', 'flipped', 'state'); const card = game.create(Card, 'AH', { suit: 'H', pip: 1 }); card.showOnlyTo(1); expect(card.toJSON(1)).to.deep.equal( { className: 'Card', _ref: 2, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1, _visible: { default: false, except: [1] } }, ); expect(card.toJSON(2)).to.deep.equal( { className: 'Card', _ref: 2, flipped: false, state: 'initial', pip: 1, _visible: { default: false, except: [1] } }, ) game.fromJSON(JSON.parse(JSON.stringify(game.allJSON(2)))); const card3 = game.first(Card)!; expect(card3.pip).to.equal(1); expect(card3.suit).to.equal(undefined); }); it("hides spaces", () => { const hand = game.create(Space, 'hand', { player: players[0] }); hand.create(Card, 'AH', { suit: 'H', pip: 1 }); hand.blockViewFor('all-but-owner'); expect(hand.toJSON(1)).to.deep.equal( { className: 'Space', name: "hand", player: "$p[1]", _ref: 2, children: [ {className: 'Card', _ref: 3, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1}, ]} ); expect(hand.toJSON(2)).to.deep.equal( { className: 'Space', name: "hand", player: "$p[1]", _ref: 2 } ); hand.blockViewFor('all'); expect(hand.toJSON(1)).to.deep.equal( { className: 'Space', name: "hand", player: "$p[1]", _ref: 2 } ); expect(hand.toJSON(2)).to.deep.equal( { className: 'Space', name: "hand", player: "$p[1]", _ref: 2 } ); hand.blockViewFor('none'); expect(hand.toJSON(1)).to.deep.equal( { className: 'Space', name: "hand", player: "$p[1]", _ref: 2, children: [ {className: 'Card', _ref: 3, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1}, ]} ); expect(hand.toJSON(2)).to.deep.equal( { className: 'Space', name: "hand", player: "$p[1]", _ref: 2, children: [ {className: 'Card', _ref: 3, flipped: false, state: 'initial', name: 'AH', suit: 'H', pip: 1}, ]} ); }); it("listens to add events", () => { const eventSpy = chai.spy(); game.onEnter(Card, eventSpy); const card = game.create(Card, "AH", {suit: "H", pip: 1}); expect(eventSpy).to.have.been.called.with(card) }); it("listens to add events from moves", () => { const eventSpy = chai.spy(); const deck = game.create(Space, 'deck'); game.create(Space, 'discard'); deck.onEnter(Card, eventSpy); const card = game.create(Card, "AH", {suit: "H", pip: 1}); card.putInto(deck); expect(eventSpy).to.have.been.called.with(card) }); it("listens to exit events from moves", () => { const eventSpy = chai.spy(); const deck = game.create(Space, 'deck'); game.create(Space, 'discard'); deck.onExit(Card, eventSpy); const card = game.create(Card, "AH", {suit: "H", pip: 1}); card.putInto(deck); expect(eventSpy).not.to.have.been.called() card.remove(); expect(eventSpy).to.have.been.called.with(card) }); it("preserves events in JSON", () => { const eventSpy = chai.spy(); game.onEnter(Card, eventSpy); game.fromJSON(JSON.parse(JSON.stringify(game.allJSON()))); game.create(Card, "AH", {suit: "H", pip: 1}); expect(eventSpy).to.have.been.called() }); it('query siblings', () => { const space = game.create(Space, 'map', {}); const card1 = space.create(Card, 'p1'); const piece1 = space.create(Piece, 'c1'); const card2 = space.create(Card, 'p2'); const card3 = space.create(Card, 'p3'); expect(card2.others(Card)).to.deep.equal([card1, card3]); expect(card2.others()).to.deep.equal([card1, piece1, card3]); expect(card2.next()).to.equal(card3); expect(card2.previous()).to.equal(card1); expect(card3.next()).to.equal(undefined); }); }); describe("graph", () => { let map: ConnectedSpaceMap; beforeEach(() => { map = game.create(ConnectedSpaceMap, 'map'); }); it("adjacency", () => { const a = map.create(Space, 'a'); const b = map.create(Space, 'b'); const c = map.create(Space, 'c'); map.connect(a, b); expect(a.isAdjacentTo(b)).to.equal(true); expect(a.isAdjacentTo(c)).to.equal(false); expect(map.isAdjacent(a, b)).to.equal(true); expect(map.isAdjacent(a, c)).to.equal(false); }) it("calculates distance", () => { const a = map.create(Space, 'a'); const b = map.create(Space, 'b'); const c = map.create(Space, 'c'); map.connect(a, b, 2); map.connect(b, c, 3); map.connect(a, c, 6); expect(a.distanceTo(c)).to.equal(5); expect(map.distanceBetween(a, c)).to.equal(5); }) it("calculates closest", () => { const a = map.create(Space, 'a'); const b = map.create(Space, 'b'); const c = map.create(Space, 'c'); map.connect(a, b, 2); map.connect(b, c, 3); map.connect(a, c, 6); expect(map.closestTo(a)).to.equal(b); }) it("finds adjacencies", () => { const a = map.create(Space, 'a'); const b = map.create(Space, 'b'); const c = map.create(Space, 'c'); const d = map.create(Space, 'd'); map.connect(a, b, 2); map.connect(b, c, 3); map.connect(a, c, 6); map.connect(c, d, 1); expect(a.adjacencies()).to.deep.equal([b, c]); expect(c.adjacencies()).to.deep.equal([a, b, d]); expect(map.allAdjacentTo(a)).to.deep.equal([b, c]); expect(map.allAdjacentTo(c)).to.deep.equal([a, b, d]); }) it("searches by distance", () => { const a = map.create(Space, 'a'); const b = map.create(Space, 'b'); const c = map.create(Space, 'c'); const d = map.create(Space, 'd'); map.connect(a, b, 2); map.connect(b, c, 3); map.connect(a, c, 6); map.connect(c, d, 1); expect(a.withinDistance(5).all(Space)).to.deep.equal([b, c]); expect(map.allWithinDistanceOf(a, 5, Space)).to.deep.equal([b, c]); }) it("searches contiguous", () => { const a = map.create(Space, 'a'); const b = map.create(Space, 'b'); const c = map.create(Space, 'c'); const d = map.create(Space, 'd'); const e = map.create(Space, 'e'); const f = map.create(Space, 'f'); map.connect(a, b, 2); map.connect(b, c, 3); map.connect(a, c, 6); map.connect(c, d, 1); map.connect(e, f, 1); expect(map.allConnectedTo(a).all(Space)).to.deep.equal([a, b, c, d]); }) }); describe('grids', () => { class Cell extends Space { color: string } it('creates squares', () => { game.create(SquareGrid, 'square', { rows: 3, columns: 3, space: Cell }); expect(game.all(Cell).length).to.equal(9); expect(game.first(Cell)!.row).to.equal(1); expect(game.first(Cell)!.column).to.equal(1); expect(game.last(Cell)!.row).to.equal(3); expect(game.last(Cell)!.column).to.equal(3); const corner = game.first(Cell, {row: 1, column: 1})!; expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1]]); const middle = game.first(Cell, {row: 2, column: 2})!; expect(middle.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1], [2,3], [3,2]]); }); it('creates squares with diagonals', () => { const square = game.create(SquareGrid, 'square', { rows: 3, columns: 3, diagonalDistance: 1.5, space: Cell }); expect(game.all(Cell).length).to.equal(9); expect(game.first(Cell)!.row).to.equal(1); expect(game.first(Cell)!.column).to.equal(1); expect(game.last(Cell)!.row).to.equal(3); expect(game.last(Cell)!.column).to.equal(3); const corner = game.first(Cell, {row: 1, column: 1})!; expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1], [2,2]]); const knight = game.first(Cell, {row: 3, column: 2})!; expect(square.distanceBetween(corner, knight)).to.equal(2.5); }); it('creates hexes', () => { game.create(HexGrid, 'hex', { rows: 3, columns: 3, space: Cell }); expect(game.all(Cell).length).to.equal(9); expect(game.first(Cell)!.row).to.equal(1); expect(game.first(Cell)!.column).to.equal(1); expect(game.last(Cell)!.row).to.equal(3); expect(game.last(Cell)!.column).to.equal(3); const corner = game.first(Cell, {row: 1, column: 1})!; expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1], [2,2]]); const middle = game.first(Cell, {row: 2, column: 2})!; expect(middle.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,1], [1,2], [2,1], [2,3], [3,2], [3,3]]); }); it('creates inverse hexes', () => { game.create(HexGrid, 'hex', { rows: 3, columns: 3, axes: 'east-by-southeast', space: Cell }); expect(game.all(Cell).length).to.equal(9); expect(game.first(Cell)!.row).to.equal(1); expect(game.first(Cell)!.column).to.equal(1); expect(game.last(Cell)!.row).to.equal(3); expect(game.last(Cell)!.column).to.equal(3); const corner = game.first(Cell, {row: 1, column: 1})!; expect(corner.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [2,1]]); const middle = game.first(Cell, {row: 2, column: 2})!; expect(middle.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,2], [1,3], [2,1], [2,3], [3,1], [3,2]]); }); it('creates hex-shaped hexes', () => { game.create(HexGrid, 'hex', { rows: 4, columns: 5, shape: 'hex', space: Cell }); expect(game.all(Cell).length).to.equal(16); expect(game.all(Cell, {row: 1}).length).to.equal(3); expect(game.all(Cell, {row: 2}).length).to.equal(4); expect(game.all(Cell, {row: 3}).length).to.equal(5); expect(game.all(Cell, {row: 4}).length).to.equal(4); const cell = game.first(Cell, {row: 2, column: 4})!; expect(cell.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,3], [2,3], [3,4], [3,5]]); }); it('creates inverse hex-shaped hexes', () => { game.create(HexGrid, 'hex', { rows: 4, columns: 5, shape: 'hex', axes: 'east-by-southeast', space: Cell }); expect(game.all(Cell).length).to.equal(16); expect(game.all(Cell, {row: 1}).length).to.equal(3); expect(game.all(Cell, {row: 2}).length).to.equal(4); expect(game.all(Cell, {row: 3}).length).to.equal(5); expect(game.all(Cell, {row: 4}).length).to.equal(4); const cell = game.first(Cell, {row: 2, column: 2})!; expect(cell.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,3], [2,3], [3,1], [3,2]]); }); it('creates square-shaped hexes', () => { game.create(HexGrid, 'hex', { rows: 4, columns: 5, shape: 'square', axes: 'east-by-southeast', space: Cell }); expect(game.all(Cell).length).to.equal(18); expect(game.all(Cell, {row: 1}).length).to.equal(5); expect(game.all(Cell, {row: 2}).length).to.equal(4); expect(game.all(Cell, {row: 3}).length).to.equal(5); expect(game.all(Cell, {row: 4}).length).to.equal(4); const cell = game.first(Cell, {row: 2, column: 1})!; expect(cell.adjacencies(Cell).map(e => [e.row, e.column])).to.deep.equal([[1,1], [1,2], [2,2], [3,0], [3,1]]); }); it('adjacencies', () => { game.create(SquareGrid, 'square', { rows: 3, columns: 3, space: Cell }); for (const cell of game.all(Cell, {row: 2})) cell.color = 'red'; const center = game.first(Cell, {row: 2, column: 2})!; expect(center.adjacencies(Cell).map(c => [c.row, c.column])).to.deep.equal([[1, 2], [2, 1], [2, 3], [3, 2]]); expect(center.adjacencies(Cell, {color: 'red'}).map(c => [c.row, c.column])).to.deep.equal([[2, 1], [2, 3]]); expect(center.isAdjacentTo(game.first(Cell, {row: 1, column: 2})!)).to.be.true; expect(center.isAdjacentTo(game.first(Cell, {row: 1, column: 1})!)).to.be.false; }); it('deep adjacencies', () => { game.create(SquareGrid, 'square', { rows: 3, columns: 3, space: Cell }); const topLeft = game.first(Cell, {row: 1, column: 1})!; const topCenter = game.first(Cell, {row: 1, column: 2})!; const center = game.first(Cell, {row: 2, column: 2})!; const p1 = topLeft.create(Piece, 'p1'); const p2 = topCenter.create(Piece, 'p2'); const p3 = center.create(Piece, 'p3'); expect(p2.adjacencies(Piece)).to.deep.equal([p1, p3]); expect(p1.adjacencies(Piece)).to.deep.equal([p2]); expect(p3.adjacencies(Piece)).to.deep.equal([p2]); }); }); describe('shapes', () => { let p1: Piece; let p2: Piece; let map: PieceGrid; beforeEach(() => { map = game.create(PieceGrid, 'map'); p1 = map.create(Piece, 'p1'); p2 = map.create(Piece, 'p2'); p1.setShape( 'ABC', 'D ', 'E ', ); p2.setShape( 'abcd', 'e f ', ); }); describe("both zero degrees", () => { it('finds overlap 1', () => { p1.column = 0; p1.row = 0; p2.column = 0; p2.row = 0; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 2', () => { p1.column = 0; p1.row = 0; p2.column = 1; p2.row = 1; expect(map.isOverlapping(p1, p2)).to.be.false; }); it('finds overlap 3', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = -1; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 4', () => { p1.column = 4; p1.row = 2; p2.column = 1; p2.row = 1; expect(map.isOverlapping(p1, p2)).to.be.false; }); }); describe("p1 at 90 degrees", () => { beforeEach(() => p1.rotation = 90); it('finds overlap 5', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = 1; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 6', () => { p1.column = 0; p1.row = 0; p2.column = -2; p2.row = 1; expect(map.isOverlapping(p1, p2)).to.be.false; }); it('finds overlap 7', () => { p1.column = 0; p1.row = 0; p2.column = 2; p2.row = 2; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 8', () => { p1.column = 2; p1.row = 4; p2.column = 3; p2.row = 2; expect(map.isOverlapping(p1, p2)).to.be.false; }); }); describe("p2 at 270 degrees", () => { beforeEach(() => p2.rotation = 270); it('finds overlap 9', () => { p1.column = -1; p1.row = 0; p2.column = 1; p2.row = 0; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 10', () => { p1.column = -1; p1.row = 0; p2.column = 0; p2.row = 1; expect(map.isOverlapping(p1, p2)).to.be.false; }); it('finds overlap 11', () => { p1.column = 0; p1.row = 0; p2.column = 0; p2.row = 2; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 12', () => { p1.column = 1; p1.row = 0; p2.column = 0; p2.row = 2; expect(map.isOverlapping(p1, p2)).to.be.false; }); }); describe("p1 at 180 degrees, p2 at 270 degrees", () => { beforeEach(() => {p1.rotation = 180; p2.rotation = 270}); it('finds overlap 13', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = -1; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 14', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = 0; p1.setEdges({ C: { up: 'UP', down: 'DOWN', left: 'LEFT', right: 'RIGHT' } }); p2.setEdges({ b: { up: 'up', down: 'down', left: 'left', right: 'right' }, f: { up: 'Up', down: 'Down', left: 'Left', right: 'Right' }, e: { right: 'stuff' } }); // d E // cf D // bCBA // ae expect(map.isOverlapping(p1, p2)).to.be.false; expect(map.adjacenciesByCell(p1, p2)).to.deep.equal([ { piece: p2, from: 'C', to: 'f' }, { piece: p2, from: 'C', to: 'e' }, { piece: p2, from: 'C', to: 'b' }, ]); expect(map.adjacenciesByEdge(p1, p2)).to.deep.equal([ { piece: p2, from: 'DOWN', to: 'Left' }, { piece: p2, from: 'UP', to: 'stuff' }, { piece: p2, from: 'RIGHT', to: 'down' }, ]); }); it('finds overlap 15', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = 1; expect(map.isOverlapping(p1, p2)).to.be.true; }); it('finds overlap 16', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = 2; p1.setEdges({ C: { up: 'UP', down: 'DOWN', left: 'LEFT', right: 'RIGHT' } }); p2.setEdges({ d: { up: 'up', down: 'down', left: 'left', right: 'right' }, f: { up: 'Up', down: 'Down', left: 'Left', right: 'Right' } }); // E // D // dCBA // cf // b // ae expect(map.isOverlapping(p1, p2)).to.be.false; expect(map.adjacenciesByCell(p1, p2)).to.deep.equal([ { piece: p2, from: 'C', to: 'f' }, { piece: p2, from: 'C', to: 'd' }, ]); expect(map.adjacenciesByEdge(p1, p2)).to.deep.equal([ { piece: p2, from: 'UP', to: 'Right' }, { piece: p2, from: 'RIGHT', to: 'down' } ]); }); it('3 body problem', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = 2; const p3 = map.create(Piece, 'p3') // unshaped p3.column = 1; p3.row = 3; p1.setEdges({ C: { up: 'UP', down: 'DOWN', left: 'LEFT', right: 'RIGHT' }, B: { up: 'UP', down: 'DOWN', left: 'LEFT', right: 'RIGHT' } }); p2.setEdges({ d: { up: 'up', down: 'down', left: 'left', right: 'right' }, f: { up: 'Up', down: 'Down', left: 'Left', right: 'Right' } }); // E // D // dCBA // cf. // b // ae expect(map.isOverlapping(p1, p2)).to.be.false; expect(map.isOverlapping(p1, p3)).to.be.false; expect(map.isOverlapping(p3, p1)).to.be.false; expect(map.isOverlapping(p3, p2)).to.be.false; expect(map.isOverlapping(p1)).to.be.false; expect(map.isOverlapping(p3)).to.be.false; expect(map.adjacenciesByCell(p1)).to.deep.equal([ { piece: p2, from: 'C', to: 'f' }, { piece: p2, from: 'C', to: 'd' }, { piece: p3, from: 'B', to: '.' } ]); expect(map.adjacenciesByEdge(p1)).to.deep.equal([ { piece: p2, from: 'UP', to: 'Right' }, { piece: p2, from: 'RIGHT', to: 'down' }, { piece: p3, from: 'UP', to: undefined } ]); expect(map.adjacenciesByEdge(p3)).to.deep.equal([ { piece: p1, from: undefined, to: 'UP' }, { piece: p2, from: undefined, to: 'Down' }, ]); }); }); it('can place shapes', () => { p1.column = 0; p1.row = 0; p2.column = -1; p2.row = -1; const ui = applyLayouts(game); expect(ui.all[p1._t.ref].relPos).to.deep.equal({ left: 25, top: 25, width: 75, height: 75 }) expect(ui.all[p2._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 100, height: 50 }) }); it('can place shapes rotated', () => { p1.column = 0; p1.row = 0; p1.rotation = 180; p2.column = 1; p2.row = 1; p2.rotation = 90; const ui = applyLayouts(game); expect(ui.all[p1._t.ref].relPos).to.deep.equal({ left: 20, top: 0, width: 60, height: 60, rotation: 180 }) expect(ui.all[p2._t.ref].relPos).to.deep.equal({ left: 40, top: 20, width: 80, height: 40, rotation: 90 }) expect(ui.all[p2._t.ref].baseStyles?.transformOrigin).to.equal('25% 50%') }); it('can find place for shapes', () => { p1.column = 4; p1.row = 5; p1.rotation = 0; p2.column = 5; p2.row = 5; p2.rotation = 90; map._fitPieceInFreePlace(p2, 4, 4, {column: 4, row: 4}); // ..ea // ABCb // D.fc // E..d expect(p2.column).equal(6); expect(p2.row).equal(4); expect(p2.rotation).equal(90); }); it('can find place for shapes even if rotation is forced', () => { p1.column = 2; p1.row = 2; p1.rotation = 180; p2.column = 2; p2.row = 2; p2.rotation = 90; map.rows = 5; map.columns = 5; map._fitPieceInFreePlace(p2, 5, 5, {column: 1, row: 1}); // ..... // d..E. // cf.D. // bCBA. // ae... expect(p2.column).equal(1); expect(p2.row).equal(2); expect(p2.rotation).equal(270); }); }); }); ================================================ FILE: src/test/render_test.ts ================================================ import chai from 'chai'; import spies from 'chai-spies'; import { Game, Space, Piece, GameElement, } from '../board/index.js'; import { applyLayouts, applyDiff } from '../ui/render.js'; import type { BaseGame } from '../board/game.js'; chai.use(spies); const { expect } = chai; describe('Render', () => { let game: BaseGame; describe('layouts', () => { beforeEach(() => { game = new Game({}); game.setBoardSize({ name: '_default', aspectRatio: 1, frame: {x:100, y:100}, screen: {x:100, y:100} }); game.layout(GameElement, { margin: 0, gap: 0, }); }); it('applies', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); const ui = applyLayouts(game); expect(ui.game.relPos).to.deep.equal({ left: 0, top: 0, width: 100, height: 100 }) expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 }) }); it('applies overlaps', () => { game.create(Space, 's1'); game.create(Space, 's2'); game.create(Space, 's3'); game.create(Space, 's4'); const p1 = game.create(Piece, 'p1'); const p2 = game.create(Piece, 'p2'); const p3 = game.create(Piece, 'p3'); const p4 = game.create(Piece, 'p4'); const ui = applyLayouts(game, () => { game.layout(Piece, { rows: 3, columns: 3, direction: 'ltr' }); }); expect(ui.all[p1._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 100 / 3, height: 100 / 3 }) expect(ui.all[p2._t.ref].relPos).to.deep.equal({ left: 100 / 3, top: 0, width: 100 / 3, height: 100 / 3 }) expect(ui.all[p3._t.ref].relPos).to.deep.equal({ left: 200 / 3, top: 0, width: 100 / 3, height: 100 / 3 }) expect(ui.all[p4._t.ref].relPos).to.deep.equal({ left: 0, top: 100 / 3, width: 100 / 3, height: 100 / 3 }) }); it('adds gaps and margins', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); const ui = applyLayouts(game, () => { game.layout(GameElement, { gap: 10, margin: 5 }); }); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 5, top: 5, width: 40, height: 40 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 55, top: 5, width: 40, height: 40 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 5, top: 55, width: 40, height: 40 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 55, top: 55, width: 40, height: 40 }) }); it('adds gaps and margins absolutely to relative sizes', () => { const outer = game.createMany(4, Space, 'outer'); const a = outer[3].create(Space, 'a'); const b = outer[3].create(Space, 'b'); const c = outer[3].create(Space, 'c'); const d = outer[3].create(Space, 'd'); const ui = applyLayouts(game, () => { outer[3].layout(GameElement, { gap: 4, margin: 2 }); }); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 4, top: 4, width: 42, height: 42 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 54, top: 4, width: 42, height: 42 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 4, top: 54, width: 42, height: 42 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 54, top: 54, width: 42, height: 42 }) }); it('areas are relative to parent', () => { const outer = game.createMany(3, Space, 'outer'); const a = outer[2].create(Space, 'a'); const b = outer[2].create(Space, 'b'); const c = outer[2].create(Space, 'c'); const d = outer[2].create(Space, 'd'); const ui = applyLayouts(game, () => { outer[2].layout(GameElement, { gap: 4, area: { left: 10, top: 20, width: 80, height: 60, } }); }); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 10, top: 20, width: 36, height: 26 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 54, top: 20, width: 36, height: 26 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 10, top: 54, width: 36, height: 26 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 54, top: 54, width: 36, height: 26 }) }); it('aligns', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 4 / 5, scaling: 'fit', alignment: 'right', }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 60, top: 0, width: 40, height: 50 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 20, top: 0, width: 40, height: 50 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 60, top: 50, width: 40, height: 50 }) }); it('aligns vertical', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 5 / 4, scaling: 'fit', alignment: 'bottom right', }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 50, top: 60, width: 50, height: 40 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 0, top: 60, width: 50, height: 40 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 50, top: 20, width: 50, height: 40 }) }); it('sizes to fit', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 4 / 5, scaling: 'fit' }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 10, top: 0, width: 40, height: 50 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 40, height: 50 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 10, top: 50, width: 40, height: 50 }) }); it('sizes to fill', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 4 / 5, scaling: 'fill' }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 62.5 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 62.5 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 0, top: 37.5, width: 50, height: 62.5 }) }); it('retains sizes', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { size: { width: 20, height: 25 }, }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 30, top: 25, width: 20, height: 25 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 25, width: 20, height: 25 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 30, top: 50, width: 20, height: 25 }) }); it('fits based on aspect ratios', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 5 / 4, scaling: 'fit' }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 0, top: 10, width: 50, height: 40 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 50, top: 10, width: 50, height: 40 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 40 }) }); it('fills based on aspect ratios', () => { const spaces = game.createMany(3, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 5 / 4, scaling: 'fill' }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 62.5, height: 50 }) expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ left: 37.5, top: 0, width: 62.5, height: 50 }) expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 62.5, height: 50 }) }); it('accommodate min row', () => { const spaces = game.createMany(10, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { rows: { min: 2 }, columns: 1, aspectRatio: 5 / 4, scaling: 'fill' }); }); expect(ui.all[spaces[0]._t.ref].relPos?.width).to.equal(62.5); expect(ui.all[spaces[0]._t.ref].relPos?.height).to.equal(50); expect(ui.all[spaces[0]._t.ref].relPos?.top).to.be.approximately(0, 0.0001); }); it('accommodate min col', () => { const spaces = game.createMany(10, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { columns: { min: 2 }, rows: 1, aspectRatio: 4 / 5, scaling: 'fill' }); }); expect(ui.all[spaces[0]._t.ref].relPos?.height).to.equal(62.5); expect(ui.all[spaces[0]._t.ref].relPos?.width).to.equal(50); expect(ui.all[spaces[0]._t.ref].relPos?.left).to.be.approximately(0, 0.0001); }); it('size overrides scaling', () => { const spaces = game.createMany(10, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { rows: { min: 2 }, columns: 1, size: { width: 5, height: 4 }, scaling: 'fill' }); }); expect(ui.all[spaces[0]._t.ref].relPos?.width).to.equal(5); expect(ui.all[spaces[0]._t.ref].relPos?.height).to.equal(4); expect(ui.all[spaces[0]._t.ref].relPos?.top).to.equal(30); }); it('isomorphic', () => { const spaces = game.createMany(9, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 4 / 5, offsetColumn: {x: 100, y: 100}, scaling: 'fit', }); }); expect(ui.all[spaces[0]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 42, top: 0 }); expect(ui.all[spaces[1]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 58, top: 20 }); expect(ui.all[spaces[2]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 74, top: 40 }); expect(ui.all[spaces[3]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 26, top: 20 }); expect(ui.all[spaces[4]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 42, top: 40 }); expect(ui.all[spaces[5]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 58, top: 60 }); expect(ui.all[spaces[6]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 10, top: 40 }); expect(ui.all[spaces[7]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 26, top: 60 }); expect(ui.all[spaces[8]._t.ref].relPos).to.deep.equal({ width: 16, height: 20, left: 42, top: 80 }); }); it('stacks', () => { const spaces = game.createMany(9, Space, 'space'); const ui = applyLayouts(game, () => { game.layout(GameElement, { aspectRatio: 4 / 5, offsetColumn: {x: -5, y: -5}, scaling: 'fit', direction: 'ltr' }); }); expect(ui.all[spaces[8]!._t.ref].relPos!.top).to.equal(0); expect(ui.all[spaces[0]!._t.ref].relPos!.top + ui.all[spaces[0]!._t.ref].relPos!.height).to.equal(100); }); it('align+scale', () => { const pieces = game.createMany(6, Piece, 'piece'); const ui = applyLayouts(game, () => { game.layout(Piece, { offsetColumn: {x: 10, y: 10}, scaling: 'fit', }); }); expect(ui.all[pieces[0]!._t.ref].relPos!.top).to.equal(0); expect(ui.all[pieces[5]!._t.ref].relPos!.top + ui.all[pieces[5]!._t.ref].relPos!.height).to.equal(100); expect(ui.all[pieces[3]!._t.ref].relPos!.left).to.equal(0); expect(ui.all[pieces[2]!._t.ref].relPos!.left + ui.all[pieces[2]!._t.ref].relPos!.width).to.equal(100); }); it('specificity', () => { class Country extends Space { } game = new Game({}); game.setBoardSize({ name: '_default', aspectRatio: 1, frame: {x:100, y:100}, screen: {x:100, y:100} }); const spaces = game.createMany(4, Space, 'space'); const space = game.create(Space, 'special'); const france = game.create(Country, 'france'); const special = game.create(Country, 'special'); const el = game.create(GameElement, 'whatev'); const ui = applyLayouts(game, () => { game.layout(spaces[2], { direction: 'btt-rtl', showBoundingBox: '1' }); game.layout('special', { direction: 'ttb-rtl', showBoundingBox: '2' }); game.layout(spaces.slice(0, 2), { direction: 'ttb', showBoundingBox: '3' }); game.layout(Country, { direction: 'rtl', showBoundingBox: '4' }); game.layout(Space, { direction: 'btt', showBoundingBox: '5' }); game.layout(GameElement, { direction: 'ltr-btt', showBoundingBox: '6' }); }); expect(ui.game.layouts[6].children.some(r => r.element === el)).to.be.true; // by GameElement expect(ui.game.layouts[5].children.some(r => r.element === spaces[3])).to.be.true; // by Space expect(ui.game.layouts[4].children.some(r => r.element === france)).to.be.true; // by more specific class expect(ui.game.layouts[3].children.some(r => r.element === spaces[0])).to.be.true; // by single ref expect(ui.game.layouts[2].children.some(r => r.element === space)).to.be.true; // by name expect(ui.game.layouts[2].children.some(r => r.element === special)).to.be.true; // by name expect(ui.game.layouts[1].children.some(r => r.element === spaces[2])).to.be.true; // by array ref }); it('can place', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); a.row = 2; a.column = 2; const ui = applyLayouts(game); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 }) }); it('can shift bounds', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); a.row = 4; a.column = 4; const ui = applyLayouts(game); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 }) }); it('can shift negative', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); a.row = -4; a.column = -4; const ui = applyLayouts(game); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 50, height: 50 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 }) }); it('can stretch bounds', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); a.row = 1; a.column = 2; d.row = 4; d.column = 2; const ui = applyLayouts(game); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 100, height: 25 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 25, width: 100, height: 25 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 100, height: 25 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 0, top: 75, width: 100, height: 25 }) }); it('can become sparse', () => { const a = game.create(Space, 'a'); const b = game.create(Space, 'b'); const c = game.create(Space, 'c'); const d = game.create(Space, 'd'); a.row = 4; a.column = 1; d.row = 1; d.column = 4; const ui = applyLayouts(game); expect(ui.all[a._t.ref].relPos).to.deep.equal({ left: 0, top: 75, width: 25, height: 25 }) expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 0, top: 0, width: 25, height: 25 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 25, top: 0, width: 25, height: 25 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 75, top: 0, width: 25, height: 25 }) }); it('can place sticky', () => { const a = game.create(Piece, 'a'); const b = game.create(Piece, 'b'); const c = game.create(Piece, 'c'); const d = game.create(Piece, 'd'); applyLayouts(game, () => { game.layout(Piece, { sticky: true }); }); a.remove(); game.resetUI(); const ui = applyLayouts(game, () => { game.layout(Piece, { sticky: true }); }); expect(b.column).to.equal(2); expect(ui.all[b._t.ref].relPos).to.deep.equal({ left: 50, top: 0, width: 50, height: 50 }) expect(ui.all[c._t.ref].relPos).to.deep.equal({ left: 0, top: 50, width: 50, height: 50 }) expect(ui.all[d._t.ref].relPos).to.deep.equal({ left: 50, top: 50, width: 50, height: 50 }) }); }); describe('applyDiff', () => { let client: BaseGame; let server: BaseGame; beforeEach(() => { client = new Game({ classRegistry: [Space, Piece] }); server = new Game({ classRegistry: [Space, Piece] }); server._ctx.trackMovement = true; client.setBoardSize({ name: '_default', aspectRatio: 1, frame: {x:100, y:100}, screen: {x:100, y:100} }); }); it("combines local and server", () => { const a = server.create(Space, 'a'); const b = server.create(Space, 'b'); a.create(Piece, 'p1'); a.create(Piece, 'p2'); client.fromJSON(server.allJSON(1)); const p1c = client.first(Piece, 'p1')!; const p2c = client.first(Piece, 'p2')!; // client move p1c.putInto(client.first('b')!); const ui1 = applyLayouts(client); const p1s = server.first(Piece, 'p1')!; // server same move p1s.putInto(b); client.fromJSON(server.allJSON(1)); const p1c2 = client.first(Piece, 'p1')!; const p2c2 = client.first(Piece, 'p2')!; const ui2 = applyLayouts(client); applyDiff(ui2.game, ui2, ui1); // pieces are retained expect(p1c).to.equal(p1c2); expect(p2c).to.equal(p2c2); // keys are retained expect(ui2.all[p1c2._t.ref].key).to.equal(ui1.all[p1c._t.ref].key); expect(ui2.all[p2c2._t.ref].key).to.equal(ui1.all[p2c._t.ref].key); // no transform since same move expect(ui2.all[p1c2._t.ref].styles?.transform).to.be.undefined expect(ui2.all[p2c2._t.ref].styles?.transform).to.be.undefined }); it("combines local and server conflicts", () => { const a = server.create(Space, 'a'); server.create(Space, 'b'); const c = server.create(Space, 'c'); a.create(Piece, 'p1'); a.create(Piece, 'p2'); client.fromJSON(server.allJSON(1)); const p1c = client.first(Piece, 'p1')!; const p2c = client.first(Piece, 'p2')!; // client move p1c.putInto(client.first('b')!); const ui1 = applyLayouts(client); const p1s = server.first(Piece, 'p1')!; // server different move p1s.putInto(c); client.fromJSON(server.allJSON(1)); const p1c2 = client.first(Piece, 'p1')!; const p2c2 = client.first(Piece, 'p2')!; const ui2 = applyLayouts(client); applyDiff(ui2.game, ui2, ui1); // piece not retained with conflicting parent moves expect(p1c).to.not.equal(p1c2); // unmoved piece is retained expect(p2c).to.equal(p2c2); // same with keys expect(ui2.all[p1c2._t.ref].key).to.not.equal(ui1.all[p1c._t.ref].key); expect(ui2.all[p2c2._t.ref].key).to.equal(ui1.all[p2c._t.ref].key); // transform for moved expect(ui2.all[p1c2._t.ref].styles?.transform).not.to.be.undefined expect(ui2.all[p2c2._t.ref].styles?.transform).to.be.undefined }); it("tracks reorders", () => { const a = server.create(Space, 'a'); const p1s = a.create(Piece, 'p1'); const p2s = a.create(Piece, 'p2'); // on bottom client.fromJSON(server.allJSON(1)); const ui1 = applyLayouts(client); const p1c = client.first(Piece, 'p1')!; const p2c = client.first(Piece, 'p2')!; expect(client.first(Piece)!.name).to.equal('p1'); // server shuffle expect(server.first(Piece)).to.equal(p1s); p1s.putInto(a, { fromBottom: 0 }); expect(server.first(Piece)).to.equal(p2s); // now on top client.fromJSON(server.allJSON(1)); const p1c2 = client.first(Piece, 'p1')!; const p2c2 = client.first(Piece, 'p2')!; const ui2 = applyLayouts(client); applyDiff(ui2.game, ui2, ui1); // tracks move expect(client.first(Piece)!.name).to.equal('p2'); expect(p1c).to.equal(p1c2); expect(p2c).to.equal(p2c2); // transform for both expect(ui2.all[p1c2._t.ref].styles?.transform).not.to.be.undefined expect(ui2.all[p2c2._t.ref].styles?.transform).not.to.be.undefined }); it("shows stack reorders if visible", () => { const a = server.create(Space, 'a'); a.setOrder('stacking'); const p1s = a.create(Piece, 'p1'); const p2s = a.create(Piece, 'p2'); // on top client.fromJSON(server.allJSON(1)); const ui1 = applyLayouts(client); const p1c = client.first(Piece, 'p1')!; const p2c = client.first(Piece, 'p2')!; expect(client.first(Piece)!.name).to.equal('p2'); // server shuffle expect(server.first(Piece)).to.equal(p2s); p2s.putInto(a, { fromBottom: 0 }); expect(server.first(Piece)).to.equal(p1s); // now on top client.fromJSON(server.allJSON(1)); const p1c2 = client.first(Piece, 'p1')!; const p2c2 = client.first(Piece, 'p2')!; const ui2 = applyLayouts(client); applyDiff(ui2.game, ui2, ui1); // tracks move expect(client.first(Piece)!.name).to.equal('p1'); expect(p1c).to.equal(p1c2); expect(p2c).to.equal(p2c2); // transform for both expect(ui2.all[p1c2._t.ref].styles?.transform).not.to.be.undefined expect(ui2.all[p2c2._t.ref].styles?.transform).not.to.be.undefined }); it("hides stack reorders if hidden", () => { const a = server.create(Space, 'a'); a.setOrder('stacking'); const p1s = a.create(Piece, 'p1'); const p2s = a.create(Piece, 'p2'); // on top a.all(Piece).hideFromAll(); client.fromJSON(server.allJSON(1)); const ui1 = applyLayouts(client); const p1c = client.first(Piece)!; const p2c = client.last(Piece)!; // server shuffle expect(server.first(Piece)).to.equal(p2s); p2s.putInto(a, { fromBottom: 0 }); expect(server.first(Piece)).to.equal(p1s); // now on top client.fromJSON(server.allJSON(1)); const p1c2 = client.first(Piece)!; const p2c2 = client.last(Piece)!; const ui2 = applyLayouts(client); applyDiff(ui2.game, ui2, ui1); // no move expect(p1c).to.equal(p1c2); expect(p2c).to.equal(p2c2); // no transform expect(ui2.all[p1c2._t.ref].styles?.transform).to.be.undefined expect(ui2.all[p2c2._t.ref].styles?.transform).to.be.undefined }); }); }); // console.log('

'); // for (const c of game._t.children) console.log(`
`); // console.log('
'); ================================================ FILE: src/test/setup-debug.js ================================================ globalThis.document={ createElement:() => {}, createTextNode: ()=>{}, head: { appendChild:() => ({appendChild:() => {}}) } }; ================================================ FILE: src/test/setup.js ================================================ globalThis.console.debug = () => {} globalThis.console.warn = () => {} globalThis.document={ createElement:() => {}, createTextNode: ()=>{}, head: { appendChild:() => ({appendChild:() => {}}) } }; ================================================ FILE: src/test/ui_test.ts ================================================ import chai from 'chai'; import Game from '../board/game.js'; import Player from '../player/player.js'; import { times } from '../utils.js'; import { createGame } from '../game-creator.js'; import { createGameStore } from '../ui/store.js'; import type { SerializedMove } from '../game-manager.js'; import { starterGame, starterGameWithConfirm, starterGameWithValidate, starterGameWithCompoundMove, starterGameWithTiles, starterGameWithTilesConfirm, starterGameWithTilesValidate, starterGameWithTilesCompound, Token } from './fixtures/games.js'; const history: SerializedMove[] = []; const { expect } = chai; describe('UI', () => { beforeEach(() => { globalThis.window = { clearTimeout: () => {}, top: { postMessage: ({ data }: { data: SerializedMove }) => history.push(data) } } as unknown as typeof globalThis.window; history.splice(0); }); afterEach(() => { // @ts-ignore delete globalThis.window; }); it("presents moves", () => { const store = getGameStore(starterGame); updateStore(store, 2, {tokens: 4}); const state = store.getState(); expect(state.pendingMoves?.[0].name).to.equal('take'); expect(state.boardPrompt).to.be.undefined; expect(state.pendingMoves?.[0].prompt).to.equal('Choose a token'); expect(Object.values(state.boardSelections).length).to.equal(4); }); it("accepts moves", () => { const store = getGameStore(starterGame); updateStore(store, 2, {tokens: 4}); let state = store.getState(); const token = state.gameManager.game.first(Token)!; expect(state.pendingMoves?.length).to.equal(1); expect(state.pendingMoves?.[0].name).to.equal('take'); expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.false; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); expect(history.length).to.equal(1); expect(history[0].name).to.equal('take'); expect(state.pendingMoves).to.deep.equal([]); expect(state.gameManager.game.first('mat')!.all(Token).length).to.equal(1); expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3); }); it("prompts confirm", () => { const store = getGameStore(starterGameWithConfirm); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); token = state.gameManager.game.first(Token)!; expect(history.length).to.equal(0); expect(state.selected).to.deep.equal([token]); expect(state.pendingMoves?.[0].name).to.equal('take'); expect(state.boardPrompt).to.be.undefined; expect(state.pendingMoves?.[0].prompt).to.equal('Choose a token'); expect(state.uncommittedArgs.token).to.equal(token); state.selectMove(state.pendingMoves?.[0], state.uncommittedArgs); state = store.getState(); expect(history.length).to.equal(1); expect(state.pendingMoves).to.deep.equal([]); }); it("validates", () => { const store = getGameStore(starterGameWithValidate); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; expect(state.boardSelections[token.branch()].error).to.equal('not first'); expect(clickMoves.length).to.equal(0); }); it("cancels confirm", () => { const store = getGameStore(starterGameWithConfirm); updateStore(store, 2, {tokens: 4}); let state = store.getState(); const token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); expect(history.length).to.equal(0); expect(state.selected?.length).to.equal(1); expect(state.pendingMoves?.[0].name).to.equal('take'); expect(state.boardPrompt).to.be.undefined; expect(state.pendingMoves?.[0].prompt).to.equal('Choose a token'); state.selectMove(); state = store.getState(); expect(history.length).to.equal(0); expect(state.gameManager.game.first('mat')!.all(Token).length).to.equal(0); expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(4); }); it("continues compound move", () => { const store = getGameStore(starterGameWithCompoundMove); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); token = state.gameManager.game.first(Token)!; expect(history.length).to.equal(0); expect(state.selected).to.be.undefined; expect(state.pendingMoves?.[0].name).to.equal('take'); expect(state.pendingMoves?.[0].args.token).to.equal(token); expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.false; expect(state.pendingMoves?.[0].selections[0].type).to.equal('choices'); expect(state.boardPrompt).to.be.undefined; // falls thru to form since no board moves state.selectMove(state.pendingMoves?.[0], {a: 1}); expect(history.length).to.equal(1); expect(state.gameManager.game.first('mat')!.all(Token).length).to.equal(1); expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3); }); it("places pieces", () => { const store = getGameStore(starterGameWithTiles); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); state.setPlacement({ column: 2, row: 2 }); const ghost = state.gameManager.game.first(Token)!; token = state.gameManager.game.first('pool')!.first(Token)!; expect(history.length).to.equal(0); expect(state.pendingMoves?.[0].selections[0].type).to.equal('place'); expect(ghost.column).to.equal(2); expect(ghost.row).to.equal(2); expect(token.column).to.be.undefined; expect(token.row).to.be.undefined; state.selectPlacement({ column: 2, row: 2 }); expect(history.length).to.equal(1); expect(history[0].name).to.equal('take'); expect(history[0].args.__placement__).to.deep.equal([2, 2]); expect(state.gameManager.game.first('tiles')!.all(Token).length).to.equal(1); expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3); }); it("places pieces with confirm", () => { const store = getGameStore(starterGameWithTilesConfirm); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); state.setPlacement({ column: 2, row: 2 }); state.selectPlacement({ column: 2, row: 2 }); state = store.getState(); token = state.gameManager.game.first(Token)!; expect(history.length).to.equal(0); expect(state.pendingMoves?.[0].selections[0].type).to.equal('place'); expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.true; expect(token.column).to.equal(2); expect(token.row).to.equal(2); expect(state.gameManager.game.first('tiles')!.all(Token).length).to.equal(1); // ghost piece expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(4); }); it("places pieces with validate", () => { const store = getGameStore(starterGameWithTilesValidate); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); state.setPlacement({ column: 1, row: 2 }); state = store.getState(); const ghost = state.placement!.piece expect(ghost.column).to.equal(1); expect(ghost.row).to.equal(2); expect(state.placement?.invalid).to.be.true; state.selectPlacement({ column: 1, row: 2 }); state = store.getState(); expect(state.error).to.equal('must be black square'); expect(history.length).to.equal(0); }); it("continues compound place piece", () => { const store = getGameStore(starterGameWithTilesCompound); updateStore(store, 2, {tokens: 4}); let state = store.getState(); let token = state.gameManager.game.first(Token)!; const clickMoves = state.boardSelections[token.branch()].clickMoves; state.selectElement(clickMoves, token); state = store.getState(); state.setPlacement({ column: 2, row: 2 }); state.selectPlacement({ column: 2, row: 2 }); state = store.getState(); expect(history.length).to.equal(0); expect(state.pendingMoves?.[0].args.token).to.equal(token); expect(state.pendingMoves?.[0].args.__placement__).to.deep.equal([2, 2]); expect(state.pendingMoves?.[0].requireExplicitSubmit).to.be.false; expect(state.pendingMoves?.[0].selections[0].type).to.equal('choices'); expect(state.boardPrompt).to.be.undefined; // falls thru to form since no board moves state.selectMove(state.pendingMoves?.[0], {a: 1}); expect(history.length).to.equal(1); expect(state.gameManager.game.first('tiles')!.all(Token).length).to.equal(1); expect(state.gameManager.game.first('pool')!.all(Token).length).to.equal(3); }); }); function getGameStore(gameCreator: (game: Game) => void) { const store = createGameStore(); const setup = createGame(Player, Game, gameCreator); store.getState().setSetup(setup); return store; } function updateStore(store: ReturnType, players: number, settings: Record) { const { setup, updateState } = store.getState(); const playerAttrs = times(players, p => ({ id: String(p), name: String(p), position: p, host: p === 1, color: '', avatar: '', tokens: 0 })); // initial state const gameManager = setup!({ players: playerAttrs, settings, randomSeed: 'rseed', }) gameManager.play(); let state = gameManager.getPlayerStates()[0].state; if (state instanceof Array) state = state[state.length - 1]; updateState({ type: 'gameUpdate', state, position: 1, currentPlayers: gameManager.players.currentPosition }); } ================================================ FILE: src/test-runner.ts ================================================ import { createGameStore } from './ui/store.js'; import { createInterface } from './interface.js'; import { times } from './utils.js'; import type { BaseGame } from './board/game.js'; import type { GameInterface, GameState, GameUpdate, SetupState } from './interface.js'; import type { Argument } from './action/action.js'; import type { SetupFunction } from './game-creator.js'; import type { default as GameManager, PlayerAttributes } from './game-manager.js'; declare global { interface Window { serverGameManager?: GameManager; } } class TestRunnerPlayer { runner: TestRunner store: ReturnType playerAttrs: PlayerAttributes player: NonNullable game: G position: number constructor(runner: TestRunner, position: number, store: ReturnType, playerAttrs: PlayerAttributes, game: G) { this.runner = runner this.position = position this.store = store this.playerAttrs = playerAttrs this.game = game } move(name: string, args: Record) { if (!this.runner.server.state) throw Error("Must call TestRunner#start first"); if (this.runner.server.state!.game.phase === 'finished') throw Error("Cannot take a move on a finished game"); if (!this.runner.server.state!.game.currentPlayers.includes(this.position)) throw Error("This player cannot take a move"); const state = this.store.getState(); globalThis.$ = state.gameManager.game._ctx.namedSpaces; this.runner.currentPosition = this.position; state.selectMove({ name, args, selections: [], requireExplicitSubmit: false }) this.runner.updatePlayersFromState(); } actions() { const pendingMoves = this.game._ctx.gameManager.getPendingMoves(this.game._ctx.gameManager.players[this.position - 1]); if (!pendingMoves) return []; return pendingMoves.moves.map(m => m.name); } } export class TestRunner { server: { interface: GameInterface; state?: GameUpdate; gameManager: GameManager; game: G }; currentPosition: number = 1; players: TestRunnerPlayer[] constructor(private setup: SetupFunction, mocks?: (game: G) => void) { if (mocks) { this.setup = (state: SetupState | GameState, options?: { rseed?: string; trackMovement?: boolean; }) => setup(state, {...options, mocks}); } const iface = createInterface(this.setup) this.server = { interface: iface, } as typeof this['server']; globalThis.window = { setTimeout, clearTimeout, top: { postMessage: ({ data }: { data: any }) => { if (this.server.state!.game.phase === 'finished') throw Error(`Game already finished. Cannot process move ${data.move}`); this.server.state = this.server.interface.processMove( this.server.state!.game, { position: this.currentPosition, data } ); this.getCurrentGame(); } } } as unknown as typeof globalThis.window; } start({players, settings}: { players: number, settings: Record }): TestRunnerPlayer[] { const playerAttrs = times(players, p => ({ id: String(p), name: String(p), position: p, host: p === 1, color: '', avatar: '' })); this.server.state = this.server.interface.initialState({ players: playerAttrs, settings, randomSeed: 'test-rseed' }); this.getCurrentGame(); this.players = playerAttrs.map((p, i) => { const store = createGameStore() const {setSetup, gameManager} = store.getState(); setSetup(this.setup); return new TestRunnerPlayer(this, i + 1, store, p as unknown as PlayerAttributes, gameManager.game as G) }); this.updatePlayersFromState(); // initial return this.players } getCurrentGame() { this.server.gameManager = globalThis.window.serverGameManager as GameManager; this.server.game = this.server.gameManager.game as G; } updatePlayers() { this.server.state = this.server.gameManager.getUpdate(); this.updatePlayersFromState(); } updatePlayersFromState() { for (const player of this.players) { const { updateState } = player.store.getState(); const state = this.server.state!.players.find(state => state.position === player.position)!; const playerState = (state.state instanceof Array) ? state.state[state.state.length - 1] : state.state; if (this.server.state!.game.phase === 'started') { updateState({ type: 'gameUpdate', state: playerState, position: state.position, currentPlayers: this.server.state!.game.currentPlayers }); } if (this.server.state!.game.phase === 'finished') { updateState({ type: 'gameFinished', state: playerState, position: state.position, winners: this.server.gameManager.winner.map(p => p.position), }); } const { gameManager } = player.store.getState(); player.game = gameManager.game as G; player.player = gameManager.players.atPosition(player.position)!; } } } ================================================ FILE: src/ui/Main.tsx ================================================ import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { gameStore } from './store.js'; import Game from './game/Game.js'; import Setup from './setup/Setup.js'; import Queue from './queue.js'; import type { GameState } from '../interface.js'; import type { SetupComponentProps } from './setup/components/settingComponents.js'; export type User = { id: string; name: string; avatar: string; playerDetails?: { color: string; position: number; ready: boolean; settings?: any; sessionURL?: string; }; }; type UsersEvent = { type: "users"; users: User[]; }; type UserOnlineEvent = { type: "userOnline"; id: string; online: boolean; }; export type GameSettings = Record // an update to the setup state export type SettingsUpdateEvent = { type: "settingsUpdate"; settings: GameSettings; seatCount: number; } export type GameUpdateEvent = { type: "gameUpdate"; state: GameState | GameState[]; position: number; currentPlayers: number[]; } export type GameFinishedEvent = { type: "gameFinished"; state: GameState | GameState[]; position: number; winners: number[]; } // indicates the disposition of a message that was processed export type MessageProcessedEvent = { type: "messageProcessed"; id: string; error?: string; } export type SeatOperation = { type: 'seat'; position: number; userID: string; color: string; name: string; settings?: any; } export type UnseatOperation = { type: 'unseat'; userID: string; } export type UpdateOperation = { type: 'update'; userID: string; color?: string; name?: string; ready?: boolean; settings?: any; } type PlayerOperation = SeatOperation | UnseatOperation | UpdateOperation export type UpdatePlayersMessage = { type: "updatePlayers"; id: string; operations: PlayerOperation[]; } export type UpdateSettingsMessage = { type: "updateSettings"; id: string; settings: GameSettings; seatCount: number } // used to actually start the game export type StartMessage = { id: string; type: 'start'; } // used to tell the top that you're ready to recv events export type ReadyMessage = { type: 'ready'; } export type SwitchPlayerMessage = { type: "switchPlayer"; index: number; } export default ({ minPlayers, maxPlayers, defaultPlayers, setupComponents }: { minPlayers: number, maxPlayers: number, defaultPlayers: number, setupComponents: Record JSX.Element> }) => { const [gameManager, updateState, setUserOnline, announcementIndex] = gameStore(s => [s.gameManager, s.updateState, s.setUserOnline, s.announcementIndex]); const [settings, setSettings] = useState(); const [seatCount, setSeatCount] = useState(defaultPlayers); const [users, setUsers] = useState([]); const [readySent, setReadySent] = useState(false); const players = useMemo(() => users.filter(u => !!u.playerDetails), [users]); const moveCallbacks = useMemo<((e: string) => void)[]>(() => [], []); const catchError = useCallback((error: string) => { if (!error) return console.error(error); }, []); const queue = useMemo(() => new Queue(1) /* speed */, []); useEffect(() => { if (gameManager.announcements[announcementIndex]) { queue.pause(); } else if (queue.paused) { setTimeout(() => queue.resume(), 500); } }, [queue, gameManager, announcementIndex]) const listener = useCallback((event: MessageEvent< UsersEvent | UserOnlineEvent | SettingsUpdateEvent | GameUpdateEvent | GameFinishedEvent | MessageProcessedEvent >) => { const data = event.data; switch(data.type) { case 'settingsUpdate': setSettings(data.settings); setSeatCount(data.seatCount); break; case 'users': setUsers(data.users); break; case 'userOnline': setUserOnline(data.id, data.online) break; case 'gameUpdate': case 'gameFinished': { if (data.state instanceof Array) { const states = data.state; let delay = data.state[0].sequence === gameManager.sequence + 1; for (let i = 0; i !== states.length; i++) { const state = states[i]; queue.schedule(() => updateState({...data, state}, i !== states.length - 1), delay); delay = true; } } else { let delay = data.state.sequence === gameManager.sequence + 1; queue.schedule(() => updateState(data as typeof data & {state: typeof data.state}), delay); // TS needs help here... } } break; case 'messageProcessed': if (data.error) { catchError(data.error); const move = moveCallbacks[parseInt(data.id)]; if (move) move(data.error); } delete moveCallbacks[parseInt(data.id)]; break; } }, [setUserOnline, moveCallbacks, gameManager, queue, updateState, catchError]); useEffect(() => { window.addEventListener('message', listener, false) const message: ReadyMessage = {type: "ready"}; if (!readySent) { window.top!.postMessage(message, "*"); setReadySent(true); } return () => window.removeEventListener('message', listener) }, [readySent, listener]); const updateSettings = useCallback((update: {settings?: GameSettings, seatCount?: number}) => { if (update.settings) setSettings(update.settings); if (update.seatCount) setSeatCount(update.seatCount); const message: UpdateSettingsMessage = { type: "updateSettings", id: 'settings', settings: update.settings ?? settings ?? {}, seatCount: update.seatCount ?? seatCount }; window.top!.postMessage(message, "*"); }, [seatCount, settings]); const updatePlayers = useCallback((operations: UpdatePlayersMessage['operations']) => { const message: UpdatePlayersMessage = { type: 'updatePlayers', id: 'updatePlayers', operations } window.top!.postMessage(message, "*"); }, []) return ( <> {gameManager.phase === 'new' && settings && } {(gameManager.phase === 'started' || gameManager.phase === 'finished') && } ); } ================================================ FILE: src/ui/assets/click.ogg.ts ================================================ export default "data:application/ogg;base64,T2dnUwACAAAAAAAAAAAISQAAAAAAAFRKKQUBHgF2b3JiaXMAAAAAAUSsAAAAAAAAAHcBAAAAAAC4AU9nZ1MAAAAAAAAAAAAACEkAAAEAAAB6l/yzEJf//////////////////8kDdm9yYmlzKwAAAFhpcGguT3JnIGxpYlZvcmJpcyBJIDIwMTIwMjAzIChPbW5pcHJlc2VudCkCAAAADQAAAEFSVElTVD1LZW5uZXlHAAAAQ09NTUVOVFM9U291bmQgZ2VuZXJhdGVkIGJ5IEdhbWVTeW50aCBmcm9tIFRzdWdpICh3d3cudHN1Z2ktc3R1ZGlvLmNvbSkBBXZvcmJpcylCQ1YBAAgAAAAxTCDFgNCQVQAAEAAAYCQpDpNmSSmllKEoeZiUSEkppZTFMImYlInFGGOMMcYYY4wxxhhjjCA0ZBUAAAQAgCgJjqPmSWrOOWcYJ45yoDlpTjinIAeKUeA5CcL1JmNuprSma27OKSUIDVkFAAACAEBIIYUUUkghhRRiiCGGGGKIIYcccsghp5xyCiqooIIKMsggg0wy6aSTTjrpqKOOOuootNBCCy200kpMMdVWY669Bl18c84555xzzjnnnHPOCUJDVgEAIAAABEIGGWQQQgghhRRSiCmmmHIKMsiA0JBVAAAgAIAAAAAAR5EUSbEUy7EczdEkT/IsURM10TNFU1RNVVVVVXVdV3Zl13Z113Z9WZiFW7h9WbiFW9iFXfeFYRiGYRiGYRiGYfh93/d93/d9IDRkFQAgAQCgIzmW4ymiIhqi4jmiA4SGrAIAZAAABAAgCZIiKZKjSaZmaq5pm7Zoq7Zty7Isy7IMhIasAgAAAQAEAAAAAACgaZqmaZqmaZqmaZqmaZqmaZqmaZpmWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWZZlWUBoyCoAQAIAQMdxHMdxJEVSJMdyLAcIDVkFAMgAAAgAQFIsxXI0R3M0x3M8x3M8R3REyZRMzfRMDwgNWQUAAAIACAAAAAAAQDEcxXEcydEkT1It03I1V3M913NN13VdV1VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWB0JBVAAAEAAAhnWaWaoAIM5BhIDRkFQCAAAAAGKEIQwwIDVkFAAAEAACIoeQgmtCa8805DprloKkUm9PBiVSbJ7mpmJtzzjnnnGzOGeOcc84pypnFoJnQmnPOSQyapaCZ0JpzznkSmwetqdKac84Z55wOxhlhnHPOadKaB6nZWJtzzlnQmuaouRSbc86JlJsntblUm3POOeecc84555xzzqlenM7BOeGcc86J2ptruQldnHPO+WSc7s0J4ZxzzjnnnHPOOeecc84JQkNWAQBAAAAEYdgYxp2CIH2OBmIUIaYhkx50jw6ToDHIKaQejY5GSqmDUFIZJ6V0gtCQVQAAIAAAhBBSSCGFFFJIIYUUUkghhhhiiCGnnHIKKqikkooqyiizzDLLLLPMMsusw84667DDEEMMMbTSSiw11VZjjbXmnnOuOUhrpbXWWiullFJKKaUgNGQVAAACAEAgZJBBBhmFFFJIIYaYcsopp6CCCggNWQUAAAIACAAAAPAkzxEd0REd0REd0REd0REdz/EcURIlURIl0TItUzM9VVRVV3ZtWZd127eFXdh139d939eNXxeGZVmWZVmWZVmWZVmWZVmWZQlCQ1YBACAAAABCCCGEFFJIIYWUYowxx5yDTkIJgdCQVQAAIACAAAAAAEdxFMeRHMmRJEuyJE3SLM3yNE/zNNETRVE0TVMVXdEVddMWZVM2XdM1ZdNVZdV2Zdm2ZVu3fVm2fd/3fd/3fd/3fd/3fd/XdSA0ZBUAIAEAoCM5kiIpkiI5juNIkgSEhqwCAGQAAAQAoCiO4jiOI0mSJFmSJnmWZ4maqZme6amiCoSGrAIAAAEABAAAAAAAoGiKp5iKp4iK54iOKImWaYmaqrmibMqu67qu67qu67qu67qu67qu67qu67qu67qu67qu67qu67qu67pAaMgqAEACAEBHciRHciRFUiRFciQHCA1ZBQDIAAAIAMAxHENSJMeyLE3zNE/zNNETPdEzPVV0RRcIDVkFAAACAAgAAAAAAMCQDEuxHM3RJFFSLdVSNdVSLVVUPVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVdU0TdM0gdCQlQAAGQAAI0EGGYQQinKQQm49WAgx5iQFoTkGocQYhKcQMww5DSJ0kEEnPbiSOcMM8+BSKBVETIONJTeOIA3CplxJ5TgIQkNWBABRAACAMcgxxBhyzknJoETOMQmdlMg5J6WT0kkpLZYYMyklphJj45yj0knJpJQYS4qdpBJjia0AAIAABwCAAAuh0JAVAUAUAABiDFIKKYWUUs4p5pBSyjHlHFJKOaecU845CB2EyjEGnYMQKaUcU84pxxyEzEHlnIPQQSgAACDAAQAgwEIoNGRFABAnAOBwJM+TNEsUJUsTRc8UZdcTTdeVNM00NVFUVcsTVdVUVdsWTVW2JU0TTU30VFUTRVUVVdOWTVW1bc80ZdlUVd0WVdW2ZdsWfleWdd8zTVkWVdXWTVW1ddeWfV/WbV2YNM00NVFUVU0UVdVUVds2Vde2NVF0VVFVZVlUVVl2ZVn3VVfWfUsUVdVTTdkVVVW2Vdn1bVWWfeF0VV1XZdn3VVkWflvXheH2feEYVdXWTdfVdVWWfWHWZWG3dd8oaZppaqKoqpooqqqpqrZtqq6tW6LoqqKqyrJnqq6syrKvq65s65ooqq6oqrIsqqosq7Ks+6os67aoqrqtyrKwm66r67bvC8Ms67pwqq6uq7Ls+6os67qt68Zx67owfKYpy6ar6rqpurpu67pxzLZtHKOq6r4qy8KwyrLv67ovtHUhUVV13ZRd41dlWfdtX3eeW/eFsm07v637ynHrutL4Oc9vHLm2bRyzbhu/rfvG8ys/YTiOpWeatm2qqq2bqqvrsm4rw6zrQlFVfV2VZd83XVkXbt83jlvXjaKq6roqy76wyrIx3MZvHLswHF3bNo5b152yrQt9Y8j3Cc9r28Zx+zrj9nWjrwwJx48AAIABBwCAABPKQKEhKwKAOAEABiHnFFMQKsUgdBBS6iCkVDEGIXNOSsUclFBKaiGU1CrGIFSOScickxJKaCmU0lIHoaVQSmuhlNZSa7Gm1GLtIKQWSmktlNJaaqnG1FqMEWMQMuekZM5JCaW0FkppLXNOSuegpA5CSqWkFEtKLVbMScmgo9JBSKmkElNJqbVQSmulpBZLSjG2FFtuMdYcSmktpBJbSSnGFFNtLcaaI8YgZM5JyZyTEkppLZTSWuWYlA5CSpmDkkpKrZWSUsyck9JBSKmDjkpJKbaSSkyhlNZKSrGFUlpsMdacUmw1lNJaSSnGkkpsLcZaW0y1dRBaC6W0FkpprbVWa2qtxlBKayWlGEtKsbUWa24x5hpKaa2kEltJqcUWW44txppTazWm1mpuMeYaW2091ppzSq3W1FKNLcaaY2291Zp77yCkFkppLZTSYmotxtZiraGU1koqsZWSWmwx5tpajDmU0mJJqcWSUowtxppbbLmmlmpsMeaaUou15tpzbDX21FqsLcaaU0u11lpzj7n1VgAAwIADAECACWWg0JCVAEAUAABBiFLOSWkQcsw5KglCzDknqXJMQikpVcxBCCW1zjkpKcXWOQglpRZLKi3FVmspKbUWay0AAKDAAQAgwAZNicUBCg1ZCQBEAQAgxiDEGIQGGaUYg9AYpBRjECKlGHNOSqUUY85JyRhzDkIqGWPOQSgphFBKKimFEEpJJaUCAAAKHAAAAmzQlFgcoNCQFQFAFAAAYAxiDDGGIHRUMioRhExKJ6mBEFoLrXXWUmulxcxaaq202EAIrYXWMkslxtRaZq3EmForAADswAEA7MBCKDRkJQCQBwBAGKMUY845ZxBizDnoHDQIMeYchA4qxpyDDkIIFWPOQQghhMw5CCGEEELmHIQQQgihgxBCCKWU0kEIIYRSSukghBBCKaV0EEIIoZRSCgAAKnAAAAiwUWRzgpGgQkNWAgB5AACAMUo5B6GURinGIJSSUqMUYxBKSalyDEIpKcVWOQehlJRa7CCU0lpsNXYQSmktxlpDSq3FWGuuIaXWYqw119RajLXmmmtKLcZaa825AADcBQcAsAMbRTYnGAkqNGQlAJAHAIAgpBRjjDGGFGKKMeecQwgpxZhzzimmGHPOOeeUYow555xzjDHnnHPOOcaYc8455xxzzjnnnHOOOeecc84555xzzjnnnHPOOeecc84JAAAqcAAACLBRZHOCkaBCQ1YCAKkAAAARVmKMMcYYGwgxxhhjjDFGEmKMMcYYY2wxxhhjjDHGmGKMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhba6211lprrbXWWmuttdZaa60AQL8KBwD/BxtWRzgpGgssNGQlABAOAAAYw5hzjjkGHYSGKeikhA5CCKFDSjkoJYRQSikpc05KSqWklFpKmXNSUiolpZZS6iCk1FpKLbXWWgclpdZSaq211joIpbTUWmuttdhBSCml1lqLLcZQSkqttdhijDWGUlJqrcXYYqwxpNJSbC3GGGOsoZTWWmsxxhhrLSm11mKMtcZaa0mptdZiizXWWgsA4G5wAIBIsHGGlaSzwtHgQkNWAgAhAQAEQow555xzEEIIIVKKMeeggxBCCCFESjHmHHQQQgghhIwx56CDEEIIIYSQMeYcdBBCCCGEEDrnHIQQQgihhFJK5xx0EEIIIZRQQukghBBCCKGEUkopHYQQQiihhFJKKSWEEEIJpZRSSimlhBBCCKGEEkoppZQQQgillFJKKaWUEkIIIZRSSimllFJCCKGUUEoppZRSSgghhFJKKaWUUkoJIYRQSimllFJKKSGEEkoppZRSSimlAACAAwcAgAAj6CSjyiJsNOHCA1BoyEoAgAwAAHHYausp1sggxZyElkuEkHIQYi4RUoo5R7FlSBnFGNWUMaUUU1Jr6JxijFFPnWNKMcOslFZKKJGC0nKstXbMAQAAIAgAMBAhM4FAARQYyACAA4QEKQCgsMDQMVwEBOQSMgoMCseEc9JpAwAQhMgMkYhYDBITqoGiYjoAWFxgyAeADI2NtIsL6DLABV3cdSCEIAQhiMUBFJCAgxNueOINT7jBCTpFpQ4CAAAAAAABAB4AAJINICIimjmODo8PkBCREZISkxOUAAAAAADgAYAPAIAkBYiIiGaOo8PjAyREZISkxOQEJQAAAAAAAAAAAAgICAAAAAAABAAAAAgIT2dnUwAEugEAAAAAAAAISQAAAgAAAK53kAkFOjM2Ndekhj2CvV1AgdsXUTYG69yxV3eJobEdXDTI8dnZ3SP6997W4dSa/TeKs53YVbJ930+NR/+/s2A0tuzedIJFCAQA8GsAsuS0NxU/atI8IutdgXAdXR6YwtyfXhEy7aotcXaVVhWsSOw05XELa/MD/EV1CPtQfRTYY70TAFTK3kVzbq8Xs+PBnL5ZdcqW7vrROclWCt72skTeInGBuv/pv48IlEzGhP08EEgggOmTDKDSG17CqLmM6nbBMrTtceV6p3E6A/ynVRMF3DtXkp7VskprO7Pcta+RNgG6ZbwkIeG2T1xaQc7H2eY2buM2buM2buMQAVUVY4gQCJlwBYDVpz5/6cqVK5uy4tOH73/9/3+vvHLp0qVLly5d2jQ/P//3//7f//t//+///UUpFEue7dlLKYHl13//75/oIhQffPZnr0BJSUlJScmzP/uzP3tJSUkJhmnxr3//7//9hRcBilMMPLsxPPjsz/7sdV5CwXp+fn5+fn7+69//+39/cXFx8brXBaampqampqamjgNAmZqampqampqaYtzPz3/3rRYXEeQlU1N+AABQpqampqaqAA=="; ================================================ FILE: src/ui/assets/index.scss ================================================ @keyframes fade-in-prompt { 0% { opacity: 0; filter: blur(2em); transform: translate(-40vw, 0) } 50% { opacity: 0; filter: blur(2em); transform: translate(-20vw, 0) } 100% { opacity: 1; filter: none; transform: none } } @keyframes fade-out-prompt { 0% { opacity: 1; filter: none; } 100% { opacity: 0; filter: blur(10em); } } @keyframes pulse-player-name { 0% { opacity: 1; filter: drop-shadow(0 0 .4em #fff) } 40% { opacity: 1; filter: drop-shadow(0 0 .4em #fff) } 90% { opacity: .7; filter: drop-shadow(0 0 0 #fff) } } @keyframes pulse-ready { 0% { transform: scale(1) } 80% { transform: scale(1.2); filter: drop-shadow(0 0 .1em #fff) } 100% { transform: scale(1) } } html, body { height: 100% } @layer game { /* z layers */ /* 0: base elements */ /* 100: animations */ /* 150: player messages */ /* 200: system messages */ html.dark { body { color: #ccd; } #background { filter: brightness(0.45) contrast(1.2); } } body { color: #002; margin: 0; padding: 0; overflow: hidden; font-family: 'DM Sans Variable', sans-serif; > #root { position: absolute; width: 100vw; height: 100vh; overflow: auto; &.orientation-flipped { transform: rotate(90deg); width: 100vh; height: 100vw; transform-origin: left bottom; left: 0; bottom: 100%; } } } .full-page-cover { width: 100vw; height: 100vh; z-index: 200; #root.orientation-flipped & { width: 100vh; height: 100vw; } #root.orientation-flipped #game.scaling-scroll & { position: absolute; width: 100%; height: 100%; } position: fixed; left: 0; top: 0; } #background { background-image: url(./grain.jpg); background-size: cover; filter: brightness(1.3) contrast(0.7); z-index: -10; } #game { position: absolute; --aspect-ratio: 1; &:not(.scaling-scroll) { top: calc(50vh - .5 * min(100vw / var(--aspect-ratio), 100vh)); left: calc(50vw - .5 * min(100vw, 100vh * var(--aspect-ratio))); width: min(100vw, 100vh * var(--aspect-ratio)); height: min(100vw / var(--aspect-ratio), 100vh); #root.orientation-flipped & { top: calc(50vw - .5 * min(100vh / var(--aspect-ratio), 100vw)); left: calc(50vh - .5 * min(100vh, 100vw * var(--aspect-ratio))); width: min(100vh, 100vw * var(--aspect-ratio)); height: min(100vh / var(--aspect-ratio), 100vw); } } &.scaling-scroll { top: 0; left: 0; width: max(100vw, 100vh * var(--aspect-ratio)); height: max(100vw / var(--aspect-ratio), 100vh); #root.orientation-flipped & { width: max(100vh, 100vw * var(--aspect-ratio)); height: max(100vh / var(--aspect-ratio), 100vw); } } user-select: none; -webkit-user-select: none; -moz-user-select: none; #play-area { position: relative; &.in-drag-movement { .transform-wrapper { transition: none; } } } * { box-sizing: border-box; } img { -webkit-user-drag: none; pointer-events: none; } .Space { > * { visibility: visible; &.bz-default { width: 100%; height: 100%; background: #ccc; html.dark & { background: #333; } } } } .Piece { visibility: visible; > * { width: 100%; height: 100%; &.bz-default { background: #ccf; border: .1em solid white; padding: .1em; overflow: hidden; } } } .info-hotspot { position: absolute; width: 100%; height: 100%; cursor: help; visibility: visible; z-index: 200; filter: none; } .droppable { visibility: visible; > .bz-default { border: .1em solid red; } } .transform-wrapper { position: absolute; transform-origin: center; transition: transform .6s, top .6s, left .6s, width .6s, height .6s; visibility: hidden; &.has-info { z-index: 200; > *:not(.info-hotspot) { pointer-events: none; } } > div { position: absolute; width: 100%; height: 100%; } &.animating { &.cross-parent { z-index: 100; } pointer-events: none; } &.dragging { z-index: 100; pointer-events: none; filter: drop-shadow(.2em .2em .2em #0008) drop-shadow(.5em .5em .5em #0008); } &.placing { z-index: 100; filter: drop-shadow(0 0 .2em #0008) drop-shadow(0 0 .5em #0008) opacity(.75); cursor: pointer; &:not(.animating) { transition: transform .2s, top .2s, left .2s, width .2s, height .2s; } } .rotator { position: absolute; z-index: 200; transition: transform .2s, top .2s, left .2s, width .2s, height .2s; transform-origin: center; > div { position: absolute; width: 1em; height: 1em; top: .2em; visibility: visible; &.left { left: .2em; cursor: sw-resize; } &.right { right: .2em; cursor: se-resize; } path { fill: white; fill-opacity: 1; stroke: black; stroke-width: 50; stroke-linecap: round; stroke-linejoin: round; paint-order: stroke markers fill; } &:hover path { fill: red; } } } } .layout-wrapper { visibility: hidden; width: 100%; height: 100%; left: 0; top: 0; position: absolute; } .clickable { cursor: pointer; } .selectable { > .bz-default { border: .1em solid yellow; &:hover { border: .1em solid red; } } } .invalid { > .bz-default { background: #fcc; } } .Piece.selected { > .bz-default { transform: scale(1.2); } } .Space.selected { > .bz-default { border: .1em solid red; } } .bz-show-grid { position: absolute; border: 1px solid #99f; outline: 1px dashed white; outline-offset: -1px; pointer-events: none; > span { position: absolute; font-size: .5rem; background: white; color: black; padding: 2px; top: 0; left: 0; } } .drawer { visibility: hidden; position: absolute; > .drawer-tab { position: absolute; visibility: visible; font-size: .5rem; text-align: center; transition: height .2s, width .2s, left .2s, top .2s, bottom .2s, right .2s; background: #0008; color: white; cursor: pointer; height: .75rem; border-radius: .75em .75em 0 0; &.multi { display: flex; flex-wrap: nowrap; } .tabs-tab { position: relative; display: inline-block; padding: 0 .5em; flex: 1 1 auto; overflow: hidden; background: #0004; &.active, &:hover { background: #fff4; } &:first-child { border-radius: .75em 0 0 0; } &:last-child { border-radius: 0 .75em 0 0; } } } &.closed > .drawer-tab:hover { height: .85rem; } &.open-direction-down > .drawer-tab { border-radius: 0 0 .75em .75em; .tabs-tab { &:first-child { border-radius: 0 0 0 .75em; } &:last-child { border-radius: 0 0 .75em 0; } } } > .drawer-content { position: absolute; inset: 0; visibility: visible; border: .1rem solid #0008; background: #fffc; transition: transform .2s; > .drawer-container { position: absolute; visibility: hidden; width: 100%; height: 100%; > * { visibility: visible; } } } } .popout-container { position: absolute; .popout-button { position: absolute; inset: 0; background: #0008; &:hover { background: #0004; } color: white; cursor: pointer; border-radius: .75em; text-align: center; } .full-page-cover { background: #444c; } .popout-close { position: absolute; top: .5vh; right: .5vh; height: 5vh; width: 5vh; fill: none; stroke: #666; stroke-width: .15vh; stroke-linecap: round; cursor: pointer; &:hover { stroke: black; } } .popout-modal { position: absolute; background: white; border: .1rem solid black; } } .player-controls { z-index: 150; position: absolute; padding: .25rem; font-size: .75rem; background: #fffc; html.dark & { background: #000c; } &.fade-out { animation: fade-out-prompt .5s forwards; } &:not(.fade-out) { animation: fade-in-prompt .4s; } form { margin: 0; } input { border-width: .05rem; } input, select, button { padding: 0.2rem 0.4rem; font-family: inherit; font-size: inherit; margin: 0.1rem; } input, select { width: 100%; } input[type=number] { width: 4em; } .error { color: #c00; } button { border: none; background: #ccc; cursor: pointer; transition: transform 0.2s; white-space: normal; &:hover { transform: scale(1.1); box-shadow: 0.2rem 0.2rem .5rem #0008; } &.selected { filter: brightness(1.3); } &.invalid { color: #555; background: #999; } } input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { opacity: 1; } .action-divider { border: 0; font-size: 80%; position: relative; text-align: center; line-height: .75em; &::before { content: ""; background: #888c; position: absolute; left: 0; top: 50%; width: calc(50% - .6rem); height: .05rem; } &::after { content: ""; background: #888c; position: absolute; right: 0; top: 50%; width: calc(50% - .6rem); height: .05rem; } } } .god-mode-enabled { position: absolute; top: 0; left: 0; font-size: .5rem; padding: 0.2rem; background: red; color: white; z-index: 200; } &.mobile { .player-controls { font-size: 1.5rem; padding: .5rem; } .drawer .drawer-tab { height: 1.35rem !important; font-size: 1rem; } } } #setup { padding: 1rem; max-width: 800px; margin: 0 auto 5rem; .heading { h1, h2, h3 { text-align: center; margin: .3em 0 .5em; } p { text-align: center; } html.dark & { background: #fff3; } font-size: 1.2em; background: #fff8; padding: 0.3rem 1.5rem; border-radius: 1rem; margin-bottom: 1rem; } #seating { margin: .2em; text-align: center; display: flex; flex-direction: row; margin-bottom: 1em; #seats { flex: 1; .seat { position: relative; select { appearance: none; font-family: 'DM Sans Variable'; text-align-last: center; text-align: center; font-size: 1.5em; height: 2.75em; border-radius: 20em; border-width: 0; padding: 0.5em 3em; width: 100%; color: white; cursor: pointer; margin: 0.2em 0; box-shadow: inset .1em .1em 0 #fff4, inset -.1em -.1em 0 #0008; filter: drop-shadow(.1em .1em .2em #0008); &:focus { outline: none; } &:disabled { opacity: unset; } html.dark & { background: #444; } } img.avatar { position: absolute; left: 0.5em; top: 0.75em; height: 3.3em; border-radius: 50%; } .invite-link { position: absolute; left: 0; top: 3.75em; width: 100%; color: white; font-size: 75%; cursor: pointer; transition: transform .2s; &:hover { transform: scale(1.2); } } .rename, .palette, .ready { position: absolute; font-size: 2em; transition: transform .2s; } .rename, .palette { &:hover { cursor: pointer; transform: scale(1.4); } } .ready { left: 1.2em; top: .8em; } .rename { right: .65em; top: .45em; } .palette { right: 1.6em; top: .40em; } .ready { animation: pulse-ready .4s; } .github-picker { padding: 1em; position: absolute !important; z-index: 1; text-align: left; left: 75%; width: 142px !important; display: block !important; > span { margin: .1em; display: inline-block; } } } svg.addSeat, svg.removeSeat { height: 2.5em; margin: .2em 1em; cursor: pointer; transition: transform .2s; &:hover { transform: scale(1.2); } } } #lobby { flex: 1; display: flex; flex-direction: column; margin-left: 1em; background: #666; border-radius: 0.5em; padding: 0.5em; color: white; font-weight: bold; font-size: 1.2em; #users { flex: 1; margin: .5em 0 0; background: #fff4; border-radius: 0 0 .2em .2em; padding: .2em; text-align: left; min-height: 50px; font-weight: normal; .user { display: inline-block; margin: .2em; position: relative; background: #666; border-radius: 10em; padding: 0.4em 0.8em 0.4em 2.4em; height: 1.2em; font-size: 1.2em; cursor: pointer; img { height: 1.8em; border-radius: 50%; top: 0.1em; position: absolute; left: 0.1em; } } } } @media only screen and (max-width: 600px) { display: block; #lobby { margin: .5rem 0 0; } } } #settings { margin: .4em .2em; font-size: 1.3em; input, select { font-family: 'DM Sans Variable'; font-size: 1em; padding: 0em 0.5em; margin: 0.1em 0; background: #eef; &:focus { outline: none; } } input[type=checkbox] { transform: scale(1.5); transform-origin: left center; margin-right: .5em; &:focus { outline: none; } } } button.ready { margin: 0 auto; display: block; white-space: normal; font-family: 'DM Sans Variable'; border-radius: .2em; border-width: 0; text-shadow: .1em .1em 0 #fff5; box-shadow: .1em .1em .2em #0008, inset .1em .1em 0 #fff9; background: linear-gradient(to bottom, #ddd, #aaa 85%, #ccc); padding: 0.3em 1.6em; font-size: 1.4em; font-weight: bold; margin-top: .5em; cursor: pointer; transition: transform .2s; &:hover { transform: scale(1.2); } } &.disabled input, &.disabled select, &.disabled button { pointer-events: none; } } .profile-badge { display: flex; flex-direction: row; margin: 0.1em; height: 1em; width: 3em; border-radius: .5em; gap: 0.1em; padding: 0.1em; .avatar { height: 100%; width: auto; aspect-ratio: 1; position: relative; img { position: absolute; top: 0; left: 0; height: 100%; border-radius: 50%; outline-color: #333; outline-style: solid; outline-width: 1px; filter: saturate(0) contrast(.6) brightness(1.2); html.dark & { outline-color: #aaa; } } &:after { content: ""; background-color: #666; outline-color: black; display: block; position: absolute; border-radius: 50%; outline-style: solid; outline-width: 2px; width: 15%; height: 15%; top: 7%; right: 7%; html.dark & { outline-color: #aaa; } } } &.online .avatar img { filter: none; } &.online .avatar:after { content: ""; background-color: #0f0; outline-color: black; outline-style: solid; outline-width: 1px; display: block; position: absolute; border-radius: 50%; width: 15%; height: 15%; top: 7%; right: 7%; html.dark & { outline-color: #aaa; } } &.current { border: .03em solid white; } .player-name { flex: 1; overflow: hidden; text-align: left; white-space: nowrap; font-size: 35%; text-overflow: ellipsis; color: white; margin: 0.44em 0 0 0.1em; } &.current .player-name { animation: pulse-player-name 2s infinite; } } #corner-controls { position: fixed; top: 1vh; left: 1vh; z-index: 200; #info-toggle { position: absolute; height: 3vh; top: 0; left: 0; svg { display: block; height: 100%; fill: white; cursor: pointer; } } #debug-toggle { position: absolute; height: 3vh; top: 0; left: 3.5vh; svg { display: block; height: 100%; fill: white; cursor: pointer; } } } #announcement-overlay { z-index: 200; } .modal-popup { position: absolute; width: max-content; max-width: 80%; background: white; color: #002; top: 4rem; left: 50%; transform: translateX(-50%); visibility: visible; filter: none; z-index: 210; padding: .5rem; box-shadow: 0.2rem 0.2rem .5rem #0008; h1, h2, h3, h4, h5, h6 { text-align: center; margin: .25em 0; } html.dark & { background: #cccccf; } } #info-overlay { z-index: 199; background: #444c; } #info-container { z-index: 210; visibility: hidden; color: #002; #info-drawer { font-family: 'DM Sans Variable'; position: absolute; left: 0.3rem; top: 0.3rem; width: clamp(20%, 10rem, 100%); background: white; border-radius: 0.3rem; transition: width 0.2s, height 0.2s; visibility: visible; z-index: 200; max-height: calc(100% - 0.6rem); overflow-x: hidden; overflow-y: scroll; box-shadow: 0.2rem 0.2rem .5rem #0008; &.collapsed { width: 2.4rem; .header { border-radius: 0.3rem; } } .header { width: 100%; height: 1.4rem; background: #ccc; border-radius: 0.3rem 0.3rem 0 0; padding: .1rem 0.25rem; box-sizing: border-box; display: flex; .title { flex: 1; } .controls { flex: 1; text-align: right; } svg { height: .8rem; cursor: pointer; &:hover { transform: scale(1.2); } } } .contents { font-size: 65%; padding: .1rem 0.25rem; width: 10rem; border-top: .1rem solid #888; h1 { margin: 0.1rem 0; font-size: 1rem; text-align: center; } ul { margin: 0 0 0 .5rem; padding: 0 0 0 .25rem; li { list-style: '⏺'; padding-left: .1rem; span { color: #002; } } } button { width: 94%; padding: 0.2rem 0.4rem; font-family: inherit; font-size: inherit; margin: 0.1rem 3%; border: none; background: #ccc; cursor: pointer; transition: transform 0.2s; white-space: normal; &:hover { transform: scale(1.05); box-shadow: 0.2rem 0.2rem .5rem #0008; } } .more-info { padding: .25rem .25rem .5rem; } } } #info-modal { &.info-element { min-width: 64%; } .element-zoom { display: inline-block; float: right; margin: 0 0 1rem 1rem; position: relative; pointer-events: none; width: 32vw; .Piece, .Space { transform: none !important; } > div { position: relative; } } .info-text { font-size: 80%; p, h1, h2, h3, h4 { margin-top: 0; } } } } #debug-overlay { font-size: 16px; z-index: 199; background: #fffc; #action-debug { overflow-y: scroll; position: absolute; right: .5em; top: 5vmin; width: calc(45% - 1em); height: calc(100% - 4em); top: 3em; #action-breakdown { font-family: 'DM Sans Variable', sans-serif; color: black; } a { color: #009; cursor: pointer; } .argument { padding: .1em .5em; background: #ddf; border: .05em solid #bbe; border-radius: .3em; } ul { padding-left: 1.2em; } li.action-block { margin-bottom: 1em; .name { font-weight: bold; } &::marker { content: '► '; color: #900; } &.impossible::marker { content: '🚫 '; } &.impossible { filter: opacity(.5); } li { margin-bottom: .4em; &.selection-type-ask::marker { content: '► '; color: #009; } &.selection-type-tree::marker { content: '🚫 '; } &.selection-type-imp::marker { content: '❌ '; } &.selection-type-sel::marker, &.selection-type-only-one::marker, &.selection-type-skip::marker { content: '✓ '; color: #090; } &.selection-type-future::marker, &.selection-type-forced::marker { content: '▷ '; } } } } .element-zoom { display: inline-block; margin: 0 0 1rem 1rem; position: relative; pointer-events: none; width: 24vw; .Piece, .Space { transform: none !important; } > div { position: relative; } } #flow-debug { font-family: 'DM Sans Variable', sans-serif; overflow-y: scroll; position: absolute; left: .5em; top: 5vmin; width: 55%; height: calc(100% - 4em); top: 3em; .subflow { background: black; color: white; width: 90%; padding: .2em 1em; margin: 1em 0; border-radius: 1.5em; } > .flow-debug-block { width: 90%; } .flow-debug-block { margin: .2em 0 .2em .4em; border-left: .2em solid var(--color); position: relative; &.current { outline: 4px solid #ff0; &::after { content: ''; position: absolute; width: 5%; height: 100%; left: 100%; top: 0; background: #ff0; clip-path: polygon(0% 0%, 100% 50%, 0% 100%); }; .header { color: #ff0; } } .header { display: flex; color: white; background: var(--color); height: 1.5em; padding: 0 .2em; > .name { height: 80%; color: var(--color); background: white; display: inline-block; border-radius: 1em; margin-left: .5em; margin-top: .25em; font-size: .75em; padding: .2em .5em; overflow-x: scroll; white-space: nowrap; } } .do-block { > .name { left: -0.15em; position: relative; &::before { content: '► ' } } } .function { font-family: monospace; font-size: 75%; line-height: 1.2em; padding-left: .4em; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; &.current { background: 4px solid #ff0; } } } } } } ================================================ FILE: src/ui/game/Game.tsx ================================================ import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'; import { gameStore } from '../store.js'; import Element from './components/Element.js'; import PlayerControls from './components/PlayerControls.js'; import InfoOverlay from './components/InfoOverlay.js'; import Debug from './components/Debug.js'; import click from '../assets/click.ogg.js'; import { GameElement } from '../../board/index.js' import classnames from 'classnames'; import type { UIMove } from '../lib.js'; import type { Argument } from '../../action/action.js'; import AnnouncementOverlay from './components/AnnouncementOverlay.js'; export default () => { const [gameManager, rendered, dev, position, pendingMoves, step, announcementIndex, dismissAnnouncement, selectMove, move, clearMove, selectElement, setBoardSize, dragElement, disambiguateElement, selected] = gameStore(s => [s.gameManager, s.rendered, s.dev, s.position, s.pendingMoves, s.step, s.announcementIndex, s.dismissAnnouncement, s.selectMove, s.move, s.clearMove, s.selectElement, s.setBoardSize, s.dragElement, s.aspectRatio, s.disambiguateElement, s.selected]); const clickAudio = useRef(null); const [mode, setMode] = useState<'game' | 'info' | 'debug'>('game'); const announcement = useMemo(() => gameManager.announcements[announcementIndex], [gameManager.announcements, announcementIndex]); if (!position) return null; const player = gameManager.players.atPosition(position); if (!player) return null; const handleSubmitMove = useCallback((pendingMove?: UIMove, args?: Record) => { if (move || disambiguateElement || selected) clickAudio.current?.play(); clearMove(); selectMove(pendingMove, args); }, [move, disambiguateElement, selected, clearMove, selectMove]); const handleSelectElement = useCallback((moves: UIMove[], element: GameElement) => { clickAudio.current?.play(); selectElement(moves, element); }, [selectElement]); const domRef = useCallback((node: HTMLDivElement) => { if (!node) return; const callback: MutationCallback = deletions => { deletions.forEach(m => m.removedNodes.forEach((d: HTMLElement) => { if (d.classList.contains('player-controls') && !d.classList.contains('fade-out')) { const fadeOut = d.cloneNode(true); (fadeOut as HTMLElement).classList.add('fade-out'); node.appendChild(fadeOut); setTimeout(() => node.removeChild(fadeOut), 500); } })); }; const observer = new MutationObserver(callback); observer.observe(node, { childList: true }); }, []); useEffect(() => { const keydownHandler = (e: KeyboardEvent) => { if (e.repeat) return; if (e.code === 'Escape') { if (mode === 'game') handleSubmitMove(); } }; window.addEventListener('keydown', keydownHandler); return () => window.removeEventListener('keydown', keydownHandler); }, [handleSubmitMove, mode]); useEffect(() => { window.addEventListener('resize', setBoardSize); return () => window.removeEventListener('resize', setBoardSize); }, [setBoardSize]); useEffect(() => { if (gameManager.game._ui.boardSize) { window.document.documentElement.style.setProperty( 'font-size', `${gameManager.game._ui.boardSize.scaling === 'scroll' ? 'max' : 'min'}(4${gameManager.game._ui.boardSize.flipped ? 'vh' : 'vw'} / var(--aspect-ratio), 4${gameManager.game._ui.boardSize.flipped ? 'vw' : 'vh'})` ); window.document.documentElement.style.setProperty( '--aspect-ratio', String(gameManager.game._ui.boardSize.aspectRatio) ) if (gameManager.game._ui.boardSize.flipped) { window.document.querySelector('#root')?.classList.add('orientation-flipped'); } else { window.document.querySelector('#root')?.classList.remove('orientation-flipped'); } return () => { window.document.documentElement.style.removeProperty('font-size'); window.document.documentElement.style.removeProperty('--aspect-ratio'); } } }, [gameManager.game._ui.boardSize]); console.debug('Showing game with pending moves:' + (pendingMoves?.map(m => ( `\n⮕ ${typeof m === 'string' ? m : `${m.name}({${ Object.entries(m.args || {}).map(([k, v]) => `${k}: ${v}`).join(', ') }}) ? ${m.selections?.length ? m.selections[0].toString() : 'no choices'}` }` )).join('') || ' none') ); return (
-1, 'browser-safari': globalThis.navigator?.userAgent.indexOf('Chrome') === -1 && globalThis.navigator?.userAgent.indexOf('Safari') > -1, 'browser-edge': globalThis.navigator?.userAgent.indexOf('Edge') > -1, 'browser-firefox': globalThis.navigator?.userAgent.indexOf('Firefox') > -1, } )} style={{ ['--aspect-ratio' as string]: gameManager.game._ui.boardSize?.aspectRatio, ['--current-player-color' as string]: gameManager.players.currentPosition.length === 1 ? gameManager.players.current()?.color : '', ['--my-player-color' as string]: gameManager.players.atPosition(position)?.color }} >