resolved gitignore conflict
BIN
static/.DS_Store → .DS_Store
vendored
6
.dockerignore
Normal file
|
@ -0,0 +1,6 @@
|
|||
venv/
|
||||
matteo_env/
|
||||
__pycache__/
|
||||
simmadome/node_modules
|
||||
data/
|
||||
.git/
|
7
.gitignore
vendored
|
@ -344,9 +344,16 @@ config.json
|
|||
games_config.json
|
||||
weather_config.json
|
||||
ids
|
||||
data/
|
||||
|
||||
# database
|
||||
matteo.db
|
||||
matteo.db-wal
|
||||
matteo.db-shm
|
||||
/data/leagues/*
|
||||
/matteo_env/Lib/site-packages/flask_socketio/__init__.py
|
||||
Pipfile
|
||||
|
||||
env
|
||||
/data/leagues
|
||||
/simmadome/build
|
||||
|
|
19
Dockerfile
|
@ -1,9 +1,20 @@
|
|||
FROM python:3.8
|
||||
EXPOSE 5000
|
||||
|
||||
# - Build stage 1: frontend (simmadome/ directory)
|
||||
FROM node:alpine AS frontend
|
||||
WORKDIR /app
|
||||
|
||||
COPY . ./
|
||||
COPY simmadome/package.json simmadome/package-lock.json ./
|
||||
RUN npm install
|
||||
COPY simmadome/ ./
|
||||
RUN npm run build
|
||||
|
||||
# - Build stage 2: backend (Python)
|
||||
FROM python:3.8
|
||||
EXPOSE 5000
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
COPY . ./
|
||||
COPY --from=frontend /app/build/ simmadome/build/
|
||||
|
||||
CMD ["python", "the_prestige.py"]
|
||||
|
|
674
LICENSE.md
Normal file
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 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 General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
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 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. Use with the GNU Affero General Public License.
|
||||
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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 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 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 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
13
Makefile
Normal file
|
@ -0,0 +1,13 @@
|
|||
SOURCES = $(wildcard ./simmadome/src/*) $(wildcard ./simmadome/public/*)
|
||||
OUTPUTS = $(wildcard ./simmadome/build/*)
|
||||
|
||||
.PHONY: run frontend
|
||||
|
||||
run: $(OUTPUTS)
|
||||
python3 the_prestige.py
|
||||
|
||||
frontend:
|
||||
(cd simmadome && npm run build)
|
||||
|
||||
$(OUTPUTS): $(SOURCES)
|
||||
(cd simmadome && npm run build)
|
126
README.md
|
@ -1,54 +1,122 @@
|
|||
# matteo-the-prestige
|
||||
# simsim discord bot
|
||||
|
||||
blaseball, blaseball, is back! in an unofficial capacity. this is completely unaffiliated with the game band
|
||||
blaseball, blaseball, is back! in an unofficial capacity. this project is completely unaffiliated with the game band.
|
||||
|
||||
custom players, custom teams, custom leagues (that last one is coming soon™) all set up in discord and watchable at https://simsim.sibr.dev
|
||||
we have custom players (generated by onomancer), custom teams, custom leagues, all set up in discord and watchable at https://simsim.sibr.dev!
|
||||
|
||||
we've also got things like custom team creation, easy setup for your teams to play against each other, and player idolization, all powered by this bot and onomancer.
|
||||
if you would like to add matteo to your server to be able to set up teams and games, you can do so with this link: https://discord.com/api/oauth2/authorize?client_id=789956166796574740&permissions=388160&scope=bot
|
||||
|
||||
accepting pull requests, check the issues for to-dos.
|
||||
|
||||
|
||||
## commands: (everything here is case sensitive, and can be prefixed with either m; or m!)
|
||||
|
||||
### team commands:
|
||||
#### creation and deletion:
|
||||
- m;saveteam
|
||||
- saves a team to the database allowing it to be used for games. send this command at the top of a list, with entries separated by new lines (shift+enter in discord, or copy+paste from notepad).
|
||||
- the first line of the list is your team's name (cannot contain emoji).
|
||||
- the second line is your team's icon and slogan, this should begin with an emoji followed by a space, followed by a short slogan.
|
||||
- saves a team to the database allowing it to be used for games. use this command at the top of a list with entries separated by new lines:
|
||||
- the first line of the list is your team's name.
|
||||
- the second line is the team's icon and slogan, generally this is an emoji followed by a space, followed by a short slogan.
|
||||
- the third line must be blank.
|
||||
- the next lines are your batters' names in the order you want them to appear in your lineup, lineups can contain any number of batters between 1 and 12.
|
||||
- the final line is your pitcher's name.
|
||||
- if you did it correctly, you'll get a team embed with a prompt to confirm. hit the 👍 and it'll be saved.
|
||||
- then another blank line seperating your batters and your pitchers.
|
||||
- the final lines are the names of the pitchers in your rotation, rotations can contain any number of pitchers between 1 and 8.
|
||||
- if you did it correctly, you'll get a team embed with a prompt to confirm. hit the 👍 and your team will be saved!
|
||||
- m;deleteteam [teamname] \(requires team ownership)
|
||||
- allows you to delete the team with the provided name. you'll get an embed with a confirmation to prevent accidental deletions. hit the 👍 and your team will be deleted.
|
||||
- m;import
|
||||
- imports an onomancer collection as a new team. you can use the new onomancer simsim setting to ensure compatibility. similarly to saveteam, you'll get a team embed with a prompt to confirm, hit the 👍 and your team will be saved!
|
||||
#### editing (all of these commands require ownership and exact spelling of the team name):
|
||||
- m;addplayer batter/pitcher [team name] \[player name]
|
||||
- adds a new player to the end of your team, either in the lineup or the rotation depending on which version you use. use addplayer batter or addplayer pitcher at the top of a list with entries separated by new lines:
|
||||
- the name of the team you want to add the player to.
|
||||
- the name of the player you want to add to the team.
|
||||
- m;moveplayer [team name] \[player name] [new lineup/rotation position number]
|
||||
- moves a player within your lineup or rotation. if you want to instead move a player from your rotation to your lineup or vice versa, use m;swapsection instead. use this command at the top of a list with entries separated by new lines:
|
||||
- the name of the team you want to move the player on.
|
||||
- the name of the player you want to move.
|
||||
- the position you want to move them too, indexed with 1 being the first position of the lineup or rotation. all players below the specified position in the lineup or rotation will be pushed down.
|
||||
- m;swapsection [team name] \[player name]
|
||||
- swaps a player from your lineup to the end of your rotation or your rotation to the end of your lineup. use this command at the top of a list with entries separated by new lines:
|
||||
- the name of the team you want to swap the player on.
|
||||
- the name of the player you want to swap.
|
||||
- m;removeplayer [team name] \[player name]
|
||||
- removes a player from your team. if there are multiple copies of the same player on a team this will only delete the first one. use this command at the top of a list with entries separated by new lines:
|
||||
- the name of the team you want to remove the player from.
|
||||
- the name of the player you want to remove.
|
||||
#### viewing and searching:
|
||||
- m;showteam [name]
|
||||
- shows information about any saved team.
|
||||
- m;showallteams
|
||||
- shows a paginated list of all teams available for games which can be scrolled through.
|
||||
- shows the lineup, rotation, and slogan of any saved team in a discord embed with primary stat star ratings for all of the players. this command has fuzzy search so you don't need to type the full name of the team as long as you give enough to identify the team you're looking for.
|
||||
- m;searchteams [searchterm]
|
||||
- shows a paginated list of all teams whose names contain the given search term.
|
||||
- m;deleteteam [teamname]
|
||||
- allows you to delete the team with the provided name if you are the owner of it, gives a confirmation first to prevent accidental deletions. if it isn't letting you delete your team, you probably created it before teams having owners was a thing, contact xvi and xie can assign you as the owner.
|
||||
- m;import
|
||||
- imports an onomancer collection as a new team. you can use the new onomancer simsim setting to ensure compatibility.
|
||||
- m;showallteams
|
||||
- shows a paginated list of all teams available for games which can be scrolled through.
|
||||
|
||||
### game commands:
|
||||
- m;startgame --day # or -d #
|
||||
- starts a game with premade teams made using saveteam. provides a link to the website where you can watch the game.
|
||||
- the --day/-d is optional, if used it'll force the game to use the #th spot in each team's rotations. if this number is larger than the number of pitchers in one or both of the teams' rotations it'll wrap around. if it is not used pitchers will be chosen randomly from the teams' rotations.
|
||||
- use this command at the top of a list with entries separated by new lines:
|
||||
- the away team's name.
|
||||
- the home team's name.
|
||||
- optionally, the number of innings, which must be greater than 2 and less than 201. if not included it will default to 9.
|
||||
- this command has fuzzy search so you don't need to type the full name of the team as long as you give enough to identify the team you're looking for.
|
||||
- m;randomgame
|
||||
- starts a 9-inning game between 2 entirely random teams. embrace chaos!
|
||||
- m;starttournament --rounddelay #
|
||||
- starts a randomly seeded tournament with the provided teams, automatically adding byes as necessary. all series have a 5 minute break between games. the current format is: best of 5 until the finals which are best of 7.
|
||||
- the --rounddelay is optional, if used, # must be between 1 and 120 and it'll set the delay between rounds to be # minutes. if not included it will default to 10.
|
||||
- use this command at the top of a list with entries separated by new lines:
|
||||
- the name of the tournament.
|
||||
- the name of each participating team on its own line.
|
||||
|
||||
### draft commands
|
||||
- m;startdraft
|
||||
- starts a draft with an arbitrary number of participants. use this command at the top of a list with entries separated by new lines:
|
||||
- for each participant's entry you need three lines:
|
||||
- their discord @
|
||||
- their team name
|
||||
- their team slogan
|
||||
- post this with all three of these things for all participants and the draft will begin.
|
||||
- the draft will begin once all participants have given a 👍 and will proceed in the order that participants were entered. each participant will select 12 hitters and 1 pitcher from a pool of 20 random players which will refresh automatically when it becomes small.
|
||||
- m;draft [name]
|
||||
- use this on your turn during a draft to pick your player.
|
||||
- you can also just use a 'd' instead of the full command.
|
||||
|
||||
### league commands
|
||||
- all of these commands are for leagues that have already been started. to start a league, click the 'create a league' button on the website and fill out the info for your league there, then use the m;claimleague command in discord to set yourself as the owner.
|
||||
- commissioner commands (all of these except for m;claimleague require ownership of the specified league):
|
||||
- m;claimleague [leaguename]
|
||||
- sets yourself as the owner of an unclaimed league created on the website. make sure to do this as soon as possible since if someone does this before you, you will not have access to the league.
|
||||
- m;addleagueowner [leaguename]
|
||||
- use this command at the top of a list of @mentions, with entries separated by new lines, of people you want to have owner powers in your league.
|
||||
- m;startleague [leaguename] --queue #/-q # --noautopostseason
|
||||
- send this command with the number of games per hour you want on the next line, minimum 1 (one game every hour), maximum 12 (one game every 5 minutes, uses spillover rules).
|
||||
- starts the playing of league games at the pace specified, by default will play the entire season and the postseason unless an owner pauses the league with the m;pauseleague command.
|
||||
- if you use the --queue #/-q # flag, the league will only play # series' at a time before automatically pausing until you use this command again.
|
||||
- if you use the --noautopostseason flag, instead of starting automatically, the league will pause at the end of the regular season and not start the postseason until you use this command again.
|
||||
- m;pauseleague [leaguename]
|
||||
- pauses the specified league after the current series finishes until the league is started again with m;startleague.
|
||||
- general commands (all of these can be used by anyone):
|
||||
- m;leaguestandings [leaguename] --season #/-s #
|
||||
- displays the current standings for the specified league.
|
||||
- by default this will display the standings for the current season but if the --season #/-s # flag is set it will instead display the standings for the #th season instead for viewing historical standings.
|
||||
- m;leaguewildcard [leaguename]
|
||||
- displays the wild card standings for the specified league. if the league doesn't have wild cards, it will instead tell you that.
|
||||
- m;leagueschedule [leaguename]
|
||||
- displays the upcoming schedule for the specified league. shows the current series and the next three series after that for every team.
|
||||
|
||||
### player commands:
|
||||
- m;showplayer [name]
|
||||
- displays any name's stars, there's a limit of 70 characters. that should be *plenty*. note: if you want to lookup a lot of different players you can do it on onomancer instead of spamming this command a bunch and clogging up discord: https://onomancer.sibr.dev/reflect
|
||||
- m;idolize [name]
|
||||
- records any name as your idol, mostly for fun.
|
||||
- m;showidol
|
||||
- displays your idol's name and stars.
|
||||
- displays your idol's name and stars in a discord embed.
|
||||
|
||||
### game commands:
|
||||
- m;startgame
|
||||
- starts a game with premade teams made using saveteam, use this command at the top of a list followed by each of these in a new line:
|
||||
- the away team's name.
|
||||
- the home team's name.
|
||||
- and finally, optionally, the number of innings, which must be greater than 2 and less than 31. if not included it will default to 9.
|
||||
|
||||
### other commands:
|
||||
- m;help [command]
|
||||
- shows the instructions from here for given command. if no command is provided, it will instead provide a list of all of the commands that instructions can be provided for.
|
||||
- shows instructions for a given command. if no command is provided, it will instead provide a list of all of the commands that instructions can be provided for.
|
||||
- m;credit
|
||||
- shows artist credit for matteo's avatar.
|
||||
- m;roman [number]
|
||||
|
@ -60,3 +128,11 @@ these folks are helping me a *ton* via patreon, and i cannot possibly thank them
|
|||
- Ale Humano
|
||||
- Chris Denmark
|
||||
- Astrid Bek
|
||||
- Kameleon
|
||||
- Ryan Littleton
|
||||
- Evie Diver
|
||||
- iliana etaoin
|
||||
|
||||
## Attribution
|
||||
|
||||
Twemoji is copyright 2020 Twitter, Inc and other contributors; code licensed under [the MIT License](http://opensource.org/licenses/MIT), graphics licensed under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/)
|
||||
|
|
39
database.py
|
@ -2,12 +2,17 @@
|
|||
import os, json, datetime, re
|
||||
import sqlite3 as sql
|
||||
|
||||
data_dir = "data"
|
||||
|
||||
def create_connection():
|
||||
#create connection, create db if doesn't exist
|
||||
conn = None
|
||||
try:
|
||||
conn = sql.connect("matteo.db")
|
||||
conn = sql.connect(os.path.join(data_dir, "matteo.db"))
|
||||
|
||||
# enable write-ahead log for performance and resilience
|
||||
conn.execute('pragma journal_mode=wal')
|
||||
|
||||
return conn
|
||||
except:
|
||||
print("oops, db connection no work")
|
||||
|
@ -181,9 +186,13 @@ def get_user_player_conn(conn, user):
|
|||
except TypeError:
|
||||
return False
|
||||
else:
|
||||
print(conn)
|
||||
conn.close()
|
||||
return False
|
||||
except:
|
||||
print(conn)
|
||||
conn.close()
|
||||
return False
|
||||
conn.close()
|
||||
return False
|
||||
|
||||
def get_user_player(user):
|
||||
conn = create_connection()
|
||||
|
@ -206,6 +215,26 @@ def save_team(name, team_json_string, user_id):
|
|||
return False
|
||||
except:
|
||||
return False
|
||||
conn.close()
|
||||
return False
|
||||
|
||||
def update_team(name, team_json_string):
|
||||
conn = create_connection()
|
||||
try:
|
||||
if conn is not None:
|
||||
c = conn.cursor()
|
||||
store_string = "UPDATE teams SET team_json_string = ? WHERE name=?"
|
||||
c.execute(store_string, (team_json_string, (re.sub('[^A-Za-z0-9 ]+', '', name)))) #this regex removes all non-standard characters
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return True
|
||||
conn.close()
|
||||
return False
|
||||
except:
|
||||
conn.close()
|
||||
return False
|
||||
conn.close()
|
||||
return False
|
||||
|
||||
def get_team(name, owner=False):
|
||||
conn = create_connection()
|
||||
|
@ -238,6 +267,8 @@ def delete_team(team):
|
|||
except:
|
||||
conn.close()
|
||||
return False
|
||||
conn.close()
|
||||
return False
|
||||
|
||||
def assign_owner(team_name, owner_id):
|
||||
conn = create_connection()
|
||||
|
@ -251,6 +282,8 @@ def assign_owner(team_name, owner_id):
|
|||
except:
|
||||
conn.close()
|
||||
return False
|
||||
conn.close()
|
||||
return False
|
||||
|
||||
def get_all_teams():
|
||||
conn = create_connection()
|
||||
|
|
278
games.py
|
@ -2,8 +2,13 @@ import json, random, os, math, jsonpickle
|
|||
from enum import Enum
|
||||
import database as db
|
||||
|
||||
data_dir = "data"
|
||||
games_config_file = os.path.join(data_dir, "games_config.json")
|
||||
|
||||
def config():
|
||||
if not os.path.exists("games_config.json"):
|
||||
if not os.path.exists(os.path.dirname(games_config_file)):
|
||||
os.makedirs(os.path.dirname(games_config_file))
|
||||
if not os.path.exists(games_config_file):
|
||||
#generate default config
|
||||
config_dic = {
|
||||
"default_length" : 3,
|
||||
|
@ -16,31 +21,23 @@ def config():
|
|||
"stolen_base_chance_mod" : 1,
|
||||
"stolen_base_success_mod" : 1
|
||||
}
|
||||
with open("games_config.json", "w") as config_file:
|
||||
with open(games_config_file, "w") as config_file:
|
||||
json.dump(config_dic, config_file, indent=4)
|
||||
return config_dic
|
||||
else:
|
||||
with open("games_config.json") as config_file:
|
||||
with open(games_config_file) as config_file:
|
||||
return json.load(config_file)
|
||||
|
||||
def all_weathers():
|
||||
if not os.path.exists("weather_config.json"):
|
||||
#generate default config
|
||||
super_weather_json = jsonpickle.encode(weather("Supernova", "🌟"))
|
||||
mid_weather_json = jsonpickle.encode(weather("Midnight", "🕶"))
|
||||
config_dic = {
|
||||
"Supernova" : super_weather_json,
|
||||
"Midnight": mid_weather_json
|
||||
}
|
||||
with open("weather_config.json", "w") as config_file:
|
||||
json.dump(config_dic, config_file, indent=4)
|
||||
with open("weather_config.json") as config_file:
|
||||
weather_dic = {}
|
||||
for weather_json in json.load(config_file).values():
|
||||
this_weather = jsonpickle.decode(weather_json, classes=weather)
|
||||
weather_dic[this_weather.name] = this_weather
|
||||
return weather_dic
|
||||
|
||||
weathers_dic = {
|
||||
#"Supernova" : weather("Supernova", "🌟"),
|
||||
#"Midnight": weather("Midnight", "🕶"),
|
||||
"Slight Tailwind": weather("Slight Tailwind", "🏌️♀️"),
|
||||
"Heavy Snow": weather("Heavy Snow", "❄"),
|
||||
"Twilight" : weather("Twilight", "👻"),
|
||||
"Thinned Veil" : weather("Thinned Veil", "🌌")
|
||||
}
|
||||
return weathers_dic
|
||||
|
||||
class appearance_outcomes(Enum):
|
||||
strikeoutlooking = "strikes out looking."
|
||||
|
@ -54,7 +51,7 @@ class appearance_outcomes(Enum):
|
|||
single = "hits a single!"
|
||||
double = "hits a double!"
|
||||
triple = "hits a triple!"
|
||||
homerun = "hits a home run!"
|
||||
homerun = "hits a dinger!"
|
||||
grandslam = "hits a grand slam!"
|
||||
|
||||
|
||||
|
@ -102,10 +99,59 @@ class team(object):
|
|||
self.name = None
|
||||
self.lineup = []
|
||||
self.lineup_position = 0
|
||||
self.rotation = []
|
||||
self.pitcher = None
|
||||
self.score = 0
|
||||
self.slogan = None
|
||||
|
||||
def find_player(self, name):
|
||||
for index in range(0,len(self.lineup)):
|
||||
if self.lineup[index].name == name:
|
||||
return (self.lineup[index], index, self.lineup)
|
||||
for index in range(0,len(self.rotation)):
|
||||
if self.rotation[index].name == name:
|
||||
return (self.rotation[index], index, self.rotation)
|
||||
else:
|
||||
return (None, None, None)
|
||||
|
||||
def average_stars(self):
|
||||
total_stars = 0
|
||||
for _player in self.lineup:
|
||||
total_stars += _player.stlats["batting_stars"]
|
||||
for _player in self.rotation:
|
||||
total_stars += _player.stlats["pitching_stars"]
|
||||
return total_stars/(len(self.lineup) + len(self.rotation))
|
||||
|
||||
def swap_player(self, name):
|
||||
this_player, index, roster = self.find_player(name)
|
||||
if this_player is not None and len(roster) > 1:
|
||||
if roster == self.lineup:
|
||||
if self.add_pitcher(this_player):
|
||||
roster.pop(index)
|
||||
return True
|
||||
else:
|
||||
if self.add_lineup(this_player)[0]:
|
||||
self.rotation.pop(index)
|
||||
return True
|
||||
return False
|
||||
|
||||
def delete_player(self, name):
|
||||
this_player, index, roster = self.find_player(name)
|
||||
if this_player is not None and len(roster) > 1:
|
||||
roster.pop(index)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def slide_player(self, name, new_spot):
|
||||
this_player, index, roster = self.find_player(name)
|
||||
if this_player is not None and new_spot <= len(roster):
|
||||
roster.pop(index)
|
||||
roster.insert(new_spot-1, this_player)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def add_lineup(self, new_player):
|
||||
if len(self.lineup) < 20:
|
||||
self.lineup.append(new_player)
|
||||
|
@ -113,34 +159,59 @@ class team(object):
|
|||
else:
|
||||
return (False, "20 players in the lineup, maximum. We're being really generous here.")
|
||||
|
||||
def set_pitcher(self, new_player):
|
||||
self.pitcher = new_player
|
||||
return (True,)
|
||||
def add_pitcher(self, new_player):
|
||||
if len(self.rotation) < 8:
|
||||
self.rotation.append(new_player)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def set_pitcher(self, rotation_slot = None, use_lineup = False):
|
||||
temp_rotation = self.rotation.copy()
|
||||
if use_lineup:
|
||||
for batter in self.rotation:
|
||||
temp_rotation.append(batter)
|
||||
if rotation_slot is None:
|
||||
self.pitcher = random.choice(temp_rotation)
|
||||
else:
|
||||
self.pitcher = temp_rotation[(rotation_slot-1) % len(temp_rotation)]
|
||||
|
||||
def is_ready(self):
|
||||
return (len(self.lineup) >= 1 and self.pitcher is not None)
|
||||
try:
|
||||
return (len(self.lineup) >= 1 and len(self.rotation) > 0)
|
||||
except AttributeError:
|
||||
self.rotation = [self.pitcher]
|
||||
self.pitcher = None
|
||||
return (len(self.lineup) >= 1 and len(self.rotation) > 0)
|
||||
|
||||
def prepare_for_save(self):
|
||||
self.lineup_position = 0
|
||||
self.score = 0
|
||||
if self.pitcher is not None and self.pitcher not in self.rotation:
|
||||
self.rotation.append(self.pitcher)
|
||||
self.pitcher = None
|
||||
for this_player in self.lineup:
|
||||
for stat in this_player.game_stats.keys():
|
||||
this_player.game_stats[stat] = 0
|
||||
return True
|
||||
for this_player in self.rotation:
|
||||
for stat in this_player.game_stats.keys():
|
||||
this_player.game_stats[stat] = 0
|
||||
return self
|
||||
|
||||
def finalize(self):
|
||||
if self.is_ready():
|
||||
if self.pitcher == None:
|
||||
self.set_pitcher()
|
||||
while len(self.lineup) <= 4:
|
||||
self.lineup.append(random.choice(self.lineup))
|
||||
return True
|
||||
else:
|
||||
self.lineup.append(random.choice(self.lineup))
|
||||
return self
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
class game(object):
|
||||
|
||||
def __init__(self, name, team1, team2, length=None):
|
||||
self.name = name
|
||||
def __init__(self, team1, team2, length=None):
|
||||
self.over = False
|
||||
self.teams = {"away" : team1, "home" : team2}
|
||||
self.inning = 1
|
||||
|
@ -160,8 +231,13 @@ class game(object):
|
|||
def get_batter(self):
|
||||
if self.top_of_inning:
|
||||
bat_team = self.teams["away"]
|
||||
counter = self.weather.counter_away
|
||||
else:
|
||||
bat_team = self.teams["home"]
|
||||
counter = self.weather.counter_home
|
||||
|
||||
if self.weather.name == "Heavy Snow" and counter == bat_team.lineup_position:
|
||||
return bat_team.pitcher
|
||||
return bat_team.lineup[bat_team.lineup_position % len(bat_team.lineup)]
|
||||
|
||||
def get_pitcher(self):
|
||||
|
@ -194,6 +270,13 @@ class game(object):
|
|||
pb_system_stat = (random.gauss(1*math.erf((bat_stat - pitch_stat)*1.5)-1.8,2.2))
|
||||
hitnum = random.gauss(2*math.erf(bat_stat/4)-1,3)
|
||||
|
||||
if self.weather.name == "Twilight":
|
||||
error_line = - (math.log(defender.stlats["defense_stars"] + 1)/50) + 1
|
||||
error_roll = random.random()
|
||||
if error_roll > error_line:
|
||||
outcome["error"] = True
|
||||
outcome["defender"] = defender
|
||||
pb_system_stat = 0.1
|
||||
|
||||
|
||||
if pb_system_stat <= 0:
|
||||
|
@ -238,7 +321,7 @@ class game(object):
|
|||
outcome["ishit"] = True
|
||||
if hitnum < 1:
|
||||
outcome["text"] = appearance_outcomes.single
|
||||
elif hitnum < 2.85:
|
||||
elif hitnum < 2.85 or "error" in outcome.keys():
|
||||
outcome["text"] = appearance_outcomes.double
|
||||
elif hitnum < 3.1:
|
||||
outcome["text"] = appearance_outcomes.triple
|
||||
|
@ -289,6 +372,7 @@ class game(object):
|
|||
run_roll = run_roll * .9 #stealing third is harder
|
||||
if run_roll < 1:
|
||||
outcome["steals"].append(f"{baserunner} was caught stealing {base_string(start_base+1)} base by {defender}!")
|
||||
self.get_pitcher().game_stats["outs_pitched"] += 1
|
||||
self.outs += 1
|
||||
else:
|
||||
outcome["steals"].append(f"{baserunner} steals {base_string(start_base+1)} base!")
|
||||
|
@ -308,6 +392,11 @@ class game(object):
|
|||
if base is not None:
|
||||
runs += 1
|
||||
self.bases = {1 : None, 2 : None, 3 : None}
|
||||
if "veil" in outcome.keys():
|
||||
if runs < 4:
|
||||
self.bases[runs] = self.get_batter()
|
||||
else:
|
||||
runs += 1
|
||||
return runs
|
||||
|
||||
elif "advance" in outcome.keys():
|
||||
|
@ -422,14 +511,26 @@ class game(object):
|
|||
def batterup(self):
|
||||
scores_to_add = 0
|
||||
result = self.at_bat()
|
||||
self.get_batter()
|
||||
if self.top_of_inning:
|
||||
offense_team = self.teams["away"]
|
||||
weather_count = self.weather.counter_away
|
||||
defense_team = self.teams["home"]
|
||||
else:
|
||||
offense_team = self.teams["home"]
|
||||
weather_count = self.weather.counter_home
|
||||
defense_team = self.teams["away"]
|
||||
|
||||
if self.weather.name == "Slight Tailwind" and "mulligan" not in self.last_update[0].keys() and not result["ishit"] and result["text"] != appearance_outcomes.walk:
|
||||
mulligan_roll_target = -((((self.get_batter().stlats["batting_stars"])-5)/6)**2)+1
|
||||
if random.random() > mulligan_roll_target and self.get_batter().stlats["batting_stars"] <= 5:
|
||||
result["mulligan"] = True
|
||||
return (result, 0)
|
||||
|
||||
if self.weather.name == "Heavy Snow" and weather_count == offense_team.lineup_position and "snow_atbat" not in self.last_update[0].keys():
|
||||
result["snow_atbat"] = True
|
||||
result["text"] = f"{offense_team.lineup[offense_team.lineup_position % len(offense_team.lineup)].name}'s hands are too cold! {self.get_batter().name} is forced to bat!"
|
||||
return (result, 0)
|
||||
|
||||
defenders = defense_team.lineup.copy()
|
||||
defenders.append(defense_team.pitcher)
|
||||
defender = random.choice(defenders) #pitcher can field outs now :3
|
||||
|
@ -447,6 +548,10 @@ class game(object):
|
|||
elif result["text"] == appearance_outcomes.homerun or result["text"] == appearance_outcomes.grandslam:
|
||||
self.get_batter().game_stats["total_bases"] += 4
|
||||
self.get_batter().game_stats["home_runs"] += 1
|
||||
if self.weather.name == "Thinned Veil":
|
||||
result["veil"] = True
|
||||
|
||||
|
||||
|
||||
scores_to_add += self.baserunner_check(defender, result)
|
||||
|
||||
|
@ -519,12 +624,21 @@ class game(object):
|
|||
for base in self.bases.keys():
|
||||
self.bases[base] = None
|
||||
self.outs = 0
|
||||
if self.top_of_inning and self.weather.name == "Heavy Snow" and self.weather.counter_away < self.teams["away"].lineup_position:
|
||||
self.weather.counter_away = self.pitcher_insert(self.teams["away"])
|
||||
|
||||
if not self.top_of_inning:
|
||||
if self.weather.name == "Heavy Snow" and self.weather.counter_home < self.teams["home"].lineup_position:
|
||||
self.weather.counter_home = self.pitcher_insert(self.teams["home"])
|
||||
self.inning += 1
|
||||
if self.inning > self.max_innings and self.teams["home"].score != self.teams["away"].score: #game over
|
||||
self.over = True
|
||||
self.top_of_inning = not self.top_of_inning
|
||||
|
||||
def pitcher_insert(self, this_team):
|
||||
rounds = math.ceil(this_team.lineup_position / len(this_team.lineup))
|
||||
position = random.randint(0, len(this_team.lineup)-1)
|
||||
return rounds * len(this_team.lineup) + position
|
||||
|
||||
def end_of_game_report(self):
|
||||
return {
|
||||
|
@ -567,19 +681,9 @@ class game(object):
|
|||
else:
|
||||
inningtext = "bottom"
|
||||
|
||||
updatestring = f"{self.last_update[0]['batter']} {self.last_update[0]['text'].value} {self.last_update[0]['defender']}{punc}\n"
|
||||
updatestring = "this isn't used but i don't want to break anything"
|
||||
|
||||
if self.last_update[1] > 0:
|
||||
updatestring += f"{self.last_update[1]} runs scored!"
|
||||
|
||||
return f"""Last update: {updatestring}
|
||||
|
||||
Score: {self.teams['away'].score} - {self.teams['home'].score}.
|
||||
Current inning: {inningtext} of {self.inning}. {self.outs} outs.
|
||||
Pitcher: {self.get_pitcher().name}
|
||||
Batter: {self.get_batter().name}
|
||||
Bases: 3: {str(self.bases[3])} 2: {str(self.bases[2])} 1: {str(self.bases[1])}
|
||||
"""
|
||||
return "this isn't used but i don't want to break anything"
|
||||
else:
|
||||
return f"""Game over! Final score: **{self.teams['away'].score} - {self.teams['home'].score}**
|
||||
Last update: {self.last_update[0]['batter']} {self.last_update[0]['text'].value} {self.last_update[0]['defender']}{punc}"""
|
||||
|
@ -589,6 +693,10 @@ class game(object):
|
|||
return "Game not started."
|
||||
|
||||
def add_stats(self):
|
||||
players = self.get_stats()
|
||||
db.add_stats(players)
|
||||
|
||||
def get_stats(self):
|
||||
players = []
|
||||
for this_player in self.teams["away"].lineup:
|
||||
players.append((this_player.name, this_player.game_stats))
|
||||
|
@ -596,7 +704,20 @@ class game(object):
|
|||
players.append((this_player.name, this_player.game_stats))
|
||||
players.append((self.teams["home"].pitcher.name, self.teams["home"].pitcher.game_stats))
|
||||
players.append((self.teams["away"].pitcher.name, self.teams["away"].pitcher.game_stats))
|
||||
db.add_stats(players)
|
||||
return players
|
||||
|
||||
def get_team_specific_stats(self):
|
||||
players = {
|
||||
self.teams["away"].name : [],
|
||||
self.teams["home"].name : []
|
||||
}
|
||||
for this_player in self.teams["away"].lineup:
|
||||
players[self.teams["away"].name].append((this_player.name, this_player.game_stats))
|
||||
for this_player in self.teams["home"].lineup:
|
||||
players[self.teams["home"].name].append((this_player.name, this_player.game_stats))
|
||||
players[self.teams["home"].name].append((self.teams["home"].pitcher.name, self.teams["home"].pitcher.game_stats))
|
||||
players[self.teams["away"].name].append((self.teams["away"].pitcher.name, self.teams["away"].pitcher.game_stats))
|
||||
return players
|
||||
|
||||
|
||||
|
||||
|
@ -619,20 +740,40 @@ def get_team(name):
|
|||
try:
|
||||
team_json = jsonpickle.decode(db.get_team(name)[0], keys=True, classes=team)
|
||||
if team_json is not None:
|
||||
if team_json.pitcher is not None: #detects old-format teams, adds pitcher
|
||||
team_json.rotation.append(team_json.pitcher)
|
||||
team_json.pitcher = None
|
||||
update_team(team_json)
|
||||
return team_json
|
||||
return None
|
||||
except AttributeError:
|
||||
team_json.rotation = []
|
||||
team_json.rotation.append(team_json.pitcher)
|
||||
team_json.pitcher = None
|
||||
update_team(team_json)
|
||||
return team_json
|
||||
except:
|
||||
return None
|
||||
|
||||
def get_team_and_owner(name):
|
||||
#try:
|
||||
counter, name, team_json_string, timestamp, owner_id = db.get_team(name, owner=True)
|
||||
team_json = jsonpickle.decode(team_json_string, keys=True, classes=team)
|
||||
if team_json is not None:
|
||||
try:
|
||||
counter, name, team_json_string, timestamp, owner_id = db.get_team(name, owner=True)
|
||||
team_json = jsonpickle.decode(team_json_string, keys=True, classes=team)
|
||||
if team_json is not None:
|
||||
if team_json.pitcher is not None: #detects old-format teams, adds pitcher
|
||||
team_json.rotation.append(team_json.pitcher)
|
||||
team_json.pitcher = None
|
||||
update_team(team_json)
|
||||
return (team_json, owner_id)
|
||||
return None
|
||||
except AttributeError:
|
||||
team_json.rotation = []
|
||||
team_json.rotation.append(team_json.pitcher)
|
||||
team_json.pitcher = None
|
||||
update_team(team_json)
|
||||
return (team_json, owner_id)
|
||||
return None
|
||||
#except:
|
||||
#return None
|
||||
except:
|
||||
return None
|
||||
|
||||
def save_team(this_team, user_id):
|
||||
try:
|
||||
|
@ -643,6 +784,15 @@ def save_team(this_team, user_id):
|
|||
except:
|
||||
return None
|
||||
|
||||
def update_team(this_team):
|
||||
try:
|
||||
this_team.prepare_for_save()
|
||||
team_json_string = jsonpickle.encode(this_team, keys=True)
|
||||
db.update_team(this_team.name, team_json_string)
|
||||
return True
|
||||
except:
|
||||
return None
|
||||
|
||||
def get_all_teams():
|
||||
teams = []
|
||||
for team_pickle in db.get_all_teams():
|
||||
|
@ -653,8 +803,22 @@ def get_all_teams():
|
|||
def search_team(search_term):
|
||||
teams = []
|
||||
for team_pickle in db.search_teams(search_term):
|
||||
this_team = jsonpickle.decode(team_pickle[0], keys=True, classes=team)
|
||||
teams.append(this_team)
|
||||
team_json = jsonpickle.decode(team_pickle[0], keys=True, classes=team)
|
||||
try:
|
||||
if team_json.pitcher is not None:
|
||||
if len(team_json.rotation) == 0: #detects old-format teams, adds pitcher
|
||||
team_json.rotation.append(team_json.pitcher)
|
||||
team_json.pitcher = None
|
||||
update_team(team_json)
|
||||
except AttributeError:
|
||||
team_json.rotation = []
|
||||
team_json.rotation.append(team_json.pitcher)
|
||||
team_json.pitcher = None
|
||||
update_team(team_json)
|
||||
except:
|
||||
return None
|
||||
|
||||
teams.append(team_json)
|
||||
return teams
|
||||
|
||||
def base_string(base):
|
||||
|
@ -674,6 +838,8 @@ class weather(object):
|
|||
def __init__(self, new_name, new_emoji):
|
||||
self.name = new_name
|
||||
self.emoji = new_emoji
|
||||
self.counter_away = 0
|
||||
self.counter_home = 0
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.emoji} {self.name}"
|
||||
return f"{self.emoji} {self.name}"
|
||||
|
|
203
league_storage.py
Normal file
|
@ -0,0 +1,203 @@
|
|||
import os, json, re, jsonpickle
|
||||
import sqlite3 as sql
|
||||
|
||||
data_dir = "data"
|
||||
league_dir = "leagues"
|
||||
|
||||
def create_connection(league_name):
|
||||
#create connection, create db if doesn't exist
|
||||
conn = None
|
||||
try:
|
||||
if not os.path.exists(os.path.join(data_dir, league_dir, league_name)):
|
||||
|
||||
os.makedirs(os.path.join(data_dir, league_dir, league_name))
|
||||
conn = sql.connect(os.path.join(data_dir, league_dir, league_name, f"{league_name}.db"))
|
||||
|
||||
# enable write-ahead log for performance and resilience
|
||||
conn.execute('pragma journal_mode=wal')
|
||||
|
||||
return conn
|
||||
except:
|
||||
print("oops, db connection no work")
|
||||
return conn
|
||||
|
||||
def create_season_connection(league_name, season_num):
|
||||
#create connection, create db if doesn't exist
|
||||
conn = None
|
||||
try:
|
||||
if not os.path.exists(os.path.join(data_dir, league_dir, league_name)):
|
||||
|
||||
os.makedirs(os.path.join(data_dir, league_dir, league_name))
|
||||
conn = sql.connect(os.path.join(data_dir, league_dir, league_name, season_num, f"{league_name}.db"))
|
||||
|
||||
# enable write-ahead log for performance and resilience
|
||||
conn.execute('pragma journal_mode=wal')
|
||||
|
||||
return conn
|
||||
except:
|
||||
print("oops, db connection no work")
|
||||
return conn
|
||||
|
||||
def state(league_name):
|
||||
if not os.path.exists(os.path.dirname(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state"))):
|
||||
os.makedirs(os.path.dirname(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state")))
|
||||
with open(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state")) as state_file:
|
||||
return json.load(state_file)
|
||||
|
||||
def init_league_db(league):
|
||||
conn = create_connection(league.name)
|
||||
|
||||
player_stats_table_check_string = """ CREATE TABLE IF NOT EXISTS stats (
|
||||
counter integer PRIMARY KEY,
|
||||
id text,
|
||||
name text,
|
||||
team_name text,
|
||||
outs_pitched integer DEFAULT 0,
|
||||
walks_allowed integer DEFAULT 0,
|
||||
hits_allowed integer DEFAULT 0,
|
||||
strikeouts_given integer DEFAULT 0,
|
||||
runs_allowed integer DEFAULT 0,
|
||||
plate_appearances integer DEFAULT 0,
|
||||
walks_taken integer DEFAULT 0,
|
||||
sacrifices integer DEFAULT 0,
|
||||
hits integer DEFAULT 0,
|
||||
home_runs integer DEFAULT 0,
|
||||
total_bases integer DEFAULT 0,
|
||||
rbis integer DEFAULT 0,
|
||||
strikeouts_taken integer DEFAULT 0
|
||||
);"""
|
||||
|
||||
teams_table_check_string = """ CREATE TABLE IF NOT EXISTS teams (
|
||||
counter integer PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
wins integer DEFAULT 0,
|
||||
losses integer DEFAULT 0,
|
||||
run_diff integer DEFAULT 0
|
||||
); """
|
||||
|
||||
if conn is not None:
|
||||
c = conn.cursor()
|
||||
c.execute(player_stats_table_check_string)
|
||||
c.execute(teams_table_check_string)
|
||||
|
||||
for team in league.teams_in_league():
|
||||
print(team)
|
||||
c.execute("INSERT INTO teams (name) VALUES (?)", (team.name,))
|
||||
|
||||
player_string = "INSERT INTO stats (name, team_name) VALUES (?,?)"
|
||||
for batter in team.lineup:
|
||||
c.execute(player_string, (batter.name, team.name))
|
||||
for pitcher in team.rotation:
|
||||
c.execute(player_string, (pitcher.name, team.name))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def save_league(league):
|
||||
if league_exists(league.name):
|
||||
state_dic = {
|
||||
"season" : league.season,
|
||||
"day" : league.day,
|
||||
"constraints" : league.constraints,
|
||||
"schedule" : league.schedule,
|
||||
"game_length" : league.game_length,
|
||||
"series_length" : league.series_length,
|
||||
"games_per_hour" : league.games_per_hour,
|
||||
"owner" : league.owner,
|
||||
"champion" : league.champion,
|
||||
"historic" : league.historic
|
||||
}
|
||||
with open(os.path.join(data_dir, league_dir, league.name, f"{league.name}.state"), "w") as state_file:
|
||||
json.dump(state_dic, state_file, indent=4)
|
||||
|
||||
def add_stats(league_name, player_game_stats_list):
|
||||
conn = create_connection(league_name)
|
||||
if conn is not None:
|
||||
c=conn.cursor()
|
||||
for team_name in player_game_stats_list.keys():
|
||||
for (name, player_stats_dic) in player_game_stats_list[team_name]:
|
||||
c.execute("SELECT * FROM stats WHERE name=? AND team_name=?",(name, team_name))
|
||||
this_player = c.fetchone()
|
||||
if this_player is not None:
|
||||
for stat in player_stats_dic.keys():
|
||||
c.execute(f"SELECT {stat} FROM stats WHERE name=? AND team_name=?",(name, team_name))
|
||||
old_value = int(c.fetchone()[0])
|
||||
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=? AND team_name=?",(player_stats_dic[stat]+old_value, name, team_name))
|
||||
else:
|
||||
c.execute("INSERT INTO stats(name) VALUES (?)",(name,))
|
||||
for stat in player_stats_dic.keys():
|
||||
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=? AND team_name=?",(player_stats_dic[stat], name, team_name))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def update_standings(league_name, update_dic):
|
||||
if league_exists(league_name):
|
||||
conn = create_connection(league_name)
|
||||
if conn is not None:
|
||||
c = conn.cursor()
|
||||
|
||||
for team_name in update_dic.keys():
|
||||
for stat_type in update_dic[team_name].keys(): #wins, losses, run_diff
|
||||
c.execute(f"SELECT {stat_type} FROM teams WHERE name = ?", (team_name,))
|
||||
old_value = int(c.fetchone()[0])
|
||||
c.execute(f"UPDATE teams SET {stat_type} = ? WHERE name = ?", (update_dic[team_name][stat_type]+old_value, team_name))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def get_standings(league_name):
|
||||
if league_exists(league_name):
|
||||
conn = create_connection(league_name)
|
||||
if conn is not None:
|
||||
c = conn.cursor()
|
||||
|
||||
c.execute("SELECT name, wins, losses, run_diff FROM teams",)
|
||||
standings_array = c.fetchall()
|
||||
conn.close()
|
||||
return standings_array
|
||||
|
||||
def season_save(league):
|
||||
if league_exists(league.name):
|
||||
seasons = 1
|
||||
with os.scandir(os.path.join(data_dir, league_dir, league.name)) as folder:
|
||||
for item in folder:
|
||||
if "." not in item.name:
|
||||
seasons += 1
|
||||
new_dir = os.path.join(data_dir, league_dir, league.name, str(seasons))
|
||||
os.makedirs(new_dir)
|
||||
with os.scandir(os.path.join(data_dir, league_dir, league.name)) as folder:
|
||||
for item in folder:
|
||||
if "." in item.name:
|
||||
os.rename(os.path.join(data_dir, league_dir, league.name, item.name), os.path.join(new_dir, item.name))
|
||||
|
||||
def get_past_standings(league_name, season_num):
|
||||
if league_exists(league_name):
|
||||
with os.scandir(os.path.join(data_dir, league_dir, league_name)) as folder:
|
||||
for item in folder:
|
||||
if item.name == str(season_num):
|
||||
conn = create_season_connection(league_name, str(item.name))
|
||||
if conn is not None:
|
||||
c = conn.cursor()
|
||||
|
||||
c.execute("SELECT name, wins, losses, run_diff FROM teams",)
|
||||
standings_array = c.fetchall()
|
||||
conn.close()
|
||||
return standings_array
|
||||
|
||||
def get_past_champion(league_name, season_num):
|
||||
if league_exists(league_name):
|
||||
with os.scandir(os.path.join(data_dir, league_dir, league_name)) as folder:
|
||||
for item in folder:
|
||||
if item.name == str(season_num):
|
||||
with open(os.path.join(data_dir, league_dir, league_name, item.name, f"{league_name}.state")) as state_file:
|
||||
state_dic = json.load(state_file)
|
||||
return state_dic["champion"]
|
||||
|
||||
def league_exists(league_name):
|
||||
with os.scandir(os.path.join(data_dir, league_dir)) as folder:
|
||||
for subfolder in folder:
|
||||
if league_name == subfolder.name:
|
||||
with os.scandir(subfolder.path) as league_folder:
|
||||
for item in league_folder:
|
||||
if item.name == f"{league_name}.db":
|
||||
return True
|
||||
return False
|
506
leagues.py
Normal file
|
@ -0,0 +1,506 @@
|
|||
import time, asyncio, json, jsonpickle, random, math, os
|
||||
import league_storage as league_db
|
||||
from itertools import chain
|
||||
from games import team, game
|
||||
from discord import Embed, Color
|
||||
|
||||
data_dir = "data"
|
||||
league_dir = "leagues"
|
||||
|
||||
class league_structure(object):
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
self.historic = False
|
||||
self.owner = None
|
||||
self.season = 1
|
||||
self.autoplay = -1
|
||||
self.champion = None
|
||||
|
||||
def setup(self, league_dic, division_games = 1, inter_division_games = 1, inter_league_games = 1, games_per_hour = 2):
|
||||
self.league = league_dic # { subleague name : { division name : [team object] } }
|
||||
self.constraints = {
|
||||
"division_games" : division_games,
|
||||
"inter_div_games" : inter_division_games,
|
||||
"inter_league_games" : inter_league_games,
|
||||
"division_leaders" : 0,
|
||||
"wild_cards" : 0
|
||||
}
|
||||
self.day = 1
|
||||
self.schedule = {}
|
||||
self.series_length = 3 #can be changed
|
||||
self.game_length = None
|
||||
self.active = False
|
||||
self.games_per_hour = games_per_hour
|
||||
|
||||
def season_reset(self):
|
||||
self.season += 1
|
||||
self.day = 1
|
||||
self.champion = None
|
||||
self.schedule = {}
|
||||
self.generate_schedule()
|
||||
save_league(self)
|
||||
|
||||
def add_stats_from_game(self, players_dic):
|
||||
league_db.add_stats(self.name, players_dic)
|
||||
|
||||
def update_standings(self, results_dic):
|
||||
league_db.update_standings(self.name, results_dic)
|
||||
|
||||
|
||||
def last_series_check(self):
|
||||
return str(math.ceil((self.day)/self.series_length) + 1) not in self.schedule.keys()
|
||||
|
||||
def day_to_series_num(self, day):
|
||||
return math.ceil((self.day)/self.series_length)
|
||||
|
||||
def tiebreaker_required(self):
|
||||
standings = {}
|
||||
matchups = []
|
||||
tournaments = []
|
||||
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
|
||||
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
|
||||
|
||||
for subleague in iter(self.league.keys()):
|
||||
team_dic = {}
|
||||
subleague_array = []
|
||||
wildcard_leaders = []
|
||||
for division in iter(self.league[subleague].keys()):
|
||||
division_standings = []
|
||||
division_standings += self.division_standings(self.league[subleague][division], standings)
|
||||
division_leaders = division_standings[:self.constraints["division_leaders"]]
|
||||
for division_team, wins, losses, diff, gb in division_standings[self.constraints["division_leaders"]:]:
|
||||
if division_team.name != division_leaders[-1][0].name and standings[division_team.name]["wins"] == standings[division_leaders[-1][0].name]["wins"]:
|
||||
matchups.append((division_team, division_standings[self.constraints["division_leaders"]-1][0], f"{division} Tiebreaker"))
|
||||
|
||||
this_div_wildcard = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
|
||||
subleague_array += this_div_wildcard
|
||||
if self.constraints["wild_cards"] > 0:
|
||||
wildcard_standings = self.division_standings(subleague_array, standings)
|
||||
wildcard_leaders = wildcard_standings[:self.constraints["wild_cards"]]
|
||||
for wildcard_team, wins, losses, diff, gb in wildcard_standings[self.constraints["wild_cards"]:]:
|
||||
if wildcard_team.name != wildcard_leaders[-1][0].name and standings[wildcard_team.name]["wins"] == standings[wildcard_leaders[-1][0].name]["wins"]:
|
||||
matchups.append((wildcard_team, wildcard_standings[self.constraints["wild_cards"]-1][0], f"{subleague} Wildcard Tiebreaker"))
|
||||
|
||||
for team_a, team_b, type in matchups:
|
||||
tourney = tournament(f"{self.name} {type}",{team_a : {"wins" : 1}, team_b : {"wins" : 0}}, finals_series_length=1, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour))
|
||||
tourney.build_bracket(by_wins = True)
|
||||
tourney.league = self
|
||||
tournaments.append(tourney)
|
||||
return tournaments
|
||||
|
||||
def find_team(self, team_name):
|
||||
for subleague in iter(self.league.keys()):
|
||||
for division in iter(self.league[subleague].keys()):
|
||||
if team_name in self.league[subleague][division]:
|
||||
return (subleague, division)
|
||||
|
||||
def teams_in_league(self):
|
||||
teams = []
|
||||
for division in self.league.values():
|
||||
for teams_list in division.values():
|
||||
teams += teams_list
|
||||
return teams
|
||||
|
||||
def teams_in_subleague(self, subleague_name):
|
||||
teams = []
|
||||
if subleague_name in self.league.keys():
|
||||
for division_list in self.league[subleague_name].values():
|
||||
teams += division_list
|
||||
return teams
|
||||
else:
|
||||
print("League not found.")
|
||||
return None
|
||||
|
||||
def teams_in_division(self, subleague_name, division_name):
|
||||
if subleague_name in self.league.keys() and division_name in self.league[subleague_name].keys():
|
||||
return self.league[subleague_name][division_name]
|
||||
else:
|
||||
print("Division in that league not found.")
|
||||
return None
|
||||
|
||||
def make_matchups(self):
|
||||
matchups = []
|
||||
batch_subleagues = [] #each sub-array is all teams in each subleague
|
||||
subleague_max = 1
|
||||
for subleague in self.league.keys():
|
||||
teams = self.teams_in_subleague(subleague)
|
||||
if subleague_max < len(teams):
|
||||
subleague_max = len(teams)
|
||||
batch_subleagues.append(teams)
|
||||
|
||||
for subleague in batch_subleagues:
|
||||
while len(subleague) < subleague_max:
|
||||
subleague.append("OFF")
|
||||
|
||||
for i in range(0, self.constraints["inter_league_games"]): #generates inter-league matchups
|
||||
unmatched_indices = [i for i in range(0, len(batch_subleagues))]
|
||||
for subleague_index in range(0, len(batch_subleagues)):
|
||||
if subleague_index in unmatched_indices:
|
||||
unmatched_indices.pop(unmatched_indices.index(subleague_index))
|
||||
match_with_index = random.choice(unmatched_indices)
|
||||
unmatched_indices.pop(unmatched_indices.index(match_with_index))
|
||||
league_a = batch_subleagues[subleague_index].copy()
|
||||
league_b = batch_subleagues[match_with_index].copy()
|
||||
random.shuffle(league_a)
|
||||
random.shuffle(league_b)
|
||||
a_home = True
|
||||
for team_a, team_b in zip(league_a, league_b):
|
||||
if a_home:
|
||||
matchups.append([team_b.name, team_a.name])
|
||||
else:
|
||||
matchups.append([team_a.name, team_b.name])
|
||||
a_home = not a_home
|
||||
|
||||
for i in range(0, self.constraints["inter_div_games"]): #inter-division matchups
|
||||
for subleague in self.league.keys():
|
||||
division_max = 1
|
||||
divisions = []
|
||||
for div in self.league[subleague].keys():
|
||||
if division_max < len(self.league[subleague][div]):
|
||||
divison_max = len(self.league[subleague][div])
|
||||
divisions.append(self.league[subleague][div])
|
||||
|
||||
last_div = None
|
||||
if len(divisions) % 2 != 0:
|
||||
if division_max % 2 != 0:
|
||||
divisions.append(["OFF" for i in range(0, division_max)])
|
||||
else:
|
||||
last_div = divisions.pop
|
||||
|
||||
divs_a = list(chain(divisions[int(len(divisions)/2):]))[0]
|
||||
if last_div is not None:
|
||||
divs_a.extend(last_div[int(len(last_div)/2):])
|
||||
random.shuffle(divs_a)
|
||||
|
||||
divs_b = list(chain(divisions[:int(len(divisions)/2)]))[0]
|
||||
if last_div is not None:
|
||||
divs_a.extend(last_div[:int(len(last_div)/2)])
|
||||
random.shuffle(divs_b)
|
||||
|
||||
a_home = True
|
||||
for team_a, team_b in zip(divs_a, divs_b):
|
||||
if a_home:
|
||||
matchups.append([team_b.name, team_a.name])
|
||||
else:
|
||||
matchups.append([team_a.name, team_b.name])
|
||||
a_home = not a_home
|
||||
|
||||
|
||||
for subleague in self.league.keys():
|
||||
for division in self.league[subleague].values(): #generate round-robin matchups
|
||||
if len(division) % 2 != 0:
|
||||
division.append("OFF")
|
||||
|
||||
for i in range(0, len(division)-1):
|
||||
teams_a = division[int(len(division)/2):]
|
||||
teams_b = division[:int(len(division)/2)]
|
||||
teams_b.reverse()
|
||||
|
||||
for team_a, team_b in zip(teams_a, teams_b):
|
||||
for j in range(0, self.constraints["division_games"]):
|
||||
if i % 2 == 0:
|
||||
matchups.append([team_b.name, team_a.name])
|
||||
else:
|
||||
matchups.append([team_a.name, team_b.name])
|
||||
|
||||
division.insert(1, division.pop())
|
||||
return matchups
|
||||
|
||||
def generate_schedule(self):
|
||||
matchups = self.make_matchups()
|
||||
random.shuffle(matchups)
|
||||
for game in matchups:
|
||||
scheduled = False
|
||||
day = 1
|
||||
while not scheduled:
|
||||
found = False
|
||||
if str(day) in self.schedule.keys():
|
||||
for game_on_day in self.schedule[str(day)]:
|
||||
for team in game:
|
||||
if team in game_on_day:
|
||||
found = True
|
||||
if not found:
|
||||
self.schedule[str(day)].append(game)
|
||||
scheduled = True
|
||||
else:
|
||||
self.schedule[str(day)] = [game]
|
||||
scheduled = True
|
||||
day += 1
|
||||
|
||||
def division_standings(self, division, standings):
|
||||
def sorter(team_in_list):
|
||||
if team_in_list[2] == 0 and team_in_list[1] == 0:
|
||||
return (0, team_in_list[3])
|
||||
return (team_in_list[1]/(team_in_list[1]+team_in_list[2]), team_in_list[3])
|
||||
|
||||
teams = division.copy()
|
||||
|
||||
for index in range(0, len(teams)):
|
||||
this_team = teams[index]
|
||||
teams[index] = [this_team, standings[teams[index].name]["wins"], standings[teams[index].name]["losses"], standings[teams[index].name]["run_diff"], 0]
|
||||
|
||||
teams.sort(key=sorter, reverse=True)
|
||||
return teams
|
||||
|
||||
def past_standings(self, season_num):
|
||||
this_embed = Embed(color=Color.purple(), title=self.name)
|
||||
standings = {}
|
||||
for team_name, wins, losses, run_diff in league_db.get_past_standings(self.name, season_num):
|
||||
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
|
||||
|
||||
this_embed.add_field(name=league_db.get_past_champion(self.name, season_num), value=f"Season {season_num} champions", inline = False)
|
||||
|
||||
for subleague in iter(self.league.keys()):
|
||||
this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False)
|
||||
for division in iter(self.league[subleague].keys()):
|
||||
teams = self.division_standings(self.league[subleague][division], standings)
|
||||
|
||||
for index in range(0, len(teams)):
|
||||
if index == self.constraints["division_leaders"] - 1:
|
||||
teams[index][4] = "-"
|
||||
else:
|
||||
games_behind = ((teams[self.constraints["division_leaders"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["division_leaders"] - 1][2]))/2
|
||||
teams[index][4] = games_behind
|
||||
teams_string = ""
|
||||
for this_team in teams:
|
||||
if this_team[2] != 0 or this_team[1] != 0:
|
||||
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
|
||||
else:
|
||||
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
|
||||
|
||||
this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
|
||||
|
||||
this_embed.set_footer(text=f"Season {season_num} Final Standings")
|
||||
return this_embed
|
||||
|
||||
def season_length(self):
|
||||
return int(list(self.schedule.keys())[-1]) * self.series_length
|
||||
|
||||
def standings_embed(self):
|
||||
this_embed = Embed(color=Color.purple(), title=f"{self.name} Season {self.season}")
|
||||
standings = {}
|
||||
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
|
||||
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
|
||||
for subleague in iter(self.league.keys()):
|
||||
this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False)
|
||||
for division in iter(self.league[subleague].keys()):
|
||||
teams = self.division_standings(self.league[subleague][division], standings)
|
||||
|
||||
for index in range(0, len(teams)):
|
||||
if index == self.constraints["division_leaders"] - 1:
|
||||
teams[index][4] = "-"
|
||||
else:
|
||||
games_behind = ((teams[self.constraints["division_leaders"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["division_leaders"] - 1][2]))/2
|
||||
teams[index][4] = games_behind
|
||||
teams_string = ""
|
||||
for this_team in teams:
|
||||
if this_team[2] != 0 or this_team[1] != 0:
|
||||
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
|
||||
else:
|
||||
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
|
||||
|
||||
this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
|
||||
|
||||
this_embed.set_footer(text=f"Standings as of day {self.day-1} / {self.season_length()}")
|
||||
return this_embed
|
||||
|
||||
def wildcard_embed(self):
|
||||
this_embed = Embed(color=Color.purple(), title=f"{self.name} Wildcard Race")
|
||||
standings = {}
|
||||
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
|
||||
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
|
||||
for subleague in iter(self.league.keys()):
|
||||
subleague_array = []
|
||||
for division in iter(self.league[subleague].keys()):
|
||||
this_div = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
|
||||
subleague_array += this_div
|
||||
|
||||
teams = self.division_standings(subleague_array, standings)
|
||||
teams_string = ""
|
||||
for index in range(0, len(teams)):
|
||||
if index == self.constraints["wild_cards"] - 1:
|
||||
teams[index][4] = "-"
|
||||
else:
|
||||
games_behind = ((teams[self.constraints["wild_cards"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["wild_cards"] - 1][2]))/2
|
||||
teams[index][4] = games_behind
|
||||
|
||||
for this_team in teams:
|
||||
if this_team[2] != 0 or this_team[1] != 0:
|
||||
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
|
||||
else:
|
||||
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
|
||||
|
||||
this_embed.add_field(name=f"{subleague} League:", value=teams_string, inline = False)
|
||||
|
||||
this_embed.set_footer(text=f"Wildcard standings as of day {self.day-1}")
|
||||
return this_embed
|
||||
|
||||
def champ_series(self):
|
||||
tournaments = []
|
||||
standings = {}
|
||||
|
||||
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
|
||||
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
|
||||
|
||||
for subleague in iter(self.league.keys()):
|
||||
team_dic = {}
|
||||
division_leaders = []
|
||||
subleague_array = []
|
||||
wildcard_leaders = []
|
||||
for division in iter(self.league[subleague].keys()):
|
||||
division_leaders += self.division_standings(self.league[subleague][division], standings)[:self.constraints["division_leaders"]]
|
||||
this_div_wildcard = [this_team for this_team, wins, losses, diff, gb in self.division_standings(self.league[subleague][division], standings)[self.constraints["division_leaders"]:]]
|
||||
subleague_array += this_div_wildcard
|
||||
if self.constraints["wild_cards"] > 0:
|
||||
wildcard_leaders = self.division_standings(subleague_array, standings)[:self.constraints["wild_cards"]]
|
||||
|
||||
for this_team, wins, losses, diff, gb in division_leaders + wildcard_leaders:
|
||||
team_dic[this_team] = {"wins" : wins}
|
||||
|
||||
subleague_tournament = tournament(f"{self.name} {subleague} Subleague Series", team_dic, series_length=3, finals_series_length=5, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour))
|
||||
subleague_tournament.build_bracket(by_wins = True)
|
||||
subleague_tournament.league = self
|
||||
tournaments.append(subleague_tournament)
|
||||
|
||||
return tournaments
|
||||
|
||||
|
||||
class tournament(object):
|
||||
def __init__(self, name, team_dic, series_length = 5, finals_series_length = 7, max_innings = 9, id = None, secs_between_games = 300, secs_between_rounds = 600):
|
||||
self.name = name
|
||||
self.teams = team_dic #key: team object, value: wins
|
||||
self.bracket = None
|
||||
self.results = None
|
||||
self.series_length = series_length
|
||||
self.finals_length = finals_series_length
|
||||
self.game_length = max_innings
|
||||
self.active = False
|
||||
self.delay = secs_between_games
|
||||
self.round_delay = secs_between_rounds
|
||||
self.finals = False
|
||||
self.id = id
|
||||
self.league = None
|
||||
self.winner = None
|
||||
self.day = None
|
||||
|
||||
if id is None:
|
||||
self.id = random.randint(1111,9999)
|
||||
else:
|
||||
self.id = id
|
||||
|
||||
|
||||
def build_bracket(self, random_sort = False, by_wins = False, manual = False):
|
||||
teams_list = list(self.teams.keys()).copy()
|
||||
|
||||
if random_sort:
|
||||
def sorter(team_in_list):
|
||||
return random.random()
|
||||
|
||||
elif by_wins:
|
||||
def sorter(team_in_list):
|
||||
return self.teams[team_in_list]["wins"] #sorts by wins
|
||||
|
||||
else: #sort by average stars
|
||||
def sorter(team_in_list):
|
||||
return team_in_list.average_stars()
|
||||
|
||||
if not manual:
|
||||
teams_list.sort(key=sorter, reverse=True)
|
||||
|
||||
|
||||
bracket_layers = int(math.ceil(math.log(len(teams_list), 2)))
|
||||
empty_slots = int(math.pow(2, bracket_layers) - len(teams_list))
|
||||
|
||||
for i in range(0, empty_slots):
|
||||
teams_list.append(None)
|
||||
|
||||
previous_bracket_layer = teams_list.copy()
|
||||
for i in range(0, bracket_layers - 1):
|
||||
this_layer = []
|
||||
for pair in range(0, int(len(previous_bracket_layer)/2)):
|
||||
if pair % 2 == 0: #if even number
|
||||
this_layer.insert(0+int(pair/2), [previous_bracket_layer.pop(0), previous_bracket_layer.pop(-1)]) #every other pair goes at front of list, moving forward
|
||||
else:
|
||||
this_layer.insert(0-int((1+pair)/2), [previous_bracket_layer.pop(int(len(previous_bracket_layer)/2)-1), previous_bracket_layer.pop(int(len(previous_bracket_layer)/2))]) #every other pair goes at end of list, moving backward
|
||||
previous_bracket_layer = this_layer
|
||||
self.bracket = bracket(previous_bracket_layer, bracket_layers)
|
||||
|
||||
def round_check(self):
|
||||
if self.bracket.depth == 1:
|
||||
self.finals = True
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
class bracket(object):
|
||||
this_bracket = []
|
||||
|
||||
def __init__(self, bracket_list, depth):
|
||||
self.this_bracket = bracket_list
|
||||
self.depth = depth
|
||||
self.bottom_row = []
|
||||
|
||||
def get_bottom_row(self):
|
||||
self.depth = 1
|
||||
self.bottom_row = []
|
||||
self.dive(self.this_bracket)
|
||||
return self.bottom_row
|
||||
|
||||
def dive(self, branch):
|
||||
if not isinstance(branch[0], list): #if it's a pair of games
|
||||
self.bottom_row.append(branch)
|
||||
else:
|
||||
self.depth += 1
|
||||
return self.dive(branch[0]), self.dive(branch[1])
|
||||
|
||||
def set_winners_dive(self, winners_list, index = 0, branch = None, parent = None):
|
||||
if branch is None:
|
||||
branch = self.this_bracket.copy()
|
||||
if not isinstance(branch[0], list): #if it's a pair of games
|
||||
if branch[0].name in winners_list or branch[1] is None:
|
||||
winner = branch[0]
|
||||
if parent is not None:
|
||||
parent[index] = winner
|
||||
elif branch[1].name in winners_list:
|
||||
winner = branch[1]
|
||||
if parent is not None:
|
||||
parent[index] = winner
|
||||
else:
|
||||
self.set_winners_dive(winners_list, index = 0, branch = branch[0], parent = branch)
|
||||
self.set_winners_dive(winners_list, index = 1, branch = branch[1], parent = branch)
|
||||
|
||||
if parent is None:
|
||||
self.this_bracket = branch
|
||||
return branch
|
||||
|
||||
def save_league(this_league):
|
||||
if not league_db.league_exists(this_league.name):
|
||||
league_db.init_league_db(this_league)
|
||||
with open(os.path.join(data_dir, league_dir, this_league.name, f"{this_league.name}.league"), "w") as league_file:
|
||||
league_json_string = jsonpickle.encode(this_league.league, keys=True)
|
||||
json.dump(league_json_string, league_file, indent=4)
|
||||
league_db.save_league(this_league)
|
||||
|
||||
def load_league_file(league_name):
|
||||
if league_db.league_exists(league_name):
|
||||
state = league_db.state(league_name)
|
||||
this_league = league_structure(league_name)
|
||||
with open(os.path.join(data_dir, league_dir, league_name, f"{this_league.name}.league")) as league_file:
|
||||
this_league.league = jsonpickle.decode(json.load(league_file), keys=True, classes=team)
|
||||
with open(os.path.join(data_dir, league_dir, league_name, f"{this_league.name}.state")) as state_file:
|
||||
state_dic = json.load(state_file)
|
||||
|
||||
this_league.day = state_dic["day"]
|
||||
this_league.schedule = state_dic["schedule"]
|
||||
this_league.constraints = state_dic["constraints"]
|
||||
this_league.game_length = state_dic["game_length"]
|
||||
this_league.series_length = state_dic["series_length"]
|
||||
this_league.owner = state_dic["owner"]
|
||||
this_league.games_per_hour = state_dic["games_per_hour"]
|
||||
this_league.historic = state_dic["historic"]
|
||||
this_league.season = state_dic["season"]
|
||||
try:
|
||||
this_league.champion = state_dic["champion"]
|
||||
except:
|
||||
this_league.champion = None
|
||||
return this_league
|
|
@ -1,32 +1,130 @@
|
|||
import asyncio, time, datetime, games, json, threading, jinja2
|
||||
from flask import Flask, url_for, Response, render_template, request, jsonify
|
||||
import asyncio, time, datetime, games, json, threading, jinja2, leagues, os, leagues
|
||||
from leagues import league_structure
|
||||
from league_storage import league_exists
|
||||
from flask import Flask, url_for, Response, render_template, request, jsonify, send_from_directory, abort
|
||||
from flask_socketio import SocketIO, emit
|
||||
import database as db
|
||||
|
||||
app = Flask("the-prestige")
|
||||
app = Flask("the-prestige", static_folder='simmadome/build')
|
||||
app.config['SECRET KEY'] = 'dev'
|
||||
#app.config['SERVER_NAME'] = '0.0.0.0:5000'
|
||||
socketio = SocketIO(app)
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return render_template("index.html")
|
||||
# Serve React App
|
||||
@app.route('/', defaults={'path': ''})
|
||||
@app.route('/<path:path>')
|
||||
def serve(path):
|
||||
if path != "" and os.path.exists(app.static_folder + '/' + path):
|
||||
return send_from_directory(app.static_folder, path)
|
||||
else:
|
||||
return send_from_directory(app.static_folder, 'index.html')
|
||||
|
||||
### API
|
||||
|
||||
@app.route('/api/teams/search')
|
||||
def search_teams():
|
||||
query = request.args.get('query')
|
||||
page_len = int(request.args.get('page_len'))
|
||||
page_num = int(request.args.get('page_num'))
|
||||
|
||||
if query is None:
|
||||
abort(400, "A query term is required")
|
||||
|
||||
result = db.search_teams(query)
|
||||
if page_len is not None: #pagination should probably be done in the sqlite query but this will do for now
|
||||
if page_num is None:
|
||||
abort(400, "A page_len argument must be accompanied by a page_num argument")
|
||||
result = result[page_num*page_len : (page_num + 1)*page_len]
|
||||
|
||||
return jsonify([json.loads(x[0])['name'] for x in result]) #currently all we need is the name but that can change
|
||||
|
||||
MAX_SUBLEAGUE_DIVISION_TOTAL = 22;
|
||||
MAX_TEAMS_PER_DIVISION = 12;
|
||||
|
||||
@app.route('/api/leagues', methods=['POST'])
|
||||
def create_league():
|
||||
config = json.loads(request.data)
|
||||
|
||||
if league_exists(config['name']):
|
||||
return jsonify({'status':'err_league_exists'}), 400
|
||||
|
||||
num_subleagues = len(config['structure']['subleagues'])
|
||||
if num_subleagues < 1 or num_subleagues % 2 != 0:
|
||||
return jsonify({'status':'err_invalid_subleague_count'}), 400
|
||||
|
||||
num_divisions = len(config['structure']['subleagues'][0]['divisions'])
|
||||
if num_subleagues * (num_divisions + 1) > MAX_SUBLEAGUE_DIVISION_TOTAL:
|
||||
return jsonify({'status':'err_invalid_subleague_division_total'}), 400
|
||||
|
||||
league_dic = {}
|
||||
err_teams = []
|
||||
for subleague in config['structure']['subleagues']:
|
||||
if subleague['name'] in league_dic:
|
||||
return jsonify({'status':'err_duplicate_name', 'cause':subleague['name']})
|
||||
|
||||
subleague_dic = {}
|
||||
for division in subleague['divisions']:
|
||||
if division['name'] in subleague_dic:
|
||||
return jsonify({'status':'err_duplicate_name', 'cause':f"{subleague['name']}/{division['name']}"}), 400
|
||||
elif len(division['teams']) > MAX_TEAMS_PER_DIVISION:
|
||||
return jsonify({'status':'err_too_many_teams', 'cause':f"{subleague['name']}/{division['name']}"})
|
||||
|
||||
teams = []
|
||||
for team_name in division['teams']:
|
||||
team = games.get_team(team_name)
|
||||
if team is None:
|
||||
err_teams.append(team_name)
|
||||
else:
|
||||
teams.append(team)
|
||||
subleague_dic[division['name']] = teams
|
||||
league_dic[subleague['name']] = subleague_dic
|
||||
|
||||
if len(err_teams) > 0:
|
||||
return jsonify({'status':'err_no_such_team', 'cause': err_teams}), 400
|
||||
|
||||
for (key, min_val) in [
|
||||
('division_series', 1),
|
||||
('inter_division_series', 1),
|
||||
('inter_league_series', 1)
|
||||
]:
|
||||
if config[key] < min_val:
|
||||
return jsonify({'status':'err_invalid_optiion_value', 'cause':key}), 400
|
||||
|
||||
new_league = league_structure(config['name'])
|
||||
new_league.setup(
|
||||
league_dic,
|
||||
division_games=config['division_series'], # need to add a check that makes sure these values are ok
|
||||
inter_division_games=config['inter_division_series'],
|
||||
inter_league_games=config['inter_league_series'],
|
||||
)
|
||||
new_league.constraints["division_leaders"] = config["top_postseason"]
|
||||
new_league.constraints["wild_cards"] = config["wildcards"]
|
||||
new_league.generate_schedule()
|
||||
leagues.save_league(new_league)
|
||||
|
||||
return jsonify({'status':'success_league_created'})
|
||||
|
||||
|
||||
|
||||
### SOCKETS
|
||||
|
||||
thread2 = threading.Thread(target=socketio.run,args=(app,'0.0.0.0'))
|
||||
thread2.start()
|
||||
|
||||
master_games_dic = {} #key timestamp : (game game, {} state)
|
||||
data_to_send = []
|
||||
game_states = []
|
||||
|
||||
@socketio.on("recieved")
|
||||
def handle_new_conn(data):
|
||||
socketio.emit("states_update", data_to_send, room=request.sid)
|
||||
socketio.emit("states_update", game_states, room=request.sid)
|
||||
|
||||
def update_loop():
|
||||
global game_states
|
||||
while True:
|
||||
game_states = {}
|
||||
game_times = iter(master_games_dic.copy().keys())
|
||||
for game_time in game_times:
|
||||
this_game, state, discrim_string = master_games_dic[game_time]
|
||||
game_states = []
|
||||
game_ids = iter(master_games_dic.copy().keys())
|
||||
for game_id in game_ids:
|
||||
this_game, state, discrim_string = master_games_dic[game_id]
|
||||
test_string = this_game.gamestate_display_full()
|
||||
state["leagueoruser"] = discrim_string
|
||||
state["display_inning"] = this_game.inning #games need to be initialized with the following keys in state:
|
||||
|
@ -84,12 +182,27 @@ def update_loop():
|
|||
state["update_emoji"] = "💎"
|
||||
state["update_text"] = updatestring
|
||||
|
||||
elif "mulligan" in this_game.last_update[0].keys():
|
||||
updatestring = ""
|
||||
punc = ""
|
||||
if this_game.last_update[0]["defender"] != "":
|
||||
punc = ", "
|
||||
|
||||
state["update_emoji"] = "🏌️♀️"
|
||||
state["update_text"] = f"{this_game.last_update[0]['batter']} would have gone out, but they took a mulligan!"
|
||||
|
||||
elif "snow_atbat" in this_game.last_update[0].keys():
|
||||
state["update_emoji"] = "❄"
|
||||
state["update_text"] = this_game.last_update[0]["text"]
|
||||
|
||||
else:
|
||||
updatestring = ""
|
||||
punc = ""
|
||||
if this_game.last_update[0]["defender"] != "":
|
||||
punc = ". "
|
||||
|
||||
|
||||
|
||||
if "fc_out" in this_game.last_update[0].keys():
|
||||
name, base_string = this_game.last_update[0]['fc_out']
|
||||
updatestring = f"{this_game.last_update[0]['batter']} {this_game.last_update[0]['text'].value.format(name, base_string)} {this_game.last_update[0]['defender']}{punc}"
|
||||
|
@ -100,35 +213,32 @@ def update_loop():
|
|||
|
||||
state["update_emoji"] = "🏏"
|
||||
state["update_text"] = updatestring
|
||||
|
||||
if "veil" in this_game.last_update[0].keys():
|
||||
state["update_emoji"] = "🌌"
|
||||
state["update_text"] += f" {this_game.last_update[0]['batter']}'s will manifests on {games.base_string(this_game.last_update[1])} base."
|
||||
elif "error" in this_game.last_update[0].keys():
|
||||
state["update_emoji"] = "👻"
|
||||
state["update_text"] = f"{this_game.last_update[0]['batter']}'s hit goes ethereal, and {this_game.last_update[0]['defender']} can't catch it! {this_game.last_update[0]['batter']} reaches base safely."
|
||||
|
||||
state["bases"] = this_game.named_bases()
|
||||
|
||||
state["top_of_inning"] = this_game.top_of_inning
|
||||
|
||||
game_states[game_time] = state
|
||||
game_states.append([game_id, state])
|
||||
|
||||
if state["update_pause"] <= 1 and state["start_delay"] < 0:
|
||||
if this_game.over:
|
||||
state["update_pause"] = 2
|
||||
if state["end_delay"] < 0:
|
||||
master_games_dic.pop(game_time)
|
||||
master_games_dic.pop(game_id)
|
||||
else:
|
||||
state["end_delay"] -= 1
|
||||
master_games_dic[game_time][1]["end_delay"] -= 1
|
||||
master_games_dic[game_id][1]["end_delay"] -= 1
|
||||
else:
|
||||
this_game.gamestate_update_full()
|
||||
|
||||
state["update_pause"] -= 1
|
||||
|
||||
global data_to_send
|
||||
template = jinja2.Environment(loader=jinja2.FileSystemLoader('templates')).get_template('game.html')
|
||||
data_to_send = []
|
||||
for timestamp in game_states:
|
||||
data_to_send.append({
|
||||
'timestamp' : timestamp,
|
||||
'league' : game_states[timestamp]['leagueoruser'] if game_states[timestamp]['is_league'] else '',
|
||||
'html' : template.render(state=game_states[timestamp])
|
||||
})
|
||||
|
||||
socketio.emit("states_update", data_to_send)
|
||||
time.sleep(6)
|
||||
socketio.emit("states_update", game_states)
|
||||
time.sleep(8)
|
44
onomancer.py
|
@ -1,12 +1,29 @@
|
|||
#interfaces with onomancer
|
||||
|
||||
import requests, json, urllib
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
import database as db
|
||||
|
||||
|
||||
onomancer_url = "https://onomancer.sibr.dev/api/"
|
||||
name_stats_hook = "getOrGenerateStats?name="
|
||||
collection_hook = "getCollection?token="
|
||||
names_hook = "getNames"
|
||||
|
||||
|
||||
def _retry_session(retries=3, backoff=0.3, status=(500, 501, 502, 503, 504)):
|
||||
session = requests.Session()
|
||||
retry = Retry(
|
||||
total=retries,
|
||||
read=retries,
|
||||
connect=retries,
|
||||
backoff_factor=backoff,
|
||||
status_forcelist=status,
|
||||
)
|
||||
adapter = HTTPAdapter(max_retries=retry)
|
||||
session.mount('https://', adapter)
|
||||
return session
|
||||
|
||||
def get_stats(name):
|
||||
player = db.get_stats(name)
|
||||
|
@ -14,7 +31,7 @@ def get_stats(name):
|
|||
return player #returns json_string
|
||||
|
||||
#yell at onomancer if not in cache or too old
|
||||
response = requests.get(onomancer_url + name_stats_hook + urllib.parse.quote_plus(name))
|
||||
response = _retry_session().get(onomancer_url + name_stats_hook + urllib.parse.quote_plus(name))
|
||||
if response.status_code == 200:
|
||||
stats = json.dumps(response.json())
|
||||
db.cache_stats(name, stats)
|
||||
|
@ -30,9 +47,32 @@ def get_scream(username):
|
|||
return scream
|
||||
|
||||
def get_collection(collection_url):
|
||||
response = requests.get(onomancer_url + collection_hook + urllib.parse.quote(collection_url))
|
||||
response = _retry_session().get(onomancer_url + collection_hook + urllib.parse.quote(collection_url))
|
||||
if response.status_code == 200:
|
||||
for player in response.json()['lineup'] + response.json()['rotation']:
|
||||
db.cache_stats(player['name'], json.dumps(player))
|
||||
|
||||
return json.dumps(response.json())
|
||||
|
||||
|
||||
def get_names(limit=20, threshold=1):
|
||||
"""
|
||||
Get `limit` random players that have at least `threshold` upvotes.
|
||||
Returns dictionary keyed by player name of stats.
|
||||
"""
|
||||
response = _retry_session().get(
|
||||
onomancer_url + names_hook,
|
||||
params={
|
||||
'limit': limit,
|
||||
'threshold': threshold,
|
||||
'with_stats': 1,
|
||||
'random': 1,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
res = {}
|
||||
for stats in response.json():
|
||||
name = stats['name']
|
||||
db.cache_stats(name, json.dumps(stats))
|
||||
res[name] = stats
|
||||
return res
|
||||
|
|
1
simmadome/.eslintcache
Normal file
|
@ -0,0 +1 @@
|
|||
[{"/Users/elijah/Documents/Projects/matteo/simmadome/src/index.tsx":"1","/Users/elijah/Documents/Projects/matteo/simmadome/src/reportWebVitals.ts":"2","/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesPage.tsx":"3","/Users/elijah/Documents/Projects/matteo/simmadome/src/GamePage.tsx":"4","/Users/elijah/Documents/Projects/matteo/simmadome/src/CreateLeague.tsx":"5","/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesUtil.tsx":"6","/Users/elijah/Documents/Projects/matteo/simmadome/src/util.tsx":"7","/Users/elijah/Documents/Projects/matteo/simmadome/src/Game.tsx":"8"},{"size":2368,"mtime":1610663769654,"results":"9","hashOfConfig":"10"},{"size":425,"mtime":1610566206674,"results":"11","hashOfConfig":"10"},{"size":4725,"mtime":1610664926203,"results":"12","hashOfConfig":"10"},{"size":1836,"mtime":1610677519051,"results":"13","hashOfConfig":"10"},{"size":18825,"mtime":1610778204901,"results":"14","hashOfConfig":"10"},{"size":1116,"mtime":1610677473305,"results":"15","hashOfConfig":"10"},{"size":961,"mtime":1610694553519,"results":"16","hashOfConfig":"10"},{"size":3089,"mtime":1610572714752,"results":"17","hashOfConfig":"10"},{"filePath":"18","messages":"19","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1bvn6qu",{"filePath":"20","messages":"21","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"22","messages":"23","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"24","messages":"25","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"26","messages":"27","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"28","messages":"29","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"30","messages":"31","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"32","messages":"33","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/elijah/Documents/Projects/matteo/simmadome/src/index.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/reportWebVitals.ts",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesPage.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/GamePage.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/CreateLeague.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/GamesUtil.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/util.tsx",[],"/Users/elijah/Documents/Projects/matteo/simmadome/src/Game.tsx",[]]
|
24
simmadome/.gitignore
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.eslintcache
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
46
simmadome/README.md
Normal file
|
@ -0,0 +1,46 @@
|
|||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
16792
simmadome/package-lock.json
generated
Normal file
56
simmadome/package.json
Normal file
|
@ -0,0 +1,56 @@
|
|||
{
|
||||
"name": "simmadome",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"proxy": "http://localhost:5000",
|
||||
"dependencies": {
|
||||
"jquery": "^3.5.1",
|
||||
"react": "^17.0.1",
|
||||
"react-dom": "^17.0.1",
|
||||
"react-router": "^5.2.0",
|
||||
"react-router-dom": "^5.2.0",
|
||||
"react-scripts": "4.0.1",
|
||||
"socket.io-client": "^3.0.5",
|
||||
"twemoji": "^13.0.1",
|
||||
"typescript": "^4.1.3",
|
||||
"web-vitals": "^0.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^5.11.8",
|
||||
"@testing-library/react": "^11.2.2",
|
||||
"@testing-library/user-event": "^12.6.0",
|
||||
"@types/jest": "^26.0.19",
|
||||
"@types/jquery": "^3.5.5",
|
||||
"@types/node": "^12.19.12",
|
||||
"@types/react": "^16.14.2",
|
||||
"@types/react-dom": "^16.9.10",
|
||||
"@types/react-router": "^5.1.10",
|
||||
"@types/react-router-dom": "^5.1.7",
|
||||
"@types/socket.io-client": "^1.4.34",
|
||||
"@types/twemoji": "^12.1.1"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
30
simmadome/public/index.html
Normal file
|
@ -0,0 +1,30 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
|
||||
<title>⚾ The Simmadome</title>
|
||||
|
||||
<meta property="og:title" content="Watch at the Simmadome" />
|
||||
<meta property="og:description" content="The Simsim: Your players, your teams, your games." />
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:site" content="@SIBR_XVI">
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
3
simmadome/public/robots.txt
Normal file
|
@ -0,0 +1,3 @@
|
|||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
325
simmadome/src/CreateLeague.css
Normal file
|
@ -0,0 +1,325 @@
|
|||
.cl_table_header > .cl_subleague_bg {
|
||||
border-top-left-radius: 0.5rem;
|
||||
border-top-right-radius: 0.5rem;
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
.cl_league_structure_table .cl_table_row:last-child .cl_subleague_bg {
|
||||
border-bottom-left-radius: 0.5rem;
|
||||
border-bottom-right-radius: 0.5rem;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
.cl_league_structure_table .cl_table_row:last-child .cl_division_delete {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
input {
|
||||
border: none;
|
||||
border-radius: 1rem;
|
||||
height: 2rem;
|
||||
padding-left: 1rem;
|
||||
background: var(--background-secondary);
|
||||
font-size: 14pt;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-webkit-appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
appearance: textfield;
|
||||
}
|
||||
input[type=number]::-webkit-inner-spin-button,
|
||||
input[type=number]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
.cl_league_main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
margin-top: 3rem;
|
||||
}
|
||||
|
||||
.cl_league_name {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.cl_league_options, .cl_league_structure, .cl_confirm_box {
|
||||
display: flex;
|
||||
background: var(--background-tertiary);
|
||||
flex-direction: column;
|
||||
max-width: 100%;
|
||||
border-radius: 1rem;
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
.cl_confirm_box {
|
||||
min-width: 55rem;
|
||||
padding: 2.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 20pt;
|
||||
}
|
||||
|
||||
.cl_league_options {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.cl_league_structure, .cl_subleague_add_align {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: min-content;
|
||||
}
|
||||
|
||||
.cl_league_structure {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.cl_league_structure_table {
|
||||
display: table;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
.cl_headers, .cl_table_row {
|
||||
display: table-row;
|
||||
height: min-content;
|
||||
}
|
||||
|
||||
.cl_table_header, .cl_delete_filler, .cl_delete_box, .cl_division_cell {
|
||||
display: table-cell;
|
||||
height:100%;
|
||||
}
|
||||
|
||||
.cl_delete_box {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.cl_league_structure_scrollbox {
|
||||
max-width: 100%;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
/* Hide scrollbar for Chrome, Safari and Opera */
|
||||
.cl_league_structure_scrollbox::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Hide scrollbar for IE, Edge and Firefox */
|
||||
.cl_league_structure_scrollbox {
|
||||
-ms-overflow-style: none; /* IE and Edge */
|
||||
scrollbar-width: none; /* Firefox */
|
||||
}
|
||||
|
||||
.cl_subleague_add_align{
|
||||
margin-left: 1.5rem;
|
||||
padding-right: 1.5rem;
|
||||
}
|
||||
|
||||
.cl_subleague_header {
|
||||
display: flex;
|
||||
width:100%;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.cl_subleague_bg {
|
||||
background: var(--background-main);
|
||||
padding: 0.5rem 1rem;
|
||||
margin: 0rem 0.5rem;
|
||||
min-width: 22rem;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.cl_subleague_name {
|
||||
flex-grow: 1;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.cl_division_name_box {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cl_division_name {
|
||||
margin-bottom: 0.5rem;
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
.cl_newteam_name {
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
.cl_division {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
background: var(--background-accent);
|
||||
}
|
||||
|
||||
.cl_team, .cl_team_add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
margin: 0.4rem 0rem;
|
||||
}
|
||||
|
||||
.cl_team_name {
|
||||
font-size: 14pt;
|
||||
padding: 0 0.5rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cl_team_add {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-bottom: 0rem;
|
||||
}
|
||||
|
||||
.cl_search_list {
|
||||
width: 95%;
|
||||
margin-top: 0.6rem;
|
||||
padding: 0.5rem;
|
||||
background: var(--background-tertiary);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.cl_search_result {
|
||||
padding: 0.2rem 0.4rem;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.cl_search_result:hover {
|
||||
background: var(--background-main);
|
||||
}
|
||||
|
||||
.cl_league_options {
|
||||
padding: 1rem;
|
||||
margin-top: 1.5rem;
|
||||
width: 55rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.cl_option_main {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-around;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cl_option_submit_box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.cl_option_box {
|
||||
margin: 1rem;
|
||||
width: max-content;
|
||||
}
|
||||
|
||||
.cl_option_label, .cl_option_err, .cl_structure_err {
|
||||
margin: 0.25rem;
|
||||
}
|
||||
|
||||
.cl_option_err, .cl_structure_err {
|
||||
color: var(--accent-red);
|
||||
}
|
||||
|
||||
.cl_option_err {
|
||||
min-height: 1.5rem;
|
||||
margin-bottom: -0.5rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.cl_structure_err {
|
||||
margin-bottom: -0.5rem;
|
||||
}
|
||||
|
||||
.cl_structure_err_div {
|
||||
margin-top: -0.25rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.cl_structure_err_team {
|
||||
margin-top: -0.5rem;
|
||||
margin-bottom: 0;
|
||||
width: 85%;
|
||||
}
|
||||
|
||||
.cl_team_name_err {
|
||||
color: var(--accent-red);
|
||||
}
|
||||
|
||||
.cl_structure_err_teams {
|
||||
width: 98%;
|
||||
}
|
||||
|
||||
.cl_subleague_add_filler, .cl_division_add_filler {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
}
|
||||
|
||||
/* button styles */
|
||||
|
||||
button > .emoji {
|
||||
margin: 0;
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
}
|
||||
|
||||
.cl_subleague_delete, .cl_team_delete, .cl_division_delete, .cl_subleague_add, .cl_division_add {
|
||||
padding: 0;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border: none;
|
||||
border-radius: 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cl_subleague_delete, .cl_team_delete, .cl_division_delete {
|
||||
background: var(--accent-red);
|
||||
}
|
||||
|
||||
.cl_subleague_add, .cl_division_add {
|
||||
background: var(--accent-green);
|
||||
}
|
||||
|
||||
.cl_subleague_add, .cl_subleague_add_filler {
|
||||
position: relative;
|
||||
top: 1.5rem;
|
||||
}
|
||||
|
||||
.cl_division_add, .cl_division_add_filler {
|
||||
margin-top: 1.25rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.cl_delete_filler {
|
||||
min-width: 3rem;
|
||||
}
|
||||
|
||||
.cl_option_submit {
|
||||
padding: 1rem 2rem;
|
||||
height: 2rem;
|
||||
border: none;
|
||||
border-radius: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--accent-green);
|
||||
font-size: 14pt;
|
||||
}
|
527
simmadome/src/CreateLeague.tsx
Normal file
|
@ -0,0 +1,527 @@
|
|||
import React, {useState, useRef, useLayoutEffect, useReducer} from 'react';
|
||||
import {removeIndex, replaceIndex, append, arrayOf, shallowClone, getUID, DistributiveOmit} from './util';
|
||||
import './CreateLeague.css';
|
||||
import twemoji from 'twemoji';
|
||||
|
||||
// CONSTS
|
||||
|
||||
const MAX_SUBLEAGUE_DIVISION_TOTAL = 22;
|
||||
const MAX_TEAMS_PER_DIVISION = 12;
|
||||
|
||||
// STATE CLASSES
|
||||
|
||||
class LeagueStructureState {
|
||||
subleagues: SubleagueState[]
|
||||
|
||||
constructor(subleagues: SubleagueState[] = []) {
|
||||
this.subleagues = subleagues;
|
||||
}
|
||||
}
|
||||
|
||||
class SubleagueState {
|
||||
name: string
|
||||
divisions: DivisionState[]
|
||||
id: string|number
|
||||
|
||||
constructor(divisions: DivisionState[] = []) {
|
||||
this.name = "";
|
||||
this.divisions = divisions;
|
||||
this.id = getUID();
|
||||
}
|
||||
}
|
||||
|
||||
class DivisionState {
|
||||
name: string
|
||||
teams: TeamState[]
|
||||
id: string|number
|
||||
|
||||
constructor() {
|
||||
this.name = "";
|
||||
this.teams = [];
|
||||
this.id = getUID();
|
||||
}
|
||||
}
|
||||
|
||||
class TeamState {
|
||||
name: string
|
||||
id: string|number
|
||||
|
||||
constructor(name: string = "") {
|
||||
this.name = name;
|
||||
this.id = getUID();
|
||||
}
|
||||
}
|
||||
|
||||
// STRUCTURE REDUCER
|
||||
|
||||
type StructureReducerActions =
|
||||
{type: 'remove_subleague', subleague_index: number} |
|
||||
{type: 'add_subleague'} |
|
||||
{type: 'rename_subleague', subleague_index: number, name: string} |
|
||||
{type: 'remove_divisions', division_index: number} |
|
||||
{type: 'add_divisions'} |
|
||||
{type: 'rename_division', subleague_index: number, division_index: number, name: string} |
|
||||
{type: 'remove_team', subleague_index: number, division_index: number, name:string} |
|
||||
{type: 'add_team', subleague_index:number, division_index:number, name:string}
|
||||
|
||||
function leagueStructureReducer(state: LeagueStructureState, action: StructureReducerActions): LeagueStructureState {
|
||||
switch (action.type) {
|
||||
case 'remove_subleague':
|
||||
return {subleagues: removeIndex(state.subleagues, action.subleague_index)};
|
||||
case 'add_subleague':
|
||||
return {subleagues: append(state.subleagues, new SubleagueState(
|
||||
arrayOf(state.subleagues[0].divisions.length, i =>
|
||||
new DivisionState()
|
||||
)
|
||||
))}
|
||||
case 'rename_subleague':
|
||||
return replaceSubleague(state, action.subleague_index, subleague => {
|
||||
let nSubleague = shallowClone(subleague);
|
||||
nSubleague.name = action.name;
|
||||
return nSubleague;
|
||||
});
|
||||
case 'remove_divisions':
|
||||
return {subleagues: state.subleagues.map(subleague => {
|
||||
let nSubleague = shallowClone(subleague);
|
||||
nSubleague.divisions = removeIndex(subleague.divisions, action.division_index)
|
||||
return nSubleague;
|
||||
})};
|
||||
case 'add_divisions':
|
||||
return {subleagues: state.subleagues.map(subleague => {
|
||||
let nSubleague = shallowClone(subleague);
|
||||
nSubleague.divisions = append(subleague.divisions, new DivisionState())
|
||||
return nSubleague;
|
||||
})};
|
||||
case 'rename_division':
|
||||
return replaceDivision(state, action.subleague_index, action.division_index, division => {
|
||||
let nDivision = shallowClone(division);
|
||||
nDivision.name = action.name;
|
||||
return nDivision;
|
||||
});
|
||||
case 'remove_team':
|
||||
return replaceDivision(state, action.subleague_index, action.division_index, division => {
|
||||
let nDivision = shallowClone(division);
|
||||
nDivision.teams = removeIndex(division.teams, division.teams.findIndex(val => val.name === action.name));
|
||||
return nDivision;
|
||||
});
|
||||
case 'add_team':
|
||||
return replaceDivision(state, action.subleague_index, action.division_index, division => {
|
||||
let nDivision = shallowClone(division);
|
||||
nDivision.teams = append(division.teams, new TeamState(action.name));
|
||||
return nDivision;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function replaceSubleague(state: LeagueStructureState, si: number, func: (val: SubleagueState) => SubleagueState) {
|
||||
return {subleagues: replaceIndex(state.subleagues, si, func(state.subleagues[si]))}
|
||||
}
|
||||
|
||||
function replaceDivision(state: LeagueStructureState, si: number, di: number, func:(val: DivisionState) => DivisionState) {
|
||||
return replaceSubleague(state, si, subleague => {
|
||||
let nSubleague = shallowClone(subleague);
|
||||
nSubleague.divisions = replaceIndex(subleague.divisions, di, func(subleague.divisions[di]));
|
||||
return nSubleague;
|
||||
});
|
||||
}
|
||||
|
||||
// OPTIONS REDUCER
|
||||
|
||||
class LeagueOptionsState {
|
||||
games_series = "3"
|
||||
intra_division_series = "8"
|
||||
inter_division_series = "16"
|
||||
inter_league_series = "8"
|
||||
top_postseason = "1"
|
||||
wildcards = "0"
|
||||
}
|
||||
|
||||
type OptionsReducerActions =
|
||||
{type: 'set_games_series', value: string} |
|
||||
{type: 'set_intra_division_series', value: string} |
|
||||
{type: 'set_inter_division_series', value: string} |
|
||||
{type: 'set_inter_league_series', value: string} |
|
||||
{type: 'set_top_postseason', value: string} |
|
||||
{type: 'set_wildcards', value: string}
|
||||
|
||||
function LeagueOptionsReducer(state: LeagueOptionsState, action: OptionsReducerActions) {
|
||||
let newState = shallowClone(state);
|
||||
switch (action.type) {
|
||||
case 'set_games_series':
|
||||
newState.games_series = action.value;
|
||||
break;
|
||||
case 'set_intra_division_series':
|
||||
newState.intra_division_series = action.value;
|
||||
break;
|
||||
case 'set_inter_division_series':
|
||||
newState.inter_division_series = action.value;
|
||||
break;
|
||||
case 'set_inter_league_series':
|
||||
newState.inter_league_series = action.value;
|
||||
break;
|
||||
case 'set_top_postseason':
|
||||
newState.top_postseason = action.value;
|
||||
break;
|
||||
case 'set_wildcards':
|
||||
newState.wildcards = action.value;
|
||||
break;
|
||||
}
|
||||
return newState
|
||||
}
|
||||
|
||||
// CREATE LEAGUE
|
||||
|
||||
let initLeagueStructure = {
|
||||
subleagues: [0, 1].map((val) =>
|
||||
new SubleagueState([0, 1].map((val) =>
|
||||
new DivisionState()
|
||||
))
|
||||
)
|
||||
};
|
||||
|
||||
function CreateLeague() {
|
||||
let [name, setName] = useState("");
|
||||
let [showError, setShowError] = useState(false);
|
||||
let [nameExists, setNameExists] = useState(false);
|
||||
let [deletedTeams, setDeletedTeams] = useState<string[]>([]);
|
||||
let [createSuccess, setCreateSuccess] = useState(false);
|
||||
let [structure, structureDispatch] = useReducer(leagueStructureReducer, initLeagueStructure);
|
||||
let [options, optionsDispatch] = useReducer(LeagueOptionsReducer, new LeagueOptionsState());
|
||||
|
||||
let self = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (self.current) {
|
||||
twemoji.parse(self.current)
|
||||
}
|
||||
})
|
||||
|
||||
if (createSuccess) {
|
||||
return(
|
||||
<div className="cl_league_main" ref={self}>
|
||||
<div className="cl_confirm_box">
|
||||
League created succesfully!
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="cl_league_main" ref={self}>
|
||||
<input type="text" className="cl_league_name" placeholder="League Name" value={name} onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameExists(false);
|
||||
}}/>
|
||||
<div className="cl_structure_err">{
|
||||
name === "" && showError ? "A name is required." :
|
||||
nameExists && showError ? "A league by that name already exists" :
|
||||
""
|
||||
}</div>
|
||||
<LeagueStructre state={structure} dispatch={structureDispatch} deletedTeams={deletedTeams} showError={showError}/>
|
||||
<div className="cl_league_options">
|
||||
<LeagueOptions state={options} dispatch={optionsDispatch} showError={showError}/>
|
||||
<div className="cl_option_submit_box">
|
||||
<button className="cl_option_submit" onClick={e => {
|
||||
if (!validRequest(name, structure, options)) {
|
||||
setShowError(true);
|
||||
} else {
|
||||
let req = new XMLHttpRequest();
|
||||
let data = makeRequest(name, structure, options);
|
||||
req.open("POST", "/api/leagues", true);
|
||||
req.setRequestHeader("Content-type", "application/json");
|
||||
req.onreadystatechange = () => {
|
||||
if(req.readyState === 4) {
|
||||
if (req.status === 200) {
|
||||
setCreateSuccess(true);
|
||||
}
|
||||
if (req.status === 400) {
|
||||
let err = JSON.parse(req.response);
|
||||
switch (err.status) {
|
||||
case 'err_league_exists':
|
||||
setNameExists(true);
|
||||
break;
|
||||
case 'err_no_such_team':
|
||||
setDeletedTeams(err.cause);
|
||||
break;
|
||||
}
|
||||
setShowError(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
req.send(data);
|
||||
}
|
||||
}}>Submit</button>
|
||||
<div className="cl_option_err">{
|
||||
!validRequest(name, structure, options) && showError ?
|
||||
"Cannot create league. Some information is missing or invalid." : ""
|
||||
}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function makeRequest(name:string, structure: LeagueStructureState, options:LeagueOptionsState) {
|
||||
return JSON.stringify({
|
||||
name: name,
|
||||
structure: {
|
||||
subleagues: structure.subleagues.map(subleague => ({
|
||||
name: subleague.name,
|
||||
divisions: subleague.divisions.map(division => ({
|
||||
name: division.name,
|
||||
teams: division.teams.map(team => team.name)
|
||||
}))
|
||||
}))
|
||||
},
|
||||
games_per_series: Number(options.games_series),
|
||||
division_series: Number(options.intra_division_series),
|
||||
inter_division_series: Number(options.inter_division_series),
|
||||
inter_league_series: Number(options.inter_league_series),
|
||||
top_postseason: Number(options.top_postseason),
|
||||
wildcards: Number(options.wildcards)
|
||||
});
|
||||
}
|
||||
|
||||
function validRequest(name:string, structure: LeagueStructureState, options:LeagueOptionsState) {
|
||||
|
||||
|
||||
return (
|
||||
name !== "" &&
|
||||
|
||||
validNumber(options.games_series) &&
|
||||
validNumber(options.intra_division_series) &&
|
||||
validNumber(options.inter_division_series) &&
|
||||
validNumber(options.inter_league_series) &&
|
||||
validNumber(options.top_postseason) &&
|
||||
validNumber(options.wildcards, 0) &&
|
||||
|
||||
structure.subleagues.length % 2 === 0 &&
|
||||
|
||||
structure.subleagues.every((subleague, si) =>
|
||||
subleague.name !== "" &&
|
||||
!structure.subleagues.slice(0, si).some(val => val.name === subleague.name) &&
|
||||
subleague.divisions.every((division, di) =>
|
||||
division.name !== "" &&
|
||||
division.teams.length >= 2 &&
|
||||
division.teams.length <= MAX_TEAMS_PER_DIVISION &&
|
||||
!subleague.divisions.slice(0, di).some(val => val.name === division.name)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function validNumber(value: string, min = 1) {
|
||||
return !isNaN(Number(value)) && Number(value) >= min;
|
||||
}
|
||||
|
||||
// LEAGUE STRUCUTRE
|
||||
|
||||
function LeagueStructre(props: {state: LeagueStructureState, dispatch: React.Dispatch<StructureReducerActions>, deletedTeams: string[], showError: boolean}) {
|
||||
let nSubleagues = props.state.subleagues.length;
|
||||
let nDivisions = props.state.subleagues[0].divisions.length;
|
||||
return (
|
||||
<div className="cl_league_structure">
|
||||
<div className="cl_league_structure_scrollbox">
|
||||
<div className="cl_subleague_add_align">
|
||||
<div className="cl_league_structure_table">
|
||||
<SubleagueHeaders subleagues={props.state.subleagues} dispatch={props.dispatch} showError={props.showError}/>
|
||||
<Divisions subleagues={props.state.subleagues} dispatch={props.dispatch} deletedTeams={props.deletedTeams} showError={props.showError}/>
|
||||
</div>
|
||||
{ (nSubleagues+1) * (nDivisions+1) < MAX_SUBLEAGUE_DIVISION_TOTAL ?
|
||||
<button className="cl_subleague_add" onClick={e => props.dispatch({type: 'add_subleague'})}>➕</button> :
|
||||
<div className="cl_subleague_add_filler"/>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div className="cl_structure_err">{props.state.subleagues.length % 2 !== 0 && props.showError ? "Must have an even number of subleagues." : ""}</div>
|
||||
{ nSubleagues * (nDivisions+2) < MAX_SUBLEAGUE_DIVISION_TOTAL ?
|
||||
<button className="cl_division_add" onClick={e => props.dispatch({type: 'add_divisions'})}>➕</button>:
|
||||
<div className="cl_division_add_filler"/>
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubleagueHeaders(props: {subleagues: SubleagueState[], dispatch: React.Dispatch<StructureReducerActions>, showError:boolean}) {
|
||||
return (
|
||||
<div className="cl_headers">
|
||||
<div key="filler" className="cl_delete_filler"/>
|
||||
{props.subleagues.map((subleague, i) => {
|
||||
let err =
|
||||
subleague.name === "" ?
|
||||
"A name is required." :
|
||||
props.subleagues.slice(0, i).some(val => val.name === subleague.name) ?
|
||||
"Each subleague must have a different name." :
|
||||
"";
|
||||
|
||||
return (
|
||||
<div key={subleague.id} className="cl_table_header">
|
||||
<div className="cl_subleague_bg">
|
||||
<SubleageHeader state={subleague} canDelete={props.subleagues.length > 1} dispatch={action =>
|
||||
props.dispatch(Object.assign({subleague_index: i}, action))
|
||||
}/>
|
||||
<div className="cl_structure_err">{props.showError ? err : ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubleageHeader(props: {state: SubleagueState, canDelete: boolean, dispatch:(action: DistributiveOmit<StructureReducerActions, 'subleague_index'>) => void}) {
|
||||
return (
|
||||
<div className="cl_subleague_header">
|
||||
<input type="text" className="cl_subleague_name" placeholder="Subleague Name" value={props.state.name} onChange={e =>
|
||||
props.dispatch({type: 'rename_subleague', name: e.target.value})
|
||||
}/>
|
||||
{props.canDelete ? <button className="cl_subleague_delete" onClick={e => props.dispatch({type: 'remove_subleague'})}>➖</button> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Divisions(props: {subleagues: SubleagueState[], dispatch: React.Dispatch<StructureReducerActions>, deletedTeams: string[], showError: boolean}) {
|
||||
return (<>
|
||||
{props.subleagues[0].divisions.map((val, di) => (
|
||||
<div key={val.id} className="cl_table_row">
|
||||
<div key="delete" className="cl_delete_box">
|
||||
{props.subleagues[0].divisions.length > 1 ?
|
||||
<button className="cl_division_delete" onClick={e => props.dispatch({type: 'remove_divisions', division_index: di})}>➖</button> :
|
||||
null
|
||||
}
|
||||
</div>
|
||||
{props.subleagues.map((subleague, si) => (
|
||||
<div key={subleague.id} className="cl_division_cell">
|
||||
<div className="cl_subleague_bg">
|
||||
<Division state={subleague.divisions[di]} dispatch={action =>
|
||||
props.dispatch(Object.assign({subleague_index: si, division_index: di}, action))
|
||||
}
|
||||
isDuplicate={subleague.divisions.slice(0, di).some(val => val.name === subleague.divisions[di].name)}
|
||||
deletedTeams={props.deletedTeams} showError={props.showError} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</>);
|
||||
}
|
||||
|
||||
function Division(props: {
|
||||
state: DivisionState,
|
||||
dispatch: (action: DistributiveOmit<StructureReducerActions, 'subleague_index'|'division_index'>) => void,
|
||||
isDuplicate: boolean,
|
||||
deletedTeams: string[],
|
||||
showError: boolean
|
||||
}) {
|
||||
|
||||
let [newName, setNewName] = useState("");
|
||||
let [searchResults, setSearchResults] = useState<string[]>([]);
|
||||
let newNameInput = useRef<HTMLInputElement>(null);
|
||||
let resultList = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (resultList.current) {
|
||||
twemoji.parse(resultList.current)
|
||||
}
|
||||
})
|
||||
|
||||
let divisionErr =
|
||||
props.state.name === "" ?
|
||||
"A name is required." :
|
||||
props.isDuplicate ?
|
||||
"Each division in a subleague must have a different name." :
|
||||
""
|
||||
|
||||
let teamsErr = props.state.teams.length < 2 ? "Must have at least 2 teams." : "";
|
||||
|
||||
return (
|
||||
<div className="cl_division">
|
||||
<div className="cl_division_name_box">
|
||||
<input type="text" className="cl_division_name" placeholder="Division Name" key="input" value={props.state.name} onChange={e =>
|
||||
props.dispatch({type: 'rename_division', name: e.target.value})
|
||||
}/>
|
||||
<div className="cl_structure_err cl_structure_err_div">{props.showError ? divisionErr : ""}</div>
|
||||
</div>
|
||||
{props.state.teams.map((team, i) => {
|
||||
let showDeleted = props.showError && props.deletedTeams.includes(team.name)
|
||||
return (<>
|
||||
<div className="cl_team" key={team.id}>
|
||||
<div className={"cl_team_name" + (showDeleted ? " cl_team_name_err" : "")}>{team.name}</div>
|
||||
<button className="cl_team_delete" onClick={e => props.dispatch({type:'remove_team', name: team.name})}>➖</button>
|
||||
</div>
|
||||
<div className="cl_structure_err cl_structure_err_team">{showDeleted ? "This team was deleted" : ""}</div>
|
||||
</>)
|
||||
})}
|
||||
{ props.state.teams.length < MAX_TEAMS_PER_DIVISION ? <>
|
||||
<div className="cl_team_add">
|
||||
<input type="text" className="cl_newteam_name" placeholder="Add team..." value={newName} ref={newNameInput}
|
||||
onChange={e => {
|
||||
let params = new URLSearchParams({query: e.target.value, page_len: '5', page_num: '0'});
|
||||
fetch("/api/teams/search?" + params.toString())
|
||||
.then(response => response.json())
|
||||
.then(data => setSearchResults(data));
|
||||
setNewName(e.target.value);
|
||||
}}/>
|
||||
</div>
|
||||
{searchResults.length > 0 && newName.length > 0 ?
|
||||
(<div className="cl_search_list" ref={resultList}>
|
||||
{searchResults.map(result =>
|
||||
<div className="cl_search_result" key={result} onClick={e => {
|
||||
props.dispatch({type:'add_team', name: result});
|
||||
setNewName("");
|
||||
if (newNameInput.current) {
|
||||
newNameInput.current.focus();
|
||||
}
|
||||
}}>{result}</div>
|
||||
)}
|
||||
</div>):
|
||||
null
|
||||
}</> :
|
||||
null
|
||||
}
|
||||
|
||||
<div className="cl_structure_err cl_structure_err_teams">{props.showError ? teamsErr : ""}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// LEAGUE OPTIONS
|
||||
|
||||
function LeagueOptions(props: {state: LeagueOptionsState, dispatch: React.Dispatch<OptionsReducerActions>, showError: boolean}) {
|
||||
return (
|
||||
<div className="cl_option_main">
|
||||
<div className="cl_option_column">
|
||||
<NumberInput title="Number of games per series" value={props.state.games_series} setValue={(value: string) =>
|
||||
props.dispatch({type: 'set_games_series', value: value})} showError={props.showError}/>
|
||||
<NumberInput title="Number of teams from top of division to postseason" value={props.state.top_postseason} setValue={(value: string) =>
|
||||
props.dispatch({type: 'set_top_postseason', value: value})} showError={props.showError}/>
|
||||
<NumberInput title="Number of wildcards" value={props.state.wildcards} minValue={0} setValue={(value: string) =>
|
||||
props.dispatch({type: 'set_wildcards', value: value})} showError={props.showError}/>
|
||||
</div>
|
||||
<div className="cl_option_column">
|
||||
<NumberInput title="Number of series with each division opponent" value={props.state.intra_division_series} setValue={(value: string) =>
|
||||
props.dispatch({type: 'set_intra_division_series', value: value})} showError={props.showError}/>
|
||||
<NumberInput title="Number of inter-divisional series" value={props.state.inter_division_series} setValue={(value: string) =>
|
||||
props.dispatch({type: 'set_inter_division_series', value: value})} showError={props.showError}/>
|
||||
<NumberInput title="Number of inter-league series" value={props.state.inter_league_series} setValue={(value: string) =>
|
||||
props.dispatch({type: 'set_inter_league_series', value: value})} showError={props.showError}/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NumberInput(props: {title: string, value: string, setValue: (newVal: string) => void, showError: boolean, minValue? : number}) {
|
||||
let minValue = 1;
|
||||
if (props.minValue !== undefined) {
|
||||
minValue = props.minValue
|
||||
}
|
||||
return (
|
||||
<div className="cl_option_box">
|
||||
<div className="cl_option_label">{props.title}</div>
|
||||
<input className="cl_option_input" type="number" min={minValue} value={props.value} onChange={e => props.setValue(e.target.value)}/>
|
||||
<div className="cl_option_err">{(isNaN(Number(props.value)) || Number(props.value) < minValue) && props.showError ? "Must be a number greater than " + minValue : ""}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CreateLeague;
|
213
simmadome/src/Game.css
Normal file
|
@ -0,0 +1,213 @@
|
|||
.game {
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background:var(--background-main);
|
||||
border: 4px solid;
|
||||
border-radius: 4px;
|
||||
border-color: var(--highlight);
|
||||
border-top: none;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
height: min-content;
|
||||
width: 100%;
|
||||
min-width: 32rem;
|
||||
max-width: 44rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
width: 100%;
|
||||
background-color: var(--background-secondary);
|
||||
border-top-right-radius: 4px;
|
||||
height: max-content;
|
||||
display: flex;
|
||||
justify-content: space-between
|
||||
}
|
||||
|
||||
.header > div {
|
||||
margin: 0.3rem 0.5rem;
|
||||
}
|
||||
|
||||
.body {
|
||||
margin: 0.5rem;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
grid-template-areas:
|
||||
"teams teams info" "players players info" "update update update";
|
||||
grid-template-rows: minmax(5.75rem, min-content) minmax(4rem, min-content) minmax(4rem, min-content);
|
||||
grid-row-gap: 0.5rem;
|
||||
grid-column-gap: 0.75rem;
|
||||
}
|
||||
|
||||
.teams {
|
||||
grid-area: teams;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-around;
|
||||
min-width: 95%;
|
||||
max-width: 100%;
|
||||
width: min-content;
|
||||
}
|
||||
|
||||
.team {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
margin: 0.25rem 0rem;
|
||||
}
|
||||
|
||||
.team_name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.info {
|
||||
grid-area: info;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
background: #4f545c;
|
||||
padding: 0.75rem 0rem;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.batting {
|
||||
font-size: 10pt;
|
||||
text-align: left;
|
||||
height: max-content;
|
||||
margin: 0.3rem 0.5rem;
|
||||
}
|
||||
|
||||
.leagueoruser {
|
||||
font-size: 10pt;
|
||||
text-align: right;
|
||||
height: max-content;
|
||||
margin: 0.3rem 0.5rem;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.outs {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
width: 60%;
|
||||
}
|
||||
|
||||
.outs_title {
|
||||
font-weight: bolder;
|
||||
}
|
||||
|
||||
.outs_count {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.out {
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.team_name, .score {
|
||||
font-size: 25px
|
||||
}
|
||||
|
||||
.score {
|
||||
background: var(--background-secondary);
|
||||
width: 40px;
|
||||
min-width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 20px;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.players {
|
||||
grid-area: players;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
grid-template-rows: auto auto;
|
||||
grid-column-gap: 0.5rem;
|
||||
margin-left: 0.3rem;
|
||||
}
|
||||
|
||||
.players > div {
|
||||
margin: 0.25rem 0rem;
|
||||
}
|
||||
|
||||
.player_type {
|
||||
text-align: end;
|
||||
font-weight: bolder;
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.player_name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: start;
|
||||
white-space: nowrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.update {
|
||||
grid-area: update;
|
||||
min-height: 3.5rem;
|
||||
padding: 0rem 0.75rem;
|
||||
height: 100%;
|
||||
background: var(--background-secondary);
|
||||
border-radius: 4px;
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.update_emoji {
|
||||
margin-right: 0.75rem;
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
.update_text {
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.base {
|
||||
height: 60px;
|
||||
}
|
||||
|
||||
.field > .base {
|
||||
margin-bottom: -25%
|
||||
}
|
||||
|
||||
@media only screen and (max-device-width: 800px) {
|
||||
.game {
|
||||
font-size: 15pt;
|
||||
}
|
||||
|
||||
.batting, .leagueoruser {
|
||||
font-size: 14pt;
|
||||
padding: 3px;
|
||||
}
|
||||
|
||||
.team_name, .score {
|
||||
font-size: 25px
|
||||
}
|
||||
|
||||
.players {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.update_emoji, .update_text {
|
||||
display: inline;
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
85
simmadome/src/Game.tsx
Normal file
|
@ -0,0 +1,85 @@
|
|||
import { GameState } from './GamesUtil';
|
||||
import twemoji from 'twemoji';
|
||||
import React, { useRef, useLayoutEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import './Game.css';
|
||||
import base_filled from './img/base_filled.png';
|
||||
import base_empty from './img/base_empty.png';
|
||||
import out_filled from './img/out_out.png';
|
||||
import out_empty from './img/out_in.png';
|
||||
|
||||
function Game(props: {gameId: string, state : GameState}) {
|
||||
let self: React.MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||
useLayoutEffect(() => {
|
||||
if (self.current) {
|
||||
twemoji.parse(self.current);
|
||||
}
|
||||
})
|
||||
|
||||
let state = props.state;
|
||||
return (
|
||||
<div className="game" ref={self}>
|
||||
<div className="header">
|
||||
<div className="inning">Inning: <span>{state.display_top_of_inning ? "🔼" : "🔽"}</span> {state.display_inning}/{state.max_innings}</div>
|
||||
<div className="title">{state.title}</div>
|
||||
<div className="weather">{state.weather_emoji} {state.weather_text}</div>
|
||||
</div>
|
||||
<div className="body">
|
||||
<div className="teams">
|
||||
<Team name={state.away_name} score={state.away_score}/>
|
||||
<Team name={state.home_name} score={state.home_score}/>
|
||||
</div>
|
||||
<div className="info">
|
||||
<div className="field">
|
||||
<Base name={state.bases[2]} />
|
||||
<div style={{display: "flex"}}>
|
||||
<Base name={state.bases[3]} />
|
||||
<Base name={state.bases[1]} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="outs">
|
||||
<div className="outs_title">OUTS</div>
|
||||
<div className="outs_count">
|
||||
{[1, 2].map((out) => <Out thisOut={out} totalOuts={state.outs} key={out} />)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="players">
|
||||
<div className="player_type">PITCHER</div>
|
||||
<div className="player_name">{state.pitcher}</div>
|
||||
<div className="player_type">BATTER</div>
|
||||
<div className="player_name batter_name">{state.batter}</div>
|
||||
</div>
|
||||
<div className="update">
|
||||
<div className="update_emoji">{state.update_emoji}</div>
|
||||
<div className="update_text">{state.update_text}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="footer">
|
||||
<div className="batting">{state.display_top_of_inning ? state.away_name : state.home_name} batting.</div>
|
||||
<div className="leagueoruser">{state.leagueoruser} (<Link to={"/game/" + props.gameId}>share</Link>)</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Team(props: {name: string, score: number}) {
|
||||
return (
|
||||
<div className="team">
|
||||
<div className="team_name">{ props.name }</div>
|
||||
<div className="score">{ props.score }</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Base(props: {name: string | null}) {
|
||||
return (
|
||||
<img className="base" alt={ props.name ?? "" } src={ props.name ? base_filled : base_empty }/>
|
||||
);
|
||||
}
|
||||
|
||||
function Out(props: {thisOut: number, totalOuts: number}) {
|
||||
return <img className="out" alt="" src={props.thisOut <= props.totalOuts ? out_filled : out_empty}/>;
|
||||
}
|
||||
|
||||
export default Game;
|
37
simmadome/src/GamePage.css
Normal file
|
@ -0,0 +1,37 @@
|
|||
#game_container {
|
||||
margin-top: 3rem;
|
||||
margin-left: 1rem;
|
||||
margin-right: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
}
|
||||
|
||||
.history_box {
|
||||
width: 100%;
|
||||
margin-top: 3rem;
|
||||
padding: 1rem;
|
||||
padding-top: 0.5rem;
|
||||
background: var(--background-main);
|
||||
border-radius: 0.25rem;
|
||||
width: 100%;
|
||||
min-width: 32rem;
|
||||
max-width: 44rem;
|
||||
box-sizing: border-box;
|
||||
border: 4px solid;
|
||||
border-radius: 4px;
|
||||
border-color: var(--highlight);
|
||||
border-top: none;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.history_title {
|
||||
font-size: 14pt;
|
||||
}
|
||||
|
||||
.history_update {
|
||||
height: 4rem;
|
||||
margin: 0.5rem;
|
||||
}
|
62
simmadome/src/GamePage.tsx
Normal file
|
@ -0,0 +1,62 @@
|
|||
import React, {useState, useRef, useLayoutEffect} from 'react';
|
||||
import twemoji from 'twemoji';
|
||||
import ReactRouter from 'react-router';
|
||||
import {GameState, useListener} from './GamesUtil';
|
||||
import './GamePage.css';
|
||||
import Game from './Game';
|
||||
import {getUID} from './util';
|
||||
|
||||
function GamePage(props: ReactRouter.RouteComponentProps<{id: string}>) {
|
||||
let [game, setGame] = useState<[string, GameState]|undefined>(undefined);
|
||||
let history = useRef<[number, string, string][]>([]);
|
||||
|
||||
useListener((newGames) => {
|
||||
let newGame = newGames.find((gamePair) => gamePair[0] === props.match.params.id);
|
||||
setGame(newGame);
|
||||
console.log(newGame);
|
||||
if (newGame !== undefined && newGame[1].start_delay < 0 && newGame[1].end_delay > 8) {
|
||||
history.current.unshift([getUID(), newGame[1].update_emoji, newGame[1].update_text]);
|
||||
if (history.current.length > 8) {
|
||||
history.current.pop();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (game === undefined) {
|
||||
return <div id="game_container">The game you're looking for either doesn't exist or has already ended.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div id="game_container">
|
||||
<Game gameId={game[0]} state={game[1]}/>
|
||||
{ history.current.length > 0 ?
|
||||
<GameHistory history={history.current}/> :
|
||||
null
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GameHistory(props: {history: [number, string, string][]}) {
|
||||
let self = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (self.current) {
|
||||
twemoji.parse(self.current);
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="history_box" ref={self}>
|
||||
<div className="history_title">History</div>
|
||||
{props.history.map((update) => (
|
||||
<div className="update history_update" key={update[0]}>
|
||||
<div className="update_emoji">{update[1]}</div>
|
||||
<div className="update_text">{update[2]}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default GamePage;
|
79
simmadome/src/GamesPage.css
Normal file
|
@ -0,0 +1,79 @@
|
|||
.container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(32rem, 1fr));
|
||||
grid-gap: 50px 30px; /*space between rows, then columns*/
|
||||
grid-auto-flow: row;
|
||||
}
|
||||
|
||||
.slot_container {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
}
|
||||
|
||||
.emptyslot, .game {
|
||||
min-height: 18.75rem;
|
||||
max-width: 44rem;
|
||||
min-width: 32rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#filters {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
#filters > * {
|
||||
padding: 0.25rem 0.5rem;
|
||||
margin: 0rem 0.5rem;
|
||||
font-size: 16pt;
|
||||
background: rgba(0,0,0,0);
|
||||
}
|
||||
|
||||
#filters > .filter {
|
||||
border-radius: 0.5rem;
|
||||
min-width: 6.25rem;
|
||||
text-align: center;
|
||||
border: none;
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#selected_filter {
|
||||
background: rgb(113, 54, 138);
|
||||
}
|
||||
|
||||
#footer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 4.5rem;
|
||||
}
|
||||
|
||||
#footer > div {
|
||||
text-align: center;
|
||||
font-size: 16pt;
|
||||
position: relative;
|
||||
top: 0.25rem;
|
||||
}
|
||||
|
||||
.emptyslot {
|
||||
border: 2px dashed white;
|
||||
border-radius: 15px;
|
||||
text-align: center;
|
||||
color: white;
|
||||
}
|
||||
|
||||
@media only screen and (max-device-width: 800px) {
|
||||
.container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(1, minmax(700px, 90%));
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
}
|
142
simmadome/src/GamesPage.tsx
Normal file
|
@ -0,0 +1,142 @@
|
|||
import React, {useState, useRef, useEffect, useLayoutEffect} from 'react';
|
||||
import {GameState, GameList, useListener} from './GamesUtil';
|
||||
import {Link} from 'react-router-dom';
|
||||
import './GamesPage.css';
|
||||
import Game from './Game';
|
||||
|
||||
function GamesPage() {
|
||||
let [search, setSearch] = useState(window.location.search);
|
||||
useEffect(() => {
|
||||
setSearch(window.location.search);
|
||||
//eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [window.location.search])
|
||||
|
||||
let searchparams = new URLSearchParams(search);
|
||||
let filter = searchparams.get('league') ?? ""
|
||||
|
||||
let [games, setGames] = useState<[string, GameState][]>([]);
|
||||
useListener(setGames);
|
||||
|
||||
let filters = useRef(filter !== "" ? [filter] : []);
|
||||
games.forEach((game) => { if (game[1].is_league && !filters.current.includes(game[1].leagueoruser)) { filters.current.push(game[1].leagueoruser) }});
|
||||
filters.current = filters.current.filter((f) => games.find((game) => game && game[1].is_league && game[1].leagueoruser === f) || f === filter);
|
||||
|
||||
let gameList = useRef<(string | null)[]>([]);
|
||||
let filterGames = games.filter((game, i) => filter === "" || game[1].leagueoruser === filter);
|
||||
updateList(gameList.current, filterGames, searchparams.get('game'));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Filters filterList={filters.current} selectedFilter={filter} />
|
||||
<Grid gameList={gameList.current.map((val) => val !== null ? filterGames.find((game) => game[0] === val) as [string, GameState] : null )}/>
|
||||
<Footer has_games={filterGames.length > 0}/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// adds and removes games from list to keep it up to date, without relocating games already in place
|
||||
function updateList(gameList: (string | null)[], games: [string, GameState][], firstGame: string | null) {
|
||||
// insert firstGame into first slot, if necessary
|
||||
if (firstGame !== null && games.find((game) => game[0] === firstGame)) {
|
||||
if (gameList.includes(firstGame)) {
|
||||
gameList[gameList.indexOf(firstGame)] = null;
|
||||
}
|
||||
gameList[0] = firstGame;
|
||||
}
|
||||
|
||||
//remove games no longer present
|
||||
for (let i = 0; i < gameList.length; i ++) {
|
||||
if (gameList[i] !== null && games.findIndex((val) => val[0] === gameList[i]) < 0) {
|
||||
gameList[i] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// add games not present
|
||||
for (let game of games) {
|
||||
if (!gameList.find((val) => val !== null && val === game[0])) {
|
||||
let firstEmpty = gameList.indexOf(null);
|
||||
if (firstEmpty < 0) {
|
||||
gameList.push(game[0])
|
||||
} else {
|
||||
gameList[firstEmpty] = game[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//remove trailing empty cells
|
||||
while (gameList[gameList.length-1] === null) {
|
||||
gameList.pop();
|
||||
}
|
||||
}
|
||||
|
||||
function Filters (props: {filterList: string[], selectedFilter: string}) {
|
||||
function Filter(innerprops: {title: string, filter:string} ) {
|
||||
let search = new URLSearchParams();
|
||||
search.append('league', innerprops.filter);
|
||||
|
||||
return (
|
||||
<Link to={innerprops.filter !== "" ? "/?" + search.toString() : "/"} className="filter" id={innerprops.filter === props.selectedFilter ? "selected_filter" : ""}>
|
||||
{innerprops.title}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div id="filters">
|
||||
<div>Filter:</div>
|
||||
<Filter title="All" filter="" key="" />
|
||||
{props.filterList.map((filter: string) =>
|
||||
<Filter title={filter} filter={filter} key={filter} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Grid(props: { gameList: GameList }) {
|
||||
let self: React.RefObject<HTMLElement> = useRef(null);
|
||||
let [numcols, setNumcols] = useState(3);
|
||||
let newList = [...props.gameList];
|
||||
|
||||
while (newList.length === 0 || newList.length % numcols !== 0) {
|
||||
newList.push(null);
|
||||
}
|
||||
|
||||
function getCols() {
|
||||
if (self.current !== null) {
|
||||
//this is a hack, but there's weirdly no "real" way to get the number of columns
|
||||
return window.getComputedStyle(self.current).getPropertyValue('grid-template-columns').split(' ').length;
|
||||
} else {
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
//set num cols after page loads, then add listener to update if window resizes
|
||||
useLayoutEffect(() => {
|
||||
setNumcols(getCols());
|
||||
window.addEventListener('resize', (event) => {
|
||||
setNumcols(getCols());
|
||||
})
|
||||
}, [])
|
||||
|
||||
let emptyKey = 0;
|
||||
return (
|
||||
<section className="container" id="container" ref={self}>
|
||||
{newList.map((game) => (
|
||||
<div className="slot_container" key={game ? game[0] : emptyKey++}>
|
||||
{game ? <Game gameId={game[0]} state={game[1]}/> : <div className="emptyslot"/>}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Footer(props: { has_games: boolean }) {
|
||||
let text = props.has_games ? "" : "No games right now. Why not head over to Discord and start one?";
|
||||
return (
|
||||
<div id="footer">
|
||||
<div>{text}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default GamesPage;
|
42
simmadome/src/GamesUtil.tsx
Normal file
|
@ -0,0 +1,42 @@
|
|||
import {useLayoutEffect} from 'react';
|
||||
import io from 'socket.io-client';
|
||||
|
||||
interface GameState {
|
||||
bases: (string | null)[];
|
||||
outs: number;
|
||||
display_top_of_inning: boolean
|
||||
display_inning: number
|
||||
max_innings: number
|
||||
title: string
|
||||
weather_emoji: string
|
||||
weather_text: string
|
||||
away_name: string
|
||||
away_score: number
|
||||
home_name: string
|
||||
home_score: number
|
||||
pitcher: string
|
||||
batter: string
|
||||
update_emoji: string
|
||||
update_text: string
|
||||
is_league: boolean
|
||||
leagueoruser: string
|
||||
start_delay: number
|
||||
end_delay: number
|
||||
}
|
||||
|
||||
type GameList = ([id: string, game: GameState] | null)[];
|
||||
|
||||
|
||||
// connects to the given url (or host if none) and waits for state updates
|
||||
const useListener = (onUpdate: (update: [string, GameState][]) => void, url: string | null = null) => {
|
||||
useLayoutEffect(() => {
|
||||
let socket = url ? io(url) : io();
|
||||
socket.on('connect', () => socket.emit('recieved', {}));
|
||||
socket.on('states_update', onUpdate);
|
||||
return () => {socket.disconnect()};
|
||||
//eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [url])
|
||||
}
|
||||
|
||||
export { useListener };
|
||||
export type { GameState, GameList };
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.1 KiB |
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
Before Width: | Height: | Size: 8.9 KiB After Width: | Height: | Size: 8.9 KiB |
BIN
simmadome/src/img/github.png
Normal file
After Width: | Height: | Size: 2.3 KiB |
BIN
simmadome/src/img/naturalblack.png
Normal file
After Width: | Height: | Size: 256 KiB |
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 4.0 KiB |
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 3.4 KiB |
BIN
simmadome/src/img/patreon.png
Normal file
After Width: | Height: | Size: 51 KiB |
BIN
simmadome/src/img/twitter.png
Executable file
After Width: | Height: | Size: 8.7 KiB |
111
simmadome/src/index.css
Normal file
|
@ -0,0 +1,111 @@
|
|||
@import url('https://fonts.googleapis.com/css2?family=Alegreya&display=swap');
|
||||
@import url('https://fonts.googleapis.com/css2?family=Goldman:wght@700&display=swap');
|
||||
|
||||
:root {
|
||||
--background-main: #2f3136;
|
||||
--background-secondary: #4f545c;
|
||||
--background-tertiary: #202225;
|
||||
--background-accent: #40444b;
|
||||
--highlight: rgb(113, 54, 138); /*matteo purple™*/
|
||||
--accent-red: #f04747;
|
||||
--accent-green: rgb(67, 181, 129);
|
||||
}
|
||||
|
||||
body {
|
||||
background-image: url("img/naturalblack.png");
|
||||
}
|
||||
/* Background pattern from Toptal Subtle Patterns */
|
||||
|
||||
* {
|
||||
font-family: 'Alegreya', serif;
|
||||
color: white;
|
||||
}
|
||||
|
||||
h2 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.link{
|
||||
position: relative;
|
||||
top: 10px;
|
||||
}
|
||||
|
||||
.h1 {
|
||||
margin: auto;
|
||||
width: 45%;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.page_header {
|
||||
color: white;
|
||||
font-family: 'Goldman', cursive;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#header {
|
||||
width: 100%;
|
||||
height: max-content;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#header .page_header {
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
#link_div {
|
||||
text-align: right;
|
||||
position: absolute;
|
||||
top: 1rem;
|
||||
right: 2rem;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.github_logo, .twitter_logo, .patreon_container {
|
||||
height: 2rem;
|
||||
width: 2rem;
|
||||
margin-left: 0.75rem;
|
||||
}
|
||||
|
||||
.patreon_container {
|
||||
border-radius: 1rem;
|
||||
background: #FF424D;
|
||||
}
|
||||
|
||||
.patreon_logo {
|
||||
box-sizing: border-box;
|
||||
padding: 0.35rem;
|
||||
height: 2rem;
|
||||
width: 2rem;
|
||||
position: relative;
|
||||
left: 0.1rem;
|
||||
bottom: 0.05rem;
|
||||
}
|
||||
|
||||
a {
|
||||
background-color: transparent;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
a:link, a:visited {
|
||||
color: lightblue;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: white;
|
||||
}
|
||||
|
||||
#utility_links {
|
||||
position: absolute;
|
||||
top: 1rem;
|
||||
left: 2rem;
|
||||
}
|
||||
|
||||
img.emoji {
|
||||
height: 1em;
|
||||
width: 1em;
|
||||
margin: 0 .05em 0 .1em;
|
||||
vertical-align: -0.1em;
|
||||
}
|
57
simmadome/src/index.tsx
Normal file
|
@ -0,0 +1,57 @@
|
|||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
|
||||
import './index.css';
|
||||
import GamesPage from './GamesPage';
|
||||
import GamePage from './GamePage';
|
||||
import CreateLeague from './CreateLeague';
|
||||
import discordlogo from "./img/discord.png";
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
import patreonLogo from './img/patreon.png';
|
||||
import githubLogo from './img/github.png';
|
||||
import twitterLogo from './img/twitter.png';
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<Router>
|
||||
<Header />
|
||||
<Switch>
|
||||
<Route path="/game/:id" component={GamePage}/>
|
||||
<Route path="/create_league" component={CreateLeague} />
|
||||
<Route path="/" component={GamesPage}/>
|
||||
</Switch>
|
||||
</Router>
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
);
|
||||
|
||||
|
||||
function Header() {
|
||||
return (
|
||||
<div id="header">
|
||||
<div id="link_div">
|
||||
<a href="https://www.patreon.com/sixteen" className="patreon_link" target="_blank" rel="noopener noreferrer">
|
||||
<div className="patreon_container">
|
||||
<img className="patreon_logo" src={patreonLogo} alt="Patreon"/>
|
||||
</div>
|
||||
</a>
|
||||
<a href="https://github.com/Sakimori/matteo-the-prestige" className="github_link" target="_blank" rel="noopener noreferrer">
|
||||
<img className="github_logo" src={githubLogo} alt="Github"/>
|
||||
</a>
|
||||
<a href="https://twitter.com/intent/follow?screen_name=SIBR_XVI" className="twitter_link" target="_blank" rel="noopener noreferrer">
|
||||
<img className="twitter_logo" src={twitterLogo} alt="Twitter"/>
|
||||
</a>
|
||||
</div>
|
||||
<div id="utility_links">
|
||||
<Link to="/create_league">Create a League</Link>
|
||||
</div>
|
||||
<a href="/" className="page_header"><h2 className="page_header" style={{fontSize:"50px"} as React.CSSProperties}>THE SIMMADOME</h2></a>
|
||||
<h2 className="page_header">Join SIBR on <a href="https://discord.gg/UhAajY2NCW" className="link"><img src={discordlogo} alt="" height="30"/></a> to start your own games!</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
1
simmadome/src/react-app-env.d.ts
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/// <reference types="react-scripts" />
|
15
simmadome/src/reportWebVitals.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
5
simmadome/src/setupTests.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom';
|
34
simmadome/src/util.tsx
Normal file
|
@ -0,0 +1,34 @@
|
|||
function removeIndex(arr: any[], index: number) {
|
||||
return arr.slice(0, index).concat(arr.slice(index+1));
|
||||
}
|
||||
|
||||
function replaceIndex<T>(arr: T[], index: number, val: T) {
|
||||
return arr.slice(0, index).concat([val]).concat(arr.slice(index+1));
|
||||
}
|
||||
|
||||
function append<T>(arr: T[], val: T) {
|
||||
return arr.concat([val]);
|
||||
}
|
||||
|
||||
function arrayOf<T>(length: number, func: (i: number) => T): T[] {
|
||||
var out: T[] = [];
|
||||
for (var i = 0; i < length; i++) {
|
||||
out.push(func(i));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function shallowClone<T>(obj: T): T {
|
||||
return Object.assign({}, obj);
|
||||
}
|
||||
|
||||
let getUID = function() { // does NOT generate UUIDs. Meant to create list keys ONLY
|
||||
let id = 0;
|
||||
return function() { return id++ }
|
||||
}()
|
||||
|
||||
type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
|
||||
//type DistributivePick<T, K extends keyof T> = T extends any ? Pick<T, K> : never;
|
||||
|
||||
export {removeIndex, replaceIndex, append, arrayOf, shallowClone, getUID};
|
||||
export type {DistributiveOmit};
|
26
simmadome/tsconfig.json
Normal file
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
|
@ -6,4 +6,4 @@ SELECT name,
|
|||
ROUND(strikeouts_given*27.0/(outs_pitched*1.0),3) as kper9,
|
||||
ROUND(strikeouts_given*1.0/walks_allowed*1.0,3) as kperbb
|
||||
FROM stats WHERE outs_pitched > 150
|
||||
ORDER BY bbper9 ASC;
|
||||
ORDER BY era ASC;
|
|
@ -1,50 +0,0 @@
|
|||
<div class="header">
|
||||
<div class="inning"></div>
|
||||
<div class="weather"></div>
|
||||
</div>
|
||||
<div class="body">
|
||||
<div class="teams">
|
||||
<div class="team">
|
||||
<div class="team_name away_name"></div>
|
||||
<div class="score away_score"></div>
|
||||
</div>
|
||||
<div class="team">
|
||||
<div class="team_name home_name"></div>
|
||||
<div class="score home_score"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info">
|
||||
<div class="field">
|
||||
<img class="base base_2" src=""/>
|
||||
<div style="display: flex;">
|
||||
<img class="base base_3" src=""/>
|
||||
<img class="base base_1" src=""/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="outs">
|
||||
<div class="outs_title">OUTS</div>
|
||||
<div class="outs_count">
|
||||
<img class="out" src=""/>
|
||||
<img class="out" src=""/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="players">
|
||||
<div class="player pitcher">
|
||||
<div class="player_type">Pitcher:</div>
|
||||
<div class="player_name pitcher_name"></div>
|
||||
</div>
|
||||
<div class="player batter">
|
||||
<div class="player_type">Batter:</div>
|
||||
<div class="player_name batter_name"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="update">
|
||||
<div class="update_emoji"></div>
|
||||
<div class="update_text"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<div class="batting"></div>
|
||||
<div class="leagueoruser"></div>
|
||||
</div>
|
|
@ -1,375 +0,0 @@
|
|||
@import url('https://fonts.googleapis.com/css2?family=Alegreya&display=swap');
|
||||
@import url('https://fonts.googleapis.com/css2?family=Goldman:wght@700&display=swap');
|
||||
body {
|
||||
background-image: url("prism.png");
|
||||
}
|
||||
/* Background pattern from Toptal Subtle Patterns */
|
||||
|
||||
div, button {
|
||||
font-family: 'Alegreya', serif;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#link_div {
|
||||
text-align: right;
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
right: 30px;
|
||||
}
|
||||
|
||||
#link_div > a {
|
||||
background-color: transparent;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#link_div > a:link, #link_div > a:visited {
|
||||
color: lightblue;
|
||||
}
|
||||
|
||||
#link_div > a:hover {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(500px, 1fr));
|
||||
grid-gap: 50px 30px; /*space between rows, then columns*/
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
grid-auto-rows: 335px;
|
||||
grid-auto-flow: row;
|
||||
}
|
||||
|
||||
#header {
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
margin-bottom: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#header > .page_header {
|
||||
margin: auto
|
||||
}
|
||||
|
||||
#filters {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
width: max-content;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
#filters > * {
|
||||
padding: 4px 8px;
|
||||
margin: 0px 8px;
|
||||
font-size: 16pt;
|
||||
background: rgba(0,0,0,0);
|
||||
}
|
||||
|
||||
#filters > .filter {
|
||||
border-radius: 8px;
|
||||
min-width: 100px;
|
||||
text-align: center;
|
||||
border: none;
|
||||
}
|
||||
|
||||
#selected_filter {
|
||||
background: rgb(113, 54, 138);
|
||||
}
|
||||
|
||||
#footer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 75px;
|
||||
}
|
||||
|
||||
#footer > div {
|
||||
text-align: center;
|
||||
font-size: 20px;
|
||||
position: relative;
|
||||
top: 5px;
|
||||
}
|
||||
|
||||
.link{
|
||||
position: relative;
|
||||
top: 10px;
|
||||
}
|
||||
|
||||
.h1 {
|
||||
margin: auto;
|
||||
width: 45%;
|
||||
color: white;
|
||||
font-family: 'Alegreya', serif;
|
||||
}
|
||||
|
||||
.page_header {
|
||||
color: white;
|
||||
font-family: 'Goldman', cursive;
|
||||
}
|
||||
|
||||
.emptyslot {
|
||||
border: 2px dashed white;
|
||||
border-radius: 15px;
|
||||
align-self: stretch;
|
||||
justify-self: stretch;
|
||||
text-align: center;
|
||||
color: white;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.game {
|
||||
font-family: 'Alegreya', serif;
|
||||
color: white;
|
||||
align-self: stretch;
|
||||
justify-self: stretch;
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #2f3136; /*discord dark theme background-secondary - the same color as the embeds*/
|
||||
border: 4px solid;
|
||||
border-radius: 4px;
|
||||
border-color: rgb(113, 54, 138); /*matteo purple™*/
|
||||
border-top: none;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-family: 'Alegreya', serif;
|
||||
color: white;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.header {
|
||||
width: 100%;
|
||||
background-color: #4f545c; /*discord's background-tertiary*/
|
||||
border-top-right-radius: 4px;
|
||||
height: max-content;
|
||||
|
||||
}
|
||||
|
||||
.inning {
|
||||
float: left;
|
||||
margin: 5px;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.weather {
|
||||
float: right;
|
||||
margin: 5px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.body {
|
||||
margin: 10px;
|
||||
display: grid;
|
||||
grid-template-columns: 60% 40%;
|
||||
grid-template-areas:
|
||||
"teams info" "players info" "update update";
|
||||
grid-template-rows: 90px;
|
||||
grid-row-gap: 8px;
|
||||
grid-column-gap: 10px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.teams {
|
||||
grid-area: teams;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-around;
|
||||
}
|
||||
|
||||
.team {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.team_name {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.info {
|
||||
grid-area: info;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
background: #4f545c;
|
||||
padding-top: 8px;
|
||||
padding-bottom: 4px;
|
||||
margin-left: 15%;
|
||||
margin-right: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.batting {
|
||||
font-size: 10pt;
|
||||
text-align: left;
|
||||
height: max-content;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.leagueoruser {
|
||||
font-size: 10pt;
|
||||
text-align: right;
|
||||
height: max-content;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.outs {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
width: 60%;
|
||||
}
|
||||
|
||||
.outs_title {
|
||||
font-weight: bolder;
|
||||
}
|
||||
|
||||
.outs_count {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.out {
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.team_name, .score {
|
||||
font-size: 25px
|
||||
}
|
||||
|
||||
.score {
|
||||
background: #4f545c; /*discord's background-accent*/
|
||||
width: 40px;
|
||||
min-width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 20px;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.players {
|
||||
grid-area: players;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-around;
|
||||
align-items: start;
|
||||
height: max-content;
|
||||
}
|
||||
|
||||
.player {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.player_name {
|
||||
overflow: hidden;
|
||||
text-align: start;
|
||||
white-space: nowrap;
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
.update {
|
||||
grid-area: update;
|
||||
margin-right: 10px;
|
||||
margin-top: 10px;
|
||||
min-height: 50px;
|
||||
}
|
||||
|
||||
.player_type {
|
||||
width: 100%;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.update_emoji, .update_text {
|
||||
display: inline
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.base {
|
||||
height: 60px;
|
||||
}
|
||||
|
||||
.base_2 {
|
||||
margin-bottom: -25%
|
||||
}
|
||||
|
||||
@media only screen and (max-device-width: 800px) {
|
||||
.container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(1, minmax(700px, 90%));
|
||||
grid-template-rows: 400px;
|
||||
grid-gap: 50px 30px; /*space between rows, then columns*/
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
grid-auto-rows: 400px;
|
||||
grid-auto-flow: row;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
|
||||
.emptyslot {
|
||||
border: none;
|
||||
border-radius: 15px;
|
||||
align-self: stretch;
|
||||
justify-self: stretch;
|
||||
text-align: center;
|
||||
color: white;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.batting {
|
||||
font-size: 15pt;
|
||||
text-align: left;
|
||||
height: max-content;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.leagueoruser {
|
||||
font-size: 15pt;
|
||||
text-align: right;
|
||||
height: max-content;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.team_name, .score {
|
||||
font-size: 23px
|
||||
}
|
||||
|
||||
.players {
|
||||
font-size: 20px;
|
||||
grid-area: players;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
padding-right: 50px;
|
||||
}
|
||||
|
||||
.update_emoji, .update_text {
|
||||
display: inline;
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
123
static/loader.js
|
@ -1,123 +0,0 @@
|
|||
$(document).ready(function (){
|
||||
var socket = io.connect();
|
||||
var lastupdate;
|
||||
var grid = document.getElementById("container");
|
||||
|
||||
|
||||
socket.on('connect', function () {
|
||||
socket.emit('recieved', { data: 'I\'m connected!' });
|
||||
});
|
||||
|
||||
socket.on("states_update", function (json) { //json is an object containing all game updates
|
||||
lastupdate = json;
|
||||
updateGames(json, $('#selected_filter').text());
|
||||
|
||||
//get all leagues
|
||||
leagues = []
|
||||
for (var game of json) {
|
||||
if (game.league != "" && !leagues.includes(game.league)) {
|
||||
leagues.push(game.league)
|
||||
}
|
||||
}
|
||||
|
||||
//remove leagues no longer present
|
||||
$('#filters .filter').each(function(index) {
|
||||
if (!leagues.includes($(this).text())) {
|
||||
if ($(this).attr('id') != 'selected_filter' && $(this).text() != "All") { //don't remove the currently selected filter or the "all" filter
|
||||
$(this).remove();
|
||||
}
|
||||
} else {
|
||||
leagues.splice(leagues.indexOf($(this).text()), 1);
|
||||
}
|
||||
})
|
||||
|
||||
// add leagues not already present
|
||||
for (var league of leagues) { // we removed the entries that are already there in the loop above
|
||||
$('#filters').append("<button class='filter'>"+league+"</button>");
|
||||
}
|
||||
|
||||
//add click handlers to each filter
|
||||
$('#filters .filter').each(function(index) {
|
||||
$(this).click(function() {
|
||||
if ($('#filters #selected_filter').text() == 'All') {
|
||||
updateGames([], ""); // clear grid when switching off of All, to make games collapse to top
|
||||
}
|
||||
$('#filters #selected_filter').attr('id', '');
|
||||
$(this).attr('id', 'selected_filter');
|
||||
updateGames(lastupdate, $(this).text());
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
const updateGames = (json, filter) => {
|
||||
|
||||
filterjson = [];
|
||||
for (var game of json) {
|
||||
if (game.league == filter || filter == "All") {
|
||||
filterjson.push(game);
|
||||
}
|
||||
}
|
||||
|
||||
if (filterjson.length == 0) {
|
||||
$('#footer div').html("No games right now. Why not head over to Discord and start one?");
|
||||
} else {
|
||||
$('#footer div').html("");
|
||||
}
|
||||
|
||||
//replace games that have ended with empty slots
|
||||
for (var slotnum = 0; slotnum < grid.children.length; slotnum++) {
|
||||
if (grid.children[slotnum].className == "game" && !filterjson.some((x) => x.timestamp == grid.children[slotnum].timestamp)) {
|
||||
grid.children[slotnum].className = "emptyslot";
|
||||
grid.children[slotnum].timestamp = null;
|
||||
grid.children[slotnum].innerHTML = "";
|
||||
}
|
||||
}
|
||||
|
||||
for (var game of filterjson) {
|
||||
//updates game in list
|
||||
for (var slotnum = 0; slotnum < grid.children.length; slotnum++) {
|
||||
if (grid.children[slotnum].timestamp == game.timestamp) {
|
||||
insertGame(slotnum, game);
|
||||
};
|
||||
};
|
||||
|
||||
//adds game to list if not there already
|
||||
if (!Array.prototype.slice.call(grid.children).some((x) => x.timestamp == game.timestamp)) {
|
||||
for (var slotnum = 0; true; slotnum++) { //this is really a while loop but shh don't tell anyone
|
||||
if (slotnum >= grid.children.length) {
|
||||
for (var i = 0; i < 3; i ++) {
|
||||
insertEmpty(grid);
|
||||
}
|
||||
}
|
||||
if (grid.children[slotnum].className == "emptyslot") {
|
||||
insertGame(slotnum, game);
|
||||
break;
|
||||
};
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
//remove last rows if not needed
|
||||
while (grid.children[grid.children.length-1].className == "emptyslot" &&
|
||||
grid.children[grid.children.length-2].className == "emptyslot" &&
|
||||
grid.children[grid.children.length-3].className == "emptyslot" &&
|
||||
grid.children.length > 3) {
|
||||
for (var i = 0; i < 3; i++) {
|
||||
grid.removeChild(grid.children[grid.children.length-1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const insertEmpty = (grid) => {
|
||||
newBox = document.createElement("DIV");
|
||||
newBox.className = "emptyslot";
|
||||
grid.appendChild(newBox);
|
||||
}
|
||||
|
||||
const insertGame = (gridboxnum, game) => {
|
||||
var thisBox = grid.children[gridboxnum];
|
||||
thisBox.innerHTML = game.html;
|
||||
thisBox.className = "game";
|
||||
thisBox.timestamp = game.timestamp;
|
||||
};
|
||||
});
|
BIN
static/prism.png
Before Width: | Height: | Size: 9.5 KiB |
Before Width: | Height: | Size: 2.1 KiB |
BIN
templates/.DS_Store
vendored
|
@ -1,57 +0,0 @@
|
|||
{% macro base(number) -%}
|
||||
{% if state.bases[number] %}/static/img/base_filled.png{% else %}/static/img/base_empty.png{% endif %}
|
||||
{%- endmacro %}
|
||||
{% macro out(number) -%}
|
||||
{% if number <= state.outs %}/static/img/out_out.png{% else %}/static/img/out_in.png{% endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
<div class="header">
|
||||
<div class="inning">Inning: {% if state.display_top_of_inning == true %}🔼{% else %}🔽{% endif %} {{ state.display_inning }}/{{ state.max_innings }}</div>
|
||||
<div class="weather">{{ state.weather_emoji }} {{ state.weather_text }}</div>
|
||||
</div>
|
||||
<div class="body">
|
||||
<div class="teams">
|
||||
<div class="team">
|
||||
<div class="team_name">{{ state.away_name }}</div>
|
||||
<div class="score">{{ state.away_score }}</div>
|
||||
</div>
|
||||
<div class="team">
|
||||
<div class="team_name">{{ state.home_name }}</div>
|
||||
<div class="score">{{ state.home_score }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info">
|
||||
<div class="field">
|
||||
<img class="base base_2" src="{{ base(2) }}"/>
|
||||
<div style="display: flex;">
|
||||
<img class="base base_3" src="{{ base(3) }}"/>
|
||||
<img class="base base_1" src="{{ base(1) }}"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="outs">
|
||||
<div class="outs_title">OUTS</div>
|
||||
<div class="outs_count">
|
||||
<img class="out" src="{{ out(1) }}"/>
|
||||
<img class="out" src="{{ out(2) }}"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="players">
|
||||
<div class="player pitcher">
|
||||
<div class="player_type">Pitcher:</div>
|
||||
<div class="player_name pitcher_name">{{ state.pitcher }}</div>
|
||||
</div>
|
||||
<div class="player batter">
|
||||
<div class="player_type">Batter:</div>
|
||||
<div class="player_name batter_name">{{ state.batter }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="update">
|
||||
<div class="update_emoji">{{ state.update_emoji }}</div>
|
||||
<div class="update_text">{{ state.update_text }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<div class="batting">{% if state.display_top_of_inning == true %}{{ state.away_name }}{% else %}{{ state.home_name }}{% endif %} batting.</div>
|
||||
<div class="leagueoruser">{{ state.leagueoruser }}</div>
|
||||
</div>
|
|
@ -1,38 +0,0 @@
|
|||
<html lang="en-US">
|
||||
<head>
|
||||
<script src="//code.jquery.com/jquery-3.5.1.min.js"></script>
|
||||
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js"></script>
|
||||
<script type="text/javascript" async src="https://platform.twitter.com/widgets.js"></script>
|
||||
<script type="text/javascript" src="static/loader.js"></script>
|
||||
<link rel="stylesheet" href="/static/games_page.css">
|
||||
<title>⚾ The Simmadome</title>
|
||||
<meta property="og:title" content="Watch at the Simmadome" />
|
||||
<meta property="og:description" content="The Simsim: Your players, your teams, your games." />
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:site" content="@SIBR_XVI">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="header">
|
||||
<div id="link_div">
|
||||
<a href="https://www.patreon.com/sixteen" class="link" target="_blank" rel="noopener noreferrer">Patreon</a><br />
|
||||
<a href="https://github.com/Sakimori/matteo-the-prestige" class="link" target="_blank" rel="noopener noreferrer">Github</a><br />
|
||||
<a href="https://twitter.com/intent/follow?screen_name=SIBR_XVI" class="link" target="_blank" rel="noopener noreferrer">Twitter</a>
|
||||
</div>
|
||||
<h2 class="page_header" style="font-size: 50px;">THE SIMMADOME</h2>
|
||||
<h2 class="page_header">Join SIBR on <a href="https://discord.gg/UhAajY2NCW" class="link"><img src="static/discord.png" height="30"></a> to start your own games!</h2>
|
||||
<div id="filters">
|
||||
<div>Filter:</div>
|
||||
<button class="filter" id="selected_filter">All</button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="container" id="container">
|
||||
<div class="emptyslot"></div>
|
||||
<div class="emptyslot"></div>
|
||||
<div class="emptyslot"></div>
|
||||
</section>
|
||||
<div id="footer">
|
||||
<div></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -29,6 +29,12 @@
|
|||
<Compile Include="debug storage.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="leagues.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="league_storage.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="main_controller.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
|
@ -58,10 +64,6 @@
|
|||
<Content Include="ids" />
|
||||
<Content Include="matteo.db" />
|
||||
<Content Include="static\discord.png" />
|
||||
<Content Include="static\game.html" />
|
||||
<Content Include="static\games_page.css" />
|
||||
<Content Include="static\loader.js" />
|
||||
<Content Include="static\prism.png" />
|
||||
<Content Include="templates\game.html" />
|
||||
<Content Include="templates\index.html" />
|
||||
</ItemGroup>
|
||||
|
|
153
the_draft.py
Normal file
|
@ -0,0 +1,153 @@
|
|||
from collections import namedtuple
|
||||
import games
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import onomancer
|
||||
|
||||
DRAFT_SIZE = 20
|
||||
REFRESH_DRAFT_SIZE = 4 # fewer players remaining than this and the list refreshes
|
||||
DRAFT_ROUNDS = 13
|
||||
|
||||
Participant = namedtuple('Participant', ['handle', 'team'])
|
||||
BOOKMARK = Participant(handle="bookmark", team=None) # keep track of start/end of draft round
|
||||
|
||||
|
||||
class Draft:
|
||||
"""
|
||||
Represents a draft party with n participants constructing their team from a pool
|
||||
of names.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def make_draft(cls):
|
||||
draft = cls()
|
||||
return draft
|
||||
|
||||
def __init__(self):
|
||||
self._id = str(uuid.uuid4())[:6]
|
||||
self._participants = []
|
||||
self._active_participant = BOOKMARK # draft mutex
|
||||
self._players = onomancer.get_names(limit=DRAFT_SIZE)
|
||||
self._round = 0
|
||||
|
||||
@property
|
||||
def round(self):
|
||||
"""
|
||||
Current draft round. 1 indexed.
|
||||
"""
|
||||
return self._round
|
||||
|
||||
@property
|
||||
def active_drafter(self):
|
||||
"""
|
||||
Handle of whomever is currently up to draft.
|
||||
"""
|
||||
return self._active_participant.handle
|
||||
|
||||
@property
|
||||
def active_drafting_team(self):
|
||||
return self._active_participant.team.name
|
||||
|
||||
def add_participant(self, handle, team_name, slogan):
|
||||
"""
|
||||
A participant is someone participating in this draft. Initializes an empty team for them
|
||||
in memory.
|
||||
|
||||
`handle`: discord @ handle, for ownership and identification
|
||||
"""
|
||||
team = games.team()
|
||||
team.name = team_name
|
||||
team.slogan = slogan
|
||||
self._participants.append(Participant(handle=handle, team=team))
|
||||
|
||||
def start_draft(self):
|
||||
"""
|
||||
Call after adding all participants and confirming they're good to go.
|
||||
"""
|
||||
self.advance_draft()
|
||||
|
||||
def refresh_players(self):
|
||||
self._players = onomancer.get_names(limit=DRAFT_SIZE)
|
||||
|
||||
def advance_draft(self):
|
||||
"""
|
||||
The participant list is treated as a circular queue with the head being popped off
|
||||
to act as the draftign mutex.
|
||||
"""
|
||||
if self._active_participant == BOOKMARK:
|
||||
self._round += 1
|
||||
self._participants.append(self._active_participant)
|
||||
self._active_participant = self._participants.pop(0)
|
||||
|
||||
def get_draftees(self):
|
||||
return list(self._players.keys())
|
||||
|
||||
def draft_player(self, handle, player_name):
|
||||
"""
|
||||
`handle` is the participant's discord handle.
|
||||
"""
|
||||
if self._active_participant.handle != handle:
|
||||
raise ValueError(f'{self._active_participant.handle} is drafting, not you')
|
||||
|
||||
player_name = player_name.strip()
|
||||
|
||||
player = self._players.get(player_name)
|
||||
if not player:
|
||||
# might be some whitespace shenanigans
|
||||
for name, stats in self._players.items():
|
||||
if name.replace('\xa0', ' ').strip().lower() == player_name.lower():
|
||||
player = stats
|
||||
break
|
||||
else:
|
||||
# still not found
|
||||
raise ValueError(f'Player `{player_name}` not in draft list')
|
||||
del self._players[player['name']]
|
||||
|
||||
if len(self._players) <= REFRESH_DRAFT_SIZE:
|
||||
self.refresh_players()
|
||||
|
||||
if self._round < DRAFT_ROUNDS:
|
||||
self._active_participant.team.add_lineup(games.player(json.dumps(player)))
|
||||
elif self._round == DRAFT_ROUNDS:
|
||||
self._active_participant.team.add_pitcher(games.player(json.dumps(player)))
|
||||
|
||||
self.advance_draft()
|
||||
if self._active_participant == BOOKMARK:
|
||||
self.advance_draft()
|
||||
|
||||
return player
|
||||
|
||||
def get_teams(self):
|
||||
teams = []
|
||||
if self._active_participant != BOOKMARK:
|
||||
teams.append((self._active_participant.handle, self._active_participant.team))
|
||||
for participant in self._participants:
|
||||
if participant != BOOKMARK:
|
||||
teams.append((participant.handle, participant.team))
|
||||
return teams
|
||||
|
||||
def finish_draft(self):
|
||||
for handle, team in self.get_teams():
|
||||
success = games.save_team(team, int(handle[3:-1]))
|
||||
if not success:
|
||||
raise Exception(f'Error saving team for {handle}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# extremely robust testing OC do not steal
|
||||
DRAFT_ROUNDS = 2
|
||||
draft = Draft.make_draft()
|
||||
draft.add_participant('@bluh', 'Bluhstein Bluhs', 'bluh bluh bluh')
|
||||
draft.add_participant('@what', 'Barcelona IDK', 'huh')
|
||||
draft.start_draft()
|
||||
|
||||
while draft.round <= DRAFT_ROUNDS:
|
||||
print(draft.get_draftees())
|
||||
cmd = input(f'{draft.round} {draft.active_drafter}:')
|
||||
drafter, player = cmd.split(' ', 1)
|
||||
try:
|
||||
draft.draft_player(drafter, player)
|
||||
except ValueError as e:
|
||||
print(e)
|
||||
print(draft.get_teams())
|