Compare commits

...
Sign in to create a new pull request.

64 commits
wasm ... main

Author SHA1 Message Date
81aca8a96c build + feat: Updated dependnecies, improved Dockerfile, /room_count 2025-02-16 11:31:40 -08:00
19f0b7f50d fix: Remove 'NY' from dictionary 2025-02-16 09:12:32 -08:00
7b17afeb22 fix: Make 'End Game' button work again 2025-01-13 17:18:51 -08:00
a3b707a7b6 build: Fix Dockerfile 2025-01-12 14:34:55 -08:00
f2642c0749 fix: Remove some invalid dictionary words 2025-01-12 14:04:09 -08:00
203f95eed5 fix: CSS layout fix that caused overlapped text 2025-01-12 13:50:56 -08:00
13bea83542 fix: "Return Tiles doesn't clear confirmed point total 2025-01-12 13:50:00 -08:00
0a4c213644 fix: Use standard JSON output for WASM to match server output 2024-12-28 22:36:17 -08:00
3e187b57fb chore: Ran cargo fmt 2024-12-28 22:35:59 -08:00
710499b664 chore: Misc. fixes & tweaks 2024-12-27 14:30:06 -08:00
f85b3be2f3 fix: Dockerfile 2024-12-27 12:24:07 -08:00
6114f69a50 fix: Don't hardcode websocket path 2024-12-26 18:55:48 -08:00
db5da6801b fix: Bug where socket gets two event listeners 2024-12-26 15:15:03 -08:00
1c81740baa fix: Remove acronym 2024-12-26 11:30:09 -08:00
0c60e3ad38 docs: Update documentation 2024-12-26 10:54:56 -08:00
1224035d7a Multiplayer (#1)
Reviewed-on: #1
Co-authored-by: Joel Therrien <joel@joeltherrien.ca>
Co-committed-by: Joel Therrien <joel@joeltherrien.ca>
2024-12-26 18:38:23 +00:00
ae33218a30 Add link to playable version 2024-02-11 12:11:50 -08:00
edeac3b2fd Fix blank letter at end-of-game bug 2023-10-13 21:56:02 -07:00
22d7ce969e Add some mitigations against blank letter bug 2023-10-13 21:30:06 -07:00
7d6e7d0113 Adjust Makefile so 'make' builds all 2023-10-13 21:16:16 -07:00
ad540e4c4b Fix bug whereby arrow ignored ephemeral tiles 2023-10-03 20:32:47 -07:00
ceb5d6c20d Clean up Typescript imports 2023-09-27 20:03:52 -07:00
79610b958b Fix end-of-game UI bugs 2023-09-25 20:50:58 -07:00
7bca436012 Improve documentation 2023-09-24 10:58:33 -07:00
55f968ae35 Add commands for building UI 2023-09-23 12:21:09 -07:00
880667b80e Remove turn log message after game over 2023-09-23 12:20:52 -07:00
2fa28ce3d4 Add arrow for fast play 2023-09-23 10:53:07 -07:00
a34ad8cd12 Improve UI; add end game button 2023-09-21 19:01:56 -07:00
75d8db4098 Improve 'Add to dictionary' UI 2023-09-21 18:55:33 -07:00
6c7a90c421 Add confirmation choice for passing 2023-09-21 18:40:41 -07:00
e0fe22e9ce Add end game conditions
Also fix some UI bugs
2023-09-20 18:59:32 -07:00
0d30ac0b46 Add AI tile count and total tile counts, other UI tweaks 2023-09-16 21:08:10 -07:00
e7c46c8efd Add standardized turn summary messages.
Same logic for both player and AI
2023-09-15 21:01:49 -07:00
e5b2e4139e Clean up UI code 2023-09-15 20:37:40 -07:00
c1d7a2f774 Add AI turn highlighting 2023-09-14 19:38:34 -07:00
a014805cbf Automate AI plays 2023-09-14 19:14:19 -07:00
ef4506b55e Refactor code to utilize TurnActions on player moves 2023-09-14 18:53:47 -07:00
8fd250170b Add rudimentry but functional AI integration into UI
Also fixed some bugs that could cause AI process to either
produce invalid words or crash.
2023-09-12 22:13:36 -07:00
9b22f1301d WIP integration of AI into game logic 2023-09-10 15:17:36 -07:00
60fabb0214 Add difficulty menu to UI (not yet functional) 2023-09-08 23:32:44 -07:00
ef655f99cd Fix bug in Rust relating to PlayedTile
The bug broke a contract that was relied on by WASM
2023-09-08 17:50:54 -07:00
e23c1d139b Add capability to convert AI plays into PlayedTiles vector 2023-09-07 19:44:07 -07:00
0887cb29aa Fix bug in AI handling of blank letters 2023-09-07 19:14:43 -07:00
4b86c031ed Add basic AI support (Rust only) 2023-09-06 20:00:14 -07:00
cdfd8b5ee9 Fix bug where UI wasn't detecting 7-letter word bonus 2023-08-24 20:37:01 -07:00
733feecfe3 Add adding words to dictionary mid-game 2023-08-24 20:29:08 -07:00
4f8f14364c Removed unused parameters in UI 2023-08-23 21:58:34 -07:00
974751bda0 Split UI code into separate files 2023-08-23 20:46:43 -07:00
de2605af67 Improve tile exchange to retain player order 2023-08-23 20:37:22 -07:00
e8cff060b0 Add 'Return Tiles' button 2023-08-23 20:23:58 -07:00
ca5ab097c5 Add basic tile exchange support
Still need to support handling if the player reordered their tray
2023-08-22 20:52:03 -07:00
960e8c31fb Fix Rust dependency issue 2023-08-22 19:02:08 -07:00
b790e48bc4 Add UI for tile exchange 2023-08-21 19:42:22 -07:00
4ba4c15e23 Transfer previous Modal code 2023-08-20 17:26:52 -07:00
800ec27c36 Slightly improve styling 2023-08-20 16:34:00 -07:00
f3d085ff99 Add LICENSE and fields to Cargo.toml 2023-08-20 16:28:42 -07:00
368dcd4a65 Add auto-scrolling for log
Styling is still a WIP
2023-08-20 10:00:10 -07:00
4c8d27b659 Improve tray handling
Fix bugs when the tray is not fully filled, and retain custom
user tray ordering between turns.
2023-08-19 14:47:34 -07:00
b33007d3c4 Downgrade serde to remove included binary 2023-08-19 09:58:16 -07:00
cb10d97724 Refactored receive_play from wasm into Game 2023-08-18 18:14:27 -07:00
cd8a4b73a9 Add support for blank characters 2023-08-17 18:30:55 -07:00
c61b2e3f75 Add display of previous tiles 2023-08-17 18:05:20 -07:00
fd7cf2d6af Add turn counting and score persistence 2023-08-16 19:37:32 -07:00
c7399b2b99 Integrate score keeping and individual trays 2023-08-15 19:35:23 -07:00
47 changed files with 9171 additions and 1655 deletions

4
.gitignore vendored
View file

@ -1,4 +1,4 @@
/target target/
/Cargo.lock
.idea/ .idea/
pkg/ pkg/
.nvmrc

2255
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,8 @@
[package] [workspace]
name = "word_grid" members = ["wordgrid", "wasm", "server"]
version = "0.1.0" resolver = "2"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
csv = "1.2.2"
rand = {version = "0.8.5", features = ["small_rng"]}
getrandom = {version = "0.2", features = ["js"]}
wasm-bindgen = { version = "0.2.87", features = ["serde-serialize"] }
serde_json = "1.0"
serde = { version = "1.0.181", features = ["derive"] }
serde-wasm-bindgen = "0.4"
tsify = { version = "0.4.5", features = ["js"] }
[workspace.dependencies]
serde_json = "1.0.132"
serde = { version = "1.0.213", features = ["derive"] }
rand = {version = "0.9.0", features = ["small_rng"]}

58
Dockerfile Normal file
View file

@ -0,0 +1,58 @@
FROM docker.io/library/ubuntu:24.04 as build-stage
LABEL authors="joel"
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install --no-install-recommends -y rustup npm gcc gcc-multilib
RUN rustup default stable
RUN cargo install wasm-pack
RUN mkdir /build
WORKDIR /build/
# for caching the dependencies downloads
COPY Cargo.toml Cargo.lock /build/
COPY wasm/Cargo.toml /build/wasm/
COPY server/Cargo.toml /build/server/
COPY wordgrid/Cargo.toml /build/wordgrid/
RUN cargo fetch
COPY ui/package.json ui/package-lock.json /build/ui/
RUN mkdir /build/wasm/pkg && echo "{}" > /build/wasm/pkg/package.json && cd ui && npm install
COPY --exclude=*/target/* wordgrid /build/wordgrid/
COPY --exclude=*/target/* --exclude=*/pkg/* wasm /build/wasm/
COPY --exclude=*/target/* server /build/server/
COPY --exclude=*/node_modules/* --exclude=*/dist/* ui /build/ui/
COPY resources /build/resources/
# for some reason wasm-pack wasn't on the PATH
RUN cd wasm && ~/.cargo/bin/wasm-pack build --target=web
# We re-run install because wasm/pkg is now actually present and this needs to be reflected (node_modules copied the old pkg directory)
RUN cd ui && npm install && npm run build
RUN cd server && cargo build --release
FROM docker.io/library/ubuntu:24.04 as final-image
LABEL authors="joel"
WORKDIR /srv/
COPY --from=build-stage /build/ui/dist /srv/static
COPY --from=build-stage /build/target/release/server server
RUN cp /srv/static/*.csv dictionary.csv
RUN echo '{"dictionary_path": "dictionary.csv", "static_path": "static"}' > config.json
RUN useradd -d /srv wordgrid && chown -R wordgrid:wordgrid /srv
USER wordgrid
# See https://rocket.rs/guide/v0.5/deploying/#containerization
ENV ROCKET_ADDRESS=0.0.0.0
ENV ROCKET_PORT=8000
ENTRYPOINT ["./server"]
EXPOSE 8000

661
LICENSE Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -1,2 +1,10 @@
build: build-all: build-rust build-ui
build-rust:
wasm-pack build --target=web wasm-pack build --target=web
build-ui:
rm -rf ui/dist ui/.parcel-cache
cd ui; npm run build
build-all: build-rust build-ui

25
README.md Normal file
View file

@ -0,0 +1,25 @@
# README
This repository contains the code for 'WordGrid', a browser game where you use letter tiles to form words.
There is support for both multiplayer and singleplayer, where singleplayer runs entirely in the browser through WebAssembly.
Here's the rough layout of the repository:
1. The core game logic resides in the `wordgrid/` folder as Rust code and is a library for either the `wasm/` code (if compiled to WebAssembly for singleplayer), or for the `server/` code (if used in multiplayer).
2. The Rust code in `wasm/` is a small compatibility layer between the library and the browser. It gets compiled using `wasm-pack` to a Node package into `wasm/pkg/` that gets read by `ui/`
3. `ui/` is a Node package that uses React & Typescript. Currently it assumes it's being run in an environment that supports both singleplayer & multiplayer. This can't be built until the `wasm/` code has been built.
4. `server/` is a Rust program that runs a small web server for multiplayer purposes.
If you want to try it now, I host a version at https://wordgrid.joeltherrien.ca
## Setup
I'd suggest just reading through the `Dockerfile` to precisely see what to do, but it's basically the following steps:
1. Ensure you have Rust, Node, npm, and wasm-pack installed.
2. Build wasm by navigating to the `wasm/` folder and running `wasm-pack build --target=web`
3. Build the ui by navigating to the `ui/` folder and running `npm run build`. You may need to first run `npm install`.
4. Build the server by navigating to the `server/` folder and running `cargo build --release`.
If you just want singleplayer, you can stop after step 3 and the static files you'll want are in `ui/dist/`. You can rename `singleplayer.html` -> `index.html` if you want to save a click.

View file

@ -28906,8 +28906,6 @@ BRISTOLS,0.892583365274051
BRISURE,-1.0 BRISURE,-1.0
BRISURES,-1.0 BRISURES,-1.0
BRIT,0.746498135823548 BRIT,0.746498135823548
BRITANNIA,-1.0
BRITANNIAS,-1.0
BRITCHES,0.277971357887034 BRITCHES,0.277971357887034
BRITH,-1.0 BRITH,-1.0
BRITHS,-1.0 BRITHS,-1.0
@ -32917,8 +32915,6 @@ CAMWHORING,-1.0
CAMWOOD,-1.0 CAMWOOD,-1.0
CAMWOODS,-1.0 CAMWOODS,-1.0
CAN,0.999172445032928 CAN,0.999172445032928
CANADA,-1.0
CANADAS,-1.0
CANAIGRE,-1.0 CANAIGRE,-1.0
CANAIGRES,-1.0 CANAIGRES,-1.0
CANAILLE,0.0 CANAILLE,0.0
@ -39330,7 +39326,6 @@ CHINDITS,-1.0
CHINE,0.801012230391303 CHINE,0.801012230391303
CHINED,0.499912888950835 CHINED,0.499912888950835
CHINES,0.961871493780271 CHINES,0.961871493780271
CHINESE,-1.0
CHING,-1.0 CHING,-1.0
CHINGS,-1.0 CHINGS,-1.0
CHINING,0.0 CHINING,0.0
@ -125575,8 +125570,6 @@ JETWAYS,-1.0
JEU,0.7158873131468 JEU,0.7158873131468
JEUNE,-1.0 JEUNE,-1.0
JEUX,0.7158873131468 JEUX,0.7158873131468
JEW,0.877870309070002
JEWED,0.0
JEWEL,0.829863409874909 JEWEL,0.829863409874909
JEWELED,0.622216801979163 JEWELED,0.622216801979163
JEWELER,0.970861354054148 JEWELER,0.970861354054148
@ -125598,10 +125591,6 @@ JEWELWEED,0.518092964911669
JEWELWEEDS,0.0209327851144639 JEWELWEEDS,0.0209327851144639
JEWFISH,0.0857695390083278 JEWFISH,0.0857695390083278
JEWFISHES,0.0857695390083278 JEWFISHES,0.0857695390083278
JEWIE,-1.0
JEWIES,-1.0
JEWING,0.0
JEWS,0.877870309070002
JEZAIL,0.0 JEZAIL,0.0
JEZAILS,0.0 JEZAILS,0.0
JEZEBEL,0.458726784905397 JEZEBEL,0.458726784905397
@ -160554,7 +160543,6 @@ NUZZLER,0.159134464615492
NUZZLERS,0.105151747447646 NUZZLERS,0.105151747447646
NUZZLES,0.159134464615492 NUZZLES,0.159134464615492
NUZZLING,0.120361336631938 NUZZLING,0.120361336631938
NY,-1.0
NYAFF,-1.0 NYAFF,-1.0
NYAFFED,-1.0 NYAFFED,-1.0
NYAFFING,-1.0 NYAFFING,-1.0
@ -208407,7 +208395,6 @@ ROLLUPS,-1.0
ROLLWAY,0.479633436705112 ROLLWAY,0.479633436705112
ROLLWAYS,0.0 ROLLWAYS,0.0
ROM,0.988361963831492 ROM,0.988361963831492
ROMA,-1.0
ROMAGE,-1.0 ROMAGE,-1.0
ROMAGES,-1.0 ROMAGES,-1.0
ROMAIKA,-1.0 ROMAIKA,-1.0
@ -209609,7 +209596,6 @@ RUBYING,0.0
RUBYLIKE,0.0 RUBYLIKE,0.0
RUBYTHROAT,0.0 RUBYTHROAT,0.0
RUBYTHROATS,0.0 RUBYTHROATS,0.0
RUC,-1.0
RUCHE,0.329741454406077 RUCHE,0.329741454406077
RUCHED,0.329741454406077 RUCHED,0.329741454406077
RUCHES,0.0 RUCHES,0.0
@ -210166,8 +210152,6 @@ RUSSETS,0.405258022927628
RUSSETTING,0.0 RUSSETTING,0.0
RUSSETTINGS,0.0 RUSSETTINGS,0.0
RUSSETY,0.405258022927628 RUSSETY,0.405258022927628
RUSSIA,-1.0
RUSSIAS,-1.0
RUSSIFIED,0.0 RUSSIFIED,0.0
RUSSIFIES,0.0 RUSSIFIES,0.0
RUSSIFY,0.0 RUSSIFY,0.0
@ -256925,13 +256909,11 @@ UDOS,0.551569741105962
UDS,-1.0 UDS,-1.0
UEY,-1.0 UEY,-1.0
UEYS,-1.0 UEYS,-1.0
UFO,-1.0
UFOLOGICAL,0.0 UFOLOGICAL,0.0
UFOLOGIES,0.0 UFOLOGIES,0.0
UFOLOGIST,0.0 UFOLOGIST,0.0
UFOLOGISTS,0.0 UFOLOGISTS,0.0
UFOLOGY,0.194248928534095 UFOLOGY,0.194248928534095
UFOS,-1.0
UG,-1.0 UG,-1.0
UGALI,-1.0 UGALI,-1.0
UGALIS,-1.0 UGALIS,-1.0

Can't render this file because it is too large.

19
server/Cargo.toml Normal file
View file

@ -0,0 +1,19 @@
[package]
name = "server"
version = "0.1.0"
edition = "2021"
# We manually specify for better caching in Podman
[[bin]]
name = "server"
path = "src/main.rs"
[dependencies]
itertools = "0.14.0"
rocket = { version = "0.5.1", features = ["json"] }
word_grid = { path="../wordgrid" }
serde_json = { workspace = true }
serde = { workspace = true }
ws = { package = "rocket_ws", version = "0.1.1" }
rand = { workspace = true }

4
server/config.json Normal file
View file

@ -0,0 +1,4 @@
{
"dictionary_path": "../resources/dictionary.csv",
"static_path": "../ui/dist"
}

129
server/src/lib.rs Normal file
View file

@ -0,0 +1,129 @@
use rocket::serde::{Deserialize, Serialize};
use rocket::tokio::sync::broadcast::Sender;
use rocket::tokio::sync::RwLock;
use std::collections::HashMap;
use std::sync::Weak;
use word_grid::api::{APIGame, ApiState, Update};
use word_grid::game::{Error, PlayedTile};
use word_grid::player_interaction::ai::Difficulty;
use ws::frame::{CloseCode, CloseFrame};
pub fn escape_characters(x: &str) -> String {
let x = x
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;");
x
}
pub type Player = String;
#[derive(Clone, Serialize, Debug)]
pub struct PartyInfo {
pub ais: Vec<Difficulty>,
pub players: Vec<Player>,
}
impl PartyInfo {
fn new(host: Player) -> Self {
Self {
ais: Vec::new(),
players: vec![host],
}
}
}
pub struct Room {
pub name: String,
pub party_info: PartyInfo,
pub game: Option<APIGame>,
pub sender: Sender<(Option<Player>, InnerRoomMessage)>,
}
impl Room {
pub fn new(key: String, host: Player) -> Self {
Self {
name: key,
party_info: PartyInfo::new(host),
game: None,
sender: Sender::new(5),
}
}
}
#[derive(Clone, Serialize, Debug)]
#[serde(tag = "type")]
pub enum RoomEvent {
PlayerJoined { player: Player },
PlayerLeft { player: Player },
AIJoined { difficulty: Difficulty },
AILeft { index: usize },
}
#[derive(Clone, Serialize, Debug)]
#[serde(tag = "type")]
pub enum GameEvent {
TurnAction { state: ApiState, committed: bool },
}
#[derive(Clone, Serialize, Debug)]
#[serde(tag = "type")]
pub enum ServerToClientMessage {
RoomChange { event: RoomEvent, info: PartyInfo },
GameEvent { event: GameEvent },
GameError { error: Error },
Invalid { reason: String },
}
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum GameMove {
Pass,
Exchange {
tiles: Vec<bool>,
},
Play {
played_tiles: Vec<Option<PlayedTile>>,
commit_move: bool,
},
AddToDictionary {
word: String,
},
}
#[derive(Deserialize, Debug)]
#[serde(tag = "type")]
pub enum ClientToServerMessage {
Load,
StartGame,
GameMove { r#move: GameMove },
AddAI { difficulty: Difficulty },
RemoveAI { index: usize },
}
#[derive(Clone, Debug)]
pub enum InnerRoomMessage {
PassThrough(ServerToClientMessage),
GameEvent(Option<Update>),
}
pub type RoomMap = HashMap<String, Weak<RwLock<Room>>>;
pub fn reject_websocket_with_reason(
ws: ws::WebSocket,
close_code: CloseCode,
reason: String,
) -> ws::Channel<'static> {
ws.channel(move |mut stream| {
Box::pin(async move {
let closeframe = CloseFrame {
code: close_code,
reason: reason.into(),
};
let _ = stream.close(Some(closeframe)).await;
Ok(())
})
})
}

434
server/src/main.rs Normal file
View file

@ -0,0 +1,434 @@
#[macro_use]
extern crate rocket;
use itertools::Itertools;
use rand::prelude::SmallRng;
use rand::SeedableRng;
use rocket::fs::FileServer;
use rocket::futures::{SinkExt, StreamExt};
use rocket::serde::json::Json;
use rocket::serde::Deserialize;
use rocket::tokio::sync::broadcast::Sender;
use rocket::tokio::sync::{Mutex, RwLock};
use rocket::tokio::time::interval;
use rocket::{tokio, State};
use server::{
escape_characters, reject_websocket_with_reason, ClientToServerMessage, GameEvent, GameMove,
InnerRoomMessage, Player, Room, RoomEvent, RoomMap, ServerToClientMessage,
};
use std::fs;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::select;
use word_grid::api::{APIGame, Update};
use word_grid::dictionary::{Dictionary, DictionaryImpl};
use word_grid::game::Game;
use ws::frame::CloseCode;
use ws::stream::DuplexStream;
use ws::Message;
async fn incoming_message_handler<E: std::fmt::Display>(
message: Option<Result<Message, E>>,
sender: &Sender<(Option<Player>, InnerRoomMessage)>,
player: &Player,
room: &Arc<RwLock<Room>>,
stream: &mut DuplexStream,
) -> bool {
match message {
None => {
panic!("Not sure when this happens")
}
Some(message) => {
match message {
Ok(message) => {
if matches!(message, Message::Ping(_)) || matches!(message, Message::Pong(_)) {
return false;
}
let message = message.to_text().unwrap();
if message.len() == 0 {
println!("Received message of length zero");
println!("Player {player:#?} is leaving");
let mut room = room.write().await;
let new_vec = room
.party_info
.players
.iter()
.filter(|p| !p.eq(&player))
.map(|p| p.clone())
.collect_vec();
room.party_info.players = new_vec;
let event = ServerToClientMessage::RoomChange {
event: RoomEvent::PlayerLeft {
player: player.clone(),
},
info: room.party_info.clone(),
};
sender
.send((None, InnerRoomMessage::PassThrough(event)))
.unwrap();
// TODO - handle case where there are no players left
return true;
}
println!("Received {message}");
let message: ClientToServerMessage = serde_json::from_str(message).unwrap();
// TODO
println!("Received {message:#?} from client {player}");
match message {
ClientToServerMessage::Load => {
return !game_load(player, None, room, stream).await
}
ClientToServerMessage::StartGame => {
let mut room = room.write().await;
if room.game.is_some() {
eprintln!(
"Player {} is trying to start an already started game",
player
);
} else {
let rng = SmallRng::from_os_rng();
let dictionary = DICTIONARY.get().unwrap().clone();
let player_names = room
.party_info
.players
.iter()
.map(|p| p.clone())
.collect_vec();
let game = Game::new_specific(
rng,
dictionary,
player_names,
room.party_info.ais.clone(),
);
let game = APIGame::new(game);
room.game = Some(game);
sender
.send((None, InnerRoomMessage::GameEvent(None)))
.unwrap();
}
}
ClientToServerMessage::GameMove { r#move } => {
let mut room = room.write().await;
if room.game.is_none() {
let event = ServerToClientMessage::Invalid {
reason: "Game hasn't been started yet".to_string(),
};
let event = serde_json::to_string(&event).unwrap();
let _ = stream.send(event.into()).await;
} else {
let game = room.game.as_mut().unwrap();
let result = match r#move {
GameMove::Pass => game.pass(&player),
GameMove::Exchange { tiles } => game.exchange(&player, tiles),
GameMove::Play {
played_tiles,
commit_move,
} => {
let result = game.play(&player, played_tiles, commit_move);
if result.is_ok() & !commit_move {
let event = ServerToClientMessage::GameEvent {
event: GameEvent::TurnAction {
state: result.unwrap(),
committed: false,
},
};
let event = serde_json::to_string(&event).unwrap();
let _ = stream.send(event.into()).await;
return false;
}
result
}
GameMove::AddToDictionary { word } => {
game.add_to_dictionary(&player, &word)
}
};
match result {
Ok(event) => {
sender
.send((None, InnerRoomMessage::GameEvent(event.update)))
.unwrap();
}
Err(error) => {
let event = ServerToClientMessage::GameError { error };
let event = serde_json::to_string(&event).unwrap();
let _ = stream.send(event.into()).await;
}
}
}
}
ClientToServerMessage::AddAI { difficulty } => {
let mut room = room.write().await;
room.party_info.ais.push(difficulty.clone());
let event = ServerToClientMessage::RoomChange {
event: RoomEvent::AIJoined { difficulty },
info: room.party_info.clone(),
};
sender
.send((None, InnerRoomMessage::PassThrough(event)))
.unwrap();
}
ClientToServerMessage::RemoveAI { index } => {
let mut room = room.write().await;
if index < room.party_info.ais.len() {
room.party_info.ais.remove(index);
let event = ServerToClientMessage::RoomChange {
event: RoomEvent::AILeft { index },
info: room.party_info.clone(),
};
sender
.send((None, InnerRoomMessage::PassThrough(event)))
.unwrap();
} else {
let event = ServerToClientMessage::Invalid {
reason: format!("{index} is out of bounds"),
};
let event = serde_json::to_string(&event).unwrap();
let _ = stream.send(event.into()).await;
}
}
}
}
Err(e) => {
println!("Received some kind of error {e}")
}
}
}
}
false
}
async fn game_load(
player: &Player,
update: Option<Update>,
room: &Arc<RwLock<Room>>,
stream: &mut DuplexStream,
) -> bool {
// The game object was modified; we need to trigger a load from this player's perspective
let mut room = room.write().await;
let mut state = room.game.as_mut().unwrap().load(&player).unwrap();
state.update = update;
let event = ServerToClientMessage::GameEvent {
event: GameEvent::TurnAction {
state,
committed: true,
},
};
let text = serde_json::to_string(&event).unwrap();
let x = stream.send(text.into()).await;
x.is_ok()
}
async fn outgoing_message_handler<E: std::fmt::Debug>(
message: Result<(Option<Player>, InnerRoomMessage), E>,
_sender: &Sender<(Option<Player>, InnerRoomMessage)>,
player: &Player,
room: &Arc<RwLock<Room>>,
stream: &mut DuplexStream,
) -> bool {
let (target, message) = message.unwrap();
println!("Inner room message - {:#?}", message);
if target.is_none() || target.unwrap() == *player {
match message {
InnerRoomMessage::PassThrough(event) => {
let text = serde_json::to_string(&event).unwrap();
let x = stream.send(text.into()).await;
x.is_err()
}
InnerRoomMessage::GameEvent(update) => !game_load(player, update, room, stream).await,
}
} else {
false
}
}
#[get("/room_count")]
async fn room_count(rooms: &State<Arc<Mutex<RoomMap>>>) -> Json<usize> {
Json(rooms.lock().await.len())
}
#[get("/room/<id>?<player_name>")]
async fn room(
id: &str,
player_name: &str,
ws: ws::WebSocket,
rooms: &State<Arc<Mutex<RoomMap>>>,
) -> ws::Channel<'static> {
let id = escape_characters(id).to_lowercase();
let player_name = escape_characters(player_name);
let rooms = Arc::clone(rooms);
let mut rooms_lock = rooms.lock().await;
let room = rooms_lock.get(&id);
let player = player_name.to_string();
fn make_join_event(room: &Room, player: &Player) -> ServerToClientMessage {
ServerToClientMessage::RoomChange {
event: RoomEvent::PlayerJoined {
player: player.clone(),
},
info: room.party_info.clone(),
}
}
let (room, mut receiver, sender, trigger_game_load) =
if room.is_none_or(|x| x.strong_count() == 0) {
println!("Creating new room");
let room = Room::new(id.to_string(), player.clone());
let event = make_join_event(&room, &player);
let sender = room.sender.clone();
let receiver = sender.subscribe();
let arc = Arc::new(RwLock::new(room));
rooms_lock.insert(id.to_string(), Arc::downgrade(&arc));
sender
.send((None, InnerRoomMessage::PassThrough(event)))
.unwrap();
(arc, receiver, sender, false)
} else {
let a = room.unwrap();
let b = a.clone();
let c = b.upgrade();
let d = c.unwrap();
let mut trigger_game_load = false;
// need to add player to group
let (sender, event) = {
let mut room = d.write().await;
// check if player is already in the room. If they are, don't allow the new connection
if room
.party_info
.players
.iter()
.map(|f| f.to_lowercase())
.contains(&player.to_lowercase())
{
return reject_websocket_with_reason(
ws,
CloseCode::Protocol,
format!("{player} is already in the room"),
);
}
if let Some(game) = &room.game {
if game.0.player_states.get_player_state(&player).is_none() {
// Game is in progress and our new player isn't a member
return reject_websocket_with_reason(
ws,
CloseCode::Protocol,
"The game is already in-progress".to_string(),
);
}
trigger_game_load = true;
}
room.party_info.players.push(player.clone());
let sender = room.sender.clone();
let event = make_join_event(&room, &player);
(sender, event)
};
let receiver = sender.subscribe();
sender
.send((None, InnerRoomMessage::PassThrough(event)))
.unwrap();
(d, receiver, sender, trigger_game_load)
};
drop(rooms_lock);
if trigger_game_load {
sender
.send((Some(player.clone()), InnerRoomMessage::GameEvent(None)))
.unwrap();
}
ws.channel(move |mut stream| {
Box::pin(async move {
let mut interval = interval(Duration::from_secs(10));
let x = loop {
let incoming_message = stream.next();
let room_message = receiver.recv();
let ping_tick = interval.tick();
select! {
// Rust formatter can't reach into this macro, hence we broke out the logic
// into sub-functions
message = incoming_message => {
if incoming_message_handler(message, &sender, &player, &room, &mut stream).await {
println!("incoming returned true");
break Ok(())
}
},
message = room_message => {
if outgoing_message_handler(message, &sender, &player, &room, &mut stream).await {
println!("outgoing returned true");
break Ok(())
}
},
_ = ping_tick => {
// send keep-alive
let message = Message::Ping(Vec::new());
let result = stream.send(message.into()).await;
// if it fails, disconnect
if let Err(e) = result {
println!("Failed to send ping for player {player:#?}; disconnecting");
println!("Received error {e}");
break Ok(())
}
}
}
};
// let's check and see if this is the last reference to the room
let weak_room = Arc::downgrade(&room);
drop(room);
if weak_room.strong_count() == 0 {
println!("Dropping {id}");
let mut rooms_lock = rooms.lock().await;
rooms_lock.remove(&id);
}
return x;
})
})
}
#[derive(Debug, Deserialize)]
struct Config {
dictionary_path: String,
static_path: String,
}
pub static DICTIONARY: OnceLock<DictionaryImpl> = OnceLock::new();
#[launch]
fn rocket() -> _ {
let config_str = fs::read_to_string("config.json").unwrap();
let config: Config = serde_json::from_str(&config_str).unwrap();
let dictionary = DictionaryImpl::create_from_path(&config.dictionary_path);
DICTIONARY.set(dictionary).unwrap();
rocket::build()
.manage(Arc::new(Mutex::new(RoomMap::new())))
.mount("/", FileServer::from(config.static_path))
.mount("/", routes![room, room_count])
}

View file

@ -1,83 +0,0 @@
use rand::rngs::SmallRng;
use rand::SeedableRng;
use crate::board::{Board, Letter};
use crate::constants::{standard_tile_pool, TRAY_LENGTH};
use crate::dictionary::{Dictionary, DictionaryImpl};
use crate::player_interaction::ai::Difficulty;
use crate::player_interaction::Tray;
pub enum Player {
Human(String),
AI{
name: String,
difficulty: Difficulty,
}
}
pub struct PlayerState {
player: Player,
score: u32,
tray: Tray
}
pub struct Game{
tile_pool: Vec<Letter>,
board: Board,
player: PlayerState,
dictionary: DictionaryImpl,
}
// Problem - I want to provide a UI to the player
// Ideally they would get some kind of 'tray' object with methods to use and run
// However I want the main game state to live in Rust, not in JS.
// Does this mean I provide Rc<RefCell<Tray>>?
// Other option - what if I just have one Game object that exposes all methods.
// At no point do they get a Tray reference that auto-updates, they need to handle that
// I just provide read-only JSON of everything, and they call the methods for updates
// This will later work out well when I build it out as an API for multiplayer.
impl Game {
pub fn new(seed: u64, dictionary_text: &str) -> Self {
let mut rng = SmallRng::seed_from_u64(seed);
let mut letters = standard_tile_pool(Some(&mut rng));
let mut tray = Tray::new(TRAY_LENGTH);
tray.fill(&mut letters);
let player = PlayerState {
player: Player::Human("Joel".to_string()),
score: 0,
tray,
};
Game {
tile_pool: letters,
board: Board::new(),
player,
dictionary: DictionaryImpl::create_from_str(dictionary_text)
}
}
pub fn get_tray(&self) -> &Tray {
&self.player.tray
}
pub fn get_tray_mut(&mut self) -> &mut Tray {
&mut self.player.tray
}
pub fn get_board(&self) -> &Board {&self.board}
pub fn get_board_mut(&mut self) -> &mut Board {
&mut self.board
}
pub fn get_dictionary(&self) -> &DictionaryImpl {
&self.dictionary
}
}

View file

@ -1,21 +0,0 @@
use wasm_bindgen::prelude::wasm_bindgen;
pub mod constants;
pub mod board;
pub mod dictionary;
pub mod player_interaction;
pub mod game;
pub mod wasm;
#[wasm_bindgen]
extern {
pub fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {}!", name));
}

View file

@ -1,5 +0,0 @@
pub struct Difficulty {
proportion: f64,
randomness: f64,
}

View file

@ -1,137 +0,0 @@
use serde::{Deserialize, Serialize};
use serde_wasm_bindgen::Error;
use tsify::Tsify;
use wasm_bindgen::JsValue;
use wasm_bindgen::prelude::wasm_bindgen;
use crate::board::{Board, CellType, Coordinates, Letter};
use crate::game::Game;
#[wasm_bindgen]
pub struct GameWasm(Game);
#[derive(Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub enum ResponseType {
OK,
ERR,
}
#[derive(Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct MyResult<E> {
response_type: ResponseType,
value: E,
}
#[derive(Deserialize, Tsify, Copy, Clone)]
#[tsify(from_wasm_abi)]
pub struct PlayedTile {
index: usize,
character: Option<char>,
}
#[wasm_bindgen]
impl GameWasm {
#[wasm_bindgen(constructor)]
pub fn new(seed: u64, dictionary_text: &str) -> GameWasm {
GameWasm(Game::new(seed, dictionary_text))
}
pub fn get_tray(&self) -> Result<JsValue, Error> {
let tray = self.0.get_tray();
serde_wasm_bindgen::to_value(tray)
}
pub fn get_board_cell_types(&self) -> Result<JsValue, Error> {
let board = self.0.get_board();
let cell_types: Vec<CellType> = board.cells.iter().map(|cell| -> CellType {
cell.cell_type.clone()
}).collect();
serde_wasm_bindgen::to_value(&cell_types)
}
pub fn receive_play(&mut self, tray_tile_locations: JsValue, commit_move: bool) -> Result<JsValue, JsValue> {
let tray_tile_locations: Vec<Option<PlayedTile>> = serde_wasm_bindgen::from_value(tray_tile_locations)?;
let mut board_instance = self.0.get_board().clone();
let tray = self.0.get_tray().clone();
let mut played_letters: Vec<(Letter, Coordinates)> = Vec::new();
for (i, played_tile) in tray_tile_locations.iter().enumerate() {
if played_tile.is_some() {
let played_tile = played_tile.unwrap();
let mut letter: Letter = tray.letters.get(i).unwrap().unwrap();
let coord = Coordinates::new_from_index(played_tile.index);
if letter.is_blank {
match played_tile.character {
None => {
panic!("You can't play a blank character without providing a letter value")
}
Some(x) => {
// TODO - I should check that the character is a valid letter
letter.text = x;
}
}
}
played_letters.push((letter, coord));
}
}
match board_instance.receive_play(played_letters) {
Err(e) => {
return Ok(serde_wasm_bindgen::to_value(
&MyResult {
response_type: ResponseType::ERR,
value: e
}).unwrap());
},
Ok(_) => {}
}
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
struct WordResult {
word: String,
score: u32,
}
let result = board_instance.calculate_scores(self.0.get_dictionary());
let result = match result {
Ok(x) => {
let words: Vec<WordResult> = x.0.iter()
.map(|(word, score)| {
WordResult {
word: word.to_string(),
score: *score
}
})
.collect();
//let total_score = x.1;
serde_wasm_bindgen::to_value(
&MyResult {
response_type: ResponseType::OK,
value: words
}).unwrap()
},
Err(e) => {
serde_wasm_bindgen::to_value(
&MyResult {
response_type: ResponseType::ERR,
value: e
}).unwrap()
}
};
Ok(result)
}
}

2051
ui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -2,13 +2,17 @@
"dependencies": { "dependencies": {
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"word_grid": "file:../pkg" "word_grid": "file:../wasm/pkg"
}, },
"devDependencies": { "devDependencies": {
"@parcel/transformer-less": "^2.9.3", "@parcel/transformer-less": "^2.9.3",
"@types/react": "^18.2.18", "@types/react": "^18.2.18",
"@types/react-dom": "^18.2.7", "@types/react-dom": "^18.2.7",
"parcel": "^2.9.3", "parcel": "^2.12.0",
"process": "^0.11.10" "process": "^0.11.10"
},
"scripts": {
"start": "parcel src/index.html",
"build": "parcel build --public-url ./ src/index.html"
} }
} }

578
ui/src/Game.tsx Normal file
View file

@ -0,0 +1,578 @@
import * as React from "react";
import {useEffect, useReducer, useRef, useState} from "react";
import {
Direction,
GRID_LENGTH,
GridArrowData,
GridArrowDispatchAction,
GridArrowDispatchActionType,
HighlightableLetterData,
LocationType,
matchCoordinate,
mergeTrays,
PlayableLetterData,
Settings,
TileDispatchAction,
TileDispatchActionType
} from "./utils";
import {TileExchangeModal} from "./TileExchange";
import {Grid, Scores, TileTray} from "./UI";
import {API, APIState, GameState, TurnAction, Tray, PlayedTile, Letter} from "./api";
function addLogInfo(existingLog: React.JSX.Element[], newItem: React.JSX.Element) {
newItem = React.cloneElement(newItem, {key: existingLog.length})
existingLog.push(newItem);
return existingLog.slice();
}
export function Game(props: {
api: API,
settings: Settings,
end_game_fn: () => void,
}) {
const [api_state, setAPIState] = useState<APIState>(undefined);
const [confirmedScorePoints, setConfirmedScorePoints] = useState<number>(-1);
const currentTurnNumber = useRef<number>(-1);
const historyProcessedNumber = useRef<number>(0);
let isGameOver = false;
if (api_state != null) {
isGameOver = api_state.public_information.game_state.type === "Ended";
}
function waitForUpdate() {
const result = props.api.load(true);
result.then(
(state) => {
setAPIState(state);
}
)
.catch((error) => {
console.log("waitForUpdate() failed")
console.log(error);
});
}
const [boardLetters, setBoardLetters] = useState<HighlightableLetterData[]>(() => {
const newLetterData = [] as HighlightableLetterData[];
for (let i = 0; i < GRID_LENGTH * GRID_LENGTH; i++) {
newLetterData.push(null);
}
return newLetterData;
});
function adjustGridArrow(existing: GridArrowData, update: GridArrowDispatchAction): GridArrowData {
if (update.action == GridArrowDispatchActionType.CLEAR) {
return null;
} else if (update.action == GridArrowDispatchActionType.CYCLE) {
// if there's nothing where the user clicked, we create a right arrow.
if (existing == null || existing.position != update.position) {
return {
direction: Direction.RIGHT, position: update.position
}
// if there's a right arrow, we shift to downwards
} else if (existing.direction == Direction.RIGHT) {
return {
direction: Direction.DOWN, position: existing.position
}
// if there's a down arrow, we clear it
} else if (existing.direction == Direction.DOWN) {
return null;
}
} else if (update.action == GridArrowDispatchActionType.SHIFT) {
if (existing == null) {
// no arrow to shift
return null;
} else {
let current_x = existing.position % GRID_LENGTH;
let current_y = Math.floor(existing.position / GRID_LENGTH);
// we loop because we want to skip over letters that are already set
while (current_x < GRID_LENGTH && current_y < GRID_LENGTH) {
if (existing.direction == Direction.RIGHT) {
current_x += 1;
} else {
current_y += 1;
}
const new_position = current_x + current_y * GRID_LENGTH;
let tray_letter_at_position = false; // need to also check if the player put a letter in the spot
for (const letter of update.playerLetters) {
if (letter != null && letter.location == LocationType.GRID && letter.index == new_position) {
tray_letter_at_position = true;
break
}
}
if (current_x < GRID_LENGTH && current_y < GRID_LENGTH && boardLetters[new_position] == null && !tray_letter_at_position) {
return {
direction: existing.direction,
position: new_position,
}
}
}
// if we reached this point without returning then we went off the board, remove arrow
return null;
}
}
}
function exchangeFunction(selectedArray: Array<boolean>) {
const result = props.api.exchange(selectedArray);
result
.then(
(api_state) => {
setAPIState(api_state);
})
.catch((error) => {
console.error({error});
logDispatch(<div>{error}</div>);
});
}
const [gridArrow, gridArrowDispatch] = useReducer(adjustGridArrow, null);
const [logInfo, logDispatch] = useReducer(addLogInfo, []);
useEffect(() => {
props.api.load(false)
.then((api_state) => {
setAPIState(api_state);
});
}, []);
function movePlayableLetters(playerLetters: PlayableLetterData[], update: TileDispatchAction) {
if (update.action === TileDispatchActionType.RETRIEVE) {
let tray: Tray = api_state.tray;
if (update.override) {
playerLetters = [];
}
return mergeTrays(playerLetters, tray.letters);
} else if (update.action === TileDispatchActionType.MOVE) {
let startIndex = matchCoordinate(playerLetters, update.start);
let endIndex = matchCoordinate(playerLetters, update.end);
if (startIndex != null) {
let startLetter = playerLetters[startIndex];
startLetter.location = update.end.location;
startLetter.index = update.end.index;
}
if (endIndex != null) {
let endLetter = playerLetters[endIndex];
endLetter.location = update.start.location;
endLetter.index = update.start.index;
}
setConfirmedScorePoints(-1);
return playerLetters.slice();
} else if (update.action === TileDispatchActionType.SET_BLANK) {
const blankLetter = playerLetters[update.blankIndex];
if (blankLetter.text !== update.newBlankValue) {
blankLetter.text = update.newBlankValue;
if (blankLetter.location == LocationType.GRID) {
setConfirmedScorePoints(-1);
}
}
return playerLetters.slice();
} else if (update.action === TileDispatchActionType.RETURN) {
setConfirmedScorePoints(-1);
gridArrowDispatch({action: GridArrowDispatchActionType.CLEAR});
return mergeTrays(playerLetters, playerLetters);
} else if (update.action === TileDispatchActionType.MOVE_TO_ARROW) {
// let's verify that the arrow is defined, otherwise do nothing
if (gridArrow != null) {
const end_position = {
location: LocationType.GRID,
index: gridArrow.position,
};
gridArrowDispatch({
action: GridArrowDispatchActionType.SHIFT,
playerLetters: playerLetters
});
return movePlayableLetters(playerLetters, {
action: TileDispatchActionType.MOVE,
start: update.start,
end: end_position,
});
} else {
return playerLetters;
}
} else {
console.error("Unknown tray update");
console.error({update});
}
}
const [playerLetters, trayDispatch] = useReducer(movePlayableLetters, []);
const logDivRef = useRef(null);
const [isTileExchangeOpen, setIsTileExchangeOpen] = useState<boolean>(false);
useEffect(() => {
// Effect is to keep the log window scrolled down
if (logDivRef.current != null) {
logDivRef.current.scrollTo(0, logDivRef.current.scrollHeight); // scroll down
}
}, [logInfo]);
function handlePlayerAction(action: TurnAction, playerName: string) {
if (action.type == "PlayTiles") {
const result = action.result;
result.words.sort((a, b) => b.score - a.score);
for (let word of result.words) {
logDispatch(<div>{playerName} received {word.score} points for playing '{word.word}.'</div>);
}
logDispatch(<div>{playerName} received a total of <strong>{result.total} points</strong> for their turn.
</div>);
} else if (action.type == "ExchangeTiles") {
logDispatch(
<div>{playerName} exchanged {action.tiles_exchanged} tile{action.tiles_exchanged > 1 ? 's' : ''} for
their turn.</div>);
} else if (action.type == "Pass") {
logDispatch(<div>{playerName} passed.</div>);
} else if (action.type == "AddToDictionary") {
logDispatch(<div>{playerName} added {action.word} to the dictionary.</div>)
} else {
console.error("Received unknown turn action: ", action);
}
}
function endGame(state: GameState) {
if (state.type != "InProgress") {
logDispatch(<h4>Scoring</h4>);
const scores = api_state.public_information.players;
let pointsBonus = 0;
for (const playerAndScore of scores) {
const name = playerAndScore.name;
if (name == state.finisher) {
// we'll do the finisher last
continue
}
const letters = state.remaining_tiles[name];
if (letters.length == 0) {
logDispatch(<div>{name} has no remaining tiles.</div>);
} else {
let pointsLost = 0;
let letterListStr = '';
for (let i = 0; i < letters.length; i++) {
const letter = letters[i];
const letterText = letter.is_blank ? 'a blank' : letter.text;
pointsLost += letter.points;
letterListStr += letterText;
// we're doing a list of 3 or more so add commas
if (letters.length > 2) {
if (i == letters.length - 2) {
letterListStr += ', and ';
} else if (i < letters.length - 2) {
letterListStr += ', ';
}
} else if (i == 0 && letters.length == 2) {
// list of 2
letterListStr += ' and ';
}
}
logDispatch(<div>{name} penalized {pointsLost} points for not using {letterListStr}.</div>);
pointsBonus += pointsLost;
}
}
if (state.finisher != null) {
logDispatch(<div>{state.finisher} receives {pointsBonus} bonus for completing first.</div>);
}
const highestScore = scores
.map((score) => score.score)
.sort((a, b) => b - a)
.at(0);
const playersAtHighest = scores.filter((score) => score.score == highestScore);
let endGameMsg: string;
if (playersAtHighest.length > 1 && state.finisher == null) {
endGameMsg = "Tie game!";
} else if (playersAtHighest.length > 1 && state.finisher != null) {
// if there's a tie then the finisher gets the win
endGameMsg = `${playersAtHighest[0].name} won by finishing first!`;
} else {
endGameMsg = `${playersAtHighest[0].name} won!`;
}
logDispatch(<h4>Game over - {endGameMsg}</h4>);
} else {
// what are we doing in this function?!
console.error("endGame was called despite the state being InProgress!");
}
}
function updateBoardLetters(newLetters: Array<Letter>) {
const newLetterData = newLetters as HighlightableLetterData[];
for (let i = 0; i < newLetterData.length; i++) {
const newLetter = newLetterData[i];
if (newLetter != null) {
newLetter.highlight = false;
}
}
// loop through the histories backwards until we reach our player
for (let j = api_state.public_information.history.length - 1; j >= 0; j--) {
const update = api_state.public_information.history[j];
if (update.player == props.settings.playerName) {
break
}
if (update.type.type === "PlayTiles") {
for (let i of update.type.locations) {
newLetterData[i].highlight = true;
}
}
}
setBoardLetters(newLetterData);
}
useEffect(() => {
if (api_state) {
console.log("In state: ", api_state.public_information.current_turn_number);
console.log("In ref: ", currentTurnNumber.current);
console.debug(api_state);
if(currentTurnNumber.current < api_state.public_information.current_turn_number){
// We only clear everything if there's a chance the board changed
// We may have gotten a dictionary update event which doesn't count
gridArrowDispatch({action: GridArrowDispatchActionType.CLEAR});
trayDispatch({action: TileDispatchActionType.RETRIEVE});
setConfirmedScorePoints(-1);
updateBoardLetters(api_state.public_information.board);
}
for (let i = historyProcessedNumber.current; i < api_state.public_information.history.length; i++) {
const update = api_state.public_information.history[i];
if (update.turn_number > currentTurnNumber.current) {
currentTurnNumber.current = update.turn_number;
logDispatch(<h4>Turn {update.turn_number + 1}</h4>);
const playerAtTurn = api_state.public_information.players[(update.turn_number) % api_state.public_information.players.length].name;
logDispatch(<div>{playerAtTurn}'s turn</div>);
}
handlePlayerAction(update.type, update.player);
}
historyProcessedNumber.current = api_state.public_information.history.length;
if (!isGameOver) {
if(api_state.public_information.current_turn_number > currentTurnNumber.current){
logDispatch(<h4>Turn {api_state.public_information.current_turn_number + 1}</h4>);
logDispatch(<div>{api_state.public_information.current_player}'s turn</div>);
currentTurnNumber.current = api_state.public_information.current_turn_number;
}
} else {
endGame(api_state.public_information.game_state);
}
if(api_state.public_information.current_player != props.settings.playerName) {
waitForUpdate();
}
}
}, [api_state]);
if(api_state == null){
return <div>Still loading</div>;
}
const playerAndScores = api_state.public_information.players;
const remainingTiles = api_state.public_information.remaining_tiles;
const isPlayersTurn = api_state.public_information.current_player.toLowerCase() == props.settings.playerName.toLowerCase();
return <>
<TileExchangeModal
playerLetters={playerLetters}
isOpen={isTileExchangeOpen}
setOpen={setIsTileExchangeOpen}
exchangeFunction={exchangeFunction}
/>
<div className="board-log">
<Grid
cellTypes={api_state.public_information.cell_types}
playerLetters={playerLetters}
boardLetters={boardLetters}
tileDispatch={trayDispatch}
arrow={gridArrow}
arrowDispatch={gridArrowDispatch}
/>
<div className="message-log">
<button className="end-game"
onClick={() => {
props.end_game_fn();
}}
>
End Game
</button>
<Scores playerScores={playerAndScores}/>
<div className="log" ref={logDivRef}>
{logInfo}
</div>
</div>
</div>
<div className="tray-row">
<div>
<div>
{remainingTiles} letters remaining
</div>
<button
disabled={remainingTiles == 0 || isGameOver || !isPlayersTurn}
onClick={() => {
trayDispatch({action: TileDispatchActionType.RETURN}); // want all tiles back on tray for tile exchange
setIsTileExchangeOpen(true);
}}>Open Tile Exchange
</button>
</div>
<TileTray letters={playerLetters} trayLength={props.settings.trayLength} trayDispatch={trayDispatch}/>
<div className="player-controls">
<button
className="check"
disabled={isGameOver || !isPlayersTurn}
onClick={async () => {
const playedTiles = playerLetters.map((i) => {
if (i == null) {
return null;
}
if (i.location === LocationType.GRID) {
let result: PlayedTile = {
index: i.index,
character: null
};
if (i.is_blank) {
result.character = i.text;
}
return result;
}
return null;
});
const committing = confirmedScorePoints > -1;
const result = props.api.play(playedTiles, committing);
result
.then(
(api_state) => {
console.log("Testing45")
console.log({api_state});
const play_tiles: TurnAction = api_state.update.type;
if (play_tiles.type == "PlayTiles") {
setConfirmedScorePoints(play_tiles.result.total);
if (committing) {
setAPIState(api_state);
}
} else {
console.error("Inaccessible branch!!!")
}
}
)
.catch((error) => {
console.error({error});
if (error.endsWith(" is not a valid word")) {
const word = error.split(' ')[0];
// For whatever reason I can't pass props.api.add_to_dictionary directly
logDispatch(<AddWordButton word={word}
addWordFn={(word) => {
props.api.add_to_dictionary(word)
.then((api_state) => {
setAPIState(api_state);
})
}}/>);
} else {
logDispatch(<div>{error}</div>);
}
});
}}>{confirmedScorePoints > -1 ? `Score ${confirmedScorePoints} points` : "Check"}</button>
<button
className="return"
disabled={isGameOver}
onClick={() => {
trayDispatch({action: TileDispatchActionType.RETURN});
}}>Return Tiles
</button>
<button
className="pass"
disabled={isGameOver || !isPlayersTurn}
onClick={() => {
if (window.confirm("Are you sure you want to pass?")) {
const result = props.api.pass();
result
.then(
(api_state) => {
setAPIState(api_state);
})
.catch((error) => {
console.error({error});
logDispatch(<div>{error}</div>);
});
}
}}>Pass
</button>
</div>
</div>
</>;
}
function AddWordButton(props: { word: string, addWordFn: (x: string) => void }) {
const [isClicked, setIsClicked] = useState<boolean>(false);
if (!isClicked) {
return <div>
<em>{props.word} is not a valid word.</em>
<button
className="add-to-dictionary"
disabled={isClicked}
onClick={() => {
setIsClicked(true);
props.addWordFn(props.word);
}}>
Add to dictionary
</button>
</div>;
} else {
return <div>
<em>Adding {props.word} to dictionary.</em>
</div>;
}
}

55
ui/src/Menu.tsx Normal file
View file

@ -0,0 +1,55 @@
import * as React from "react";
import {useState} from "react";
import {Settings} from "./utils";
import {Game} from "./Game";
import {API, Difficulty} from "./api";
import {WasmAPI} from "./wasm_api";
import {AISelection} from "./UI";
export function Menu(props: {settings: Settings, dictionary_text: string}) {
const [aiRandomness, setAIRandomness] = useState<number>(6);
const [proportionDictionary, setProportionDictionary] = useState<number>(7);
const [game, setGame] = useState<React.JSX.Element>(null);
// Can change log scale to control shape of curve using following equation:
// aiRandomness = log(1 + x*(n-1))/log(n) when x, the user input, ranges between 0 and 1
const logBase: number = 10000;
const processedAIRandomness = Math.log(1 + (logBase - 1)*aiRandomness/100) / Math.log(logBase);
const processedProportionDictionary = 1.0 - proportionDictionary / 100;
if (game == null) {
return <dialog open>
<div className="new-game">
<AISelection
aiRandomness={aiRandomness}
setAIRandomness={setAIRandomness}
proportionDictionary={proportionDictionary}
setProportionDictionary={setProportionDictionary}
/>
<div className="selection-buttons">
<button onClick={() => {
const seed = new Date().getTime();
//const seed = 136; // seed for starting with a blank
const difficulty: Difficulty = {
proportion: processedProportionDictionary,
randomness: processedAIRandomness,
};
const game_wasm: API = new WasmAPI(BigInt(seed), props.dictionary_text, difficulty);
const game = <Game settings={props.settings} api={game_wasm} key={seed} end_game_fn={() => setGame(null)}/>
setGame(game);
}}>New Game</button>
</div>
</div>
</dialog>
} else {
return game;
}
}

39
ui/src/Modal.tsx Normal file
View file

@ -0,0 +1,39 @@
import {useEffect, useRef} from "react";
export function Modal(props: {
isOpen: boolean;
setOpen: (isOpen: boolean) => void;
children: any;
}){
const ref = useRef<HTMLDialogElement>();
useEffect(() => {
if(props.isOpen){
// @ts-ignore
ref.current.showModal();
} else {
// @ts-ignore
ref.current.close();
}
}, [props.isOpen])
return(
// The style part is just to make sure the dialog is hidden the split second before useEffect runs,
// in case the dialog content is derived from whatever determines isOpen
<dialog ref={ref} style={!props.isOpen ? {display: 'none'} : null}>
<div className="close-button-div" >
<button onClick={(e) => {
// we manually trigger a close anyway because the children can get updated before the dialog gets closed otherwise
// @ts-ignore
ref.current.close();
props.setOpen(false);
}}></button>
</div>
<div>
{props.children}
</div>
</dialog>
);
}

128
ui/src/TileExchange.tsx Normal file
View file

@ -0,0 +1,128 @@
import {addNTimes, PlayableLetterData} from "./utils";
import {useEffect, useState} from "react";
import {Modal} from "./Modal";
import * as React from "react";
import {Letter} from "./api";
export function TileExchangeModal(props: {
playerLetters: PlayableLetterData[],
isOpen: boolean,
setOpen: (isOpen: boolean) => void,
exchangeFunction: (selectedArray: Array<boolean>) => void
}) {
function clearExchangeTiles() {
const array: boolean[] = [];
addNTimes(array, false, props.playerLetters.length);
return array;
}
const [tilesToExchange, setTilesToExchange] = useState<boolean[]>(clearExchangeTiles);
useEffect(() => {
setTilesToExchange(clearExchangeTiles());
}, [props.playerLetters])
let tilesExchangedSelected = 0;
for (let i of tilesToExchange) {
if(i) {
tilesExchangedSelected++;
}
}
return <Modal isOpen={props.isOpen} setOpen={(isOpen) => {
setTilesToExchange(clearExchangeTiles());
props.setOpen(isOpen);
}}>
<div className="tile-exchange-dialog">
<div className="instructions">
Click on each tile you'd like to exchange. You currently have {tilesExchangedSelected} tiles selected.
</div>
<div className="selection-buttons">
<button onClick={() => {
const array: boolean[] = [];
addNTimes(array, true, props.playerLetters.length);
setTilesToExchange(array);
}}>Select All</button>
<button onClick={() => {
setTilesToExchange(clearExchangeTiles());
}}>Select None</button>
</div>
<TilesExchangedTray
tray={props.playerLetters}
selectedArray={tilesToExchange}
setSelectedArray={setTilesToExchange}
trayLength={props.playerLetters.length}
/>
<div className="finish-buttons">
<button onClick={() => {
setTilesToExchange(clearExchangeTiles());
props.setOpen(false);
}}>Cancel</button>
<button disabled = {tilesExchangedSelected == 0} onClick={() => {
props.exchangeFunction(tilesToExchange);
props.setOpen(false);
}}>Exchange</button>
</div>
</div>
</Modal>;
}
function TilesExchangedTray(props: {
tray: Array<PlayableLetterData>,
trayLength: number,
selectedArray: Array<boolean>,
setSelectedArray: (x: Array<boolean>) => void,
}){
const divContent = [];
for(let i=0; i<props.trayLength; i++) {
divContent.push(<span key={i} />); // empty tile elements
}
for(let i = 0; i<props.trayLength; i++){
const tileData = props.tray[i];
const toggleFunction = () => {
props.selectedArray[i] = !props.selectedArray[i];
props.setSelectedArray(props.selectedArray.slice());
}
if(tileData != null){
divContent[tileData.index] =
<DummyExchangeTile key={tileData.index} letter={tileData} isSelected={props.selectedArray[i]} onClick={toggleFunction}/>;
}
}
return <div className="tray-container">
<div className="tray">
{divContent}
</div>
</div>;
}
function DummyExchangeTile(props: {
letter: Letter,
isSelected: boolean,
onClick: () => void,
}){
let textClassName = "text";
if(props.letter.is_blank) {
textClassName += " prev-blank";
}
let letterClassName = "letter";
if(props.isSelected){
letterClassName += ' selected-tile';
}
return <div className={letterClassName} onClick={props.onClick}>
<div className={textClassName}>{props.letter.text}</div>
<div className="letter-points">{props.letter.points}</div>
</div>;
}

306
ui/src/UI.tsx Normal file
View file

@ -0,0 +1,306 @@
import * as React from "react";
import {ChangeEvent, JSX} from "react";
import {
cellTypeToDetails,
CoordinateData,
GridArrowData,
GridArrowDispatch,
GridArrowDispatchActionType,
HighlightableLetterData,
LocationType,
PlayableLetterData,
TileDispatch,
TileDispatchActionType,
} from "./utils";
import {APIPlayer, CellType} from "./api";
export function TileSlot(props: {
tile?: React.JSX.Element | null,
location: CoordinateData,
tileDispatch: TileDispatch,
arrowDispatch?: GridArrowDispatch,
}): React.JSX.Element {
let isDraggable = props.tile != null;
function onDragStart(e: React.DragEvent<HTMLDivElement>) {
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("wordGrid/coords", JSON.stringify(props.location));
}
function onDrop(e: React.DragEvent<HTMLDivElement>) {
const startLocation: CoordinateData = JSON.parse(e.dataTransfer.getData("wordGrid/coords"));
const thisLocation = props.location;
props.tileDispatch({action: TileDispatchActionType.MOVE, start: startLocation, end: thisLocation});
}
let className = "tileSpot";
if (props.location.location === LocationType.GRID) {
className += " ephemeral";
}
let onClick: () => void;
if(props.arrowDispatch != null && props.location.location == LocationType.GRID) {
onClick = () => {
props.arrowDispatch({action: GridArrowDispatchActionType.CYCLE, position: props.location.index});
}
} else if(props.location.location == LocationType.TRAY && props.tile != null && props.tile.props.data.text != ' ' && props.tile.props.data.text != '') {
onClick = () => {
props.tileDispatch({
action: TileDispatchActionType.MOVE_TO_ARROW, end: null, start: props.location,
});
}
}
return <div className={className}
draggable={isDraggable}
onDragStart={onDragStart}
onDrop={onDrop}
onClick={onClick}
onDragOver={(e) => {e.preventDefault()}}
>
{props.tile}
</div>
}
export function Letter(props: { data: HighlightableLetterData, letterUpdater?: (value: string) => void }): React.JSX.Element {
function modifyThisLetter(value:string){
props.letterUpdater(value);
}
function onBlankInput(e: ChangeEvent<HTMLInputElement>){
let value = e.target.value.toUpperCase();
if(value.length > 1){
value = value[value.length - 1];
} else if(value.length == 0){
modifyThisLetter(value);
return;
}
// Now check that it's a letter
let is_letter = value.match("[A-Z]") != null;
if(is_letter){
modifyThisLetter(value);
} else {
// Cancel and do nothing
e.preventDefault();
}
}
if(props.data.is_blank && props.data.ephemeral) {
return <div className="letter">
<input className="blank-input" type="text" onChange={onBlankInput} value={props.data.text} />
<div className="letter-points">{props.data.points}</div>
</div>
} else {
let className = "text";
if (props.data.is_blank) { // not ephemeral
className += " prev-blank";
}
let letterClassName = "letter";
if (props.data.highlight) {
letterClassName += " highlight";
}
return <div className={letterClassName}>
<div className={className}>{props.data.text}</div>
<div className="letter-points">{props.data.points}</div>
</div>
}
}
export function TileTray(props: { letters: Array<PlayableLetterData>, trayLength: number, trayDispatch: TileDispatch }): React.JSX.Element {
let elements: JSX.Element[] = [];
for (let i=0; i<props.trayLength; i++) {
elements.push(
<TileSlot
key={"empty" + i}
location={{location: LocationType.TRAY, index: i}}
tileDispatch={props.trayDispatch} />
);
}
props.letters
.forEach((letter, i) => {
if (letter != null && letter.location === LocationType.TRAY) {
elements[letter.index] =
<TileSlot
tile={<Letter
data={{...letter, highlight: false}}
letterUpdater={(value) => {
props.trayDispatch({action: TileDispatchActionType.SET_BLANK, blankIndex: i, newBlankValue: value})
}}
/>}
key={"letter_tray" + letter.index}
location={{location: LocationType.TRAY, index: letter.index}}
tileDispatch={props.trayDispatch} />
}
});
return (
<div className="tray">
{elements}
</div>
)
}
export function Arrow(props: {
data: GridArrowData,
dispatch: GridArrowDispatch,
}) {
return <div
className={`arrow ${props.data.direction}`}
>
</div>;
}
export function Grid(props: {
cellTypes: CellType[],
playerLetters: Array<PlayableLetterData>,
boardLetters: HighlightableLetterData[],
tileDispatch: TileDispatch,
arrow: GridArrowData,
arrowDispatch: GridArrowDispatch,
}) {
const elements = props.cellTypes.map((ct, i) => {
const {className, text} = cellTypeToDetails(ct);
let tileElement: JSX.Element;
if (props.boardLetters[i] != null) {
tileElement = <Letter data={props.boardLetters[i]} />;
} else {
tileElement = <>
<span>{text}</span>
<TileSlot
location={{location: LocationType.GRID, index: i}}
tileDispatch={props.tileDispatch}
arrowDispatch={props.arrowDispatch}
/>
</>;
}
let arrowElement: JSX.Element;
if(props.arrow != null && props.arrow.position == i) {
arrowElement = <Arrow data={props.arrow} dispatch={props.arrowDispatch} />;
}
return <div key={i} className={"grid-spot " + className}>
{tileElement}
{arrowElement}
</div>;
});
props.playerLetters
.forEach((letter, i) => {
if (letter != null && letter.location === LocationType.GRID) {
const ct = props.cellTypes[letter.index];
const {className} = cellTypeToDetails(ct);
elements[letter.index] =
<div key={"letter" + letter.index} className={"grid-spot " + className}>
<TileSlot
tile={<Letter
data={{...letter, highlight: false}}
letterUpdater={(value) => {
props.tileDispatch({action: TileDispatchActionType.SET_BLANK, blankIndex: i, newBlankValue: value});
}}
/>}
location={{location: LocationType.GRID, index: letter.index}}
tileDispatch={props.tileDispatch} />
</div>;
}
});
return <div className="board-grid">
{elements}
</div>
}
export function Scores(props: {playerScores: Array<APIPlayer>}){
let elements = props.playerScores.map((ps) => {
return <div key={ps.name}>
<h3>{ps.name}</h3>
<div>{ps.score}</div>
<div>({ps.tray_tiles} tiles remaining)</div>
</div>;
});
return <div className="scoring">
{elements}
</div>
}
export function AISelection(props: {
aiRandomness: number,
setAIRandomness: (x: number) => void,
proportionDictionary: number,
setProportionDictionary: (x: number) => void,
}) {
// Can change log scale to control shape of curve using following equation:
// aiRandomness = log(1 + x*(n-1))/log(n) when x, the user input, ranges between 0 and 1
const logBase: number = 10000;
const processedAIRandomness = Math.log(1 + (logBase - 1)*props.aiRandomness/100) / Math.log(logBase);
//const processedProportionDictionary = 1.0 - props.proportionDictionary / 100;
return <>
<div className="ai-grid">
<label htmlFor="proportion-dictionary">AI's proportion of dictionary:</label>
<input type="number"
name="proportion-dictionary"
value={props.proportionDictionary}
onInput={(e) => {
props.setProportionDictionary(e.currentTarget.valueAsNumber);
}}
min={1}
max={100}/>
<label htmlFor="randomness">Level of randomness in AI:</label>
<input type="number"
name="randomness"
value={props.aiRandomness}
onInput={(e) => {
props.setAIRandomness(e.currentTarget.valueAsNumber);
}}
min={0}
max={100}/>
</div>
<details>
<ul>
<li>
"AI's proportion of dictionary" controls what percent of the total AI dictionary
the AI can form words with. At 100%, it has access to its entire dictionary -
although this dictionary is still less than what the player has access to.</li>
<li>
<div>
"Level of randomness in AI" controls the degree to which the AI picks the optimal move
for each of its turns. At 0, it always picks the highest scoring move it can do using the
dictionary it has access to. At 1, it picks from its available moves at random.
</div>
<div>
Note that "Level of randomness in AI" is now mapped on a log scale.
Your current setting is equivalent to {(100*processedAIRandomness).toFixed(1)}% on the previous scale.
</div>
</li>
</ul>
</details>
</>
}

91
ui/src/api.ts Normal file
View file

@ -0,0 +1,91 @@
export interface Tray {
letters: (Letter | null)[];
}
export interface ScoreResult {
words: WordResult[];
total: number;
}
export interface WordResult {
word: string;
score: number;
}
export interface PlayedTile {
index: number;
character?: string;
}
export interface Difficulty {
proportion: number;
randomness: number;
}
export interface Letter {
text: string;
points: number;
ephemeral: boolean;
is_blank: boolean;
}
export type TurnAction = { type: "Pass" } | { type: "ExchangeTiles"; tiles_exchanged: number } | { type: "PlayTiles"; result: ScoreResult; locations: number[] } | {type: "AddToDictionary"; word: string;};
export enum CellType {
Normal = "Normal",
DoubleWord = "DoubleWord",
DoubleLetter = "DoubleLetter",
TripleLetter = "TripleLetter",
TripleWord = "TripleWord",
Start = "Start",
}
export type GameState = { type: "InProgress" } | { type: "Ended"; finisher?: string; remaining_tiles: {[id: string]: Letter[]} };
export interface APIPlayer {
name: string;
tray_tiles: number;
score: number
}
export interface PublicInformation {
game_state: GameState;
board: Array<Letter>;
cell_types: Array<CellType>;
current_player: string;
players: Array<APIPlayer>;
remaining_tiles: number;
history: Array<Update>;
current_turn_number: number;
}
export interface Update {
type: TurnAction,
player: string;
turn_number: number;
}
export interface APIState {
public_information: PublicInformation;
tray: Tray;
update?: Update;
}
export interface Result<A, B> {
"Ok"?: A;
"Err"?: B;
}
export function is_ok<A, B>(result: Result<A, B>): boolean {
return result["Ok"] != null;
}
export interface API {
exchange: (selection: Array<boolean>) => Promise<APIState>;
pass: () => Promise<APIState>;
play: (tiles: Array<PlayedTile>, commit: boolean) => Promise<APIState>;
add_to_dictionary: (word: string) => Promise<APIState>;
load: (wait: boolean) => Promise<APIState>;
}

View file

@ -1,274 +0,0 @@
import * as React from "react";
import {GameWasm, Letter as LetterData, MyResult, PlayedTile, Tray, WordResult} from "word_grid";
import {createRoot} from "react-dom/client";
import {Children, useMemo, useReducer, useState} from "react";
export enum LocationType {
GRID,
TRAY
}
enum CellType {
Normal = "Normal",
DoubleWord = "DoubleWord",
DoubleLetter = "DoubleLetter",
TripleLetter = "TripleLetter",
TripleWord = "TripleWord",
Start = "Start",
}
function cell_type_to_details(cell_type: CellType): {className: string, text: string} {
let className: string;
let text: string;
switch (cell_type) {
case CellType.Normal:
className = "grid-spot-normal";
text = "";
break;
case CellType.DoubleWord:
className = "grid-spot-double-word";
text = "Double Word Score";
break;
case CellType.DoubleLetter:
className = "grid-spot-double-letter";
text = "Double Letter Score";
break;
case CellType.TripleLetter:
className = "grid-spot-triple-letter";
text = "Triple Letter Score";
break;
case CellType.TripleWord:
className = "grid-spot-triple-word";
text = "Triple Word Score";
break;
case CellType.Start:
className = "grid-spot-start";
text = "★";
break;
}
return {className: className, text: text};
}
export interface CoordinateData {
location: LocationType;
index: number;
}
export type PlayableLetterData = LetterData & CoordinateData;
function matchCoordinate(playerLetters: PlayableLetterData[], coords: CoordinateData): number {
for (let i=0; i<playerLetters.length; i++){
let letter = playerLetters[i];
if (letter.location === coords.location && letter.index === coords.index) {
return i;
}
}
return null; // no match
}
type TileDispatch = React.Dispatch<{start: CoordinateData, end: CoordinateData}>;
function movePlayableLetters(playerLetters: PlayableLetterData[], update: {start: CoordinateData, end: CoordinateData}) {
let startIndex = matchCoordinate(playerLetters, update.start);
let endIndex = matchCoordinate(playerLetters, update.end);
if(startIndex != null) {
let startLetter = playerLetters[startIndex];
startLetter.location = update.end.location;
startLetter.index = update.end.index;
}
if(endIndex != null) {
let endLetter = playerLetters[endIndex];
endLetter.location = update.start.location;
endLetter.index = update.start.index;
}
return playerLetters.slice();
}
export function Game(props: {wasm: GameWasm}) {
const cellTypes = useMemo(() => {
return props.wasm.get_board_cell_types();
}, []);
const [playerLetters, dispatch] = useReducer(movePlayableLetters, null, (_) => {
let tray: Tray = props.wasm.get_tray();
// initial state
let letters: PlayableLetterData[] = tray.letters.map((ld, i) => {
ld["location"] = LocationType.TRAY;
ld["index"] = i;
return ld as PlayableLetterData;
})
return letters;
})
return <>
<Grid cellTypes={cellTypes} playerLetters={playerLetters} dispatch={dispatch}/>
<TileTray letters={playerLetters} trayLength={7} dispatch={dispatch}/>
<button onClick={(e) => {
const playedTiles = playerLetters.map((i) => {
if (i === undefined) {
return null;
}
if (i.location === LocationType.GRID) {
let result: PlayedTile = {
index: i.index,
character: undefined
};
if (i.is_blank) {
result.character = i.text;
}
return result;
}
return null;
});
const result: MyResult<Array<WordResult> | string> = props.wasm.receive_play(playedTiles, false);
console.log({result});
if(result.response_type === "ERR") {
alert(result.value);
} else {
let total_points = 0;
for (let word_result of (result.value as Array<WordResult>)) {
total_points += word_result.score;
}
alert(`You would score ${total_points} points.`);
}
}}>Check Submission</button>
</>;
}
export function TileSlot(props: { tile: React.JSX.Element | undefined, location: CoordinateData, dispatch: TileDispatch }): React.JSX.Element {
let isDraggable = props.tile !== undefined;
function onDragStart(e: React.DragEvent<HTMLDivElement>) {
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("wordGrid/coords", JSON.stringify(props.location));
}
function onDrop(e: React.DragEvent<HTMLDivElement>) {
const startLocation: CoordinateData = JSON.parse(e.dataTransfer.getData("wordGrid/coords"));
const thisLocation = props.location;
props.dispatch({start: startLocation, end: thisLocation});
}
let className = "tileSpot";
if (props.location.location === LocationType.GRID) {
className += " ephemeral";
}
return <div className={className}
draggable={isDraggable}
onDragStart={onDragStart}
onDrop={onDrop}
onDragOver={(e) => {e.preventDefault()}}
>
{props.tile}
</div>
}
export function Letter(props: { data: LetterData }): React.JSX.Element {
return <div className="letter">
<div className="text">{props.data.text}</div>
<div className="letter-points">{props.data.points}</div>
</div>
}
export function TileTray(props: { letters: Array<PlayableLetterData>, trayLength: number, dispatch: TileDispatch }): React.JSX.Element {
let elements: JSX.Element[] = [];
for (let i=0; i<props.trayLength; i++) {
elements.push(
<TileSlot
tile={undefined}
key={"empty" + i}
location={{location: LocationType.TRAY, index: i}}
dispatch={props.dispatch} />
);
}
for (let letter of props.letters) {
if (letter.location === LocationType.TRAY) {
elements[letter.index] =
<TileSlot
tile={<Letter data={letter} />}
key={"letter" + letter.index}
location={{location: LocationType.TRAY, index: letter.index}}
dispatch={props.dispatch} />
}
}
return (
<div className="tray">
{elements}
</div>
)
}
function Grid(props: {cellTypes: CellType[], playerLetters: Array<PlayableLetterData>, dispatch: TileDispatch}) {
const elements = props.cellTypes.map((ct, i) => {
const {className, text} = cell_type_to_details(ct);
return <div key={i} className={"grid-spot " + className}>
<span>{text}</span>
<TileSlot
tile={undefined}
location={{location: LocationType.GRID, index: i}}
dispatch={props.dispatch} />
</div>;
});
for (let letter of props.playerLetters) {
if (letter.location === LocationType.GRID) {
const ct = props.cellTypes[letter.index];
const {className, text} = cell_type_to_details(ct);
elements[letter.index] =
<div key={"letter" + letter.index} className={"grid-spot " + className}>
<TileSlot
tile={<Letter data={letter} />}
location={{location: LocationType.GRID, index: letter.index}}
dispatch={props.dispatch} />
</div>;
}
}
return <div className="board-grid">
{elements}
</div>
}

View file

@ -1,13 +1,13 @@
<!doctype html> <!DOCTYPE html>
<html lang="en-US"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="UTF-8">
<link rel="stylesheet" href="style.less" />
<title>Word Grid</title> <title>Word Grid</title>
</head> </head>
<body> <body>
<script src="index.tsx" type="module"></script> <ul>
<div id="root"></div> <li><a href="singleplayer.html">Singleplayer</a></li>
</body> <li><a href="multiplayer.html">Multiplayer</a></li>
</ul>
</body>
</html> </html>

12
ui/src/multiplayer.html Normal file
View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.less" />
<title>Word Grid</title>
</head>
<body>
<script src="multiplayer.tsx" type="module"></script>
<div id="root"></div>
</body>
</html>

175
ui/src/multiplayer.tsx Normal file
View file

@ -0,0 +1,175 @@
import * as React from "react";
import {useRef, useState} from "react";
import {createRoot} from "react-dom/client";
import {AISelection} from "./UI";
import {ClientToServerMessage, WSAPI, PartyInfo, ServerToClientMessage} from "./ws_api";
import {Game} from "./Game";
const LOGBASE = 10000;
function unprocessAIRandomness(processedAIRandomness: number): string {
const x = 100 * (LOGBASE ** processedAIRandomness - 1) / (LOGBASE - 1)
return x.toFixed(0)
}
function unprocessedAIProportion(processedProportion: number): string {
return (100 * (1 - processedProportion)).toFixed(0);
}
export function Menu(): React.JSX.Element {
const [roomName, setRoomName] = useState<string>("");
const [socket, setSocket] = useState<WebSocket>(null);
const [partyInfo, setPartyInfo] = useState<PartyInfo>(null);
const [playerName, setPlayerName] = useState<string>("");
const [aiRandomness, setAIRandomness] = useState<number>(6);
const [proportionDictionary, setProportionDictionary] = useState<number>(7);
const gameAPI = useRef<WSAPI>(null);
const [game, setGame] = useState<React.JSX.Element>(null);
const validSettings = roomName.length > 0 && !roomName.includes("/") && playerName.length > 0 && !playerName.includes("?") && !playerName.includes("&");
// Can change log scale to control shape of curve using following equation:
// aiRandomness = log(1 + x*(n-1))/log(n) when x, the user input, ranges between 0 and 1
const processedAIRandomness = Math.log(1 + (LOGBASE - 1) * aiRandomness / 100) / Math.log(LOGBASE);
const processedProportionDictionary = 1.0 - proportionDictionary / 100;
if (game) {
return game;
} else if (socket != null && partyInfo == null) {
return <div><p>Connecting to {roomName}</p></div>
} else if (partyInfo != null) {
const players = partyInfo.players.map((x) => {
return <li key={x}>{x}</li>;
});
const ais = partyInfo.ais.map((x, i) => {
return <li key={i} className="side-grid">
<span>Proportion: {unprocessedAIProportion(x.proportion)} / Randomness: {unprocessAIRandomness(x.randomness)}</span>
<button onClick={() => {
const event = {
type: "RemoveAI",
index: i
};
socket.send(JSON.stringify(event));
}
}>Delete
</button>
</li>
});
return <dialog open className="multiplayer-lobby">
<p>Connected to {roomName}</p>
Players: <ol>
{players}
</ol>
AIs: <ol>
{ais}
</ol>
<details className="multiplayer-ai-details">
<summary>Add AI</summary>
<AISelection aiRandomness={aiRandomness} setAIRandomness={setAIRandomness}
proportionDictionary={proportionDictionary}
setProportionDictionary={setProportionDictionary}/>
<button onClick={() => {
const event = {
type: "AddAI",
difficulty: {
proportion: processedProportionDictionary,
randomness: processedAIRandomness,
}
};
socket.send(JSON.stringify(event));
}}>
Add AI
</button>
</details>
<div className="side-grid">
<button onClick={() => {
socket.close();
setSocket(null);
setPartyInfo(null);
gameAPI.current = null;
}}>Disconnect
</button>
<button onClick={() => {
const event: ClientToServerMessage = {
type: "StartGame"
};
socket.send(JSON.stringify(event));
}}>Start Game
</button>
</div>
</dialog>
} else {
return <dialog open>
<div className="multiplayer-inputs-grid">
<label>
Room Name:
<input type="text" value={roomName} onChange={(e) => {
setRoomName(e.target.value)
}}></input>
</label>
<label>
Player Name:
<input type="text" value={playerName} onChange={(e) => {
setPlayerName(e.target.value)
}}></input>
</label>
<button
disabled={!validSettings}
onClick={() => {
let socket = new WebSocket(`/room/${roomName}?player_name=${playerName}`);
socket.addEventListener("message", (event) => {
const input: ServerToClientMessage = JSON.parse(event.data);
if (input.type == "RoomChange") {
setPartyInfo(input.info);
} else if (input.type == "GameEvent" && game == null) {
// start game
if(gameAPI.current == null) {
gameAPI.current = new WSAPI(socket);
}
setGame(<Game api={gameAPI.current} settings={{
playerName: playerName,
trayLength: 7,
}} end_game_fn={function (): void {
socket.close();
setSocket(null);
setPartyInfo(null);
setGame(null);
gameAPI.current = null;
}}/>);
}
//console.log("Message from server ", event.data);
});
socket.addEventListener("close", (event) => {
console.log({event});
setSocket(null);
setPartyInfo(null);
setGame(null);
gameAPI.current = null;
if (event.reason != null && event.reason.length > 0) {
alert(`Disconnected with reason "${event.reason} & code ${event.code}"`);
}
});
setSocket(socket);
}}>Connect
</button>
</div>
</dialog>;
}
}
async function run() {
const root = createRoot(document.getElementById("root"));
root.render(<Menu/>);
}
run();

13
ui/src/singleplayer.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.less" />
<title>Word Grid</title>
</head>
<body>
<script src="singleplayer.tsx" type="module"></script>
<div id="root"></div>
</body>
</html>

View file

@ -1,7 +1,7 @@
import init, {greet, GameWasm} from '../node_modules/word_grid/word_grid.js'; import init from 'word_grid';
import {Game} from "./elements";
import {createRoot} from "react-dom/client"; import {createRoot} from "react-dom/client";
import * as React from "react"; import * as React from "react";
import {Menu} from "./Menu";
// @ts-ignore // @ts-ignore
const dictionary_url = new URL("../../resources/dictionary.csv", import.meta.url); const dictionary_url = new URL("../../resources/dictionary.csv", import.meta.url);
@ -45,15 +45,12 @@ async function run() {
}) })
} }
let game = new GameWasm(BigInt(1234), dictionary_text);
const cellTypes = game.get_board_cell_types();
console.log({cellTypes});
const root = createRoot(document.getElementById("root")); const root = createRoot(document.getElementById("root"));
root.render(<Game wasm={game} />); root.render(<Menu dictionary_text={dictionary_text} settings={{
trayLength: 7,
playerName: 'Player',
}}/>);
} }

View file

@ -3,7 +3,7 @@
@board-length: 15; @board-length: 15;
@tile-star-size: 45px; @tile-star-size: 45px;
.tray { .tray { // Don't put under tray-row as this also gets used in tile exchange
display: grid; display: grid;
grid-template-columns: repeat(7, @tile-width); grid-template-columns: repeat(7, @tile-width);
grid-gap: 5px; grid-gap: 5px;
@ -13,6 +13,34 @@
margin: 10px; margin: 10px;
} }
.tray-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
width: @board-length*@tile-width;
.player-controls {
display: grid;
grid-template-areas: "check return"
"check pass";
grid-template-rows: 1fr 1fr;
grid-template-columns: 1fr 1fr;
.check {
grid-area: check;
}
.return {
grid-area: return;
}
.pass {
grid-area: pass;
}
}
}
.board-grid { .board-grid {
//grid-area: grid; //grid-area: grid;
display: grid; display: grid;
@ -21,6 +49,7 @@
justify-content: center; justify-content: center;
grid-gap: 1px; grid-gap: 1px;
user-select: none; user-select: none;
flex: initial;
} }
.grid-spot { .grid-spot {
@ -38,9 +67,23 @@
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
z-index: 2;
}
.arrow {
color: red;
font-size: @tile-font-size+10;
position: absolute;
top: 0;
left: 10px;
z-index: 1; z-index: 1;
} }
.down {
transform: rotate(90deg);
}
.ephemeral { .ephemeral {
opacity: 75%; opacity: 75%;
} }
@ -79,6 +122,8 @@
.tileSpot { .tileSpot {
height: @tile-width; height: @tile-width;
width: @tile-width; width: @tile-width;
} }
.letter { .letter {
@ -104,4 +149,179 @@
padding-right: 5px; padding-right: 5px;
} }
input {
position: absolute;
width: 100%;
top: 5px;
text-align: center;
font-size: @tile-font-size;
background: none;
border: none;
padding: 0;
font-style: italic;
left: 0; /* Fixes a weird display bug where the input is shifted to the right when the tile is on the grid */
}
.prev-blank {
font-style: italic;
}
}
.highlight {
color: red;
}
.board-log {
display: grid;
grid-template-columns: @tile-width*@board-length+15px 1fr;
max-height: @tile-width*@board-length + 15px;
margin: 1em;
}
.message-log {
border-color: black;
border-style: solid;
border-width: 2px;
margin: 5px;
max-height: inherit;
display: grid;
grid-template-rows: 0 7em 1fr;
.log {
overflow-y: scroll;
padding: 0.5em;
}
button.end-game {
margin: 0.5em;
width: fit-content;
height: fit-content;
z-index: 1; // because it's in a zero-height area we need to put it on top
}
.scoring {
text-align: center;
display: flex;
span {
font-size: 20px;
}
div {
margin-left: 10px;
margin-right: 10px;
flex: 1;
}
}
}
.multiplayer-inputs-grid {
display: grid;
//grid-template-columns: 3fr 2fr;
//grid-column-gap: 1em;
grid-row-gap: 0.5em;
label {
display: grid;
grid-template-columns: 3fr 2fr;
}
}
.ai-grid{
display: grid;
grid-template-columns: 3fr 2fr;
grid-column-gap: 1em;
grid-row-gap: 0.5em;
}
.side-grid {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 1em;
}
.multiplayer-ai-details {
button {
margin: 1em;
}
}
dialog {
border-radius: 10px;
z-index: 1;
width: 50em;
.new-game {
width: 50em;
.selection-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
justify-items: center;
padding-top: 1em;
button {
width: 40%;
}
}
}
.close-button-div {
display: flex;
justify-content: end;
button {
border: 0;
background-color: inherit;
font-size: 1.5rem;
color: #aaaaaa;
font-weight: bold;
&:hover {
color: black;
cursor: pointer;
}
}
}
.tile-exchange-dialog {
.selection-buttons {
display: flex;
justify-content: space-around;
button {
width: 40%;
}
}
.finish-buttons {
.selection-buttons();
}
.tray-container {
display: flex;
justify-content: center;
margin: 20px;
}
.selected-tile {
bottom: 10px;
}
}
}
button.add-to-dictionary {
padding: 0;
margin: 0 0 0 1em;
}
div.log {
line-height: 1.5em;
} }

155
ui/src/utils.ts Normal file
View file

@ -0,0 +1,155 @@
import * as React from "react";
import {CellType, Letter as LetterData} from "./api";
export interface Settings {
trayLength: number;
playerName: string;
}
export enum LocationType {
GRID,
TRAY
}
export interface CoordinateData {
location: LocationType;
index: number;
}
export type PlayableLetterData = LetterData & CoordinateData;
export type HighlightableLetterData = LetterData & {highlight: boolean};
export enum TileDispatchActionType {
MOVE,
RETRIEVE,
SET_BLANK,
RETURN,
MOVE_TO_ARROW,
}
export type TileDispatchAction = {action: TileDispatchActionType, start?: CoordinateData, end?: CoordinateData, newBlankValue?: string, blankIndex?: number, override?: boolean};
export type TileDispatch = React.Dispatch<TileDispatchAction>;
export enum Direction {
RIGHT = "right",
DOWN = "down",
}
export interface GridArrowData {
direction: Direction,
position: number,
}
export enum GridArrowDispatchActionType {
CLEAR,
CYCLE,
SHIFT,
}
// I need to include the playerLetters as an argument because I can't define gridArrow after defining the playerLetters in <Game>
export type GridArrowDispatchAction = {
action: GridArrowDispatchActionType,
position?: number,
playerLetters?: PlayableLetterData[] // only needs to be defined on action type SHIFT
};
export type GridArrowDispatch = React.Dispatch<GridArrowDispatchAction>;
export function matchCoordinate(playerLetters: PlayableLetterData[], coords: CoordinateData): number {
for (let i=0; i<playerLetters.length; i++){
let letter = playerLetters[i];
if (letter != null && letter.location === coords.location && letter.index === coords.index) {
return i;
}
}
return null; // no match
}
export function cellTypeToDetails(cell_type: CellType): {className: string, text: string} {
let className: string;
let text: string;
switch (cell_type) {
case CellType.Normal:
className = "grid-spot-normal";
text = "";
break;
case CellType.DoubleWord:
className = "grid-spot-double-word";
text = "Double Word Score";
break;
case CellType.DoubleLetter:
className = "grid-spot-double-letter";
text = "Double Letter Score";
break;
case CellType.TripleLetter:
className = "grid-spot-triple-letter";
text = "Triple Letter Score";
break;
case CellType.TripleWord:
className = "grid-spot-triple-word";
text = "Triple Word Score";
break;
case CellType.Start:
className = "grid-spot-start";
text = "★";
break;
}
return {className: className, text: text};
}
export function addNTimes<T>(array: T[], toAdd: T, times: number) {
for (let i=0; i<times; i++) {
array.push(toAdd);
}
}
export function mergeTrays(existing: PlayableLetterData[], newer: (LetterData | null)[]): PlayableLetterData[] {
let trayLength = Math.max(existing.length, newer.length);
// we may need to check against the existing tray to retain whatever user reorderings there are
const freeSpots = new Array<number | null>();
for (let i = 0; i<trayLength; i++) {
freeSpots.push(i);
}
existing.filter((x) => {
return x != null;
}).forEach((x) => {
if (x.location === LocationType.TRAY) {
freeSpots[x.index] = null;
}
});
const firstNotNull = (): number => {
for (let i of freeSpots) {
if (i !== null) {
freeSpots[i] = null;
return i;
}
}
return null;
}
return newer.map((ld, i) => {
if (ld != null) {
if (existing[i] != null && existing[i].location === LocationType.TRAY) {
ld["index"] = existing[i].index;
} else {
ld["index"] = firstNotNull();
}
ld["location"] = LocationType.TRAY;
}
return ld as PlayableLetterData;
});
}
export const GRID_LENGTH = 15;

71
ui/src/wasm_api.tsx Normal file
View file

@ -0,0 +1,71 @@
import {API, APIState, Difficulty, PlayedTile, Result, is_ok} from "./api";
import {WasmAPI as RawAPI} from 'word_grid';
export class WasmAPI implements API{
private wasm: RawAPI;
constructor(seed: bigint, dictionary_text: string, difficulty: Difficulty) {
this.wasm = new RawAPI(seed, dictionary_text, difficulty);
}
add_to_dictionary(word: string): Promise<APIState> {
return new Promise((resolve, reject) => {
let api_state: Result<APIState, any> = this.wasm.add_to_dictionary(word);
if(is_ok(api_state)) {
resolve(api_state.Ok);
} else {
reject(api_state.Err);
}
});
}
exchange(selection: Array<boolean>): Promise<APIState> {
return new Promise((resolve, reject) => {
let api_state: Result<APIState, any> = this.wasm.exchange(selection);
if(is_ok(api_state)) {
resolve(api_state.Ok);
} else {
reject(api_state.Err);
}
});
}
load(_wait: boolean): Promise<APIState> {
return new Promise((resolve, reject) => {
let api_state: Result<APIState, any> = this.wasm.load();
if(is_ok(api_state)) {
resolve(api_state.Ok);
} else {
reject(api_state.Err);
}
});
}
pass(): Promise<APIState> {
return new Promise((resolve, reject) => {
let api_state: Result<APIState, any> = this.wasm.pass();
if(is_ok(api_state)) {
resolve(api_state.Ok);
} else {
reject(api_state.Err);
}
});
}
play(tiles: Array<PlayedTile>, commit: boolean): Promise<APIState> {
return new Promise((resolve, reject) => {
let api_state: Result<APIState, any> = this.wasm.play(tiles, commit);
if(is_ok(api_state)) {
resolve(api_state.Ok);
} else {
reject(api_state.Err);
}
});
}
}

209
ui/src/ws_api.tsx Normal file
View file

@ -0,0 +1,209 @@
import {API, APIState, Difficulty, PlayedTile} from "./api";
export type Player = string;
export interface AI {
proportion: number
randomness: number
}
export interface PartyInfo {
ais: AI[]
players: Player[]
}
export type RoomEvent = {
type: "PlayerJoined" | "PlayerLeft"
player: Player
} | {
type: "AIJoined",
difficulty: Difficulty
} | {
type: "AILeft"
index: number
}
export type GameEvent = {
type: "TurnAction"
state: APIState
committed: boolean
}
export type ServerToClientMessage = {
type: "RoomChange"
event: RoomEvent
info: PartyInfo
} | {
type: "GameEvent"
event: GameEvent
} | {
type: "GameError"
error: any
} | {
type: "Invalid"
reason: string
}
type GameMove = {
type: "Pass"
} | {
type: "Exchange"
tiles: Array<boolean>
} | {
type: "Play"
played_tiles: Array<PlayedTile>
commit_move: boolean
} | {
type: "AddToDictionary"
word: string
}
export type ClientToServerMessage = {
type: "Load" | "StartGame"
} | {
type: "GameMove"
move: GameMove
} | {
type: "AddAI"
difficulty: Difficulty
} | {
type: "RemoveAI"
index: number
}
interface PromiseInput {
resolve: (value: GameEvent) => void
reject: (error: any) => void
type: string // recorded for debug purposes
}
export class WSAPI implements API{
private socket: WebSocket;
private currentPromiseInput: PromiseInput | null;
constructor(socket: WebSocket) {
this.socket = socket;
this.currentPromiseInput = null;
this.socket.addEventListener("message", (event) => {
let data: ServerToClientMessage = JSON.parse(event.data);
console.log("Message from server ", event.data);
if(data.type == "GameEvent") {
if(this.currentPromiseInput != null) {
this.currentPromiseInput.resolve(data.event);
this.currentPromiseInput = null;
} else {
console.error("Received game data but no promise is queued");
console.error({data});
}
} else if(data.type == "GameError") {
if(this.currentPromiseInput != null) {
this.currentPromiseInput.reject(data.error);
this.currentPromiseInput = null;
} else {
console.error("Received error game data but no promise is queued");
console.error({data});
}
}
});
}
private register_promise(resolve: (value: GameEvent) => void, reject: (value: any) => void, type: string) {
const newPromise = {
resolve: resolve,
reject: reject,
type: type,
};
if(this.currentPromiseInput != null) {
console.error("We are setting a new promise before the current one has resolved")
console.error("Current promise: ", this.currentPromiseInput);
console.error("New promise: ", newPromise);
// Some of the rejects take statements from the server and log them; maybe don't send this to reject
//this.currentPromiseInput.reject("New promise was registered");
}
this.currentPromiseInput = newPromise;
}
add_to_dictionary(word: string): Promise<APIState> {
return new Promise((resolve, reject) => {
this.register_promise(resolve, reject, "AddToDictionary");
let event: ClientToServerMessage = {
type: "GameMove",
move: {
type: "AddToDictionary",
word
}
};
this.socket.send(JSON.stringify(event));
}).then((game_event: GameEvent) => {
return game_event.state;
});
}
exchange(selection: Array<boolean>): Promise<APIState> {
return new Promise((resolve, reject) => {
this.register_promise(resolve, reject, "Exchange");
let event: ClientToServerMessage = {
type: "GameMove",
move: {
type: "Exchange",
tiles: selection
}
};
this.socket.send(JSON.stringify(event));
}).then((game_event: GameEvent) => {
return game_event.state;
});
}
load(wait: boolean): Promise<APIState> {
return new Promise((resolve, reject) => {
this.register_promise(resolve, reject, `Load with wait=${wait}`);
if(!wait) {
let event: ClientToServerMessage = {
type: "Load"
}
this.socket.send(JSON.stringify(event));
}
}).then((game_event: GameEvent) => {
return game_event.state;
});
}
pass(): Promise<APIState> {
return new Promise((resolve, reject) => {
this.register_promise(resolve, reject, "Pass");
let event: ClientToServerMessage = {
type: "GameMove",
move: {
type: "Pass",
}
};
this.socket.send(JSON.stringify(event));
}).then((game_event: GameEvent) => {
return game_event.state;
});
}
play(tiles: Array<PlayedTile>, commit: boolean): Promise<APIState> {
return new Promise((resolve, reject) => {
this.register_promise(resolve, reject, "Play");
let event: ClientToServerMessage = {
type: "GameMove",
move: {
type: "Play",
played_tiles: tiles,
commit_move: commit,
}
};
this.socket.send(JSON.stringify(event));
}).then((game_event: GameEvent) => {
return game_event.state;
});
}
}

View file

@ -1,7 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "commonjs", "module": "commonjs",
"target": "ES2023", "target": "ES2022",
"jsx": "react-jsx", "jsx": "react-jsx",
"lib": [ "lib": [
"es2023", "es2023",

2
wasm/.cargo/config.toml Normal file
View file

@ -0,0 +1,2 @@
[build]
rustflags = ['--cfg', 'getrandom_backend="wasm_js"']

19
wasm/Cargo.toml Normal file
View file

@ -0,0 +1,19 @@
[package]
name = "wasm"
version = "0.1.0"
edition = "2021"
# We manually specify path for better caching in Podman
[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]
[dependencies]
serde-wasm-bindgen = "0.6.5"
wasm-bindgen = "0.2.92"
word_grid = { version = "0.1.0", path = "../wordgrid" }
serde = { workspace = true }
# This is actually required; ignore RustRover saying it's not used
# Also required is .cargo/config.toml; see https://docs.rs/getrandom/latest/getrandom/#webassembly-support
getrandom = {version = "0.3.1", features = ["wasm_js"]}

64
wasm/src/lib.rs Normal file
View file

@ -0,0 +1,64 @@
use serde::Serialize;
use serde_wasm_bindgen::Serializer;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use word_grid::api::APIGame;
use word_grid::game::{Game, PlayedTile};
use word_grid::player_interaction::ai::Difficulty;
const PLAYER_NAME: &str = "Player";
const SERIALIZER: Serializer = Serializer::json_compatible();
#[wasm_bindgen]
pub struct WasmAPI(APIGame);
#[wasm_bindgen]
impl WasmAPI {
#[wasm_bindgen(constructor)]
pub fn new(seed: u64, dictionary_text: &str, ai_difficulty: JsValue) -> Self {
let difficulty: Difficulty = serde_wasm_bindgen::from_value(ai_difficulty).unwrap();
let game = Game::new(
seed,
dictionary_text,
vec![PLAYER_NAME.to_string()],
vec![difficulty],
);
WasmAPI(APIGame::new(game))
}
pub fn exchange(&mut self, selection: JsValue) -> JsValue {
let selection: Vec<bool> = serde_wasm_bindgen::from_value(selection).unwrap();
let result = self.0.exchange(PLAYER_NAME, selection);
result.serialize(&SERIALIZER).unwrap()
}
pub fn pass(&mut self) -> JsValue {
let result = self.0.pass(PLAYER_NAME);
result.serialize(&SERIALIZER).unwrap()
}
pub fn load(&mut self) -> JsValue {
let result = self.0.load(PLAYER_NAME);
result.serialize(&SERIALIZER).unwrap()
}
pub fn play(&mut self, tray_tile_locations: JsValue, commit_move: bool) -> JsValue {
let tray_tile_locations: Vec<Option<PlayedTile>> =
serde_wasm_bindgen::from_value(tray_tile_locations).unwrap();
let result = self.0.play(PLAYER_NAME, tray_tile_locations, commit_move);
result.serialize(&SERIALIZER).unwrap()
}
pub fn add_to_dictionary(&mut self, word: &str) -> JsValue {
let result = self.0.add_to_dictionary(PLAYER_NAME, word);
result.serialize(&SERIALIZER).unwrap()
}
}

18
wordgrid/Cargo.toml Normal file
View file

@ -0,0 +1,18 @@
[package]
name = "word_grid"
version = "0.1.0"
edition = "2021"
authors = ["Joel Therrien"]
repository = "https://git.joeltherrien.ca/joel/WordGrid"
license = "AGPL-3"
description = "A (WIP) package for playing 'WordGrid'."
# We manually specify for better caching in Podman
[lib]
path = "src/lib.rs"
[dependencies]
csv = "1.3.0"
serde = { workspace = true }
rand = { workspace = true }

241
wordgrid/src/api.rs Normal file
View file

@ -0,0 +1,241 @@
use crate::board::{CellType, Letter};
use crate::game::{
Error, Game, GameState, PlayedTile, Player, PlayerState, TurnAction, TurnAdvanceResult,
};
use crate::player_interaction::Tray;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ApiPlayer {
name: String,
tray_tiles: usize,
score: u32,
}
impl ApiPlayer {
fn from(player_state: &PlayerState) -> ApiPlayer {
ApiPlayer {
name: player_state.player.get_name().to_string(),
tray_tiles: player_state.tray.count(),
score: player_state.score,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Update {
r#type: TurnAction,
player: String,
turn_number: usize,
}
pub type ApiBoard = Vec<Option<Letter>>;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PublicInformation {
game_state: GameState,
board: ApiBoard,
cell_types: Vec<CellType>,
current_player: String,
players: Vec<ApiPlayer>,
remaining_tiles: usize,
history: Vec<Update>,
current_turn_number: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ApiState {
public_information: PublicInformation,
tray: Tray,
pub update: Option<Update>,
}
pub struct APIGame(pub Game, Vec<Update>);
impl APIGame {
pub fn new(game: Game) -> APIGame {
APIGame(game, vec![])
}
fn is_players_turn(&self, player: &str) -> bool {
self.0.current_player_name().eq_ignore_ascii_case(player)
}
fn player_exists(&self, player: &str) -> bool {
self.0.player_states.get_player_state(player).is_some()
}
fn player_exists_and_turn(&self, player: &str) -> Result<(), Error> {
if !self.player_exists(&player) {
Err(Error::InvalidPlayer(player.to_string()))
} else if !self.is_players_turn(&player) {
Err(Error::WrongTurn(player.to_string()))
} else {
Ok(())
}
}
fn build_result(
&self,
tray: Tray,
game_state: Option<GameState>,
update: Option<Update>,
) -> ApiState {
ApiState {
public_information: self.build_public_information(game_state, &self.1),
tray,
update,
}
}
fn build_public_information(
&self,
game_state: Option<GameState>,
history: &Vec<Update>,
) -> PublicInformation {
let game_state = game_state.unwrap_or_else(|| self.0.get_state());
let cell_types = self
.0
.get_board()
.cells
.iter()
.map(|cell| -> CellType { cell.cell_type })
.collect::<Vec<CellType>>();
let board: Vec<Option<Letter>> = self
.0
.get_board()
.cells
.iter()
.map(|cell| -> Option<Letter> { cell.value.clone() })
.collect();
let players = self
.0
.player_states
.0
.iter()
.map(|p| ApiPlayer::from(p))
.collect::<Vec<ApiPlayer>>();
PublicInformation {
game_state,
board,
cell_types,
current_player: self.0.current_player_name(),
players,
remaining_tiles: self.0.get_remaining_tiles(),
history: history.clone(),
current_turn_number: self.0.get_number_turns(),
}
}
pub fn exchange(&mut self, player: &str, tray_tiles: Vec<bool>) -> Result<ApiState, Error> {
self.player_exists_and_turn(player)?;
let turn_number = self.0.get_number_turns();
let (tray, turn_action, game_state) = self.0.exchange_tiles(tray_tiles)?;
let update = Update {
r#type: turn_action,
player: player.to_string(),
turn_number,
};
self.1.push(update.clone());
Ok(self.build_result(tray, Some(game_state), Some(update)))
}
pub fn pass(&mut self, player: &str) -> Result<ApiState, Error> {
self.player_exists_and_turn(player)?;
let turn_number = self.0.get_number_turns();
let game_state = self.0.pass()?;
let tray = self.0.player_states.get_tray(player).unwrap().clone();
let update = Update {
r#type: TurnAction::Pass,
player: player.to_string(),
turn_number,
};
self.1.push(update.clone());
Ok(self.build_result(tray, Some(game_state), Some(update)))
}
pub fn load(&mut self, player: &str) -> Result<ApiState, Error> {
if !self.player_exists(player) {
Err(Error::InvalidPlayer(player.to_string()))
} else {
while self.is_ai_turn() {
let turn_number = self.0.get_number_turns();
let (result, _) = self.0.advance_turn()?;
if let TurnAdvanceResult::AIMove { name, action } = result {
self.1.push(Update {
r#type: action,
player: name,
turn_number,
});
} else {
unreachable!("We already checked that the current player is AI");
}
}
let tray = self.0.player_states.get_tray(player).unwrap().clone();
Ok(self.build_result(tray, None, None))
}
}
pub fn play(
&mut self,
player: &str,
tray_tile_locations: Vec<Option<PlayedTile>>,
commit_move: bool,
) -> Result<ApiState, Error> {
self.player_exists_and_turn(&player)?;
let turn_number = self.0.get_number_turns();
let (turn_action, game_state) = self.0.receive_play(tray_tile_locations, commit_move)?;
let tray = self.0.player_states.get_tray(&player).unwrap().clone();
let update = Update {
r#type: turn_action,
player: player.to_string(),
turn_number,
};
if commit_move {
self.1.push(update.clone())
}
Ok(self.build_result(tray, Some(game_state), Some(update)))
}
pub fn add_to_dictionary(&mut self, player: &str, word: &str) -> Result<ApiState, Error> {
let word = word.to_uppercase();
self.0.add_word(&word);
let update = Update {
r#type: TurnAction::AddToDictionary { word },
player: player.to_string(),
turn_number: self.0.get_number_turns(),
};
self.1.push(update.clone());
let tray = self.0.player_states.get_tray(&player).unwrap().clone();
Ok(self.build_result(tray, None, Some(update)))
}
pub fn is_ai_turn(&self) -> bool {
let current_player = self.0.current_player_name();
matches!(
self.0
.player_states
.get_player_state(&current_player)
.unwrap()
.player,
Player::AI { .. }
)
}
}

View file

@ -1,30 +1,31 @@
use crate::constants::{ALL_LETTERS_BONUS, GRID_LENGTH, TRAY_LENGTH};
use crate::dictionary::DictionaryImpl;
use crate::game::Error;
use serde::{Deserialize, Serialize};
use std::borrow::BorrowMut;
use std::collections::HashSet; use std::collections::HashSet;
use std::fmt; use std::fmt;
use std::fmt::{Formatter, Write}; use std::fmt::{Formatter, Write};
use serde::{Deserialize, Serialize};
use tsify::Tsify;
use crate::constants::{ALL_LETTERS_BONUS, GRID_LENGTH, TRAY_LENGTH};
use crate::dictionary::DictionaryImpl;
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
enum Direction { pub enum Direction {
Row, Column Row,
Column,
} }
impl Direction { impl Direction {
fn invert(&self) -> Self { pub fn invert(&self) -> Self {
match &self { match &self {
Direction::Row => {Direction::Column} Direction::Row => Direction::Column,
Direction::Column => {Direction::Row} Direction::Column => Direction::Row,
} }
} }
} }
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Coordinates (pub u8, pub u8); pub struct Coordinates(pub u8, pub u8);
impl Coordinates { impl Coordinates {
pub fn new_from_index(index: usize) -> Self { pub fn new_from_index(index: usize) -> Self {
let y = index / GRID_LENGTH as usize; let y = index / GRID_LENGTH as usize;
let x = index % GRID_LENGTH as usize; let x = index % GRID_LENGTH as usize;
@ -34,32 +35,35 @@ impl Coordinates {
fn add(&self, direction: Direction, i: i8) -> Option<Self> { fn add(&self, direction: Direction, i: i8) -> Option<Self> {
let proposed = match direction { let proposed = match direction {
Direction::Column => {(self.0 as i8, self.1 as i8+i)} Direction::Column => (self.0 as i8, self.1 as i8 + i),
Direction::Row => {(self.0 as i8+i, self.1 as i8)} Direction::Row => (self.0 as i8 + i, self.1 as i8),
}; };
if proposed.0 < 0 || proposed.0 >= GRID_LENGTH as i8 || proposed.1 < 0 || proposed.1 >= GRID_LENGTH as i8 { if proposed.0 < 0
|| proposed.0 >= GRID_LENGTH as i8
|| proposed.1 < 0
|| proposed.1 >= GRID_LENGTH as i8
{
None None
} else{ } else {
Some(Coordinates(proposed.0 as u8, proposed.1 as u8)) Some(Coordinates(proposed.0 as u8, proposed.1 as u8))
} }
} }
fn increment(&self, direction: Direction) -> Option<Self>{ pub fn increment(&self, direction: Direction) -> Option<Self> {
self.add(direction, 1) self.add(direction, 1)
} }
fn decrement(&self, direction: Direction) -> Option<Self>{ pub fn decrement(&self, direction: Direction) -> Option<Self> {
self.add(direction, -1) self.add(direction, -1)
} }
fn map_to_index(&self) -> usize { pub fn map_to_index(&self) -> usize {
(self.0 + GRID_LENGTH*self.1) as usize (self.0 + GRID_LENGTH * self.1) as usize
} }
} }
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Tsify)] #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[tsify(from_wasm_abi)]
pub struct Letter { pub struct Letter {
pub text: char, pub text: char,
pub points: u32, pub points: u32,
@ -79,28 +83,27 @@ impl Letter {
pub fn new(text: Option<char>, points: u32) -> Letter { pub fn new(text: Option<char>, points: u32) -> Letter {
match text { match text {
None => { None => Letter {
Letter {
text: ' ', text: ' ',
points, points,
ephemeral: true, ephemeral: true,
is_blank: true, is_blank: true,
} },
} Some(text) => Letter {
Some(text) => {
Letter {
text, text,
points, points,
ephemeral: true, ephemeral: true,
is_blank: false, is_blank: false,
} },
}
} }
} }
pub fn partial_match(&self, other: &Letter) -> bool {
self == other || (self.is_blank && other.is_blank && self.points == other.points)
}
} }
#[derive(Debug, Copy, Clone, Serialize)] #[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub enum CellType { pub enum CellType {
Normal, Normal,
DoubleWord, DoubleWord,
@ -135,28 +138,25 @@ impl<'a> ToString for Word<'a> {
} }
text text
} }
} }
impl <'a> Word<'a> { impl<'a> Word<'a> {
pub fn calculate_score(&self) -> u32 {
fn calculate_score(&self) -> u32{
let mut multiplier = 1; let mut multiplier = 1;
let mut unmultiplied_score = 0; let mut unmultiplied_score = 0;
for cell in self.cells.as_slice() { for cell in self.cells.as_slice() {
let cell_value = cell.value.unwrap(); let cell_value = cell.value.unwrap();
if cell_value.ephemeral { if cell_value.ephemeral {
let cell_multiplier = let cell_multiplier = match cell.cell_type {
match cell.cell_type { CellType::Normal => 1,
CellType::Normal => {1}
CellType::DoubleWord => { CellType::DoubleWord => {
multiplier *= 2; multiplier *= 2;
1 1
} }
CellType::DoubleLetter => {2} CellType::DoubleLetter => 2,
CellType::TripleLetter => {3} CellType::TripleLetter => 3,
CellType::TripleWord => { CellType::TripleWord => {
multiplier *= 3; multiplier *= 3;
1 1
@ -181,7 +181,6 @@ impl Board {
pub fn new() -> Self { pub fn new() -> Self {
let mut cells = Vec::new(); let mut cells = Vec::new();
/// Since the board is symmetrical in both directions for the purposes of our logic we can keep our coordinates in one corner /// Since the board is symmetrical in both directions for the purposes of our logic we can keep our coordinates in one corner
/// ///
/// # Arguments /// # Arguments
@ -194,7 +193,7 @@ impl Board {
GRID_LENGTH - x - 1 GRID_LENGTH - x - 1
} else { } else {
x x
} };
} }
for i_orig in 0..GRID_LENGTH { for i_orig in 0..GRID_LENGTH {
@ -215,12 +214,10 @@ impl Board {
} }
// Double letters // Double letters
if (i % 4 == 2) && (j % 4 == 2) && !( if (i % 4 == 2) && (j % 4 == 2) && !(i == 2 && j == 2) {
i == 2 && j == 2
) {
typee = CellType::DoubleLetter; typee = CellType::DoubleLetter;
} }
if (i.min(j) == 0 && i.max(j) == 3) || (i.min(j)==3 && i.max(j) == 7) { if (i.min(j) == 0 && i.max(j) == 3) || (i.min(j) == 3 && i.max(j) == 7) {
typee = CellType::DoubleLetter; typee = CellType::DoubleLetter;
} }
@ -239,11 +236,10 @@ impl Board {
value: None, value: None,
coordinates: Coordinates(j_orig, i_orig), coordinates: Coordinates(j_orig, i_orig),
}) })
} }
} }
Board {cells} Board { cells }
} }
pub fn get_cell(&self, coordinates: Coordinates) -> Result<&Cell, &str> { pub fn get_cell(&self, coordinates: Coordinates) -> Result<&Cell, &str> {
@ -255,24 +251,28 @@ impl Board {
} }
} }
pub fn get_cell_mut(&mut self, coordinates: Coordinates) -> Result<&mut Cell, &str> { pub fn get_cell_mut(&mut self, coordinates: Coordinates) -> Result<&mut Cell, Error> {
if coordinates.0 >= GRID_LENGTH || coordinates.1 >= GRID_LENGTH { if coordinates.0 >= GRID_LENGTH || coordinates.1 >= GRID_LENGTH {
Err("x & y must be within the board's coordinates") Err(Error::Other(
"x & y must be within the board's coordinates".to_string(),
))
} else { } else {
let index = coordinates.map_to_index(); let index = coordinates.map_to_index();
Ok(self.cells.get_mut(index).unwrap()) Ok(self.cells.get_mut(index).unwrap())
} }
} }
pub fn calculate_scores(
pub fn calculate_scores(&self, dictionary: &DictionaryImpl) -> Result<(Vec<(Word, u32)>, u32), String> { &self,
dictionary: &DictionaryImpl,
) -> Result<(Vec<(Word, u32)>, u32), Error> {
let (words, tiles_played) = self.find_played_words()?; let (words, tiles_played) = self.find_played_words()?;
let mut words_and_scores = Vec::new(); let mut words_and_scores = Vec::new();
let mut total_score = 0; let mut total_score = 0;
for word in words { for word in words {
if !dictionary.contains_key(&word.to_string()) { if !dictionary.contains_key(&word.to_string()) {
return Err(format!("{} is not a valid word", word.to_string())); return Err(Error::InvalidWord(word.to_string()));
} }
let score = word.calculate_score(); let score = word.calculate_score();
@ -287,10 +287,9 @@ impl Board {
Ok((words_and_scores, total_score)) Ok((words_and_scores, total_score))
} }
pub fn find_played_words(&self) -> Result<(Vec<Word>, u8), &str> { pub fn find_played_words(&self) -> Result<(Vec<Word>, u8), Error> {
// We don't assume that the move is valid, so let's first establish that // We don't assume that the move is valid, so let's first establish that
// Let's first establish what rows and columns tiles were played in // Let's first establish what rows and columns tiles were played in
let mut rows_played = HashSet::with_capacity(15); let mut rows_played = HashSet::with_capacity(15);
let mut columns_played = HashSet::with_capacity(15); let mut columns_played = HashSet::with_capacity(15);
@ -314,9 +313,9 @@ impl Board {
} }
if rows_played.is_empty() { if rows_played.is_empty() {
return Err("Tiles need to be played") return Err(Error::NoTilesPlayed);
} else if rows_played.len() > 1 && columns_played.len() > 1 { } else if rows_played.len() > 1 && columns_played.len() > 1 {
return Err("Tiles need to be played on one row or column") return Err(Error::TilesNotStraight);
} }
let direction = if rows_played.len() > 1 { let direction = if rows_played.len() > 1 {
@ -328,10 +327,10 @@ impl Board {
let starting_row = *rows_played.iter().min().unwrap(); let starting_row = *rows_played.iter().min().unwrap();
let starting_column = *columns_played.iter().min().unwrap(); let starting_column = *columns_played.iter().min().unwrap();
let mut starting_coords = Coordinates(starting_row, starting_column); let starting_coords = Coordinates(starting_row, starting_column);
let main_word = self.find_word_at_position(starting_coords, direction).unwrap(); let main_word = self
.find_word_at_position(starting_coords, direction)
starting_coords = main_word.coords; .unwrap();
let mut words = Vec::new(); let mut words = Vec::new();
let mut observed_tiles_played = 0; let mut observed_tiles_played = 0;
@ -355,25 +354,25 @@ impl Board {
// there are tiles not part of the main word // there are tiles not part of the main word
if observed_tiles_played != tiles_played { if observed_tiles_played != tiles_played {
return Err("Played tiles cannot have empty gap"); return Err(Error::TilesHaveGap);
} }
// don't want the case of a single letter word // don't want the case of a single letter word
if main_word.cells.len() > 1 { if main_word.cells.len() > 1 {
words.push(main_word); words.push(main_word);
} else if words.is_empty() { } else if words.is_empty() {
return Err("All words must be at least one letter"); return Err(Error::OneLetterWord);
} }
// need to verify that the play is 'anchored' // need to verify that the play is 'anchored'
let mut anchored = false; let mut anchored = false;
'outer: for word in words.as_slice() { 'outer: for word in words.as_slice() {
for cell in word.cells.as_slice() { for cell in word.cells.as_slice() {
// either one of the letters // either one of the letters
if !cell.value.as_ref().unwrap().ephemeral || (cell.coordinates.0 == GRID_LENGTH / 2 && cell.coordinates.1 == GRID_LENGTH / 2){ if !cell.value.as_ref().unwrap().ephemeral
|| (cell.coordinates.0 == GRID_LENGTH / 2
&& cell.coordinates.1 == GRID_LENGTH / 2)
{
anchored = true; anchored = true;
break 'outer; break 'outer;
} }
@ -383,23 +382,27 @@ impl Board {
if anchored { if anchored {
Ok((words, tiles_played)) Ok((words, tiles_played))
} else { } else {
return Err("Played tiles must be anchored to something") Err(Error::UnanchoredWord)
} }
} }
fn find_word_at_position(&self, mut start_coords: Coordinates, direction: Direction) -> Option<Word> { pub fn find_word_at_position(
&self,
mut start_coords: Coordinates,
direction: Direction,
) -> Option<Word> {
// let's see how far we can backtrack to the start of the word // let's see how far we can backtrack to the start of the word
let mut times_moved = 0; let mut times_moved = 0;
loop { loop {
let one_back = start_coords.add(direction, -times_moved); let one_back = start_coords.add(direction, -times_moved);
match one_back { match one_back {
None => { break } None => break,
Some(new_coords) => { Some(new_coords) => {
let cell = self.get_cell(new_coords).unwrap(); let cell = self.get_cell(new_coords).unwrap();
if cell.value.is_some(){ if cell.value.is_some() {
times_moved += 1; times_moved += 1;
} else { } else {
break break;
} }
} }
} }
@ -419,11 +422,11 @@ impl Board {
loop { loop {
let position = start_coords.add(direction, cells.len() as i8); let position = start_coords.add(direction, cells.len() as i8);
match position { match position {
None => {break} None => break,
Some(x) => { Some(x) => {
let cell = self.get_cell(x).unwrap(); let cell = self.get_cell(x).unwrap();
match cell.value { match cell.value {
None => {break} None => break,
Some(_) => { Some(_) => {
cells.push(cell); cells.push(cell);
} }
@ -438,16 +441,16 @@ impl Board {
}) })
} }
pub fn receive_play(&mut self, play: Vec<(Letter, Coordinates)>) -> Result<(), String> { pub fn receive_play(&mut self, play: Vec<(Letter, Coordinates)>) -> Result<(), Error> {
for (mut letter, coords) in play { for (mut letter, coords) in play {
{ {
let mut cell = match self.get_cell_mut(coords) { let cell = self.get_cell_mut(coords)?;
Ok(cell) => {cell}
Err(e) => {return Err(e.to_string())}
};
if cell.value.is_some() { if cell.value.is_some() {
return Err(format!("There's already a letter at {:?}", coords)); return Err(Error::Other(format!(
"There's already a letter at {:?}",
coords
)));
} }
letter.ephemeral = true; letter.ephemeral = true;
@ -458,11 +461,20 @@ impl Board {
Ok(()) Ok(())
} }
pub fn fix_tiles(&mut self) {
for cell in self.cells.iter_mut() {
match cell.value.borrow_mut() {
None => {}
Some(x) => {
x.ephemeral = false;
}
}
}
}
} }
impl fmt::Display for Board { impl fmt::Display for Board {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut str = String::new(); let mut str = String::new();
let normal = "\x1b[48;5;174m\x1b[38;5;0m"; let normal = "\x1b[48;5;174m\x1b[38;5;0m";
@ -479,57 +491,82 @@ impl fmt::Display for Board {
let cell = self.get_cell(coords).unwrap(); let cell = self.get_cell(coords).unwrap();
let color = match cell.cell_type { let color = match cell.cell_type {
CellType::Normal => {normal} CellType::Normal => normal,
CellType::DoubleWord => {double_word} CellType::DoubleWord => double_word,
CellType::DoubleLetter => {double_letter} CellType::DoubleLetter => double_letter,
CellType::TripleLetter => {triple_letter} CellType::TripleLetter => triple_letter,
CellType::TripleWord => {triple_word} CellType::TripleWord => triple_word,
CellType::Start => {double_word} CellType::Start => double_word,
}; };
let content = match &cell.value { let content = match &cell.value {
None => {' '} None => ' ',
Some(letter) => {letter.text} Some(letter) => letter.text,
}; };
str.write_str(color).unwrap(); str.write_str(color).unwrap();
str.write_char(content).unwrap(); str.write_char(content).unwrap();
} }
str.write_str("\x1b[0m\n").unwrap(); str.write_str("\x1b[0m\n").unwrap();
} }
write!(f, "{}", str) write!(f, "{}", str)
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::dictionary::Dictionary;
use super::*; use super::*;
use crate::dictionary::Dictionary;
#[test] #[test]
fn test_cell_types() { fn test_cell_types() {
let board = Board::new(); let board = Board::new();
assert!(matches!(board.get_cell(Coordinates(0, 0)).unwrap().cell_type, CellType::TripleWord)); assert!(matches!(
assert!(matches!(board.get_cell(Coordinates(1, 0)).unwrap().cell_type, CellType::Normal)); board.get_cell(Coordinates(0, 0)).unwrap().cell_type,
assert!(matches!(board.get_cell(Coordinates(0, 1)).unwrap().cell_type, CellType::Normal)); CellType::TripleWord
assert!(matches!(board.get_cell(Coordinates(1, 1)).unwrap().cell_type, CellType::DoubleWord)); ));
assert!(matches!(
board.get_cell(Coordinates(1, 0)).unwrap().cell_type,
CellType::Normal
));
assert!(matches!(
board.get_cell(Coordinates(0, 1)).unwrap().cell_type,
CellType::Normal
));
assert!(matches!(
board.get_cell(Coordinates(1, 1)).unwrap().cell_type,
CellType::DoubleWord
));
assert!(matches!(board.get_cell(Coordinates(13, 13)).unwrap().cell_type, CellType::DoubleWord)); assert!(matches!(
assert!(matches!(board.get_cell(Coordinates(14, 14)).unwrap().cell_type, CellType::TripleWord)); board.get_cell(Coordinates(13, 13)).unwrap().cell_type,
assert!(matches!(board.get_cell(Coordinates(11, 14)).unwrap().cell_type, CellType::DoubleLetter)); CellType::DoubleWord
));
assert!(matches!(
board.get_cell(Coordinates(14, 14)).unwrap().cell_type,
CellType::TripleWord
));
assert!(matches!(
board.get_cell(Coordinates(11, 14)).unwrap().cell_type,
CellType::DoubleLetter
));
assert!(matches!(board.get_cell(Coordinates(7, 7)).unwrap().cell_type, CellType::Start)); assert!(matches!(
assert!(matches!(board.get_cell(Coordinates(8, 6)).unwrap().cell_type, CellType::DoubleLetter)); board.get_cell(Coordinates(7, 7)).unwrap().cell_type,
assert!(matches!(board.get_cell(Coordinates(5, 9)).unwrap().cell_type, CellType::TripleLetter)); CellType::Start
));
assert!(matches!(
board.get_cell(Coordinates(8, 6)).unwrap().cell_type,
CellType::DoubleLetter
));
assert!(matches!(
board.get_cell(Coordinates(5, 9)).unwrap().cell_type,
CellType::TripleLetter
));
} }
#[test] #[test]
fn test_cell_coordinates() { fn test_cell_coordinates() {
let board = Board::new(); let board = Board::new();
@ -562,7 +599,6 @@ mod tests {
board.get_cell_mut(Coordinates(5, 0)).unwrap().value = Some(Letter::new_fixed('O', 0)); board.get_cell_mut(Coordinates(5, 0)).unwrap().value = Some(Letter::new_fixed('O', 0));
board.get_cell_mut(Coordinates(6, 0)).unwrap().value = Some(Letter::new_fixed('L', 0)); board.get_cell_mut(Coordinates(6, 0)).unwrap().value = Some(Letter::new_fixed('L', 0));
board.get_cell_mut(Coordinates(9, 8)).unwrap().value = Some(Letter::new_fixed('G', 0)); board.get_cell_mut(Coordinates(9, 8)).unwrap().value = Some(Letter::new_fixed('G', 0));
board.get_cell_mut(Coordinates(10, 8)).unwrap().value = Some(Letter::new_fixed('G', 0)); board.get_cell_mut(Coordinates(10, 8)).unwrap().value = Some(Letter::new_fixed('G', 0));
@ -570,7 +606,9 @@ mod tests {
println!("x is {}", x); println!("x is {}", x);
let first_word = board.find_word_at_position(Coordinates(8, x), Direction::Column); let first_word = board.find_word_at_position(Coordinates(8, x), Direction::Column);
match first_word { match first_word {
None => { panic!("Expected to find word JOEL") } None => {
panic!("Expected to find word JOEL")
}
Some(x) => { Some(x) => {
assert_eq!(x.coords.0, 8); assert_eq!(x.coords.0, 8);
assert_eq!(x.coords.1, 6); assert_eq!(x.coords.1, 6);
@ -582,7 +620,9 @@ mod tests {
let single_letter_word = board.find_word_at_position(Coordinates(8, 9), Direction::Row); let single_letter_word = board.find_word_at_position(Coordinates(8, 9), Direction::Row);
match single_letter_word { match single_letter_word {
None => { panic!("Expected to find letter L") } None => {
panic!("Expected to find letter L")
}
Some(x) => { Some(x) => {
assert_eq!(x.coords.0, 8); assert_eq!(x.coords.0, 8);
assert_eq!(x.coords.1, 9); assert_eq!(x.coords.1, 9);
@ -595,7 +635,9 @@ mod tests {
println!("x is {}", x); println!("x is {}", x);
let word = board.find_word_at_position(Coordinates(x, 0), Direction::Row); let word = board.find_word_at_position(Coordinates(x, 0), Direction::Row);
match word { match word {
None => { panic!("Expected to find word IS") } None => {
panic!("Expected to find word IS")
}
Some(x) => { Some(x) => {
assert_eq!(x.coords.0, 0); assert_eq!(x.coords.0, 0);
assert_eq!(x.coords.1, 0); assert_eq!(x.coords.1, 0);
@ -609,7 +651,9 @@ mod tests {
println!("x is {}", x); println!("x is {}", x);
let word = board.find_word_at_position(Coordinates(x, 0), Direction::Row); let word = board.find_word_at_position(Coordinates(x, 0), Direction::Row);
match word { match word {
None => { panic!("Expected to find word COOL") } None => {
panic!("Expected to find word COOL")
}
Some(x) => { Some(x) => {
assert_eq!(x.coords.0, 3); assert_eq!(x.coords.0, 3);
assert_eq!(x.coords.1, 0); assert_eq!(x.coords.1, 0);
@ -624,7 +668,9 @@ mod tests {
let word = board.find_word_at_position(Coordinates(10, 8), Direction::Row); let word = board.find_word_at_position(Coordinates(10, 8), Direction::Row);
match word { match word {
None => { panic!("Expected to find word EGG") } None => {
panic!("Expected to find word EGG")
}
Some(x) => { Some(x) => {
assert_eq!(x.coords.0, 8); assert_eq!(x.coords.0, 8);
assert_eq!(x.coords.1, 8); assert_eq!(x.coords.1, 8);
@ -645,10 +691,10 @@ mod tests {
is_blank: false, is_blank: false,
}); });
match board.find_played_words() { assert!(matches!(
Ok(_) => {panic!("Expected error")} board.find_played_words(),
Err(e) => {assert_eq!(e, "All words must be at least one letter");} Err(Error::OneLetterWord)
} ));
board.get_cell_mut(Coordinates(7, 7)).unwrap().value = Some(Letter { board.get_cell_mut(Coordinates(7, 7)).unwrap().value = Some(Letter {
text: 'I', text: 'I',
@ -712,10 +758,7 @@ mod tests {
board.get_cell_mut(Coordinates(8, 9)).unwrap().value = Some(make_letter('L', true)); board.get_cell_mut(Coordinates(8, 9)).unwrap().value = Some(make_letter('L', true));
let words = board.find_played_words(); let words = board.find_played_words();
match words { assert!(matches!(words, Err(Error::UnanchoredWord)));
Ok(_) => {panic!("Expected the not-anchored error")}
Err(x) => {assert_eq!(x, "Played tiles must be anchored to something")}
}
// Adding anchor // Adding anchor
board.get_cell_mut(Coordinates(7, 6)).unwrap().value = Some(make_letter('I', false)); board.get_cell_mut(Coordinates(7, 6)).unwrap().value = Some(make_letter('I', false));
@ -732,7 +775,6 @@ mod tests {
assert!(board.find_played_words().is_ok()); assert!(board.find_played_words().is_ok());
} }
#[test] #[test]
fn test_word_finding_with_break() { fn test_word_finding_with_break() {
// Verify that if I play my tiles on one row or column but with a break in-between I get an error // Verify that if I play my tiles on one row or column but with a break in-between I get an error
@ -751,21 +793,14 @@ mod tests {
board.get_cell_mut(Coordinates(8, 6)).unwrap().value = Some(Letter::new_fixed('J', 0)); board.get_cell_mut(Coordinates(8, 6)).unwrap().value = Some(Letter::new_fixed('J', 0));
board.get_cell_mut(Coordinates(8, 7)).unwrap().value = Some(make_letter('O', true)); board.get_cell_mut(Coordinates(8, 7)).unwrap().value = Some(make_letter('O', true));
board.get_cell_mut(Coordinates(8, 8)).unwrap().value = Some(make_letter('E', true)); board.get_cell_mut(Coordinates(8, 8)).unwrap().value = Some(make_letter('E', true));
board.get_cell_mut(Coordinates(8, 9)).unwrap().value = Some(Letter::new_fixed( 'L', 0)); board.get_cell_mut(Coordinates(8, 9)).unwrap().value = Some(Letter::new_fixed('L', 0));
board.get_cell_mut(Coordinates(8, 11)).unwrap().value = Some(make_letter('I', true)); board.get_cell_mut(Coordinates(8, 11)).unwrap().value = Some(make_letter('I', true));
board.get_cell_mut(Coordinates(8, 12)).unwrap().value = Some(Letter::new_fixed('S', 0)); board.get_cell_mut(Coordinates(8, 12)).unwrap().value = Some(Letter::new_fixed('S', 0));
let words = board.find_played_words(); let words = board.find_played_words();
match words { assert!(matches!(words, Err(Error::TilesHaveGap)));
Ok(_) => {panic!("Expected to find an error!")}
Err(x) => {
assert_eq!(x, "Played tiles cannot have empty gap")
} }
}
}
#[test] #[test]
fn test_word_finding_whole_board() { fn test_word_finding_whole_board() {
@ -781,15 +816,12 @@ mod tests {
} }
let words = board.find_played_words(); let words = board.find_played_words();
match words { assert!(matches!(words, Err(Error::NoTilesPlayed)));
Ok(_) => {panic!("Expected to find no words")}
Err(x) => {assert_eq!(x, "Tiles need to be played")}
}
board.get_cell_mut(Coordinates(8, 6)).unwrap().value = Some(Letter::new_fixed('J', 8)); board.get_cell_mut(Coordinates(8, 6)).unwrap().value = Some(Letter::new_fixed('J', 8));
board.get_cell_mut(Coordinates(8, 7)).unwrap().value = Some(make_letter('O', true, 1)); board.get_cell_mut(Coordinates(8, 7)).unwrap().value = Some(make_letter('O', true, 1));
board.get_cell_mut(Coordinates(8, 8)).unwrap().value = Some(make_letter('E', true, 1)); board.get_cell_mut(Coordinates(8, 8)).unwrap().value = Some(make_letter('E', true, 1));
board.get_cell_mut(Coordinates(8, 9)).unwrap().value = Some(Letter::new_fixed( 'L', 1)); board.get_cell_mut(Coordinates(8, 9)).unwrap().value = Some(Letter::new_fixed('L', 1));
board.get_cell_mut(Coordinates(0, 0)).unwrap().value = Some(Letter::new_fixed('I', 1)); board.get_cell_mut(Coordinates(0, 0)).unwrap().value = Some(Letter::new_fixed('I', 1));
board.get_cell_mut(Coordinates(1, 0)).unwrap().value = Some(Letter::new_fixed('S', 1)); board.get_cell_mut(Coordinates(1, 0)).unwrap().value = Some(Letter::new_fixed('S', 1));
@ -800,7 +832,7 @@ mod tests {
board.get_cell_mut(Coordinates(6, 0)).unwrap().value = Some(Letter::new_fixed('L', 1)); board.get_cell_mut(Coordinates(6, 0)).unwrap().value = Some(Letter::new_fixed('L', 1));
fn check_board(board: &mut Board, inverted: bool) { fn check_board(board: &mut Board, inverted: bool) {
let dictionary = DictionaryImpl::create_from_path("resources/dictionary.csv"); let dictionary = DictionaryImpl::create_from_path("../resources/dictionary.csv");
println!("{}", board); println!("{}", board);
let words = board.find_played_words(); let words = board.find_played_words();
match words { match words {
@ -813,7 +845,9 @@ mod tests {
assert_eq!(word.calculate_score(), 8 + 1 + 2 + 1); assert_eq!(word.calculate_score(), 8 + 1 + 2 + 1);
} }
Err(e) => { panic!("Expected to find a word to play; found error {}", e) } Err(e) => {
panic!("Expected to find a word to play; found error {}", e)
}
} }
let maybe_invert = |coords: Coordinates| { let maybe_invert = |coords: Coordinates| {
@ -830,12 +864,21 @@ mod tests {
return direction; return direction;
}; };
board.get_cell_mut(maybe_invert(Coordinates(9, 8))).unwrap().value = Some(Letter::new_fixed('G', 2)); board
board.get_cell_mut(maybe_invert(Coordinates(10, 8))).unwrap().value = Some(Letter::new_fixed('G', 2)); .get_cell_mut(maybe_invert(Coordinates(9, 8)))
.unwrap()
.value = Some(Letter::new_fixed('G', 2));
board
.get_cell_mut(maybe_invert(Coordinates(10, 8)))
.unwrap()
.value = Some(Letter::new_fixed('G', 2));
let word = board.find_word_at_position(Coordinates(8, 8), maybe_invert_direction(Direction::Row)); let word = board
.find_word_at_position(Coordinates(8, 8), maybe_invert_direction(Direction::Row));
match word { match word {
None => {panic!("Expected to find word EGG")} None => {
panic!("Expected to find word EGG")
}
Some(x) => { Some(x) => {
assert_eq!(x.coords.0, 8); assert_eq!(x.coords.0, 8);
assert_eq!(x.coords.1, 8); assert_eq!(x.coords.1, 8);
@ -843,7 +886,6 @@ mod tests {
assert_eq!(x.to_string(), "EGG"); assert_eq!(x.to_string(), "EGG");
assert_eq!(x.calculate_score(), 2 + 2 + 2); assert_eq!(x.calculate_score(), 2 + 2 + 2);
assert!(dictionary.is_word_valid(&x)); assert!(dictionary.is_word_valid(&x));
} }
} }
@ -862,20 +904,29 @@ mod tests {
assert_eq!(word.calculate_score(), 8 + 1 + 2 + 1); assert_eq!(word.calculate_score(), 8 + 1 + 2 + 1);
assert!(!dictionary.is_word_valid(word)); assert!(!dictionary.is_word_valid(word));
} }
Err(e) => { panic!("Expected to find a word to play; found error {}", e) } Err(e) => {
panic!("Expected to find a word to play; found error {}", e)
}
} }
let scores = board.calculate_scores(&dictionary); let scores = board.calculate_scores(&dictionary);
match scores { match scores {
Ok(_) => {panic!("Expected an error")} Ok(_) => {
Err(e) => {assert_eq!(e, "JOEL is not a valid word")} panic!("Expected an error")
}
Err(e) => {
if let Error::InvalidWord(w) = e {
assert_eq!(w, "JOEL");
} else {
panic!("Expected an InvalidPlay error")
}
}
} }
let mut alt_dictionary = DictionaryImpl::new(); let mut alt_dictionary = DictionaryImpl::new();
alt_dictionary.insert("JOEL".to_string(), 0.5); alt_dictionary.insert("JOEL".to_string(), 0.5);
alt_dictionary.insert("EGG".to_string(), 0.5); alt_dictionary.insert("EGG".to_string(), 0.5);
let scores = board.calculate_scores(&alt_dictionary); let scores = board.calculate_scores(&alt_dictionary);
match scores { match scores {
Ok((words, total_score)) => { Ok((words, total_score)) => {
@ -892,18 +943,19 @@ mod tests {
assert_eq!(total_score, 18); assert_eq!(total_score, 18);
} }
Err(e) => {panic!("Wasn't expecting to encounter error {e}")} Err(e) => {
panic!("Wasn't expecting to encounter error {e}")
}
} }
// replace one of the 'G' in EGG with an ephemeral to trigger an error // replace one of the 'G' in EGG with an ephemeral to trigger an error
board.get_cell_mut(maybe_invert(Coordinates(9, 8))).unwrap().value = Some(make_letter('G', true, 2)); board
.get_cell_mut(maybe_invert(Coordinates(9, 8)))
.unwrap()
.value = Some(make_letter('G', true, 2));
let words = board.find_played_words(); let words = board.find_played_words();
match words { assert!(matches!(words, Err(Error::TilesNotStraight)));
Ok(_) => { panic!("Expected error as we played tiles in multiple rows and columns") }
Err(e) => { assert_eq!(e, "Tiles need to be played on one row or column") }
}
} }
// make a copy of the board now with x and y swapped // make a copy of the board now with x and y swapped
@ -920,7 +972,6 @@ mod tests {
cell_new.value = Some(*x); cell_new.value = Some(*x);
} }
} }
} }
} }
@ -929,8 +980,5 @@ mod tests {
println!("Checking inverted board"); println!("Checking inverted board");
check_board(&mut inverted_board, true); check_board(&mut inverted_board, true);
} }
} }

View file

@ -1,6 +1,6 @@
use rand::prelude::SliceRandom;
use rand::{Rng};
use crate::board::Letter; use crate::board::Letter;
use rand::prelude::SliceRandom;
use rand::Rng;
pub const GRID_LENGTH: u8 = 15; pub const GRID_LENGTH: u8 = 15;
pub const TRAY_LENGTH: u8 = 7; pub const TRAY_LENGTH: u8 = 7;
@ -49,5 +49,4 @@ pub fn standard_tile_pool<R: Rng>(rng: Option<&mut R>) -> Vec<Letter> {
} }
letters letters
} }

View file

@ -1,10 +1,9 @@
use crate::board::Word;
use csv::Reader;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::str::FromStr; use std::str::FromStr;
use csv::Reader;
use crate::board::Word;
pub trait Dictionary { pub trait Dictionary {
fn create_from_reader<T: std::io::Read>(reader: Reader<T>) -> Self; fn create_from_reader<T: std::io::Read>(reader: Reader<T>) -> Self;
fn create_from_path(path: &str) -> Self; fn create_from_path(path: &str) -> Self;
fn create_from_str(data: &str) -> Self; fn create_from_str(data: &str) -> Self;
@ -14,8 +13,7 @@ pub trait Dictionary {
} }
pub type DictionaryImpl = HashMap<String, f64>; pub type DictionaryImpl = HashMap<String, f64>;
impl Dictionary for DictionaryImpl{ impl Dictionary for DictionaryImpl {
fn create_from_reader<T: std::io::Read>(mut reader: Reader<T>) -> Self { fn create_from_reader<T: std::io::Read>(mut reader: Reader<T>) -> Self {
let mut map = HashMap::new(); let mut map = HashMap::new();
@ -27,7 +25,6 @@ impl Dictionary for DictionaryImpl{
let score = f64::from_str(score).unwrap(); let score = f64::from_str(score).unwrap();
map.insert(word, score); map.insert(word, score);
} }
map map
@ -57,7 +54,6 @@ impl Dictionary for DictionaryImpl{
} }
map map
} }
fn substring_set(&self) -> HashSet<&str> { fn substring_set(&self) -> HashSet<&str> {
@ -65,11 +61,10 @@ impl Dictionary for DictionaryImpl{
for (word, _score) in self.iter() { for (word, _score) in self.iter() {
for j in 0..word.len() { for j in 0..word.len() {
for k in (j+1)..(word.len()+1) { for k in (j + 1)..(word.len() + 1) {
set.insert(&word[j..k]); set.insert(&word[j..k]);
} }
} }
} }
set set
@ -85,18 +80,16 @@ impl Dictionary for DictionaryImpl{
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_dictionary() { fn test_dictionary() {
let dictionary = HashMap::create_from_path("resources/dictionary.csv"); let dictionary = HashMap::create_from_path("../resources/dictionary.csv");
assert_eq!(dictionary.len(), 279429); assert_eq!(dictionary.len(), 279411);
assert!(dictionary.contains_key("AA")); assert!(dictionary.contains_key("AA"));
assert!(dictionary.contains_key("AARDVARK")); assert!(dictionary.contains_key("AARDVARK"));
assert!((dictionary.get("AARDVARK").unwrap() - 0.5798372).abs() < 0.0001) assert!((dictionary.get("AARDVARK").unwrap() - 0.5798372).abs() < 0.0001)
} }
#[test] #[test]
@ -131,11 +124,8 @@ mod tests {
assert!(set.contains("JOH")); assert!(set.contains("JOH"));
assert!(set.contains("OHN")); assert!(set.contains("OHN"));
assert!(!set.contains("XY")); assert!(!set.contains("XY"));
assert!(!set.contains("JH")); assert!(!set.contains("JH"));
assert!(!set.contains("JE")); assert!(!set.contains("JE"));
} }
} }

635
wordgrid/src/game.rs Normal file
View file

@ -0,0 +1,635 @@
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use crate::board::{Board, Coordinates, Letter};
use crate::constants::{standard_tile_pool, TRAY_LENGTH};
use crate::dictionary::{Dictionary, DictionaryImpl};
use crate::player_interaction::ai::{Difficulty, AI};
use crate::player_interaction::Tray;
use rand::prelude::SliceRandom;
use rand::rngs::SmallRng;
use rand::SeedableRng;
use serde::{Deserialize, Serialize, Serializer};
pub enum Player {
Human(String),
AI {
name: String,
difficulty: Difficulty,
object: AI,
},
}
#[derive(Debug, Clone)]
pub enum Error {
InvalidPlayer(String),
WrongTurn(String),
Other(String),
InvalidWord(String),
GameFinished,
NoTilesPlayed,
TilesNotStraight,
TilesHaveGap,
OneLetterWord,
UnanchoredWord,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self {
Error::InvalidPlayer(player) => {
write!(f, "{player} doesn't exist")
}
Error::WrongTurn(player) => {
write!(f, "It's not {player}'s turn")
}
Error::Other(msg) => {
write!(f, "Other error: {msg}")
}
Error::InvalidWord(word) => {
write!(f, "{word} is not a valid word")
}
Error::GameFinished => {
write!(f, "Moves cannot be made after a game has finished")
}
Error::NoTilesPlayed => {
write!(f, "Tiles need to be played")
}
Error::TilesNotStraight => {
write!(f, "Tiles need to be played on one row or column")
}
Error::TilesHaveGap => {
write!(f, "Played tiles cannot have empty gap")
}
Error::OneLetterWord => {
write!(f, "All words must be at least two letters")
}
Error::UnanchoredWord => {
write!(f, "Played tiles must be anchored to something")
}
}
}
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl Player {
pub fn get_name(&self) -> &str {
match &self {
Player::Human(name) => name,
Player::AI { name, .. } => name,
}
}
}
pub struct PlayerState {
pub player: Player,
pub score: u32,
pub tray: Tray,
}
#[derive(Deserialize, Copy, Clone, Debug)]
pub struct PlayedTile {
pub index: usize,
pub character: Option<char>, // we only set this if PlayedTile is a blank
}
impl PlayedTile {
pub fn convert_tray(
tray_tile_locations: &Vec<Option<PlayedTile>>,
tray: &Tray,
) -> Vec<(Letter, Coordinates)> {
let mut played_letters: Vec<(Letter, Coordinates)> = Vec::new();
for (i, played_tile) in tray_tile_locations.iter().enumerate() {
if played_tile.is_some() {
let played_tile = played_tile.unwrap();
let mut letter: Letter = tray.letters.get(i).unwrap().unwrap();
let coord = Coordinates::new_from_index(played_tile.index);
if letter.is_blank {
match played_tile.character {
None => {
panic!(
"You can't play a blank character without providing a letter value"
)
}
Some(x) => {
// TODO - check that x is a valid alphabet letter
letter.text = x;
}
}
}
played_letters.push((letter, coord));
}
}
played_letters
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WordResult {
word: String,
score: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScoreResult {
words: Vec<WordResult>,
total: u32,
}
pub struct PlayerStates(pub Vec<PlayerState>);
impl PlayerStates {
fn get_player_name_by_turn_id(&self, id: usize) -> &str {
let id_mod = id % self.0.len();
let state = self.0.get(id_mod).unwrap();
state.player.get_name()
}
pub fn get_player_state(&self, name: &str) -> Option<&PlayerState> {
self.0
.iter()
.filter(|state| state.player.get_name().eq_ignore_ascii_case(name))
.nth(0)
}
pub fn get_player_state_mut(&mut self, name: &str) -> Option<&mut PlayerState> {
self.0
.iter_mut()
.filter(|state| state.player.get_name().eq_ignore_ascii_case(name))
.nth(0)
}
pub fn get_tray(&self, name: &str) -> Option<&Tray> {
let player = self.get_player_state(name)?;
Some(&player.tray)
}
pub fn get_tray_mut(&mut self, name: &str) -> Option<&mut Tray> {
let player = self.get_player_state_mut(name)?;
Some(&mut player.tray)
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum GameState {
InProgress,
Ended {
finisher: Option<String>,
remaining_tiles: HashMap<String, Vec<Letter>>,
},
}
pub struct Game {
pub tile_pool: Vec<Letter>,
rng: SmallRng,
board: Board,
pub player_states: PlayerStates,
dictionary: DictionaryImpl,
turn_order: usize,
turns_not_played: usize,
state: GameState,
}
impl Game {
pub fn new_specific(
mut rng: SmallRng,
dictionary: DictionaryImpl,
player_names: Vec<String>,
ai_difficulties: Vec<Difficulty>,
) -> Self {
let mut letters = standard_tile_pool(Some(&mut rng));
let mut player_states: Vec<PlayerState> = player_names
.iter()
.map(|name| {
let mut tray = Tray::new(TRAY_LENGTH);
tray.fill(&mut letters);
PlayerState {
player: Player::Human(name.clone()),
score: 0,
tray,
}
})
.collect();
let ai_length = ai_difficulties.len();
for (i, ai_difficulty) in ai_difficulties.into_iter().enumerate() {
let ai = AI::new(ai_difficulty, &dictionary);
let mut tray = Tray::new(TRAY_LENGTH);
tray.fill(&mut letters);
let ai_player_name = if ai_length > 1 {
format!("AI {}", i + 1)
} else {
"AI".to_string()
};
player_states.push(PlayerState {
player: Player::AI {
name: ai_player_name,
difficulty: ai_difficulty,
object: ai,
},
score: 0,
tray,
});
}
// let's shuffle player_states so that humans don't always go first
player_states.shuffle(&mut rng);
Game {
tile_pool: letters,
rng,
board: Board::new(),
player_states: PlayerStates(player_states),
dictionary,
turn_order: 0,
turns_not_played: 0,
state: GameState::InProgress,
}
}
pub fn new(
seed: u64,
dictionary_text: &str,
player_names: Vec<String>,
ai_difficulties: Vec<Difficulty>,
) -> Self {
let rng = SmallRng::seed_from_u64(seed);
let dictionary = DictionaryImpl::create_from_str(dictionary_text);
Self::new_specific(rng, dictionary, player_names, ai_difficulties)
}
pub fn get_board(&self) -> &Board {
&self.board
}
pub fn set_board(&mut self, new_board: Board) {
self.board = new_board;
}
fn fill_trays(&mut self) {
for state in self.player_states.0.iter_mut() {
let tray = &mut state.tray;
tray.fill(&mut self.tile_pool);
}
}
pub fn get_dictionary(&self) -> &DictionaryImpl {
&self.dictionary
}
fn verify_game_in_progress(&self) -> Result<(), Error> {
if !matches!(self.state, GameState::InProgress) {
return Err(Error::GameFinished);
}
Ok(())
}
pub fn receive_play(
&mut self,
tray_tile_locations: Vec<Option<PlayedTile>>,
commit_move: bool,
) -> Result<(TurnAction, GameState), Error> {
self.verify_game_in_progress()?;
let player = self.current_player_name();
let mut board_instance = self.get_board().clone();
let mut tray = self.player_states.get_tray(&player).unwrap().clone();
let played_letters: Vec<(Letter, Coordinates)> =
PlayedTile::convert_tray(&tray_tile_locations, &tray);
for (i, played_tile) in tray_tile_locations.iter().enumerate() {
if played_tile.is_some() {
*tray.letters.get_mut(i).unwrap() = None;
}
}
board_instance.receive_play(played_letters)?;
let x = board_instance.calculate_scores(self.get_dictionary())?;
let total_score = x.1;
let words: Vec<WordResult> =
x.0.iter()
.map(|(word, score)| WordResult {
word: word.to_string(),
score: *score,
})
.collect();
if commit_move {
let player_state = self.player_states.get_player_state_mut(&player).unwrap();
player_state.score += total_score;
player_state.tray = tray;
board_instance.fix_tiles();
self.set_board(board_instance);
self.fill_trays();
self.increment_turn(true);
if self.get_player_tile_count(&player).unwrap() == 0 {
// game is over
self.end_game(Some(player));
}
}
let locations = tray_tile_locations
.iter()
.filter_map(|x| x.as_ref())
.map(|x| x.index)
.collect::<Vec<usize>>();
Ok((
TurnAction::PlayTiles {
result: ScoreResult {
words,
total: total_score,
},
locations,
},
self.get_state(),
))
}
pub fn exchange_tiles(
&mut self,
tray_tile_locations: Vec<bool>,
) -> Result<(Tray, TurnAction, GameState), Error> {
self.verify_game_in_progress()?;
let player = self.current_player_name();
let tray = match self.player_states.get_tray_mut(&player) {
None => return Err(Error::InvalidPlayer(player)),
Some(x) => x,
};
if tray.letters.len() != tray_tile_locations.len() {
return Err(Error::Other(
"Incoming tray and existing tray have different lengths".to_string(),
));
}
let tile_pool = &mut self.tile_pool;
let mut tiles_exchanged = 0;
for (i, played_tile) in tray_tile_locations.iter().enumerate() {
if *played_tile {
let letter = tray.letters.get_mut(i).unwrap();
if letter.is_some() {
tile_pool.push(letter.unwrap().clone());
*letter = None;
tiles_exchanged += 1;
}
}
}
tile_pool.shuffle(&mut self.rng);
tray.fill(&mut self.tile_pool);
let tray = tray.clone();
let state = self.increment_turn(false);
Ok((
tray,
TurnAction::ExchangeTiles { tiles_exchanged },
state.clone(),
))
}
pub fn add_word(&mut self, word: &str) {
let word = word.to_uppercase();
self.dictionary.insert(word, -1.0);
}
pub fn pass(&mut self) -> Result<GameState, Error> {
self.verify_game_in_progress()?;
Ok(self.increment_turn(false).clone())
}
fn increment_turn(&mut self, played: bool) -> &GameState {
self.turn_order += 1;
if !played {
self.turns_not_played += 1;
// check if game has ended due to passing
if self.turns_not_played >= 2 * self.player_states.0.len() {
self.end_game(None);
}
} else {
self.turns_not_played = 0;
}
&self.state
}
fn end_game(&mut self, finisher: Option<String>) {
let mut finished_letters_map = HashMap::new();
let mut points_forfeit = 0;
for player in self.player_states.0.iter_mut() {
let tray = &mut player.tray;
let mut letters_remaining = Vec::new();
let mut player_points_lost = 0;
for letter in tray.letters.iter_mut() {
if let Some(letter) = letter {
player_points_lost += letter.points;
letters_remaining.push(letter.clone());
}
*letter = None;
}
points_forfeit += player_points_lost;
player.score -= player_points_lost;
finished_letters_map.insert(player.player.get_name().to_string(), letters_remaining);
}
if let Some(finisher) = &finisher {
let state = self.player_states.get_player_state_mut(finisher).unwrap();
state.score += points_forfeit;
}
self.state = GameState::Ended {
finisher,
remaining_tiles: finished_letters_map,
};
}
pub fn current_player_name(&self) -> String {
self.player_states
.get_player_name_by_turn_id(self.turn_order)
.to_string()
}
pub fn advance_turn(&mut self) -> Result<(TurnAdvanceResult, GameState), Error> {
let current_player = self.current_player_name();
let state = self
.player_states
.get_player_state_mut(&current_player)
.ok_or(Error::InvalidPlayer(current_player.clone()))?;
if let Player::AI { object, .. } = &mut state.player {
let tray = &mut state.tray;
let best_move = object.find_best_move(tray, &self.board, &mut self.rng);
//let best_move: Option<CompleteMove> = None;
match best_move {
None => {
// no available moves; exchange all tiles
let mut to_exchange = Vec::with_capacity(TRAY_LENGTH as usize);
for tile_spot in tray.letters.iter() {
match tile_spot {
None => {
to_exchange.push(false);
}
Some(_) => {
to_exchange.push(true);
}
}
}
if self.tile_pool.is_empty() {
let game_state = self.increment_turn(false);
Ok((
TurnAdvanceResult::AIMove {
name: current_player,
action: TurnAction::Pass,
},
game_state.clone(),
))
} else {
let (_, action, game_state) = self.exchange_tiles(to_exchange)?;
Ok((
TurnAdvanceResult::AIMove {
name: current_player,
action,
},
game_state,
))
}
}
Some(best_move) => {
let play = best_move.convert_to_play(tray);
let (action, game_state) = self.receive_play(play, true)?;
Ok((
TurnAdvanceResult::AIMove {
name: current_player,
action,
},
game_state,
))
}
}
} else {
Ok((
TurnAdvanceResult::HumanInputRequired {
name: self.current_player_name(),
},
self.get_state(),
))
}
}
pub fn get_remaining_tiles(&self) -> usize {
self.tile_pool.len()
}
pub fn get_number_turns(&self) -> usize {
self.turn_order
}
pub fn get_player_tile_count(&self, player: &str) -> Result<usize, String> {
let tray = match self.player_states.get_tray(&player) {
None => return Err(format!("Player {} not found", player)),
Some(x) => x,
};
Ok(tray.count())
}
pub fn get_state(&self) -> GameState {
self.state.clone()
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum TurnAction {
Pass,
ExchangeTiles {
tiles_exchanged: usize,
},
PlayTiles {
result: ScoreResult,
locations: Vec<usize>,
},
AddToDictionary {
word: String,
},
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
pub enum TurnAdvanceResult {
HumanInputRequired { name: String },
AIMove { name: String, action: TurnAction },
}
#[cfg(test)]
mod tests {
use crate::game::Game;
use crate::player_interaction::ai::Difficulty;
use std::fs;
#[test]
fn test_game() {
let seed = 124;
let dictionary_path = "../resources/dictionary.csv";
let dictionary_string = fs::read_to_string(dictionary_path).unwrap();
let mut game = Game::new(
seed,
&dictionary_string,
vec!["Player".to_string()],
vec![Difficulty {
proportion: 0.5,
randomness: 0.0,
}],
);
let current_player = game.current_player_name();
println!("Current player is {current_player}");
assert_eq!(current_player, "Player");
assert_eq!(0, game.turns_not_played);
game.increment_turn(false);
assert_eq!(1, game.turns_not_played);
assert_eq!(game.current_player_name(), "AI");
let result = game.advance_turn();
println!("AI move is {result:?}");
assert_eq!(game.current_player_name(), "Player");
assert_eq!(0, game.turns_not_played);
}
}

6
wordgrid/src/lib.rs Normal file
View file

@ -0,0 +1,6 @@
pub mod api;
pub mod board;
pub mod constants;
pub mod dictionary;
pub mod game;
pub mod player_interaction;

View file

@ -1,14 +1,11 @@
use serde::{Deserialize, Serialize};
use tsify::Tsify;
use crate::board::Letter; use crate::board::Letter;
use serde::{Deserialize, Serialize};
pub mod ai; pub mod ai;
#[derive(Debug, Serialize, Deserialize, Tsify)] #[derive(Debug, Serialize, Deserialize, Clone)]
#[tsify(from_wasm_abi)]
pub struct Tray { pub struct Tray {
pub letters: Vec<Option<Letter>> pub letters: Vec<Option<Letter>>,
} }
impl Tray { impl Tray {
@ -17,9 +14,7 @@ impl Tray {
for _ in 0..tray_length { for _ in 0..tray_length {
letters.push(None); letters.push(None);
} }
Tray { Tray { letters }
letters
}
} }
pub fn fill(&mut self, standard_tile_pool: &mut Vec<Letter>) { pub fn fill(&mut self, standard_tile_pool: &mut Vec<Letter>) {
@ -36,20 +31,21 @@ impl Tray {
} }
} }
pub fn count(&self) -> usize {
self.letters.iter().filter(|l| l.is_some()).count()
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_tray() { fn test_tray() {
let mut letters = vec![ let mut letters = vec![
Letter::new(Some('E'), 3), Letter::new(Some('E'), 3),
Letter::new(Some('O'), 2), Letter::new(Some('O'), 2),
Letter::new(Some('J'), 1) Letter::new(Some('J'), 1),
]; ];
let mut tray = Tray::new(5); let mut tray = Tray::new(5);
@ -83,8 +79,5 @@ mod tests {
assert_eq!(tray.letters.get(2).unwrap().unwrap().text, 'E'); assert_eq!(tray.letters.get(2).unwrap().unwrap().text, 'E');
assert!(tray.letters.get(3).unwrap().is_none()); assert!(tray.letters.get(3).unwrap().is_none());
assert!(tray.letters.get(4).unwrap().is_none()); assert!(tray.letters.get(4).unwrap().is_none());
} }
} }

File diff suppressed because it is too large Load diff