Shared leaderboard, a games hub, AGPL, and two new street conditions
The high score table moves out of the browser and into a service, so every player is on one board. It is a Node process with SQLite, no build step and no native modules - node:sqlite ships with the runtime and Node runs the TypeScript directly. Everything in a request is treated as hostile: names forced to a printable subset, every number range-checked, and scores refused if they could not have happened in the days claimed. Bodies capped, submissions rate limited per address. It still cannot prove a score is real, and server/README.md says so plainly rather than implying otherwise. The game degrades properly without it: the board says it cannot reach town, posting happens behind the closing standings, and play is untouched. Deployment is three containers behind the host's nginx - the hub at /, the game at /lemonade/, the scores service at /api/ - so the game keeps its own container and a second game is just another service. Licensing: AGPL-3.0-or-later, Affero because the leaderboard is a network service. NOTICE.md credits Bob Jamison and Charlie Kellner, records that this is clean-room work, and is honest about the one thing it is not: some on-screen wording is quoted from the original and cannot be licensed by us. The street can now get better as well as worse. The summer fair brings the town out and lifts what they will pay; a rival on the next corner takes a share and lingers. Both show in the art and in the crowd. Over 500 seasons a player who reads the briefing survives every time and finishes around $25.80; one who ignores it goes broke 70% of the time.
This commit is contained in:
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# Notice, credits and provenance
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
An independent reimplementation of the lemonade-stand business simulation that
|
||||||
|
went round schools and home computers from the 1970s onward, written from
|
||||||
|
scratch in TypeScript in 2026.
|
||||||
|
|
||||||
|
## Credit where it is due
|
||||||
|
|
||||||
|
- **Bob Jamison**, Minnesota Educational Computing Consortium (MECC), 1973 —
|
||||||
|
wrote the original *Lemonade Stand* for time-shared systems.
|
||||||
|
- **Charlie Kellner**, 1979 — wrote the Apple II version that most people
|
||||||
|
actually remember, distributed by Apple Computer.
|
||||||
|
- Every magazine and type-in book that carried a listing of it, which is how a
|
||||||
|
lot of us first met the thing.
|
||||||
|
|
||||||
|
This project is not affiliated with, endorsed by, or connected to MECC, its
|
||||||
|
successors, or Apple. No original source code was used, consulted or copied.
|
||||||
|
|
||||||
|
## How this code came to exist
|
||||||
|
|
||||||
|
Clean-room, and worth being specific about because it is what makes the licence
|
||||||
|
below meaningful:
|
||||||
|
|
||||||
|
- **The simulation is ours.** The demand curve, the weather profiles, the sign
|
||||||
|
returns and the event probabilities in `src/game/constants.ts` are a
|
||||||
|
reconstruction, tuned by running several hundred headless seasons until the
|
||||||
|
game *behaved* the way it is remembered. It is not the original arithmetic,
|
||||||
|
and it is documented as a reconstruction in the source.
|
||||||
|
- **The rules are not ours to own.** Buy glasses, buy signs, set a price, read
|
||||||
|
the weather — game mechanics are ideas rather than expression, and nobody
|
||||||
|
gets to fence them off. We use them freely and so may you.
|
||||||
|
- **The artwork and the music are ours.** Every pixel is SVG drawn in code and
|
||||||
|
every note is generated by the synth in `src/audio/`. There are no imported
|
||||||
|
assets of any kind.
|
||||||
|
|
||||||
|
## The one place we are standing on someone else's work
|
||||||
|
|
||||||
|
Some **on-screen wording** is reproduced from the original from memory, because
|
||||||
|
it is the part people remember word for word:
|
||||||
|
|
||||||
|
| Where | Text |
|
||||||
|
| --- | --- |
|
||||||
|
| `IntroScreen.tsx` | "HI! WELCOME TO LEMONSVILLE, CALIFORNIA!" and the paragraph after it |
|
||||||
|
| `ReportScreen.tsx` | "$$ LEMONSVILLE DAILY FINANCIAL REPORT $$" |
|
||||||
|
| `TradingScreen.tsx` | the thunderstorm message |
|
||||||
|
| `BriefingScreen.tsx` | the street-crew and heat-wave messages |
|
||||||
|
|
||||||
|
Short functional labels (`GLASSES SOLD`, `WEATHER REPORT: SUNNY`) are hard to
|
||||||
|
express any other way and are not really anyone's creative property. The longer
|
||||||
|
passages are a different matter: they are someone's writing, quoted here as
|
||||||
|
homage rather than authored by us. We cannot license what we did not write, so
|
||||||
|
that wording is **not** covered by this project's licence and is used on a
|
||||||
|
fair-use/de-minimis footing.
|
||||||
|
|
||||||
|
If that footing is not comfortable for a given use, the fix is small and
|
||||||
|
self-contained: rewrite those few strings in your own voice. Nothing else in
|
||||||
|
the project depends on them.
|
||||||
|
|
||||||
|
The name *Lemonade Stand* is descriptive and is used descriptively. It is not
|
||||||
|
claimed as a mark of this project.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
Copyright (C) 2026 John Coffey.
|
||||||
|
|
||||||
|
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 — see [LICENSE](LICENSE).
|
||||||
|
|
||||||
|
AGPL rather than plain GPL because the leaderboard is a network service: §13
|
||||||
|
means anyone who runs a modified copy of this for other people over a network
|
||||||
|
has to offer them its source. Running the game without the scores service is
|
||||||
|
entirely supported and imposes nothing extra.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
*None of the above is legal advice.*
|
||||||
@@ -38,6 +38,9 @@ pocket money.
|
|||||||
glass you made.
|
glass you made.
|
||||||
- Street crews close the road now and then, and they tend to stay for a
|
- Street crews close the road now and then, and they tend to stay for a
|
||||||
second day.
|
second day.
|
||||||
|
- The summer fair brings half the town past your stand, in a spending mood.
|
||||||
|
- A rival sometimes sets up on the next corner and takes a share of the
|
||||||
|
street until they get bored and move on.
|
||||||
- Signs work, but with sharp diminishing returns — the fourth one barely
|
- Signs work, but with sharp diminishing returns — the fourth one barely
|
||||||
earns its 15 cents.
|
earns its 15 cents.
|
||||||
|
|
||||||
@@ -50,21 +53,20 @@ as long as you like; **RETIRE** closes the books and shows the standings.
|
|||||||
|
|
||||||
## High scores
|
## High scores
|
||||||
|
|
||||||
Retiring writes every player's closing balance to a top-ten table kept in
|
One board, shared by everybody. Retiring posts every player's closing balance
|
||||||
`localStorage`, reachable from the title screen and from the standings. Runs
|
to the scores service, and the top 50 comes back ranked best first — ties break
|
||||||
from the summer you just finished are picked out in yellow. Ties break on the
|
on the shorter season, then the earlier date. Runs from the summer you just
|
||||||
shorter season, then on the earlier date.
|
finished are picked out in yellow.
|
||||||
|
|
||||||
There is no way to clear the table. A stand leaves the list only by being
|
There is no way to clear it. A stand leaves the list only by being pushed off
|
||||||
pushed off the bottom by a better one, so a good summer stands until somebody
|
the bottom by a better one, so a good summer stands until somebody beats it.
|
||||||
beats it.
|
|
||||||
|
|
||||||
The table is per-browser, not per-device, and it is the one piece of state the
|
The board lives in `server/`, not in the browser, so it is the one part of the
|
||||||
game keeps between visits. Anything already in storage can be edited by hand,
|
game that needs a line out. With the service unreachable the game plays exactly
|
||||||
so every field is validated on the way back in and malformed rows are dropped
|
as normal and the board says so plainly rather than breaking; posting happens
|
||||||
rather than trusted. If storage is unavailable — a private window, or a browser
|
behind the closing standings, so a slow network never holds up the end of a
|
||||||
set to block site data — the game plays normally and the table simply stays
|
season. See [server/README.md](server/README.md) for the API, the validation
|
||||||
empty.
|
and what a board with no accounts can and cannot promise.
|
||||||
|
|
||||||
## How it is put together
|
## How it is put together
|
||||||
|
|
||||||
@@ -110,8 +112,9 @@ than the tube, `Fit` scales it down rather than clipping or scrolling it.
|
|||||||
### The people on the street
|
### The people on the street
|
||||||
|
|
||||||
How many figures walk on is driven by trade, not decoration. Before you have
|
How many figures walk on is driven by trade, not decoration. Before you have
|
||||||
priced anything it comes from the forecast — a hot day fills the pavement, road
|
priced anything it comes from the forecast and the day's conditions — a hot day
|
||||||
works empty it, a downpour leaves one soul hurrying past under an umbrella.
|
or the fair fills the pavement, road works and a rival empty it, a downpour
|
||||||
|
leaves one soul hurrying past under an umbrella.
|
||||||
Once the day has traded it comes from the glasses that actually crossed the
|
Once the day has traded it comes from the glasses that actually crossed the
|
||||||
counter, so the report shows you the crowd you earned. In a heat wave they fan
|
counter, so the report shows you the crowd you earned. In a heat wave they fan
|
||||||
themselves.
|
themselves.
|
||||||
@@ -133,11 +136,44 @@ not stutter when React re-renders. `MUSIC` and `SOUND` toggle independently.
|
|||||||
|
|
||||||
## Two people, two browsers
|
## Two people, two browsers
|
||||||
|
|
||||||
There is no server and no shared state: the whole game is a static bundle and
|
The game itself is a static bundle and lives entirely in the page. Two people
|
||||||
lives entirely in the page. Two people on two machines, two browsers, or two
|
on two machines, two browsers or two profiles play completely independent
|
||||||
profiles are completely independent — different seeds, different weather,
|
games — different seeds, different weather, different books. Nothing about a
|
||||||
different books.
|
season is shared or synchronised.
|
||||||
|
|
||||||
The one thing two tabs in the *same* browser profile share is `localStorage`,
|
The only thing they have in common is the leaderboard they both post to at the
|
||||||
which holds the high score table and the skin. They stay in step: each tab
|
end. The skin preference is the one thing still kept in the browser.
|
||||||
listens for the other's writes and refreshes rather than going stale.
|
|
||||||
|
## Deploying
|
||||||
|
|
||||||
|
Three containers behind the host's nginx, which does TLS and routing and serves
|
||||||
|
nothing off disk:
|
||||||
|
|
||||||
|
| Path | Container | What it is |
|
||||||
|
| ----------- | ----------------- | -------------------------- |
|
||||||
|
| `/` | `games-hub` | the list of games |
|
||||||
|
| `/lemonade/`| `lemonade-web` | this game, a static bundle |
|
||||||
|
| `/api/` | `lemonade-scores` | the shared leaderboard |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f deploy/compose.yml up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
`deploy/nginx-host.conf.example` is the host-side server block. The game's
|
||||||
|
asset paths are baked in at build time, so `BASE_PATH` in the compose file has
|
||||||
|
to match the path nginx proxies it to. Only the scores container writes
|
||||||
|
anything: a named volume holding the SQLite database, which is the one piece of
|
||||||
|
state that must survive a redeploy.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
AGPL-3.0-or-later — see [LICENSE](LICENSE).
|
||||||
|
|
||||||
|
Affero rather than plain GPL because the leaderboard is a network service:
|
||||||
|
anyone running a modified copy of it for other people has to offer them the
|
||||||
|
source. Running the game on its own imposes nothing extra.
|
||||||
|
|
||||||
|
The simulation, the artwork and the music are original work. The game's *rules*
|
||||||
|
are not anyone's property, and some of the on-screen wording is quoted from the
|
||||||
|
1979 original as homage rather than authored here. [NOTICE.md](NOTICE.md) sets
|
||||||
|
out exactly what came from where, and credits the people who wrote it first.
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# games.jcoffey.dev
|
||||||
|
#
|
||||||
|
# Three containers, one domain. The host's nginx does TLS and routes paths to
|
||||||
|
# them; nothing is served off the host's disk.
|
||||||
|
#
|
||||||
|
# / -> games-hub the list of games
|
||||||
|
# /lemonade/ -> lemonade-web the game, a static bundle
|
||||||
|
# /api/ -> lemonade-scores the shared leaderboard
|
||||||
|
#
|
||||||
|
# Run from the repository root:
|
||||||
|
# docker compose -f deploy/compose.yml up -d --build
|
||||||
|
|
||||||
|
services:
|
||||||
|
games-hub:
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: hub/Dockerfile
|
||||||
|
image: games-hub:latest
|
||||||
|
container_name: games-hub
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- '127.0.0.1:5186:8080'
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
- /var/cache/nginx
|
||||||
|
- /var/run
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
|
||||||
|
lemonade-web:
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: web/Dockerfile
|
||||||
|
args:
|
||||||
|
# Must match the path the host proxies, or asset URLs will be wrong.
|
||||||
|
BASE_PATH: /lemonade/
|
||||||
|
image: lemonade-web:latest
|
||||||
|
container_name: lemonade-web
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- '127.0.0.1:5185:8080'
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
- /var/cache/nginx
|
||||||
|
- /var/run
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
|
||||||
|
lemonade-scores:
|
||||||
|
build:
|
||||||
|
context: ../server
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: lemonade-scores:latest
|
||||||
|
container_name: lemonade-scores
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- '127.0.0.1:5184:5184'
|
||||||
|
environment:
|
||||||
|
TRUST_PROXY: '1'
|
||||||
|
DB_PATH: /data/scores.db
|
||||||
|
# The only writable path, and the only state that must survive a redeploy.
|
||||||
|
volumes:
|
||||||
|
- lemonade-scores-data:/data
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
lemonade-scores-data:
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Host-side nginx for games.jcoffey.dev. TLS, logging and proxying only -
|
||||||
|
# nothing is read from disk here, every path goes to a container.
|
||||||
|
#
|
||||||
|
# Copy into the host's sites-available, adjust the certificate paths, then
|
||||||
|
# `nginx -t && systemctl reload nginx`.
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
listen [::]:443 ssl http2;
|
||||||
|
server_name games.jcoffey.dev;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/games.jcoffey.dev/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/games.jcoffey.dev/privkey.pem;
|
||||||
|
|
||||||
|
access_log /var/log/nginx/games.jcoffey.dev.access.log;
|
||||||
|
error_log /var/log/nginx/games.jcoffey.dev.error.log;
|
||||||
|
|
||||||
|
# The leaderboard. TRUST_PROXY=1 in the container means it reads the
|
||||||
|
# forwarded address, so the rate limit applies per player rather than
|
||||||
|
# counting every submission as coming from nginx.
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://127.0.0.1:5184;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /lemonade/ {
|
||||||
|
proxy_pass http://127.0.0.1:5185/;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Everything else is the list of games.
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:5186;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name games.jcoffey.dev;
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# The front door for games.jcoffey.dev. Static, no build step: adding a game is
|
||||||
|
# one more card in index.html.
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY hub/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY hub/public /usr/share/nginx/html
|
||||||
|
EXPOSE 8080
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
|
||||||
|
CMD wget -qO- http://127.0.0.1:8080/healthz >/dev/null || exit 1
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
server {
|
||||||
|
listen 8080;
|
||||||
|
server_name _;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /healthz {
|
||||||
|
access_log off;
|
||||||
|
return 200 "ok\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" shape-rendering="crispEdges">
|
||||||
|
<rect width="32" height="32" fill="#2b45b8"/>
|
||||||
|
<rect x="6" y="4" width="20" height="3" fill="#d24b3e"/>
|
||||||
|
<rect x="6" y="7" width="20" height="3" fill="#f2f6ff"/>
|
||||||
|
<rect x="10" y="12" width="12" height="12" fill="#f7de5a"/>
|
||||||
|
<rect x="12" y="10" width="8" height="2" fill="#e0a92b"/>
|
||||||
|
<rect x="22" y="15" width="3" height="5" fill="#e0a92b"/>
|
||||||
|
<rect x="6" y="25" width="20" height="3" fill="#8a5a2b"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 505 B |
@@ -0,0 +1,163 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="theme-color" content="#1d1136" />
|
||||||
|
<title>Games · jcoffey.dev</title>
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Small browser games. No accounts, no tracking, no installs — just open one and play."
|
||||||
|
/>
|
||||||
|
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--ink: #241640;
|
||||||
|
--cream: #fff6e6;
|
||||||
|
--lemon: #ffd93d;
|
||||||
|
--pink: #ff5d8f;
|
||||||
|
--teal: #2ec4b6;
|
||||||
|
--dim: #b9a9e0;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100dvh;
|
||||||
|
padding: clamp(24px, 6vw, 72px) clamp(16px, 5vw, 40px);
|
||||||
|
background:
|
||||||
|
radial-gradient(90% 60% at 15% 0%, rgba(255, 93, 143, 0.28) 0%, transparent 60%),
|
||||||
|
radial-gradient(80% 60% at 90% 15%, rgba(46, 196, 182, 0.24) 0%, transparent 55%),
|
||||||
|
radial-gradient(120% 90% at 50% 100%, #3a2168 0%, #1d1136 55%, #0e0820 100%);
|
||||||
|
background-attachment: fixed;
|
||||||
|
color: var(--cream);
|
||||||
|
font-family: ui-rounded, "Nunito", "Avenir Next", "Segoe UI", system-ui, sans-serif;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
main { width: min(760px, 100%); }
|
||||||
|
|
||||||
|
header { margin-bottom: clamp(28px, 6vw, 48px); }
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: clamp(2.4rem, 9vw, 4rem);
|
||||||
|
font-weight: 900;
|
||||||
|
letter-spacing: -0.03em;
|
||||||
|
line-height: 0.95;
|
||||||
|
color: var(--lemon);
|
||||||
|
-webkit-text-stroke: 3px var(--ink);
|
||||||
|
paint-order: stroke fill;
|
||||||
|
text-shadow: 6px 6px 0 var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
header p {
|
||||||
|
margin: 1.1rem 0 0;
|
||||||
|
max-width: 44ch;
|
||||||
|
color: var(--dim);
|
||||||
|
font-size: clamp(1rem, 2.6vw, 1.15rem);
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 20px; }
|
||||||
|
|
||||||
|
.game {
|
||||||
|
display: block;
|
||||||
|
padding: clamp(18px, 4vw, 28px);
|
||||||
|
border: 3px solid var(--ink);
|
||||||
|
border-radius: 22px;
|
||||||
|
background: linear-gradient(165deg, #5a3a9e 0%, #3c2470 100%);
|
||||||
|
box-shadow: 7px 7px 0 var(--ink);
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
transition: transform 120ms ease, box-shadow 120ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.game:hover, .game:focus-visible {
|
||||||
|
transform: translate(-3px, -3px);
|
||||||
|
box-shadow: 10px 10px 0 var(--ink);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.game:active { transform: translate(3px, 3px); box-shadow: 3px 3px 0 var(--ink); }
|
||||||
|
|
||||||
|
.game h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: clamp(1.5rem, 4.5vw, 2rem);
|
||||||
|
font-weight: 900;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.game p { margin: 0.6rem 0 0; color: var(--dim); line-height: 1.55; max-width: 52ch; }
|
||||||
|
|
||||||
|
.tags { margin-top: 1rem; display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
|
||||||
|
.tags span {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
padding: 0.28em 0.8em;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 2px solid var(--ink);
|
||||||
|
background: var(--lemon);
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tags span.alt { background: var(--teal); }
|
||||||
|
.tags span.alt2 { background: var(--pink); color: var(--cream); }
|
||||||
|
|
||||||
|
footer {
|
||||||
|
margin-top: clamp(36px, 8vw, 64px);
|
||||||
|
color: var(--dim);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer a { color: var(--lemon); }
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.game { transition: none; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<header>
|
||||||
|
<h1>Games</h1>
|
||||||
|
<p>
|
||||||
|
Small browser games. Nothing to install, no account to make, and no
|
||||||
|
tracking — open one and play.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<a class="game" href="/lemonade/">
|
||||||
|
<h2>Lemonade Stand</h2>
|
||||||
|
<p>
|
||||||
|
The 1979 business sim, rebuilt. Read the weather, buy your glasses,
|
||||||
|
price the jug and hope it doesn't rain. Play it as the Atari left
|
||||||
|
it, or in a cel-shaded remaster with a funk band — same rules
|
||||||
|
either way.
|
||||||
|
</p>
|
||||||
|
<div class="tags">
|
||||||
|
<span>1–4 players</span>
|
||||||
|
<span class="alt">Leaderboard</span>
|
||||||
|
<span class="alt2">Remastered</span>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<p>
|
||||||
|
Free software, AGPL-3.0-or-later. Built by John Coffey.
|
||||||
|
</p>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+9
-4
@@ -1,13 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "lemonade",
|
"name": "lemonade-stand",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "1.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
"lint": "oxlint",
|
"lint": "oxlint",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"scores": "node --watch server/src/index.ts",
|
||||||
|
"dev:all": "node scripts/dev-all.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"react": "^19.2.8",
|
"react": "^19.2.8",
|
||||||
@@ -21,5 +23,8 @@
|
|||||||
"oxlint": "^1.79.0",
|
"oxlint": "^1.79.0",
|
||||||
"typescript": "~6.0.2",
|
"typescript": "~6.0.2",
|
||||||
"vite": "^8.2.2"
|
"vite": "^8.2.2"
|
||||||
}
|
},
|
||||||
|
"description": "A browser recreation of the Atari 8-bit BASIC classic, with a cel-shaded remaster.",
|
||||||
|
"license": "AGPL-3.0-or-later",
|
||||||
|
"author": "John Coffey"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Runs the game and the scores service together, so `npm run dev:all` is all
|
||||||
|
// you need for a working leaderboard on localhost.
|
||||||
|
import { spawn } from 'node:child_process'
|
||||||
|
|
||||||
|
const children = [
|
||||||
|
spawn('npm', ['run', 'scores'], { stdio: 'inherit', shell: false }),
|
||||||
|
spawn('npm', ['run', 'dev'], { stdio: 'inherit', shell: false }),
|
||||||
|
]
|
||||||
|
|
||||||
|
const stop = () => {
|
||||||
|
for (const c of children) c.kill('SIGTERM')
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
process.on('SIGINT', stop)
|
||||||
|
process.on('SIGTERM', stop)
|
||||||
|
for (const c of children) c.on('exit', stop)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# node:sqlite is built into the runtime and the server runs straight from
|
||||||
|
# TypeScript, so there is no build stage, no compiler and no native module.
|
||||||
|
FROM node:26-alpine
|
||||||
|
|
||||||
|
ENV NODE_ENV=production \
|
||||||
|
PORT=5184 \
|
||||||
|
DB_PATH=/data/scores.db \
|
||||||
|
TRUST_PROXY=1
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY src ./src
|
||||||
|
|
||||||
|
# The database is the only writable path; everything else can stay read-only.
|
||||||
|
RUN mkdir -p /data && chown -R node:node /data
|
||||||
|
USER node
|
||||||
|
VOLUME ["/data"]
|
||||||
|
EXPOSE 5184
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD node -e "fetch('http://127.0.0.1:5184/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
||||||
|
|
||||||
|
CMD ["node", "src/index.ts"]
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# Lemonade scores service
|
||||||
|
|
||||||
|
The leaderboard everybody shares. A single Node process with SQLite, no build
|
||||||
|
step and no native modules: `node:sqlite` ships with the runtime and Node runs
|
||||||
|
the TypeScript directly.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
| Method | Path | Purpose |
|
||||||
|
| ------ | -------------- | ------------------------------------------- |
|
||||||
|
| GET | `/api/health` | liveness, used by the container healthcheck |
|
||||||
|
| GET | `/api/scores` | the top 50, best first |
|
||||||
|
| POST | `/api/scores` | submit 1–4 players from one finished season |
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
// POST /api/scores
|
||||||
|
{ "entries": [ { "name": "ADA", "assets": 4635, "days": 12,
|
||||||
|
"glasses": 800, "seed": 1234, "broke": false } ] }
|
||||||
|
// 201 -> { "ids": ["17"], "scores": [ ...the new board... ] }
|
||||||
|
```
|
||||||
|
|
||||||
|
## What it does and does not guarantee
|
||||||
|
|
||||||
|
Everything in a request is treated as hostile. Names are forced to a printable
|
||||||
|
uppercase subset and cut to 12 characters. Every number must be an integer in
|
||||||
|
range, and a score is refused if it could not have happened: assets above
|
||||||
|
`$2.00 + $25 a day`, or glasses above 400 a day, are rejected as impossible for
|
||||||
|
the days claimed. Bodies are capped at 4 KB and submissions at 30 an hour per
|
||||||
|
address, which is why `TRUST_PROXY=1` matters behind nginx — otherwise every
|
||||||
|
request looks like it came from the proxy.
|
||||||
|
|
||||||
|
**It cannot prove a score is real.** There are no accounts and no signing, so
|
||||||
|
anyone willing to craft a request can post a plausible score under any name.
|
||||||
|
The checks stop nonsense and casual spam, not a determined forger. That is a
|
||||||
|
deliberate trade for a game with no sign-up; if the board ever needs to be
|
||||||
|
trustworthy it needs identities, which is a different piece of work.
|
||||||
|
|
||||||
|
Only the best 500 rows are kept; the rest are pruned on write.
|
||||||
|
|
||||||
|
## Running it
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run scores # from the repo root, on :5184
|
||||||
|
npm run dev:all # game and scores service together
|
||||||
|
```
|
||||||
|
|
||||||
|
Environment: `PORT` (5184), `DB_PATH` (`./data/scores.db`), `TRUST_PROXY`
|
||||||
|
(`1` behind a proxy).
|
||||||
|
|
||||||
|
## Deploying
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f server/compose.yml up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
The container is read-only apart from the named volume holding the database —
|
||||||
|
that volume is the one piece of state that must survive a redeploy. In front
|
||||||
|
of it, nginx terminates TLS and proxies `/api/` through:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://127.0.0.1:5184;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The game itself is a static bundle and needs no server; point it at another
|
||||||
|
origin with `VITE_SCORES_API=https://example.org/api` at build time, or serve
|
||||||
|
both from one origin and leave it on the default `/api`.
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
||||||
|
import { DatabaseSync } from 'node:sqlite'
|
||||||
|
import { mkdirSync } from 'node:fs'
|
||||||
|
import { dirname } from 'node:path'
|
||||||
|
import { MAX_ENTRIES_PER_POST, validateBatch } from './validate.ts'
|
||||||
|
|
||||||
|
const PORT = Number(process.env.PORT ?? 5184)
|
||||||
|
const DB_PATH = process.env.DB_PATH ?? './data/scores.db'
|
||||||
|
/** Behind nginx the socket address is the proxy, so take the forwarded hop. */
|
||||||
|
const TRUST_PROXY = process.env.TRUST_PROXY === '1'
|
||||||
|
const BOARD_LIMIT = 50
|
||||||
|
/** Rows kept on disk. The board only ever shows the top of this. */
|
||||||
|
const KEEP_ROWS = 500
|
||||||
|
const MAX_BODY_BYTES = 4096
|
||||||
|
|
||||||
|
mkdirSync(dirname(DB_PATH), { recursive: true })
|
||||||
|
const db = new DatabaseSync(DB_PATH)
|
||||||
|
db.exec(`
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
CREATE TABLE IF NOT EXISTS scores (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
assets INTEGER NOT NULL,
|
||||||
|
days INTEGER NOT NULL,
|
||||||
|
glasses INTEGER NOT NULL,
|
||||||
|
seed INTEGER NOT NULL,
|
||||||
|
broke INTEGER NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS scores_rank
|
||||||
|
ON scores (assets DESC, days ASC, created_at ASC);
|
||||||
|
`)
|
||||||
|
|
||||||
|
const selectTop = db.prepare(
|
||||||
|
`SELECT id, name, assets, days, glasses, broke, created_at
|
||||||
|
FROM scores ORDER BY assets DESC, days ASC, created_at ASC LIMIT ?`,
|
||||||
|
)
|
||||||
|
const insertScore = db.prepare(
|
||||||
|
`INSERT INTO scores (name, assets, days, glasses, seed, broke, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
)
|
||||||
|
const prune = db.prepare(
|
||||||
|
`DELETE FROM scores WHERE id NOT IN (
|
||||||
|
SELECT id FROM scores ORDER BY assets DESC, days ASC, created_at ASC LIMIT ?
|
||||||
|
)`,
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- throttle
|
||||||
|
|
||||||
|
interface Bucket {
|
||||||
|
count: number
|
||||||
|
resetAt: number
|
||||||
|
}
|
||||||
|
const posts = new Map<string, Bucket>()
|
||||||
|
const POST_WINDOW_MS = 60 * 60 * 1000
|
||||||
|
const POST_LIMIT = 30
|
||||||
|
|
||||||
|
function overPostLimit(ip: string): boolean {
|
||||||
|
const now = Date.now()
|
||||||
|
const b = posts.get(ip)
|
||||||
|
if (!b || now > b.resetAt) {
|
||||||
|
posts.set(ip, { count: 1, resetAt: now + POST_WINDOW_MS })
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.count += 1
|
||||||
|
return b.count > POST_LIMIT
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buckets are tiny, but a long-lived process should still not hoard them.
|
||||||
|
setInterval(() => {
|
||||||
|
const now = Date.now()
|
||||||
|
for (const [ip, b] of posts) if (now > b.resetAt) posts.delete(ip)
|
||||||
|
}, POST_WINDOW_MS).unref()
|
||||||
|
|
||||||
|
function clientIp(req: IncomingMessage): string {
|
||||||
|
if (TRUST_PROXY) {
|
||||||
|
const fwd = req.headers['x-forwarded-for']
|
||||||
|
const first = (Array.isArray(fwd) ? fwd[0] : fwd)?.split(',')[0]?.trim()
|
||||||
|
if (first) return first
|
||||||
|
}
|
||||||
|
return req.socket.remoteAddress ?? 'unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ replies
|
||||||
|
|
||||||
|
function send(res: ServerResponse, status: number, body: unknown) {
|
||||||
|
const payload = JSON.stringify(body)
|
||||||
|
res.writeHead(status, {
|
||||||
|
'content-type': 'application/json; charset=utf-8',
|
||||||
|
'cache-control': 'no-store',
|
||||||
|
// A public board with no cookies and no credentials.
|
||||||
|
'access-control-allow-origin': '*',
|
||||||
|
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
||||||
|
'access-control-allow-headers': 'content-type',
|
||||||
|
'access-control-max-age': '86400',
|
||||||
|
})
|
||||||
|
res.end(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBody(req: IncomingMessage): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let size = 0
|
||||||
|
const chunks: Buffer[] = []
|
||||||
|
req.on('data', (c: Buffer) => {
|
||||||
|
size += c.length
|
||||||
|
if (size > MAX_BODY_BYTES) {
|
||||||
|
reject(new Error('body too large'))
|
||||||
|
req.destroy()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chunks.push(c)
|
||||||
|
})
|
||||||
|
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
||||||
|
req.on('error', reject)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------- routes
|
||||||
|
|
||||||
|
const board = () =>
|
||||||
|
(selectTop.all(BOARD_LIMIT) as Record<string, unknown>[]).map((r) => ({
|
||||||
|
id: String(r.id),
|
||||||
|
name: r.name as string,
|
||||||
|
assets: r.assets as number,
|
||||||
|
days: r.days as number,
|
||||||
|
glasses: r.glasses as number,
|
||||||
|
broke: r.broke === 1,
|
||||||
|
at: r.created_at as number,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const server = createServer(async (req, res) => {
|
||||||
|
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)
|
||||||
|
const path = url.pathname.replace(/\/+$/, '') || '/'
|
||||||
|
|
||||||
|
if (req.method === 'OPTIONS') return send(res, 204, {})
|
||||||
|
if (path === '/api/health') return send(res, 200, { ok: true })
|
||||||
|
|
||||||
|
if (path === '/api/scores' && req.method === 'GET') {
|
||||||
|
return send(res, 200, { scores: board() })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/api/scores' && req.method === 'POST') {
|
||||||
|
const ip = clientIp(req)
|
||||||
|
if (overPostLimit(ip)) return send(res, 429, { error: 'too many submissions' })
|
||||||
|
|
||||||
|
let parsed: unknown
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(await readBody(req))
|
||||||
|
} catch {
|
||||||
|
return send(res, 400, { error: 'invalid JSON' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const check = validateBatch(parsed)
|
||||||
|
if (!check.ok) return send(res, 400, { error: check.why })
|
||||||
|
|
||||||
|
const now = Date.now()
|
||||||
|
const ids: string[] = []
|
||||||
|
for (const e of check.entries) {
|
||||||
|
const info = insertScore.run(e.name, e.assets, e.days, e.glasses, e.seed, e.broke ? 1 : 0, now)
|
||||||
|
ids.push(String(info.lastInsertRowid))
|
||||||
|
}
|
||||||
|
prune.run(KEEP_ROWS)
|
||||||
|
|
||||||
|
return send(res, 201, { ids, scores: board() })
|
||||||
|
}
|
||||||
|
|
||||||
|
send(res, 404, { error: 'not found' })
|
||||||
|
})
|
||||||
|
|
||||||
|
server.listen(PORT, () => {
|
||||||
|
console.log(`[scores] listening on :${PORT}, db ${DB_PATH}, max ${MAX_ENTRIES_PER_POST}/post`)
|
||||||
|
})
|
||||||
|
|
||||||
|
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
|
||||||
|
process.on(sig, () => {
|
||||||
|
server.close(() => {
|
||||||
|
db.close()
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
/**
|
||||||
|
* Everything here treats the request body as hostile. A public leaderboard
|
||||||
|
* with no accounts cannot prove a score is real - what it can do is refuse
|
||||||
|
* anything impossible, keep names printable, and stop one client filling the
|
||||||
|
* table on its own.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface Entry {
|
||||||
|
name: string
|
||||||
|
assets: number
|
||||||
|
days: number
|
||||||
|
glasses: number
|
||||||
|
seed: number
|
||||||
|
broke: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MAX_ENTRIES_PER_POST = 4
|
||||||
|
export const NAME_MAX = 12
|
||||||
|
|
||||||
|
/** The simulation's best possible day is about $12.50; $25 leaves headroom. */
|
||||||
|
const MAX_CENTS_PER_DAY = 2500
|
||||||
|
const STARTING_ASSETS = 200
|
||||||
|
const MAX_GLASSES_PER_DAY = 400
|
||||||
|
const MAX_DAYS = 365
|
||||||
|
|
||||||
|
const isInt = (v: unknown, lo: number, hi: number): v is number =>
|
||||||
|
typeof v === 'number' && Number.isInteger(v) && v >= lo && v <= hi
|
||||||
|
|
||||||
|
/** Printable, uppercase, and short enough to fit the board. */
|
||||||
|
export function cleanName(raw: unknown): string {
|
||||||
|
if (typeof raw !== 'string') return 'ANON'
|
||||||
|
const cleaned = raw
|
||||||
|
.toUpperCase()
|
||||||
|
.replace(/[^A-Z0-9 .'-]/g, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.slice(0, NAME_MAX)
|
||||||
|
return cleaned || 'ANON'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Validated = { ok: true; entry: Entry } | { ok: false; why: string }
|
||||||
|
|
||||||
|
export function validateEntry(raw: unknown): Validated {
|
||||||
|
if (typeof raw !== 'object' || raw === null) return { ok: false, why: 'not an object' }
|
||||||
|
const e = raw as Record<string, unknown>
|
||||||
|
|
||||||
|
if (!isInt(e.days, 1, MAX_DAYS)) return { ok: false, why: 'days out of range' }
|
||||||
|
if (!isInt(e.assets, 0, 10_000_00)) return { ok: false, why: 'assets out of range' }
|
||||||
|
if (!isInt(e.glasses, 0, MAX_DAYS * MAX_GLASSES_PER_DAY))
|
||||||
|
return { ok: false, why: 'glasses out of range' }
|
||||||
|
if (!isInt(e.seed, 0, 9_999_999)) return { ok: false, why: 'seed out of range' }
|
||||||
|
if (typeof e.broke !== 'boolean') return { ok: false, why: 'broke must be a boolean' }
|
||||||
|
|
||||||
|
// No stand can earn more than the simulation allows in the days it traded.
|
||||||
|
if (e.assets > STARTING_ASSETS + e.days * MAX_CENTS_PER_DAY)
|
||||||
|
return { ok: false, why: 'assets impossible for that many days' }
|
||||||
|
if (e.glasses > e.days * MAX_GLASSES_PER_DAY)
|
||||||
|
return { ok: false, why: 'glasses impossible for that many days' }
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
entry: {
|
||||||
|
name: cleanName(e.name),
|
||||||
|
assets: e.assets,
|
||||||
|
days: e.days,
|
||||||
|
glasses: e.glasses,
|
||||||
|
seed: e.seed,
|
||||||
|
broke: e.broke,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateBatch(raw: unknown): { ok: true; entries: Entry[] } | { ok: false; why: string } {
|
||||||
|
const list = Array.isArray(raw) ? raw : (raw as { entries?: unknown })?.entries
|
||||||
|
if (!Array.isArray(list)) return { ok: false, why: 'expected an array of entries' }
|
||||||
|
if (list.length === 0) return { ok: false, why: 'no entries' }
|
||||||
|
if (list.length > MAX_ENTRIES_PER_POST) return { ok: false, why: 'too many entries' }
|
||||||
|
|
||||||
|
const entries: Entry[] = []
|
||||||
|
for (const item of list) {
|
||||||
|
const v = validateEntry(item)
|
||||||
|
if (!v.ok) return v
|
||||||
|
entries.push(v.entry)
|
||||||
|
}
|
||||||
|
return { ok: true, entries }
|
||||||
|
}
|
||||||
@@ -452,6 +452,12 @@ html[data-skin='modern'] .statusbar {
|
|||||||
.cel-sign { font-size: 21px; fill: #d1483f; letter-spacing: 0.5px; }
|
.cel-sign { font-size: 21px; fill: #d1483f; letter-spacing: 0.5px; }
|
||||||
.cel-price { font-size: 12px; fill: #5a3ea8; }
|
.cel-price { font-size: 12px; fill: #5a3ea8; }
|
||||||
|
|
||||||
|
.cel-bunting { animation: cel-bunting 5s ease-in-out infinite alternate; }
|
||||||
|
@keyframes cel-bunting {
|
||||||
|
from { transform: translateY(0) rotate(-0.4deg); }
|
||||||
|
to { transform: translateY(3px) rotate(0.4deg); }
|
||||||
|
}
|
||||||
|
|
||||||
.cel-rays { animation: cel-spin 72s linear infinite; }
|
.cel-rays { animation: cel-spin 72s linear infinite; }
|
||||||
@keyframes cel-spin { to { transform: rotate(360deg); } }
|
@keyframes cel-spin { to { transform: rotate(360deg); } }
|
||||||
|
|
||||||
|
|||||||
+39
-25
@@ -5,16 +5,16 @@ import { synth } from './audio/synth'
|
|||||||
import { WEATHER } from './game/constants'
|
import { WEATHER } from './game/constants'
|
||||||
import { dollars, randomSeed, rollDay, simulate } from './game/engine'
|
import { dollars, randomSeed, rollDay, simulate } from './game/engine'
|
||||||
import { makeRng, type Rng } from './game/rng'
|
import { makeRng, type Rng } from './game/rng'
|
||||||
import { HIGH_SCORE_KEY, addScores, loadScores, type Score } from './game/highscores'
|
import { fetchScores, submitScores, type Score } from './game/highscores'
|
||||||
import { activePlayers, initialState, reducer } from './game/reducer'
|
import { activePlayers, initialState, reducer } from './game/reducer'
|
||||||
import type { Decision } from './game/types'
|
import type { CarryOver, Decision } from './game/types'
|
||||||
import { useSkin } from './skin'
|
import { useSkin } from './skin'
|
||||||
import { BootScreen } from './components/BootScreen'
|
import { BootScreen } from './components/BootScreen'
|
||||||
import { BriefingScreen } from './components/BriefingScreen'
|
import { BriefingScreen } from './components/BriefingScreen'
|
||||||
import { Btn, Crt, Fit } from './components/Crt'
|
import { Btn, Crt, Fit } from './components/Crt'
|
||||||
import { DecideScreen } from './components/DecideScreen'
|
import { DecideScreen } from './components/DecideScreen'
|
||||||
import { GameOverScreen } from './components/GameOverScreen'
|
import { GameOverScreen } from './components/GameOverScreen'
|
||||||
import { HighScoreScreen } from './components/HighScoreScreen'
|
import { HighScoreScreen, type BoardState } from './components/HighScoreScreen'
|
||||||
import { IntroScreen } from './components/IntroScreen'
|
import { IntroScreen } from './components/IntroScreen'
|
||||||
import { ReportScreen } from './components/ReportScreen'
|
import { ReportScreen } from './components/ReportScreen'
|
||||||
import { TradingScreen } from './components/TradingScreen'
|
import { TradingScreen } from './components/TradingScreen'
|
||||||
@@ -30,7 +30,8 @@ export default function App() {
|
|||||||
const [sfx, setSfx] = useState(true)
|
const [sfx, setSfx] = useState(true)
|
||||||
const started = useRef(false)
|
const started = useRef(false)
|
||||||
const { skin, toggle: toggleSkin } = useSkin()
|
const { skin, toggle: toggleSkin } = useSkin()
|
||||||
const [scores, setScores] = useState<Score[]>(loadScores)
|
const [scores, setScores] = useState<Score[]>([])
|
||||||
|
const [boardState, setBoardState] = useState<BoardState>('loading')
|
||||||
const [freshScores, setFreshScores] = useState<string[]>([])
|
const [freshScores, setFreshScores] = useState<string[]>([])
|
||||||
|
|
||||||
const active = activePlayers(state)
|
const active = activePlayers(state)
|
||||||
@@ -65,17 +66,15 @@ export default function App() {
|
|||||||
synth.setSfx(sfx)
|
synth.setSfx(sfx)
|
||||||
}, [sfx])
|
}, [sfx])
|
||||||
|
|
||||||
/**
|
/** The board lives in town, so it is fetched rather than remembered. */
|
||||||
* Two tabs in one browser share localStorage. Nothing else is shared - the
|
const loadBoard = useCallback(async () => {
|
||||||
* game itself lives entirely in the page - but the table should not go
|
setBoardState('loading')
|
||||||
* stale just because the other tab finished a season first.
|
try {
|
||||||
*/
|
setScores(await fetchScores())
|
||||||
useEffect(() => {
|
setBoardState('ready')
|
||||||
const onStorage = (e: StorageEvent) => {
|
} catch {
|
||||||
if (e.key === HIGH_SCORE_KEY || e.key === null) setScores(loadScores())
|
setBoardState('error')
|
||||||
}
|
}
|
||||||
window.addEventListener('storage', onStorage)
|
|
||||||
return () => window.removeEventListener('storage', onStorage)
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const blip = useCallback(() => synth.blip(), [])
|
const blip = useCallback(() => synth.blip(), [])
|
||||||
@@ -101,8 +100,8 @@ export default function App() {
|
|||||||
// -------------------------------------------------------------- handlers
|
// -------------------------------------------------------------- handlers
|
||||||
|
|
||||||
const beginDay = useCallback(
|
const beginDay = useCallback(
|
||||||
(day: number, streetCrewYesterday: boolean) => {
|
(day: number, yesterday: CarryOver) => {
|
||||||
const conditions = rollDay(day, rng.current, streetCrewYesterday)
|
const conditions = rollDay(day, rng.current, yesterday)
|
||||||
dispatch({ type: 'BEGIN_DAY', conditions })
|
dispatch({ type: 'BEGIN_DAY', conditions })
|
||||||
if (conditions.heatWave) synth.heat()
|
if (conditions.heatWave) synth.heat()
|
||||||
else if (conditions.weather === 'sunny') synth.sunshine()
|
else if (conditions.weather === 'sunny') synth.sunshine()
|
||||||
@@ -114,7 +113,7 @@ export default function App() {
|
|||||||
wake()
|
wake()
|
||||||
synth.select()
|
synth.select()
|
||||||
dispatch({ type: 'START', names })
|
dispatch({ type: 'START', names })
|
||||||
beginDay(1, false)
|
beginDay(1, { streetCrew: false, rival: false })
|
||||||
}
|
}
|
||||||
|
|
||||||
const submit = (decision: Decision) => {
|
const submit = (decision: Decision) => {
|
||||||
@@ -140,27 +139,36 @@ export default function App() {
|
|||||||
const nextDay = () => {
|
const nextDay = () => {
|
||||||
synth.select()
|
synth.select()
|
||||||
dispatch({ type: 'NEXT_DAY' })
|
dispatch({ type: 'NEXT_DAY' })
|
||||||
beginDay(state.day + 1, state.streetCrewYesterday)
|
beginDay(state.day + 1, state.yesterday)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Close the books: everyone who traded gets a line in the table. */
|
/**
|
||||||
|
* Close the books. The standings show straight away; posting to the town
|
||||||
|
* board happens behind them, so a slow or missing line out never holds the
|
||||||
|
* end of a season hostage.
|
||||||
|
*/
|
||||||
const retire = () => {
|
const retire = () => {
|
||||||
synth.fanfare()
|
synth.fanfare()
|
||||||
const glassesFor = (id: number) =>
|
const glassesFor = (id: number) =>
|
||||||
state.history.reduce((n, r) => (r.playerId === id ? n + r.glassesSold : n), 0)
|
state.history.reduce((n, r) => (r.playerId === id ? n + r.glassesSold : n), 0)
|
||||||
const { table, added } = addScores(
|
const entries = state.players.map((p) => ({
|
||||||
state.players.map((p) => ({
|
|
||||||
name: p.name,
|
name: p.name,
|
||||||
assets: p.assets,
|
assets: p.assets,
|
||||||
days: p.bankruptDay ?? state.day,
|
days: p.bankruptDay ?? state.day,
|
||||||
glasses: glassesFor(p.id),
|
glasses: glassesFor(p.id),
|
||||||
seed: state.seed,
|
seed: state.seed,
|
||||||
broke: p.bankrupt,
|
broke: p.bankrupt,
|
||||||
})),
|
}))
|
||||||
)
|
|
||||||
setScores(table)
|
|
||||||
setFreshScores(added)
|
|
||||||
dispatch({ type: 'RETIRE' })
|
dispatch({ type: 'RETIRE' })
|
||||||
|
setBoardState('loading')
|
||||||
|
submitScores(entries)
|
||||||
|
.then(({ ids, scores: table }) => {
|
||||||
|
setScores(table)
|
||||||
|
setFreshScores(ids)
|
||||||
|
setBoardState('ready')
|
||||||
|
})
|
||||||
|
.catch(() => setBoardState('error'))
|
||||||
}
|
}
|
||||||
|
|
||||||
const restart = () => {
|
const restart = () => {
|
||||||
@@ -174,6 +182,7 @@ export default function App() {
|
|||||||
wake()
|
wake()
|
||||||
synth.select()
|
synth.select()
|
||||||
dispatch({ type: 'SHOW_SCORES' })
|
dispatch({ type: 'SHOW_SCORES' })
|
||||||
|
if (boardState !== 'ready') void loadBoard()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- render
|
// ---------------------------------------------------------------- render
|
||||||
@@ -317,11 +326,16 @@ export default function App() {
|
|||||||
{state.phase === 'scores' && (
|
{state.phase === 'scores' && (
|
||||||
<HighScoreScreen
|
<HighScoreScreen
|
||||||
scores={scores}
|
scores={scores}
|
||||||
|
state={boardState}
|
||||||
highlight={freshScores}
|
highlight={freshScores}
|
||||||
onBack={() => {
|
onBack={() => {
|
||||||
synth.select()
|
synth.select()
|
||||||
dispatch({ type: 'CLOSE_SCORES' })
|
dispatch({ type: 'CLOSE_SCORES' })
|
||||||
}}
|
}}
|
||||||
|
onRetry={() => {
|
||||||
|
synth.select()
|
||||||
|
void loadBoard()
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Fit>
|
</Fit>
|
||||||
|
|||||||
@@ -39,6 +39,22 @@ export function BriefingScreen({
|
|||||||
<Line className="warn">STREET.</Line>
|
<Line className="warn">STREET.</Line>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{conditions.festival && (
|
||||||
|
<>
|
||||||
|
<Line />
|
||||||
|
<Line className="accent">THE SUMMER FAIR IS ON TODAY. HALF</Line>
|
||||||
|
<Line className="accent">THE TOWN WILL COME PAST, AND THEY</Line>
|
||||||
|
<Line className="accent">ARE OUT TO SPEND.</Line>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{conditions.rival && (
|
||||||
|
<>
|
||||||
|
<Line />
|
||||||
|
<Line className="warn">SOMEBODY HAS SET UP A STAND ON THE</Line>
|
||||||
|
<Line className="warn">NEXT CORNER. YOU WILL BE SPLITTING</Line>
|
||||||
|
<Line className="warn">THE STREET WITH THEM.</Line>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<Line />
|
<Line />
|
||||||
<div className="row center">
|
<div className="row center">
|
||||||
<Btn kind="primary" onClick={onContinue}>
|
<Btn kind="primary" onClick={onContinue}>
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ export function CelScene({
|
|||||||
traffic?: number
|
traffic?: number
|
||||||
variant?: 'full' | 'strip'
|
variant?: 'full' | 'strip'
|
||||||
}) {
|
}) {
|
||||||
const { weather, heatWave, streetCrew, storm } = conditions
|
const { weather, heatWave, streetCrew, festival, rival, storm } = conditions
|
||||||
const key = storm ? 'storm' : weather
|
const key = storm ? 'storm' : weather
|
||||||
const m = MOODS[key] ?? MOODS.sunny
|
const m = MOODS[key] ?? MOODS.sunny
|
||||||
const daylight = !storm && weather !== 'cloudy'
|
const daylight = !storm && weather !== 'cloudy'
|
||||||
@@ -206,6 +206,19 @@ export function CelScene({
|
|||||||
<rect x="0" y="252" width="640" height="8" fill={m.groundShade} opacity="0.5" />
|
<rect x="0" y="252" width="640" height="8" fill={m.groundShade} opacity="0.5" />
|
||||||
<rect x="0" y="248" width="640" height="5" fill={INK} opacity="0.35" />
|
<rect x="0" y="248" width="640" height="5" fill={INK} opacity="0.35" />
|
||||||
|
|
||||||
|
{/* --- the competition, small and further down the street ---- */}
|
||||||
|
{rival && (
|
||||||
|
<g stroke={INK} strokeWidth="3" strokeLinejoin="round" opacity="0.9">
|
||||||
|
<ellipse cx="566" cy="256" rx="52" ry="6" fill={INK} opacity={m.shadow} stroke="none" />
|
||||||
|
<rect x="524" y="208" width="7" height="48" fill="#9A6435" />
|
||||||
|
<rect x="601" y="208" width="7" height="48" fill="#9A6435" />
|
||||||
|
<path d="M516 190 H616 V206 q-12 12 -25 0 q-12 12 -25 0 q-12 12 -25 0 q-12 12 -25 0 Z" fill="#4FC3F7" />
|
||||||
|
<rect x="512" y="184" width="108" height="9" rx="4" fill="#E0A867" />
|
||||||
|
<rect x="518" y="230" width="96" height="12" rx="3" fill="#E0A867" />
|
||||||
|
<rect x="524" y="242" width="84" height="16" rx="3" fill="#FFF6DC" />
|
||||||
|
</g>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* --- the stand --------------------------------------------- */}
|
{/* --- the stand --------------------------------------------- */}
|
||||||
<g stroke={INK} strokeWidth="4" strokeLinejoin="round">
|
<g stroke={INK} strokeWidth="4" strokeLinejoin="round">
|
||||||
<ellipse cx="320" cy="286" rx="150" ry="13" fill={INK} opacity={m.shadow} stroke="none" />
|
<ellipse cx="320" cy="286" rx="150" ry="13" fill={INK} opacity={m.shadow} stroke="none" />
|
||||||
@@ -280,6 +293,30 @@ export function CelScene({
|
|||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
|
|
||||||
|
{/* --- the fair ---------------------------------------------- */}
|
||||||
|
{festival && (
|
||||||
|
<g className="cel-bunting">
|
||||||
|
<path d="M-10 70 Q160 118 330 74 T670 84" fill="none" stroke={INK} strokeWidth="3" />
|
||||||
|
{Array.from({ length: 22 }, (_, i) => {
|
||||||
|
const t = i / 21
|
||||||
|
// Follows the same sag as the line above it.
|
||||||
|
const x = -10 + t * 680
|
||||||
|
const y = 70 + Math.sin(t * Math.PI * 2) * 6 + 34 * Math.sin(t * Math.PI)
|
||||||
|
const fill = ['#FF5D8F', '#FFD93D', '#2EC4B6', '#8E7DFF'][i % 4]
|
||||||
|
return (
|
||||||
|
<path
|
||||||
|
key={i}
|
||||||
|
d={`M${x - 8} ${y} L${x + 8} ${y} L${x} ${y + 17} Z`}
|
||||||
|
fill={fill}
|
||||||
|
stroke={INK}
|
||||||
|
strokeWidth="2.5"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</g>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* --- the street ------------------------------------------- */}
|
{/* --- the street ------------------------------------------- */}
|
||||||
{walkers.map((w) => (
|
{walkers.map((w) => (
|
||||||
<g
|
<g
|
||||||
|
|||||||
@@ -2,17 +2,23 @@ import { dollars } from '../game/engine'
|
|||||||
import { MAX_SCORES, type Score } from '../game/highscores'
|
import { MAX_SCORES, type Score } from '../game/highscores'
|
||||||
import { Btn, Line } from './Crt'
|
import { Btn, Line } from './Crt'
|
||||||
|
|
||||||
|
export type BoardState = 'loading' | 'ready' | 'error'
|
||||||
|
|
||||||
const shortDate = (at: number) =>
|
const shortDate = (at: number) =>
|
||||||
new Date(at).toLocaleDateString(undefined, { day: '2-digit', month: 'short' }).toUpperCase()
|
new Date(at).toLocaleDateString(undefined, { day: '2-digit', month: 'short' }).toUpperCase()
|
||||||
|
|
||||||
export function HighScoreScreen({
|
export function HighScoreScreen({
|
||||||
scores,
|
scores,
|
||||||
|
state,
|
||||||
highlight,
|
highlight,
|
||||||
onBack,
|
onBack,
|
||||||
|
onRetry,
|
||||||
}: {
|
}: {
|
||||||
scores: Score[]
|
scores: Score[]
|
||||||
|
state: BoardState
|
||||||
highlight: string[]
|
highlight: string[]
|
||||||
onBack: () => void
|
onBack: () => void
|
||||||
|
onRetry: () => void
|
||||||
}) {
|
}) {
|
||||||
const fresh = new Set(highlight)
|
const fresh = new Set(highlight)
|
||||||
|
|
||||||
@@ -21,14 +27,32 @@ export function HighScoreScreen({
|
|||||||
<Line className="center inv-line">$$ BEST STANDS IN LEMONSVILLE $$</Line>
|
<Line className="center inv-line">$$ BEST STANDS IN LEMONSVILLE $$</Line>
|
||||||
<Line />
|
<Line />
|
||||||
|
|
||||||
{scores.length === 0 ? (
|
{state === 'loading' && (
|
||||||
|
<>
|
||||||
|
<Line className="center dim">CALLING LEMONSVILLE</Line>
|
||||||
|
<Line className="center blink">█</Line>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state === 'error' && (
|
||||||
|
<>
|
||||||
|
<Line className="center warn">CANNOT REACH LEMONSVILLE.</Line>
|
||||||
|
<Line />
|
||||||
|
<Line className="center dim">THE BOARD IS KEPT IN TOWN, NOT IN</Line>
|
||||||
|
<Line className="center dim">THIS BROWSER, SO IT NEEDS A LINE OUT.</Line>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state === 'ready' && scores.length === 0 && (
|
||||||
<>
|
<>
|
||||||
<Line className="center dim">NO STANDS HAVE CLOSED THEIR BOOKS YET.</Line>
|
<Line className="center dim">NO STANDS HAVE CLOSED THEIR BOOKS YET.</Line>
|
||||||
<Line />
|
<Line />
|
||||||
<Line className="center dim">RETIRE AT THE END OF A SUMMER TO</Line>
|
<Line className="center dim">RETIRE AT THE END OF A SUMMER TO</Line>
|
||||||
<Line className="center dim">TAKE A PLACE ON THIS LIST.</Line>
|
<Line className="center dim">TAKE A PLACE ON THIS LIST.</Line>
|
||||||
</>
|
</>
|
||||||
) : (
|
)}
|
||||||
|
|
||||||
|
{state === 'ready' &&
|
||||||
scores.map((s, i) => (
|
scores.map((s, i) => (
|
||||||
<div className={`report-row score-row ${fresh.has(s.id) ? 'is-new' : ''}`} key={s.id}>
|
<div className={`report-row score-row ${fresh.has(s.id) ? 'is-new' : ''}`} key={s.id}>
|
||||||
<span className="report-label">
|
<span className="report-label">
|
||||||
@@ -41,17 +65,19 @@ export function HighScoreScreen({
|
|||||||
</span>
|
</span>
|
||||||
<span className="report-value money">{dollars(s.assets)}</span>
|
<span className="report-value money">{dollars(s.assets)}</span>
|
||||||
</div>
|
</div>
|
||||||
))
|
))}
|
||||||
)}
|
|
||||||
|
|
||||||
<Line />
|
<Line />
|
||||||
<Line className="center dim">TOP {MAX_SCORES}, KEPT IN THIS BROWSER.</Line>
|
<Line className="center dim">
|
||||||
<Line className="center dim">A STAND LEAVES ONLY BY BEING BEATEN.</Line>
|
{state === 'ready'
|
||||||
<Line />
|
? `TOP ${MAX_SCORES}, FROM EVERY STAND IN TOWN.`
|
||||||
|
: ' '}
|
||||||
|
</Line>
|
||||||
<div className="row center">
|
<div className="row center">
|
||||||
<Btn kind="primary" onClick={onBack}>
|
<Btn kind="primary" onClick={onBack}>
|
||||||
BACK
|
BACK
|
||||||
</Btn>
|
</Btn>
|
||||||
|
{state !== 'loading' && <Btn onClick={onRetry}>REFRESH</Btn>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ function cloud(cx: number, cy: number, fill: string): Rect[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function PixelScene({ conditions, price }: { conditions: DayConditions; price?: number }) {
|
export function PixelScene({ conditions, price }: { conditions: DayConditions; price?: number }) {
|
||||||
const { weather, heatWave, streetCrew, storm } = conditions
|
const { weather, heatWave, streetCrew, festival, rival, storm } = conditions
|
||||||
|
|
||||||
const sky = useMemo(() => {
|
const sky = useMemo(() => {
|
||||||
if (storm) return ['#2b3350', '#3d4468']
|
if (storm) return ['#2b3350', '#3d4468']
|
||||||
@@ -138,6 +138,27 @@ export function PixelScene({ conditions, price }: { conditions: DayConditions; p
|
|||||||
rects.push({ x: 0, y: ROWS - 1, w: COLS, fill: PALETTE.e })
|
rects.push({ x: 0, y: ROWS - 1, w: COLS, fill: PALETTE.e })
|
||||||
rects.push({ x: 0, y: ROWS - 2, w: COLS, fill: '#6fc258' })
|
rects.push({ x: 0, y: ROWS - 2, w: COLS, fill: '#6fc258' })
|
||||||
|
|
||||||
|
if (festival) {
|
||||||
|
// A line of bunting strung above the stand.
|
||||||
|
for (let x = 2; x < COLS - 2; x += 2) {
|
||||||
|
rects.push({ x, y: 3 + (x % 4 === 0 ? 0 : 1), w: 1, fill: x % 4 === 0 ? PALETTE.r : PALETTE.Y })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rival) {
|
||||||
|
// A smaller stand further down the street.
|
||||||
|
rects.push(
|
||||||
|
{ x: 33, y: 13, w: 6, fill: PALETTE.c },
|
||||||
|
{ x: 33, y: 14, w: 6, fill: PALETTE.w },
|
||||||
|
{ x: 33, y: 15, w: 1, fill: PALETTE.n },
|
||||||
|
{ x: 38, y: 15, w: 1, fill: PALETTE.n },
|
||||||
|
{ x: 33, y: 16, w: 6, fill: PALETTE.n },
|
||||||
|
{ x: 33, y: 17, w: 6, fill: PALETTE.w },
|
||||||
|
{ x: 33, y: 18, w: 1, fill: PALETTE.n },
|
||||||
|
{ x: 38, y: 18, w: 1, fill: PALETTE.n },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (streetCrew) {
|
if (streetCrew) {
|
||||||
// A pair of road cones and a barrier where the customers used to walk.
|
// A pair of road cones and a barrier where the customers used to walk.
|
||||||
for (const cx of [2, 36]) {
|
for (const cx of [2, 36]) {
|
||||||
|
|||||||
@@ -41,7 +41,9 @@ export function ReportScreen({
|
|||||||
const events = [
|
const events = [
|
||||||
WEATHER[conditions.weather].label,
|
WEATHER[conditions.weather].label,
|
||||||
conditions.heatWave ? 'HEAT WAVE' : null,
|
conditions.heatWave ? 'HEAT WAVE' : null,
|
||||||
|
conditions.festival ? 'SUMMER FAIR' : null,
|
||||||
conditions.streetCrew ? 'STREET CREWS' : null,
|
conditions.streetCrew ? 'STREET CREWS' : null,
|
||||||
|
conditions.rival ? 'RIVAL STAND' : null,
|
||||||
conditions.storm ? 'THUNDERSTORM' : null,
|
conditions.storm ? 'THUNDERSTORM' : null,
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
|
|||||||
@@ -63,6 +63,11 @@ export const HEAT_WAVE_TRAFFIC = 1.5
|
|||||||
export const HEAT_WAVE_CEILING = 1.25
|
export const HEAT_WAVE_CEILING = 1.25
|
||||||
/** Street crews close the road; a handful of regulars still find you. */
|
/** Street crews close the road; a handful of regulars still find you. */
|
||||||
export const STREET_CREW_TRAFFIC = 0.2
|
export const STREET_CREW_TRAFFIC = 0.2
|
||||||
|
/** A fair or a parade: the whole town is out, and out to spend. */
|
||||||
|
export const FESTIVAL_TRAFFIC = 1.9
|
||||||
|
export const FESTIVAL_CEILING = 1.2
|
||||||
|
/** A stand on the next corner takes a little under half the street. */
|
||||||
|
export const RIVAL_TRAFFIC = 0.58
|
||||||
|
|
||||||
/** Signs: +20% for the first, tailing off to a hard ceiling near +50%. */
|
/** Signs: +20% for the first, tailing off to a hard ceiling near +50%. */
|
||||||
export function signFactor(signs: number): number {
|
export function signFactor(signs: number): number {
|
||||||
|
|||||||
+29
-6
@@ -1,6 +1,9 @@
|
|||||||
import {
|
import {
|
||||||
|
FESTIVAL_CEILING,
|
||||||
|
FESTIVAL_TRAFFIC,
|
||||||
HEAT_WAVE_CEILING,
|
HEAT_WAVE_CEILING,
|
||||||
HEAT_WAVE_TRAFFIC,
|
HEAT_WAVE_TRAFFIC,
|
||||||
|
RIVAL_TRAFFIC,
|
||||||
STREET_CREW_TRAFFIC,
|
STREET_CREW_TRAFFIC,
|
||||||
SIGN_COST,
|
SIGN_COST,
|
||||||
WEATHER,
|
WEATHER,
|
||||||
@@ -9,14 +12,14 @@ import {
|
|||||||
signFactor,
|
signFactor,
|
||||||
} from './constants'
|
} from './constants'
|
||||||
import { chance, type Rng } from './rng'
|
import { chance, type Rng } from './rng'
|
||||||
import type { DayConditions, DayResult, Decision, Player, Weather } from './types'
|
import type { CarryOver, DayConditions, DayResult, Decision, Player, Weather } from './types'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Roll the weather and the day's events. The storm is decided here but must
|
* Roll the weather and the day's events. The storm is decided here but must
|
||||||
* not be shown to the player until their money is committed - that is the
|
* not be shown to the player until their money is committed - that is the
|
||||||
* whole cruelty of a cloudy day.
|
* whole cruelty of a cloudy day.
|
||||||
*/
|
*/
|
||||||
export function rollDay(day: number, rng: Rng, streetCrewYesterday: boolean): DayConditions {
|
export function rollDay(day: number, rng: Rng, yesterday: CarryOver): DayConditions {
|
||||||
const roll = rng()
|
const roll = rng()
|
||||||
let weather: Weather
|
let weather: Weather
|
||||||
if (roll < 0.5) weather = 'sunny'
|
if (roll < 0.5) weather = 'sunny'
|
||||||
@@ -29,9 +32,22 @@ export function rollDay(day: number, rng: Rng, streetCrewYesterday: boolean): Da
|
|||||||
const heatWave = weather === 'hot' && chance(rng, 0.35)
|
const heatWave = weather === 'hot' && chance(rng, 0.35)
|
||||||
const storm = weather === 'cloudy' && chance(rng, 0.25)
|
const storm = weather === 'cloudy' && chance(rng, 0.25)
|
||||||
// Road works run for two days once they start, and never on day 1 or 2.
|
// Road works run for two days once they start, and never on day 1 or 2.
|
||||||
const streetCrew = day > 2 && (streetCrewYesterday ? chance(rng, 0.5) : chance(rng, 0.12))
|
const streetCrew = day > 2 && (yesterday.streetCrew ? chance(rng, 0.5) : chance(rng, 0.12))
|
||||||
|
// Nobody holds a fair on a dug-up street, or in the rain.
|
||||||
|
const festival = day > 1 && !streetCrew && !storm && chance(rng, 0.1)
|
||||||
|
// A rival sets up once there is business worth taking, and lingers.
|
||||||
|
const rival = day > 3 && (yesterday.rival ? chance(rng, 0.6) : chance(rng, 0.14))
|
||||||
|
|
||||||
return { day, weather, heatWave, streetCrew, storm, costPerGlass: costPerGlass(day) }
|
return {
|
||||||
|
day,
|
||||||
|
weather,
|
||||||
|
heatWave,
|
||||||
|
streetCrew,
|
||||||
|
festival,
|
||||||
|
rival,
|
||||||
|
storm,
|
||||||
|
costPerGlass: costPerGlass(day),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The most glasses a player can pay for today, given signs already planned. */
|
/** The most glasses a player can pay for today, given signs already planned. */
|
||||||
@@ -59,6 +75,11 @@ export function simulate(
|
|||||||
ceiling *= HEAT_WAVE_CEILING
|
ceiling *= HEAT_WAVE_CEILING
|
||||||
}
|
}
|
||||||
if (cond.streetCrew) traffic *= STREET_CREW_TRAFFIC
|
if (cond.streetCrew) traffic *= STREET_CREW_TRAFFIC
|
||||||
|
if (cond.festival) {
|
||||||
|
traffic *= FESTIVAL_TRAFFIC
|
||||||
|
ceiling *= FESTIVAL_CEILING
|
||||||
|
}
|
||||||
|
if (cond.rival) traffic *= RIVAL_TRAFFIC
|
||||||
|
|
||||||
const demand =
|
const demand =
|
||||||
traffic *
|
traffic *
|
||||||
@@ -99,8 +120,10 @@ export function streetBusyness(cond: DayConditions): number {
|
|||||||
if (cond.storm) return 0.18
|
if (cond.storm) return 0.18
|
||||||
const base = WEATHER[cond.weather].traffic / 140
|
const base = WEATHER[cond.weather].traffic / 140
|
||||||
const heat = cond.heatWave ? 1.35 : 1
|
const heat = cond.heatWave ? 1.35 : 1
|
||||||
const crew = cond.streetCrew ? 0.2 : 1
|
const crew = cond.streetCrew ? STREET_CREW_TRAFFIC : 1
|
||||||
return Math.max(0, Math.min(1, base * heat * crew))
|
const fair = cond.festival ? 1.6 : 1
|
||||||
|
const rival = cond.rival ? RIVAL_TRAFFIC : 1
|
||||||
|
return Math.max(0, Math.min(1, base * heat * crew * fair * rival))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How busy it actually was, from the glasses that crossed the counter. */
|
/** How busy it actually was, from the glasses that crossed the counter. */
|
||||||
|
|||||||
+42
-47
@@ -1,6 +1,14 @@
|
|||||||
export const HIGH_SCORE_KEY = 'lemonade.highscores.v1'
|
/**
|
||||||
const KEY = HIGH_SCORE_KEY
|
* The leaderboard is one table shared by everybody, held by the scores
|
||||||
export const MAX_SCORES = 10
|
* service rather than the browser. Nothing about it is trusted on the way in:
|
||||||
|
* the server decides what is plausible, and the client re-checks the shape of
|
||||||
|
* whatever comes back before putting it on screen.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const BASE = (import.meta.env.VITE_SCORES_API ?? '/api').replace(/\/+$/, '')
|
||||||
|
const TIMEOUT_MS = 8000
|
||||||
|
|
||||||
|
export const MAX_SCORES = 50
|
||||||
|
|
||||||
export interface Score {
|
export interface Score {
|
||||||
id: string
|
id: string
|
||||||
@@ -9,15 +17,14 @@ export interface Score {
|
|||||||
assets: number
|
assets: number
|
||||||
days: number
|
days: number
|
||||||
glasses: number
|
glasses: number
|
||||||
seed: number
|
|
||||||
/** Epoch milliseconds, for the tie-break and the date column. */
|
|
||||||
at: number
|
at: number
|
||||||
broke: boolean
|
broke: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type NewScore = Omit<Score, 'id' | 'at'>
|
export type NewScore = Omit<Score, 'id' | 'at'>
|
||||||
|
|
||||||
const isScore = (v: unknown): v is Score => {
|
/** Rows arrive over the network, so every field is checked before use. */
|
||||||
|
function isScore(v: unknown): v is Score {
|
||||||
if (typeof v !== 'object' || v === null) return false
|
if (typeof v !== 'object' || v === null) return false
|
||||||
const s = v as Record<string, unknown>
|
const s = v as Record<string, unknown>
|
||||||
return (
|
return (
|
||||||
@@ -26,58 +33,46 @@ const isScore = (v: unknown): v is Score => {
|
|||||||
Number.isFinite(s.assets) &&
|
Number.isFinite(s.assets) &&
|
||||||
Number.isFinite(s.days) &&
|
Number.isFinite(s.days) &&
|
||||||
Number.isFinite(s.glasses) &&
|
Number.isFinite(s.glasses) &&
|
||||||
Number.isFinite(s.seed) &&
|
|
||||||
Number.isFinite(s.at) &&
|
Number.isFinite(s.at) &&
|
||||||
typeof s.broke === 'boolean'
|
typeof s.broke === 'boolean'
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const rank = (a: Score, b: Score) => b.assets - a.assets || a.days - b.days || a.at - b.at
|
const parseBoard = (body: unknown): Score[] => {
|
||||||
|
const rows = (body as { scores?: unknown })?.scores
|
||||||
/**
|
if (!Array.isArray(rows)) return []
|
||||||
* Anything already in storage was written by someone who can edit it freely,
|
return rows
|
||||||
* so every field is checked before it is trusted.
|
|
||||||
*/
|
|
||||||
export function loadScores(): Score[] {
|
|
||||||
try {
|
|
||||||
const raw = window.localStorage.getItem(KEY)
|
|
||||||
if (!raw) return []
|
|
||||||
const parsed: unknown = JSON.parse(raw)
|
|
||||||
if (!Array.isArray(parsed)) return []
|
|
||||||
return parsed
|
|
||||||
.filter(isScore)
|
.filter(isScore)
|
||||||
.map((s) => ({ ...s, name: s.name.slice(0, 12).toUpperCase() }))
|
.map((s) => ({ ...s, name: s.name.slice(0, 12) }))
|
||||||
.sort(rank)
|
|
||||||
.slice(0, MAX_SCORES)
|
.slice(0, MAX_SCORES)
|
||||||
} catch {
|
|
||||||
// Private windows, blocked site data, or corrupt JSON: play without a table.
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function persist(scores: Score[]): void {
|
async function call(path: string, init?: RequestInit): Promise<unknown> {
|
||||||
try {
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
window.localStorage.setItem(KEY, JSON.stringify(scores))
|
...init,
|
||||||
} catch {
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||||
// Nothing to do - the run still shows in the table until the tab closes.
|
headers: { 'content-type': 'application/json', ...(init?.headers ?? {}) },
|
||||||
|
})
|
||||||
|
const body: unknown = await res.json().catch(() => null)
|
||||||
|
if (!res.ok) {
|
||||||
|
const why = (body as { error?: string })?.error
|
||||||
|
throw new Error(why ?? `scores service returned ${res.status}`)
|
||||||
}
|
}
|
||||||
|
return body
|
||||||
}
|
}
|
||||||
|
|
||||||
const newId = () =>
|
export async function fetchScores(): Promise<Score[]> {
|
||||||
typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
return parseBoard(await call('/scores'))
|
||||||
? crypto.randomUUID()
|
}
|
||||||
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
|
||||||
|
|
||||||
/**
|
/** Posts a whole table's worth of players at once and returns the new board. */
|
||||||
* Returns the saved table and the ids of the entries this call added. The
|
export async function submitScores(
|
||||||
* table only ever loses a row by being pushed past MAX_SCORES by a better
|
entries: NewScore[],
|
||||||
* one - there is no way to clear it.
|
): Promise<{ ids: string[]; scores: Score[] }> {
|
||||||
*/
|
const body = await call('/scores', { method: 'POST', body: JSON.stringify({ entries }) })
|
||||||
export function addScores(entries: NewScore[]): { table: Score[]; added: string[] } {
|
const ids = (body as { ids?: unknown })?.ids
|
||||||
const at = Date.now()
|
return {
|
||||||
const fresh: Score[] = entries.map((e) => ({ ...e, id: newId(), at }))
|
ids: Array.isArray(ids) ? ids.filter((i): i is string => typeof i === 'string') : [],
|
||||||
const table = [...loadScores(), ...fresh].sort(rank).slice(0, MAX_SCORES)
|
scores: parseBoard(body),
|
||||||
persist(table)
|
}
|
||||||
const kept = new Set(table.map((s) => s.id))
|
|
||||||
return { table, added: fresh.filter((s) => kept.has(s.id)).map((s) => s.id) }
|
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-5
@@ -1,6 +1,6 @@
|
|||||||
import { STARTING_ASSETS } from './constants'
|
import { STARTING_ASSETS } from './constants'
|
||||||
import { isBankrupt } from './engine'
|
import { isBankrupt } from './engine'
|
||||||
import type { DayConditions, DayResult, Decision, Phase, Player } from './types'
|
import type { CarryOver, DayConditions, DayResult, Decision, Phase, Player } from './types'
|
||||||
|
|
||||||
export interface GameState {
|
export interface GameState {
|
||||||
phase: Phase
|
phase: Phase
|
||||||
@@ -13,8 +13,8 @@ export interface GameState {
|
|||||||
decisions: Record<number, Decision>
|
decisions: Record<number, Decision>
|
||||||
results: DayResult[]
|
results: DayResult[]
|
||||||
history: DayResult[]
|
history: DayResult[]
|
||||||
/** True while road works were in progress yesterday, so they can run on. */
|
/** Conditions in force yesterday, so the ones that persist can run on. */
|
||||||
streetCrewYesterday: boolean
|
yesterday: CarryOver
|
||||||
retired: boolean
|
retired: boolean
|
||||||
/** Where the high score table was opened from, so BACK can return there. */
|
/** Where the high score table was opened from, so BACK can return there. */
|
||||||
scoresReturn: Phase
|
scoresReturn: Phase
|
||||||
@@ -30,7 +30,7 @@ export const initialState = (seed: number, phase: Phase = 'boot'): GameState =>
|
|||||||
decisions: {},
|
decisions: {},
|
||||||
results: [],
|
results: [],
|
||||||
history: [],
|
history: [],
|
||||||
streetCrewYesterday: false,
|
yesterday: { streetCrew: false, rival: false },
|
||||||
retired: false,
|
retired: false,
|
||||||
scoresReturn: 'title',
|
scoresReturn: 'title',
|
||||||
})
|
})
|
||||||
@@ -117,7 +117,10 @@ export function reducer(state: GameState, action: Action): GameState {
|
|||||||
phase: 'trading',
|
phase: 'trading',
|
||||||
results: action.results,
|
results: action.results,
|
||||||
history: [...state.history, ...action.results],
|
history: [...state.history, ...action.results],
|
||||||
streetCrewYesterday: state.conditions?.streetCrew ?? false,
|
yesterday: {
|
||||||
|
streetCrew: state.conditions?.streetCrew ?? false,
|
||||||
|
rival: state.conditions?.rival ?? false,
|
||||||
|
},
|
||||||
players: state.players.map((p) => {
|
players: state.players.map((p) => {
|
||||||
const r = byId.get(p.id)
|
const r = byId.get(p.id)
|
||||||
if (!r) return p
|
if (!r) return p
|
||||||
|
|||||||
@@ -20,12 +20,23 @@ export interface DayConditions {
|
|||||||
day: number
|
day: number
|
||||||
weather: Weather
|
weather: Weather
|
||||||
heatWave: boolean
|
heatWave: boolean
|
||||||
|
/** Road works. The street empties and they tend to stay a second day. */
|
||||||
streetCrew: boolean
|
streetCrew: boolean
|
||||||
|
/** A town event: half of Lemonsville walks past, and in a spending mood. */
|
||||||
|
festival: boolean
|
||||||
|
/** Somebody else has set up on the next corner and takes a share. */
|
||||||
|
rival: boolean
|
||||||
/** Only ever true on a cloudy day, and only revealed after decisions are locked in. */
|
/** Only ever true on a cloudy day, and only revealed after decisions are locked in. */
|
||||||
storm: boolean
|
storm: boolean
|
||||||
costPerGlass: number
|
costPerGlass: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Conditions that run on into tomorrow rather than being rolled fresh. */
|
||||||
|
export interface CarryOver {
|
||||||
|
streetCrew: boolean
|
||||||
|
rival: boolean
|
||||||
|
}
|
||||||
|
|
||||||
export interface DayResult {
|
export interface DayResult {
|
||||||
playerId: number
|
playerId: number
|
||||||
decision: Decision
|
decision: Decision
|
||||||
|
|||||||
@@ -3,5 +3,19 @@ import { defineConfig } from 'vite'
|
|||||||
|
|
||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
// The game is served under a path on games.jcoffey.dev, so asset URLs have
|
||||||
|
// to be built for it. Local development stays at the root.
|
||||||
|
base: process.env.BASE_PATH ?? '/',
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
// The game talks to /api in every environment; in development that is the
|
||||||
|
// scores service on 5184, in production it is nginx in front of the
|
||||||
|
// container. Nothing in the client needs to know the difference.
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: process.env.SCORES_TARGET ?? 'http://localhost:5184',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# The game is a static bundle. It is built here and served by nginx, in its own
|
||||||
|
# container - it shares nothing with the scores service but the domain.
|
||||||
|
FROM node:26-alpine AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY tsconfig*.json vite.config.ts index.html ./
|
||||||
|
COPY public ./public
|
||||||
|
COPY src ./src
|
||||||
|
# Must match where the host proxies it, or the asset URLs will be wrong.
|
||||||
|
ARG BASE_PATH=/lemonade/
|
||||||
|
ENV BASE_PATH=${BASE_PATH}
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
EXPOSE 8080
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
|
||||||
|
CMD wget -qO- http://127.0.0.1:8080/healthz >/dev/null || exit 1
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
server {
|
||||||
|
listen 8080;
|
||||||
|
server_name _;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
|
||||||
|
# Hashed filenames, so they can be cached hard.
|
||||||
|
location /assets/ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /healthz {
|
||||||
|
access_log off;
|
||||||
|
return 200 "ok\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user