Compare commits
No commits in common. "main" and "wasm" have entirely different histories.
21 changed files with 1065 additions and 4652 deletions
|
@ -2,10 +2,6 @@
|
|||
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'."
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
@ -16,7 +12,7 @@ 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.171", features = ["derive"] }
|
||||
serde-wasm-bindgen = "0.4.5"
|
||||
serde = { version = "1.0.181", features = ["derive"] }
|
||||
serde-wasm-bindgen = "0.4"
|
||||
tsify = { version = "0.4.5", features = ["js"] }
|
||||
|
||||
|
|
661
LICENSE
661
LICENSE
|
@ -1,661 +0,0 @@
|
|||
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/>.
|
10
Makefile
10
Makefile
|
@ -1,10 +1,2 @@
|
|||
build-all: build-rust build-ui
|
||||
|
||||
build-rust:
|
||||
build:
|
||||
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
|
||||
|
|
24
README.md
24
README.md
|
@ -1,24 +0,0 @@
|
|||
# README
|
||||
|
||||
This repository contains the code for 'WordGrid', a (currently) single-player browser game where you use letter tiles to form words.
|
||||
|
||||
Game logic resides in `src/` as Rust code, which gets compiled into WebAssembly.
|
||||
|
||||
UI logic resides in `ui/src/`, which gets bundled by Parcel into the web application.
|
||||
|
||||
If you want to try it now, I host a version at https://joeltherrien.ca/wordgrid
|
||||
|
||||
## Setup
|
||||
|
||||
* Make sure you have [Node.js](https://nodejs.org/en) installed and [rustup and Cargo](https://www.rust-lang.org/learn/get-started).
|
||||
|
||||
1. Clone this repository.
|
||||
2. If not already installed, install the Rust `wasm32-unknown-unknown` target with `rustup target add wasm32-unknown-unknown`.
|
||||
3. In the base project directory, run `make build-all` to build both the Rust wasm project (gets stored in `pkg/`) and the final bundled web files (gets stored in `ui/dist/`).
|
||||
4. Place the files in `ui/dist/` onto a web server and access them.
|
||||
|
||||
During development, you'll often want to serve the UI component in serve mode that auto-updates when you make a change. In the `ui/` directory you can run `npm run start`. Note that Parcel doesn't always detect changes to the compiled Rust code, so if you recompile the Rust code with changes you should delete `ui/.parcel-cache/` and `ui/dist/` or else the UI may continue to use older WASM.
|
||||
|
||||
## Future Plans
|
||||
|
||||
I intend on building a multiplayer component to this game, where the Rust code will form a webserver for connecting players and the UI will make server calls instead of calling web assembly.
|
40
src/board.rs
40
src/board.rs
|
@ -1,20 +1,18 @@
|
|||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
use std::fmt::{Formatter, Write};
|
||||
use std::borrow::BorrowMut;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tsify::Tsify;
|
||||
use crate::constants::{ALL_LETTERS_BONUS, GRID_LENGTH, TRAY_LENGTH};
|
||||
use crate::dictionary::DictionaryImpl;
|
||||
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Direction {
|
||||
enum Direction {
|
||||
Row, Column
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
pub fn invert(&self) -> Self {
|
||||
fn invert(&self) -> Self {
|
||||
match &self {
|
||||
Direction::Row => {Direction::Column}
|
||||
Direction::Column => {Direction::Row}
|
||||
|
@ -22,7 +20,7 @@ impl Direction {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Coordinates (pub u8, pub u8);
|
||||
|
||||
impl Coordinates {
|
||||
|
@ -47,20 +45,20 @@ impl Coordinates {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn increment(&self, direction: Direction) -> Option<Self>{
|
||||
fn increment(&self, direction: Direction) -> Option<Self>{
|
||||
self.add(direction, 1)
|
||||
}
|
||||
|
||||
pub fn decrement(&self, direction: Direction) -> Option<Self>{
|
||||
fn decrement(&self, direction: Direction) -> Option<Self>{
|
||||
self.add(direction, -1)
|
||||
}
|
||||
|
||||
pub fn map_to_index(&self) -> usize {
|
||||
fn map_to_index(&self) -> usize {
|
||||
(self.0 + GRID_LENGTH*self.1) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Tsify, PartialEq, Eq, Hash)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct Letter {
|
||||
pub text: char,
|
||||
|
@ -100,10 +98,6 @@ impl Letter {
|
|||
}
|
||||
}
|
||||
|
||||
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)]
|
||||
|
@ -147,7 +141,7 @@ impl<'a> ToString for Word<'a> {
|
|||
|
||||
impl <'a> Word<'a> {
|
||||
|
||||
pub fn calculate_score(&self) -> u32{
|
||||
fn calculate_score(&self) -> u32{
|
||||
let mut multiplier = 1;
|
||||
let mut unmultiplied_score = 0;
|
||||
|
||||
|
@ -334,9 +328,11 @@ impl Board {
|
|||
let starting_row = *rows_played.iter().min().unwrap();
|
||||
let starting_column = *columns_played.iter().min().unwrap();
|
||||
|
||||
let starting_coords = Coordinates(starting_row, starting_column);
|
||||
let mut starting_coords = Coordinates(starting_row, starting_column);
|
||||
let main_word = self.find_word_at_position(starting_coords, direction).unwrap();
|
||||
|
||||
starting_coords = main_word.coords;
|
||||
|
||||
let mut words = Vec::new();
|
||||
let mut observed_tiles_played = 0;
|
||||
|
||||
|
@ -391,7 +387,7 @@ impl Board {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn find_word_at_position(&self, mut start_coords: Coordinates, direction: Direction) -> Option<Word> {
|
||||
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 mut times_moved = 0;
|
||||
loop {
|
||||
|
@ -445,7 +441,7 @@ impl Board {
|
|||
pub fn receive_play(&mut self, play: Vec<(Letter, Coordinates)>) -> Result<(), String> {
|
||||
for (mut letter, coords) in play {
|
||||
{
|
||||
let cell = match self.get_cell_mut(coords) {
|
||||
let mut cell = match self.get_cell_mut(coords) {
|
||||
Ok(cell) => {cell}
|
||||
Err(e) => {return Err(e.to_string())}
|
||||
};
|
||||
|
@ -462,16 +458,6 @@ impl Board {
|
|||
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 {
|
||||
|
|
513
src/game.rs
513
src/game.rs
|
@ -1,14 +1,9 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::rngs::SmallRng;
|
||||
use rand::SeedableRng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tsify::Tsify;
|
||||
use crate::board::{Board, Coordinates, Letter};
|
||||
use crate::board::{Board, Letter};
|
||||
use crate::constants::{standard_tile_pool, TRAY_LENGTH};
|
||||
use crate::dictionary::{Dictionary, DictionaryImpl};
|
||||
use crate::player_interaction::ai::{AI, CompleteMove, Difficulty};
|
||||
use crate::player_interaction::ai::Difficulty;
|
||||
use crate::player_interaction::Tray;
|
||||
|
||||
pub enum Player {
|
||||
|
@ -16,513 +11,73 @@ pub enum Player {
|
|||
AI{
|
||||
name: String,
|
||||
difficulty: Difficulty,
|
||||
object: AI,
|
||||
}
|
||||
}
|
||||
|
||||
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, Tsify, Copy, Clone, Debug)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
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(Debug, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct WordResult {
|
||||
word: String,
|
||||
player: Player,
|
||||
score: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
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(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(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, Tsify, Debug, Clone)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum GameState {
|
||||
InProgress,
|
||||
Ended {
|
||||
finisher: Option<String>,
|
||||
remaining_tiles: HashMap<String, Vec<Letter>>,
|
||||
},
|
||||
tray: Tray
|
||||
}
|
||||
|
||||
pub struct Game{
|
||||
pub tile_pool: Vec<Letter>,
|
||||
rng: SmallRng,
|
||||
tile_pool: Vec<Letter>,
|
||||
board: Board,
|
||||
pub player_states: PlayerStates,
|
||||
player: PlayerState,
|
||||
dictionary: DictionaryImpl,
|
||||
turn_order: usize,
|
||||
turns_not_played: usize,
|
||||
state: GameState,
|
||||
}
|
||||
|
||||
// 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, player_names: Vec<String>, ai_difficulties: Vec<Difficulty>) -> Self {
|
||||
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 dictionary = DictionaryImpl::create_from_str(dictionary_text);
|
||||
|
||||
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);
|
||||
let player = PlayerState {
|
||||
player: Player::Human("Joel".to_string()),
|
||||
score: 0,
|
||||
tray,
|
||||
};
|
||||
|
||||
Game {
|
||||
tile_pool: letters,
|
||||
rng,
|
||||
board: Board::new(),
|
||||
player_states: PlayerStates(player_states),
|
||||
dictionary,
|
||||
turn_order: 0,
|
||||
turns_not_played: 0,
|
||||
state: GameState::InProgress,
|
||||
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 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_board_mut(&mut self) -> &mut Board {
|
||||
&mut self.board
|
||||
}
|
||||
|
||||
pub fn get_dictionary(&self) -> &DictionaryImpl {
|
||||
&self.dictionary
|
||||
}
|
||||
|
||||
fn verify_game_in_progress(&self) -> Result<(), String> {
|
||||
if !matches!(self.state, GameState::InProgress) {
|
||||
return Err("Moves cannot be made after a game has finished".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn receive_play(&mut self, tray_tile_locations: Vec<Option<PlayedTile>>, commit_move: bool) -> Result<(TurnAction, GameState), String> {
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Ok((TurnAction::PlayTiles {
|
||||
result: ScoreResult {
|
||||
words,
|
||||
total: total_score,
|
||||
},
|
||||
}, self.state.clone()))
|
||||
}
|
||||
|
||||
pub fn exchange_tiles(&mut self, tray_tile_locations: Vec<bool>) -> Result<(Tray, TurnAction, GameState), String> {
|
||||
self.verify_game_in_progress()?;
|
||||
|
||||
let player = self.current_player_name();
|
||||
let tray = match self.player_states.get_tray_mut(&player) {
|
||||
None => {return Err(format!("Player {} not found", player))}
|
||||
Some(x) => {x}
|
||||
};
|
||||
|
||||
if tray.letters.len() != tray_tile_locations.len() {
|
||||
return Err("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: String) {
|
||||
let word = word.to_uppercase();
|
||||
|
||||
self.dictionary.insert(word, -1.0);
|
||||
}
|
||||
|
||||
pub fn pass(&mut self) -> Result<GameState, String> {
|
||||
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 mut 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), String> {
|
||||
let current_player = self.current_player_name();
|
||||
let state = self.player_states.get_player_state_mut(¤t_player).ok_or("There should be a player available")?;
|
||||
|
||||
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.state.clone()))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
pub fn get_remaining_tiles(&self) -> usize {
|
||||
self.tile_pool.len()
|
||||
}
|
||||
|
||||
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()
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Tsify, Debug)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum TurnAction {
|
||||
Pass,
|
||||
ExchangeTiles{
|
||||
tiles_exchanged: usize
|
||||
},
|
||||
PlayTiles{
|
||||
result: ScoreResult
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Tsify, Debug)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum TurnAdvanceResult {
|
||||
HumanInputRequired{
|
||||
name: String
|
||||
},
|
||||
AIMove{
|
||||
name: String,
|
||||
action: TurnAction,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use std::fs;
|
||||
use crate::game::Game;
|
||||
use crate::player_interaction::ai::Difficulty;
|
||||
|
||||
#[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);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -5,7 +5,7 @@ use crate::board::Letter;
|
|||
|
||||
pub mod ai;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Tsify, Clone)]
|
||||
#[derive(Debug, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct Tray {
|
||||
pub letters: Vec<Option<Letter>>
|
||||
|
@ -36,12 +36,6 @@ impl Tray {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn count(&self) -> usize {
|
||||
self.letters.iter()
|
||||
.filter(|l| l.is_some())
|
||||
.count()
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load diff
222
src/wasm.rs
222
src/wasm.rs
|
@ -3,9 +3,8 @@ use serde_wasm_bindgen::Error;
|
|||
use tsify::Tsify;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
use crate::board::{CellType, Letter};
|
||||
use crate::game::{Game, GameState, PlayedTile};
|
||||
use crate::player_interaction::ai::Difficulty;
|
||||
use crate::board::{Board, CellType, Coordinates, Letter};
|
||||
use crate::game::Game;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct GameWasm(Game);
|
||||
|
@ -19,30 +18,30 @@ pub enum ResponseType {
|
|||
|
||||
#[derive(Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct MyResult<E: Serialize> {
|
||||
pub struct MyResult<E> {
|
||||
response_type: ResponseType,
|
||||
value: E,
|
||||
game_state: Option<GameState>,
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[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, ai_difficulty: JsValue) -> GameWasm {
|
||||
|
||||
let difficulty: Difficulty = serde_wasm_bindgen::from_value(ai_difficulty).unwrap();
|
||||
|
||||
GameWasm(Game::new(seed, dictionary_text, vec!["Player".to_string()], vec![difficulty]))
|
||||
pub fn new(seed: u64, dictionary_text: &str) -> GameWasm {
|
||||
GameWasm(Game::new(seed, dictionary_text))
|
||||
}
|
||||
|
||||
pub fn get_tray(&self, name: &str) -> Result<JsValue, Error> {
|
||||
let tray = self.0.player_states.get_tray(name);
|
||||
pub fn get_tray(&self) -> Result<JsValue, Error> {
|
||||
let tray = self.0.get_tray();
|
||||
|
||||
serde_wasm_bindgen::to_value(&tray)
|
||||
serde_wasm_bindgen::to_value(tray)
|
||||
}
|
||||
|
||||
pub fn get_board_cell_types(&self) -> Result<JsValue, Error> {
|
||||
|
@ -55,159 +54,84 @@ impl GameWasm {
|
|||
serde_wasm_bindgen::to_value(&cell_types)
|
||||
}
|
||||
|
||||
pub fn get_board_letters(&self) -> Result<JsValue, Error> {
|
||||
let board = self.0.get_board();
|
||||
|
||||
let letters: Vec<Option<Letter>> = board.cells.iter().map(|cell| -> Option<Letter> {
|
||||
cell.value.clone()
|
||||
}).collect();
|
||||
|
||||
serde_wasm_bindgen::to_value(&letters)
|
||||
}
|
||||
|
||||
pub fn receive_play(&mut self, tray_tile_locations: JsValue, commit_move: bool) -> Result<JsValue, Error> {
|
||||
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 result = self.0.receive_play(tray_tile_locations, commit_move);
|
||||
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 result {
|
||||
Ok((x, game_state)) => {
|
||||
serde_wasm_bindgen::to_value(&MyResult {
|
||||
response_type: ResponseType::OK,
|
||||
value: x,
|
||||
game_state: Some(game_state)
|
||||
})
|
||||
},
|
||||
Err(e) => {
|
||||
serde_wasm_bindgen::to_value(&MyResult {
|
||||
response_type: ResponseType::ERR,
|
||||
value: e,
|
||||
game_state: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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(_) => {}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
pub fn get_scores(&self) -> Result<JsValue, JsValue> {
|
||||
|
||||
#[derive(Serialize, Deserialize, Tsify)]
|
||||
#[derive(Debug, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct PlayerAndScore {
|
||||
name: String,
|
||||
struct WordResult {
|
||||
word: String,
|
||||
score: u32,
|
||||
}
|
||||
|
||||
let scores: Vec<PlayerAndScore> = self.0.player_states.0.iter()
|
||||
.map(|player_state| {
|
||||
PlayerAndScore {
|
||||
name: player_state.player.get_name().to_string(),
|
||||
score: player_state.score,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
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
|
||||
}
|
||||
|
||||
Ok(serde_wasm_bindgen::to_value(&scores)?)
|
||||
})
|
||||
.collect();
|
||||
//let total_score = x.1;
|
||||
|
||||
}
|
||||
|
||||
pub fn exchange_tiles(&mut self, tray_tile_locations: JsValue) -> Result<JsValue, Error>{
|
||||
|
||||
let tray_tile_locations: Vec<bool> = serde_wasm_bindgen::from_value(tray_tile_locations)?;
|
||||
|
||||
match self.0.exchange_tiles(tray_tile_locations) {
|
||||
Ok((_, turn_action, state)) => {
|
||||
serde_wasm_bindgen::to_value(&MyResult {
|
||||
serde_wasm_bindgen::to_value(
|
||||
&MyResult {
|
||||
response_type: ResponseType::OK,
|
||||
value: turn_action,
|
||||
game_state: Some(state),
|
||||
})
|
||||
value: words
|
||||
}).unwrap()
|
||||
|
||||
},
|
||||
Err(e) => {
|
||||
serde_wasm_bindgen::to_value(&MyResult {
|
||||
serde_wasm_bindgen::to_value(
|
||||
&MyResult {
|
||||
response_type: ResponseType::ERR,
|
||||
value: e,
|
||||
game_state: None,
|
||||
})
|
||||
value: e
|
||||
}).unwrap()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(result)
|
||||
|
||||
}
|
||||
|
||||
pub fn add_word(&mut self, word: String) {
|
||||
self.0.add_word(word);
|
||||
}
|
||||
|
||||
pub fn skip_turn(&mut self) -> Result<JsValue, Error>{
|
||||
let result = self.0.pass();
|
||||
match result {
|
||||
Ok(game_state) => {
|
||||
Ok(serde_wasm_bindgen::to_value(&MyResult {
|
||||
response_type: ResponseType::OK,
|
||||
value: "Turn passed",
|
||||
game_state: Some(game_state),
|
||||
})?)
|
||||
},
|
||||
Err(e) => {
|
||||
Ok(serde_wasm_bindgen::to_value(&MyResult {
|
||||
response_type: ResponseType::ERR,
|
||||
value: e,
|
||||
game_state: None,
|
||||
})?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn advance_turn(&mut self) -> Result<JsValue, Error> {
|
||||
let result = self.0.advance_turn();
|
||||
|
||||
match result {
|
||||
Ok((turn_advance_result, game_state)) => {
|
||||
Ok(serde_wasm_bindgen::to_value(&MyResult {
|
||||
response_type: ResponseType::OK,
|
||||
value: turn_advance_result,
|
||||
game_state: Some(game_state),
|
||||
})?)
|
||||
},
|
||||
Err(e) => {
|
||||
Ok(serde_wasm_bindgen::to_value(&MyResult {
|
||||
response_type: ResponseType::ERR,
|
||||
value: e,
|
||||
game_state: None,
|
||||
})?)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
pub fn get_current_player(&self) -> String {
|
||||
self.0.current_player_name()
|
||||
}
|
||||
|
||||
pub fn get_remaining_tiles(&self) -> usize {
|
||||
self.0.get_remaining_tiles()
|
||||
}
|
||||
|
||||
pub fn get_player_tile_count(&self, player: &str) -> Result<JsValue, Error> {
|
||||
match self.0.get_player_tile_count(player) {
|
||||
Ok(count) => {
|
||||
Ok(serde_wasm_bindgen::to_value(&MyResult{
|
||||
response_type: ResponseType::OK,
|
||||
value: count,
|
||||
game_state: None,
|
||||
})?)
|
||||
},
|
||||
Err(msg) => {
|
||||
Ok(serde_wasm_bindgen::to_value(&MyResult{
|
||||
response_type: ResponseType::OK,
|
||||
value: msg,
|
||||
game_state: None,
|
||||
})?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
1446
ui/package-lock.json
generated
1446
ui/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -10,9 +10,5 @@
|
|||
"@types/react-dom": "^18.2.7",
|
||||
"parcel": "^2.9.3",
|
||||
"process": "^0.11.10"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "parcel src/index.html",
|
||||
"build": "parcel build --public-url ./ src/index.html"
|
||||
}
|
||||
}
|
||||
|
|
557
ui/src/Game.tsx
557
ui/src/Game.tsx
|
@ -1,557 +0,0 @@
|
|||
import * as React from "react";
|
||||
import {useEffect, useMemo, useReducer, useRef, useState} from "react";
|
||||
import {
|
||||
GameState,
|
||||
GameWasm,
|
||||
MyResult,
|
||||
PlayedTile,
|
||||
PlayerAndScore,
|
||||
ScoreResult,
|
||||
Tray,
|
||||
TurnAction,
|
||||
TurnAdvanceResult
|
||||
} from "../../pkg/word_grid";
|
||||
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";
|
||||
|
||||
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: {
|
||||
wasm: GameWasm,
|
||||
settings: Settings,
|
||||
end_game_fn: () => void,
|
||||
}) {
|
||||
|
||||
const cellTypes = useMemo(() => {
|
||||
return props.wasm.get_board_cell_types();
|
||||
}, []);
|
||||
|
||||
const [isGameOver, setGameOver] = useState<boolean>(false);
|
||||
const [confirmedScorePoints, setConfirmedScorePoints] = useState<number>(-1);
|
||||
|
||||
const [boardLetters, setBoardLetters] = useState<HighlightableLetterData[]>(() => {
|
||||
const newLetterData = [] as HighlightableLetterData[];
|
||||
for(let i=0; i<GRID_LENGTH * GRID_LENGTH; i++) {
|
||||
newLetterData.push(undefined);
|
||||
}
|
||||
return newLetterData;
|
||||
|
||||
});
|
||||
|
||||
function adjustGridArrow(existing: GridArrowData, update: GridArrowDispatchAction): GridArrowData {
|
||||
console.log({update});
|
||||
|
||||
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: MyResult<TurnAction | string> = props.wasm.exchange_tiles(selectedArray);
|
||||
|
||||
if(result.response_type === "ERR") {
|
||||
logDispatch(<div><em>{(result.value as string)}</em></div>);
|
||||
} else {
|
||||
handlePlayerAction(result.value as TurnAction, props.settings.playerName);
|
||||
setTurnCount(turnCount + 1);
|
||||
|
||||
if(result.game_state.type === "Ended") {
|
||||
endGame(result.game_state);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function addWordFn(word: string) {
|
||||
props.wasm.add_word(word);
|
||||
}
|
||||
|
||||
|
||||
const [gridArrow, gridArrowDispatch] = useReducer(adjustGridArrow, null);
|
||||
const [logInfo, logDispatch] = useReducer(addLogInfo, []);
|
||||
|
||||
|
||||
function movePlayableLetters(playerLetters: PlayableLetterData[], update: TileDispatchAction) {
|
||||
|
||||
if(update.action === TileDispatchActionType.RETRIEVE) {
|
||||
|
||||
let tray: Tray = props.wasm.get_tray("Player");
|
||||
|
||||
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) {
|
||||
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 [turnCount, setTurnCount] = useState<number>(1);
|
||||
const playerAndScores: PlayerAndScore[] = useMemo(() => {
|
||||
return props.wasm.get_scores();
|
||||
}, [turnCount, isGameOver]);
|
||||
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const newLetterData = props.wasm.get_board_letters() as HighlightableLetterData[];
|
||||
|
||||
// we need to go through and set 'highlight' field to either true or false
|
||||
// it will always be false if the player that just went was the AI
|
||||
// TODO - build in support for multiple other players
|
||||
for(let i=0; i<newLetterData.length; i++) {
|
||||
const newLetter = newLetterData[i];
|
||||
if(boardLetters[i] === undefined && newLetter !== undefined && playerTurnName == props.settings.playerName) {
|
||||
newLetter.highlight = true;
|
||||
} else if(newLetter !== undefined) {
|
||||
newLetter.highlight = false;
|
||||
}
|
||||
}
|
||||
setBoardLetters(newLetterData);
|
||||
}, [turnCount]);
|
||||
|
||||
const playerTurnName = useMemo(() => {
|
||||
return props.wasm.get_current_player();
|
||||
}, [turnCount]);
|
||||
|
||||
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]);
|
||||
|
||||
const remainingTiles = useMemo(() => {
|
||||
return props.wasm.get_remaining_tiles();
|
||||
}, [turnCount, isGameOver]);
|
||||
|
||||
const remainingAITiles = useMemo(() => {
|
||||
let result = props.wasm.get_player_tile_count(props.settings.aiName) as MyResult<number | String>;
|
||||
if(result.response_type == "OK") {
|
||||
return result.value as number;
|
||||
} else {
|
||||
console.error(result.value);
|
||||
return -1;
|
||||
}
|
||||
|
||||
}, [turnCount, isGameOver]);
|
||||
|
||||
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>);
|
||||
}
|
||||
|
||||
// Clear any on-screen arrows
|
||||
gridArrowDispatch({action: GridArrowDispatchActionType.CLEAR});
|
||||
}
|
||||
|
||||
function endGame(state: GameState) {
|
||||
|
||||
if(state.type != "InProgress") {
|
||||
|
||||
setGameOver(true);
|
||||
logDispatch(<h4>Scoring</h4>);
|
||||
|
||||
const scores = props.wasm.get_scores() as PlayerAndScore[];
|
||||
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.get(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 runAI() {
|
||||
const result: MyResult<TurnAdvanceResult> = props.wasm.advance_turn();
|
||||
if(result.response_type === "OK" && result.value.type == "AIMove") {
|
||||
handlePlayerAction(result.value.action, props.settings.aiName);
|
||||
if(result.game_state.type === "Ended") {
|
||||
endGame(result.game_state);
|
||||
}
|
||||
|
||||
} else {
|
||||
// this would be quite surprising
|
||||
console.error({result});
|
||||
}
|
||||
|
||||
setTurnCount(turnCount + 1);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
trayDispatch({action: TileDispatchActionType.RETRIEVE});
|
||||
setConfirmedScorePoints(-1);
|
||||
if(!isGameOver){
|
||||
logDispatch(<h4>Turn {turnCount}</h4>);
|
||||
logDispatch(<div>{playerTurnName}'s turn</div>);
|
||||
if(playerTurnName != props.settings.playerName && !isGameOver) {
|
||||
runAI();
|
||||
}
|
||||
}
|
||||
}, [turnCount]);
|
||||
|
||||
|
||||
return <>
|
||||
<TileExchangeModal
|
||||
playerLetters={playerLetters}
|
||||
isOpen={isTileExchangeOpen}
|
||||
setOpen={setIsTileExchangeOpen}
|
||||
exchangeFunction={exchangeFunction}
|
||||
/>
|
||||
<div className="board-log">
|
||||
<Grid
|
||||
cellTypes={cellTypes}
|
||||
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>
|
||||
<div>
|
||||
{props.settings.aiName} has {remainingAITiles} tiles
|
||||
</div>
|
||||
<button
|
||||
disabled={remainingTiles == 0 || isGameOver}
|
||||
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}
|
||||
onClick={() => {
|
||||
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<{ type: "PlayTiles"; result: ScoreResult } | string> = props.wasm.receive_play(playedTiles, confirmedScorePoints > -1);
|
||||
console.log({result});
|
||||
|
||||
if(result.response_type === "ERR") {
|
||||
const message = result.value as string;
|
||||
if (message.endsWith("is not a valid word")) {
|
||||
// extract out word
|
||||
const word = message.split(" ")[0];
|
||||
logDispatch(<AddWordButton word={word} addWordFn={addWordFn} />);
|
||||
} else {
|
||||
logDispatch(<div><em>{message}</em></div>);
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
const score_result = (result.value as { type: "PlayTiles"; result: ScoreResult }).result;
|
||||
const total_points = score_result.total;
|
||||
|
||||
|
||||
if (confirmedScorePoints > -1) {
|
||||
handlePlayerAction({type: "PlayTiles", result: score_result}, props.settings.playerName);
|
||||
setTurnCount(turnCount + 1);
|
||||
}
|
||||
|
||||
if (result.game_state.type === "Ended") {
|
||||
endGame(result.game_state);
|
||||
}
|
||||
|
||||
setConfirmedScorePoints(total_points);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}}>{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}
|
||||
onClick={() => {
|
||||
if (window.confirm("Are you sure you want to pass?")) {
|
||||
const result = props.wasm.skip_turn() as MyResult<string>;
|
||||
handlePlayerAction({type: "Pass"}, props.settings.playerName);
|
||||
setTurnCount(turnCount + 1);
|
||||
|
||||
if (result.game_state.type === "Ended") {
|
||||
endGame(result.game_state);
|
||||
}
|
||||
}
|
||||
}}>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>{props.word} was added to dictionary.</em>
|
||||
</div>;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
import * as React from "react";
|
||||
import {useState} from "react";
|
||||
import {Difficulty, GameWasm} from '../../pkg/word_grid';
|
||||
import {Settings} from "./utils";
|
||||
import {Game} from "./Game";
|
||||
|
||||
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">
|
||||
<div className="grid">
|
||||
<label htmlFor="proportion-dictionary">AI's proportion of dictionary:</label>
|
||||
<input type="number"
|
||||
name="proportion-dictionary"
|
||||
value={proportionDictionary}
|
||||
onInput={(e) => {
|
||||
setProportionDictionary(parseInt(e.currentTarget.value));
|
||||
}}
|
||||
min={1}
|
||||
max={100}/>
|
||||
<label htmlFor="randomness">Level of randomness in AI:</label>
|
||||
<input type="number"
|
||||
name="randomness"
|
||||
value={aiRandomness}
|
||||
onInput={(e) => {
|
||||
setAIRandomness(parseInt(e.currentTarget.value));
|
||||
}}
|
||||
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>
|
||||
<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 = new GameWasm(BigInt(seed), props.dictionary_text, difficulty);
|
||||
const game = <Game settings={props.settings} wasm={game_wasm} key={seed} end_game_fn={() => setGame(null)}/>
|
||||
setGame(game);
|
||||
}}>New Game</button>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
} else {
|
||||
return game;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
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>
|
||||
);
|
||||
|
||||
}
|
|
@ -1,128 +0,0 @@
|
|||
import {addNTimes, PlayableLetterData} from "./utils";
|
||||
import {useEffect, useState} from "react";
|
||||
import {Modal} from "./Modal";
|
||||
import {Letter as LetterData} from "../../pkg/word_grid";
|
||||
import * as React from "react";
|
||||
|
||||
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: LetterData,
|
||||
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>;
|
||||
}
|
248
ui/src/UI.tsx
248
ui/src/UI.tsx
|
@ -1,248 +0,0 @@
|
|||
import * as React from "react";
|
||||
import {ChangeEvent, JSX} from "react";
|
||||
import {PlayerAndScore} from "../../pkg/word_grid";
|
||||
import {
|
||||
CellType,
|
||||
cellTypeToDetails,
|
||||
CoordinateData,
|
||||
GridArrowData,
|
||||
GridArrowDispatch,
|
||||
GridArrowDispatchActionType,
|
||||
HighlightableLetterData,
|
||||
LocationType,
|
||||
PlayableLetterData,
|
||||
TileDispatch,
|
||||
TileDispatchActionType,
|
||||
} from "./utils";
|
||||
|
||||
|
||||
export function TileSlot(props: {
|
||||
tile?: React.JSX.Element | undefined,
|
||||
location: CoordinateData,
|
||||
tileDispatch: TileDispatch,
|
||||
arrowDispatch?: GridArrowDispatch,
|
||||
}): 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.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: undefined, 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] !== undefined) {
|
||||
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<PlayerAndScore>}){
|
||||
let elements = props.playerScores.map((ps) => {
|
||||
return <div key={ps.name}>
|
||||
<h3>{ps.name}</h3>
|
||||
<span>{ps.score}</span>
|
||||
</div>;
|
||||
});
|
||||
|
||||
return <div className="scoring">
|
||||
{elements}
|
||||
</div>
|
||||
}
|
274
ui/src/elements.tsx
Normal file
274
ui/src/elements.tsx
Normal file
|
@ -0,0 +1,274 @@
|
|||
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>
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
import init from '../../pkg/word_grid.js';
|
||||
import init, {greet, GameWasm} from '../node_modules/word_grid/word_grid.js';
|
||||
import {Game} from "./elements";
|
||||
import {createRoot} from "react-dom/client";
|
||||
import * as React from "react";
|
||||
import {Menu} from "./Menu";
|
||||
|
||||
// @ts-ignore
|
||||
const dictionary_url = new URL("../../resources/dictionary.csv", import.meta.url);
|
||||
|
@ -45,14 +45,15 @@ 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"));
|
||||
root.render(<Menu dictionary_text={dictionary_text} settings={{
|
||||
trayLength: 7,
|
||||
playerName: 'Player',
|
||||
aiName: 'AI',
|
||||
|
||||
}}/>);
|
||||
root.render(<Game wasm={game} />);
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -3,44 +3,16 @@
|
|||
@board-length: 15;
|
||||
@tile-star-size: 45px;
|
||||
|
||||
.tray { // Don't put under tray-row as this also gets used in tile exchange
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, @tile-width);
|
||||
grid-gap: 5px;
|
||||
height: @tile-width;
|
||||
width: fit-content;
|
||||
background-color: #bbb59d;
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
.tray-row {
|
||||
.tray {
|
||||
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;
|
||||
}
|
||||
}
|
||||
grid-template-columns: repeat(7, @tile-width);
|
||||
grid-gap: 5px;
|
||||
height: @tile-width;
|
||||
width: fit-content;
|
||||
background-color: #bbb59d;
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
|
||||
|
||||
.board-grid {
|
||||
//grid-area: grid;
|
||||
display: grid;
|
||||
|
@ -49,7 +21,6 @@
|
|||
justify-content: center;
|
||||
grid-gap: 1px;
|
||||
user-select: none;
|
||||
flex: initial;
|
||||
}
|
||||
|
||||
.grid-spot {
|
||||
|
@ -67,23 +38,9 @@
|
|||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 2;
|
||||
|
||||
}
|
||||
|
||||
.arrow {
|
||||
color: red;
|
||||
font-size: @tile-font-size+10;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 10px;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.down {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.ephemeral {
|
||||
opacity: 75%;
|
||||
}
|
||||
|
@ -122,8 +79,6 @@
|
|||
.tileSpot {
|
||||
height: @tile-width;
|
||||
width: @tile-width;
|
||||
|
||||
|
||||
}
|
||||
|
||||
.letter {
|
||||
|
@ -149,156 +104,4 @@
|
|||
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: 1.5em 6em 1fr;
|
||||
|
||||
.log {
|
||||
overflow-y: scroll;
|
||||
padding: 0.5em;
|
||||
}
|
||||
|
||||
button.end-game {
|
||||
margin: 0.5em;
|
||||
width: fit-content;
|
||||
height: fit-content;
|
||||
}
|
||||
|
||||
.scoring {
|
||||
text-align: center;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-rows: none;
|
||||
|
||||
span {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
div {
|
||||
margin-left: 10px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
dialog {
|
||||
border-radius: 10px;
|
||||
z-index: 1;
|
||||
|
||||
.new-game {
|
||||
width: 50em;
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: 3fr 2fr;
|
||||
grid-column-gap: 1em;
|
||||
grid-row-gap: 0.5em;
|
||||
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
165
ui/src/utils.ts
165
ui/src/utils.ts
|
@ -1,165 +0,0 @@
|
|||
import {Letter as LetterData, Letter} from "../../pkg/word_grid";
|
||||
import * as React from "react";
|
||||
|
||||
export enum CellType {
|
||||
Normal = "Normal",
|
||||
DoubleWord = "DoubleWord",
|
||||
DoubleLetter = "DoubleLetter",
|
||||
TripleLetter = "TripleLetter",
|
||||
TripleWord = "TripleWord",
|
||||
Start = "Start",
|
||||
}
|
||||
|
||||
|
||||
export interface Settings {
|
||||
trayLength: number;
|
||||
playerName: string;
|
||||
aiName: 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 !== undefined && 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: (Letter | undefined)[]): 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 !== undefined && 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 !== undefined) {
|
||||
|
||||
if (existing[i] !== undefined && 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;
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "ES2022",
|
||||
"target": "ES2023",
|
||||
"jsx": "react-jsx",
|
||||
"lib": [
|
||||
"es2023",
|
||||
|
|
Loading…
Reference in a new issue