From ac2f3039367fd82bb16b66f8276cd5cc71fcea68 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Tue, 12 Jan 2021 15:36:56 -0500 Subject: [PATCH 01/44] switched to gpl3 --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. From 1189fb219abd7a1206b6c365b316368e1bf65a7b Mon Sep 17 00:00:00 2001 From: Astrid Date: Wed, 13 Jan 2021 12:56:00 +0100 Subject: [PATCH 02/44] Update Dockerfile for frontend build --- .dockerignore | 6 ++++++ .gitignore | 2 ++ Dockerfile | 19 +++++++++++++++---- 3 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5c484d3 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +venv/ +matteo_env/ +__pycache__/ +simmadome/node_modules +data/ +.git/ \ No newline at end of file diff --git a/.gitignore b/.gitignore index b4a7181..af99f24 100644 --- a/.gitignore +++ b/.gitignore @@ -344,6 +344,7 @@ config.json games_config.json weather_config.json ids +data/ # database matteo.db @@ -351,5 +352,6 @@ matteo.db-wal matteo.db-shm /data/leagues/* /matteo_env/Lib/site-packages/flask_socketio/__init__.py +Pipfile env diff --git a/Dockerfile b/Dockerfile index 75d8a22..fc250eb 100644 --- a/Dockerfile +++ b/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"] From cfd4af5f7cf677cbcf43aba1bc1d4317d1f78309 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Wed, 13 Jan 2021 15:27:59 -0500 Subject: [PATCH 03/44] added another patron --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 343a2fd..e22791b 100644 --- a/README.md +++ b/README.md @@ -99,3 +99,4 @@ these folks are helping me a *ton* via patreon, and i cannot possibly thank them - Ryan Littleton - Evie Diver - iliana etaoin +- Stephen Bell From 22115ee2c3d4247542c2b7f61341f2264ed1d6a6 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Wed, 13 Jan 2021 20:55:12 -0500 Subject: [PATCH 04/44] closed #142 --- the_prestige.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index a805b93..086c0e0 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1394,7 +1394,6 @@ def game_over_embed(game): title_string += f" with {game.inning - (game.max_innings+1)} extra innings.\n" else: title_string += ".\n" - title_string += game.weather.emoji + game.weather.name winning_team = game.teams['home'].name if game.teams['home'].score > game.teams['away'].score else game.teams['away'].name winstring = f"{game.teams['away'].score} to {game.teams['home'].score}\n" @@ -1406,7 +1405,10 @@ def game_over_embed(game): winstring += f"{winning_team} wins!" embed = discord.Embed(color=discord.Color.dark_purple(), title=title_string) - embed.add_field(name="Final score:", value=winstring) + embed.add_field(name="Final score:", value=winstring, inline=False) + embed.add_field(name=f"{game.teams['away'].name} pitcher:", value=game.teams['away'].pitcher.name) + embed.add_field(name=f"{game.teams['home'].name} pitcher:", value=game.teams['home'].pitcher.name) + embed.set_footer(text=game.weather.emoji + game.weather.name) return embed def get_team_fuzzy_search(team_name): From ae256de645b4f456625d67bd0d78a8b5b17bf442 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Wed, 13 Jan 2021 22:34:46 -0500 Subject: [PATCH 05/44] implemented thinned veil and twilight weathers --- games.py | 25 +++++++++++++++++++++---- main_controller.py | 9 +++++++++ the_prestige.py | 2 ++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/games.py b/games.py index d917bca..83104a2 100644 --- a/games.py +++ b/games.py @@ -31,13 +31,14 @@ def config(): def all_weathers(): weathers_dic = { #"Supernova" : weather("Supernova", "🌟"), - "Midnight": weather("Midnight", "πŸ•Ά"), + #"Midnight": weather("Midnight", "πŸ•Ά"), "Slight Tailwind": weather("Slight Tailwind", "πŸŒοΈβ€β™€οΈ"), - "Heavy Snow": weather("Heavy Snow", "❄") + "Heavy Snow": weather("Heavy Snow", "❄"), + "Twilight" : weather("Twilight", "πŸŒƒ"), + "Thinned Veil" : weather("Thinned Veil", "🌌") } return weathers_dic - class appearance_outcomes(Enum): strikeoutlooking = "strikes out looking." strikeoutswinging = "strikes out swinging." @@ -269,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 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: @@ -313,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 @@ -384,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(): @@ -535,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) diff --git a/main_controller.py b/main_controller.py index 73da0a7..215572e 100644 --- a/main_controller.py +++ b/main_controller.py @@ -110,6 +110,8 @@ def update_loop(): 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}" @@ -120,6 +122,13 @@ 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"] += " {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]['defender']} lost sight of the ball! {this_game.last_update[0]['batter']} reaches {games.base_string(this_game.last_update[1])} on the error." state["bases"] = this_game.named_bases() diff --git a/the_prestige.py b/the_prestige.py index 086c0e0..9c98076 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1134,6 +1134,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals wins_in_series[winner_name] = 1 final_embed = game_over_embed(game) + final_embed.add_field(name="Series score:", value=f"{wins_in_series[game.teams['away'].name]} - {wins_in_series[game.teams['home'].name]}") await channel.send(f"A {tourney.name} game just ended!") await channel.send(embed=final_embed) if wins_in_series[winner_name] >= int((tourney.series_length+1)/2) and not finals: @@ -1502,6 +1503,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, league.update_standings({winner_name : winner_dic, loser_name : loser_dic}) leagues.save_league(league) final_embed = game_over_embed(game) + final_embed.add_field(name="Series score:", value=f"{series_results[game.teams['away'].name]['wins']} - {series_results[game.teams['home'].name]['wins']}") await channel.send(f"A {league.name} game just ended!") await channel.send(embed=final_embed) if series_results[winner_name]["wins"] + series_results[winner_name]["losses"] < league.series_length: From 3def1378a9711b3f9a4ac087f3d517baf7016c96 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Wed, 13 Jan 2021 23:21:28 -0500 Subject: [PATCH 06/44] bugfixes for veil and twilight, changed veil text and emoji --- games.py | 6 +++--- main_controller.py | 8 ++++---- the_prestige.py | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/games.py b/games.py index 83104a2..5a314c3 100644 --- a/games.py +++ b/games.py @@ -34,7 +34,7 @@ def all_weathers(): #"Midnight": weather("Midnight", "πŸ•Ά"), "Slight Tailwind": weather("Slight Tailwind", "πŸŒοΈβ€β™€οΈ"), "Heavy Snow": weather("Heavy Snow", "❄"), - "Twilight" : weather("Twilight", "πŸŒƒ"), + "Twilight" : weather("Twilight", "πŸ‘»"), "Thinned Veil" : weather("Thinned Veil", "🌌") } return weathers_dic @@ -270,11 +270,11 @@ 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 weather.name == "Twilight": + 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["error"] = True outcome["defender"] = defender pb_system_stat = 0.1 diff --git a/main_controller.py b/main_controller.py index 215572e..c66af65 100644 --- a/main_controller.py +++ b/main_controller.py @@ -125,10 +125,10 @@ def update_loop(): if "veil" in this_game.last_update[0].keys(): state["update_emoji"] = "🌌" - state["update_text"] += " {this_game.last_update[0]['batter']}'s will manifests on {games.base_string(this_game.last_update[1])} base!" + 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]['defender']} lost sight of the ball! {this_game.last_update[0]['batter']} reaches {games.base_string(this_game.last_update[1])} on the error." + 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() @@ -150,4 +150,4 @@ def update_loop(): state["update_pause"] -= 1 socketio.emit("states_update", game_states) - time.sleep(1) \ No newline at end of file + time.sleep(4) \ No newline at end of file diff --git a/the_prestige.py b/the_prestige.py index 9c98076..aad0568 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -202,7 +202,7 @@ class StartRandomGameCommand(Command): channel = msg.channel await msg.delete() - await channel.send("Rolling the bones...") + await channel.send("Rolling the bones... This might take a while.") teamslist = games.get_all_teams() game = games.game(random.choice(teamslist).finalize(), random.choice(teamslist).finalize()) From 5826574a1d1f23d364d7a4cb4ba530b0ae4e5028 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Thu, 14 Jan 2021 00:20:43 -0500 Subject: [PATCH 07/44] startleague command attempt --- league_storage.py | 5 +++-- leagues.py | 4 ++++ main_controller.py | 2 +- the_prestige.py | 44 ++++++++++++++++++++++++++++++++++++++------ 4 files changed, 46 insertions(+), 9 deletions(-) diff --git a/league_storage.py b/league_storage.py index 63a7fe7..dcc4555 100644 --- a/league_storage.py +++ b/league_storage.py @@ -98,7 +98,8 @@ def save_league(league): "series_length" : league.series_length, "games_per_hour" : league.games_per_hour, "owner" : league.owner, - "historic" : league.historic + "historic" : league.historic, + "season" : league.season } 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) @@ -154,5 +155,5 @@ def league_exists(league_name): with os.scandir(os.path.join(data_dir, league_dir)) as folder: for subfolder in folder: if league_name in subfolder.name: - return not state(league_name)["historic"] + return True return False \ No newline at end of file diff --git a/leagues.py b/leagues.py index b685d8a..791a1ec 100644 --- a/leagues.py +++ b/leagues.py @@ -12,6 +12,7 @@ class league_structure(object): self.name = name self.historic = False self.owner = None + self.season = 1 def setup(self, league_dic, division_games = 1, inter_division_games = 1, inter_league_games = 1, games_per_hour = 2): self.league = league_dic #key: subleague, value: {division : team_name} @@ -332,4 +333,7 @@ def load_league_file(league_name): 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"] return this_league \ No newline at end of file diff --git a/main_controller.py b/main_controller.py index c66af65..d2338be 100644 --- a/main_controller.py +++ b/main_controller.py @@ -150,4 +150,4 @@ def update_loop(): state["update_pause"] -= 1 socketio.emit("states_update", game_states) - time.sleep(4) \ No newline at end of file + time.sleep(1) \ No newline at end of file diff --git a/the_prestige.py b/the_prestige.py index aad0568..ef99604 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -726,7 +726,7 @@ class StartDraftCommand(Command): return draft_message class DebugLeagueStart(Command): - name = "startleague" + name = "startdebugleague" async def execute(self, msg, command): if not league_exists("test2"): @@ -743,19 +743,50 @@ class DebugLeagueStart(Command): }, division_games=6, inter_division_games=3, inter_league_games=3, games_per_hour = 12) league.generate_schedule() leagues.save_league(league) - else: - league = leagues.load_league_file("test2") - await start_league_day(msg.channel, league, autoplay = 2) class DebugLeagueDisplay(Command): - name = "displayleague" + name = "displaydebugleague" async def execute(self, msg, command): if league_exists("test2"): league = leagues.load_league_file("test2") await msg.channel.send(embed=league.standings_embed()) +class StartLeagueCommand(Command): + name = "startleague" + template = "m;startleague [league name]" + description = """Optional flag: `--queue X` or `-q X` to play X number of series before stopping. +Plays a league with a given name, provided that league has been saved on the website.""" + async def execute(self, msg, command): + league_name = command.split("-").strip() + autoplay = None + + try: + if "--queue " in command: + autoplay = int(command.split("--queue ")[1]) + elif "-q " in command: + autoplay = int(command.split("--queue ")[1]) + if autoplay is not None and autoplay <= 0: + raise ValueError + elif autoplay is None: + autoplay = -1 + except: + await msg.channel.send("Sorry boss, the queue flag needs a natural number. Any whole number over 0 will do just fine.") + return + + if league_exists(league_name): + league = leagues.load_league_file(league_name) + if league.historic: + await msg.channel.send("That league is done and dusted, chief. Sorry.") + return + for active_league in active_leagues: + if active_league.name == league.name: + await msg.channel.send("That league is already running, boss. Patience is a virtue, you know.") + return + await start_league_day(msg.channel, league, autoplay = autoplay) + else: + await msg.channel.send("Couldn't find that league, boss. Did you save it on the website?") commands = [ IntroduceCommand(), @@ -1464,7 +1495,8 @@ async def start_league_day(channel, league, autoplay = 1): async def league_day_watcher(channel, league, games_list, filter_url, autoplay, last = False): league.active = True autoplay -= 1 - active_leagues.append(league) + if league not in active_leagues: + active_leagues.append(league) series_results = {} while league.active: From da8607e2950bd2284d00b03a56c2ae1a19236b5a Mon Sep 17 00:00:00 2001 From: Sakimori Date: Thu, 14 Jan 2021 00:25:24 -0500 Subject: [PATCH 08/44] fixed some blocking bugs in startleague --- league_storage.py | 18 ++---------------- leagues.py | 4 +--- the_prestige.py | 5 +++-- 3 files changed, 6 insertions(+), 21 deletions(-) diff --git a/league_storage.py b/league_storage.py index dcc4555..c0ad6a6 100644 --- a/league_storage.py +++ b/league_storage.py @@ -72,34 +72,20 @@ def init_league_db(league): for pitcher in team.rotation: c.execute(player_string, (pitcher.name, team.name)) - state_dic = { - "day" : league.day, - "schedule" : league.schedule, - "game_length" : league.game_length, - "series_length" : league.series_length, - "games_per_hour" : league.games_per_hour, - "owner" : None, - "historic" : False - } - 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"), "w") as state_file: - json.dump(state_dic, state_file, indent=4) - conn.commit() conn.close() def save_league(league): if league_exists(league.name): state_dic = { + "season" : league.season, "day" : league.day, "schedule" : league.schedule, "game_length" : league.game_length, "series_length" : league.series_length, "games_per_hour" : league.games_per_hour, "owner" : league.owner, - "historic" : league.historic, - "season" : league.season + "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) diff --git a/leagues.py b/leagues.py index 791a1ec..fc92657 100644 --- a/leagues.py +++ b/leagues.py @@ -315,9 +315,7 @@ def save_league(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) - return True - else: - league_db.save_league(this_league) + league_db.save_league(this_league) def load_league_file(league_name): if league_db.league_exists(league_name): diff --git a/the_prestige.py b/the_prestige.py index ef99604..1c7e2c8 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -759,14 +759,14 @@ class StartLeagueCommand(Command): Plays a league with a given name, provided that league has been saved on the website.""" async def execute(self, msg, command): - league_name = command.split("-").strip() + league_name = command.split("-")[0].strip() autoplay = None try: if "--queue " in command: autoplay = int(command.split("--queue ")[1]) elif "-q " in command: - autoplay = int(command.split("--queue ")[1]) + autoplay = int(command.split("-q ")[1]) if autoplay is not None and autoplay <= 0: raise ValueError elif autoplay is None: @@ -808,6 +808,7 @@ commands = [ SearchTeamsCommand(), StartGameCommand(), StartTournamentCommand(), + StartLeagueCommand(), StartRandomGameCommand(), CreditCommand(), RomanCommand(), From b83bf771cae0516250476d4a90b9df142894afa8 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Thu, 14 Jan 2021 00:37:58 -0500 Subject: [PATCH 09/44] made leagues save properly after autoplaying --- the_prestige.py | 1 + 1 file changed, 1 insertion(+) diff --git a/the_prestige.py b/the_prestige.py index 1c7e2c8..fd5ded9 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1579,6 +1579,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, if last or autoplay == 0: #if this series was the last of the season OR number of series to autoplay has been reached await channel.send(embed=league.standings_embed()) await channel.send(f"The {league.name} is no longer autoplaying.") + leagues.save_league(league) active_leagues.pop(active_leagues.index(league)) return From 4acaca0fb19db6797b1f32929a1186c94184f0dc Mon Sep 17 00:00:00 2001 From: Sakimori Date: Thu, 14 Jan 2021 02:37:23 -0500 Subject: [PATCH 10/44] added the startleague command --- the_prestige.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index fd5ded9..c34fc97 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1555,7 +1555,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] for i in range(0, len(validminutes)): if now.minute > validminutes[i]: - if i <= len(validminutes)-1: + if i <= len(validminutes)-2: delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) else: delta = datetime.timedelta(minutes= (60 - now.minute)) @@ -1588,7 +1588,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] for i in range(0, len(validminutes)): if now.minute > validminutes[i]: - if i < len(validminutes)-1: + if i < len(validminutes)-2: delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) else: delta = datetime.timedelta(minutes= (60 - now.minute)) From 6b56c87beff50aa14e4af3eb03ebc1ca4e931148 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Thu, 14 Jan 2021 17:47:57 -0500 Subject: [PATCH 11/44] added handling for postseason constraints --- league_storage.py | 1 + leagues.py | 4 +++- main_controller.py | 2 ++ sql scripts/pitching leaders.sql | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/league_storage.py b/league_storage.py index d2aea60..ff1375f 100644 --- a/league_storage.py +++ b/league_storage.py @@ -81,6 +81,7 @@ def save_league(league): state_dic = { "season" : league.season, "day" : league.day, + "constraints" : league.constraints, "schedule" : league.schedule, "game_length" : league.game_length, "series_length" : league.series_length, diff --git a/leagues.py b/leagues.py index 23ac5ff..dfb9c3a 100644 --- a/leagues.py +++ b/leagues.py @@ -19,7 +19,9 @@ class league_structure(object): self.constraints = { "division_games" : division_games, "inter_div_games" : inter_division_games, - "inter_league_games" : inter_league_games + "inter_league_games" : inter_league_games, + "division_leaders" : 0, + "wild_cards" : 0 } self.day = 1 self.schedule = {} diff --git a/main_controller.py b/main_controller.py index 61b0a73..8086dad 100644 --- a/main_controller.py +++ b/main_controller.py @@ -62,6 +62,8 @@ def create_league(): 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) diff --git a/sql scripts/pitching leaders.sql b/sql scripts/pitching leaders.sql index d4885fb..27bda9c 100644 --- a/sql scripts/pitching leaders.sql +++ b/sql scripts/pitching leaders.sql @@ -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; \ No newline at end of file +ORDER BY era ASC; \ No newline at end of file From 333476548d1cb38b675e8dce5df6045f019a392e Mon Sep 17 00:00:00 2001 From: Sakimori Date: Thu, 14 Jan 2021 23:39:08 -0500 Subject: [PATCH 12/44] standings and wildcard commands added --- leagues.py | 67 +++++++++++++++-- the_prestige.py | 196 +++++++++++++++++++++++++++++++++--------------- 2 files changed, 196 insertions(+), 67 deletions(-) diff --git a/leagues.py b/leagues.py index dfb9c3a..9356d45 100644 --- a/leagues.py +++ b/leagues.py @@ -13,6 +13,7 @@ class league_structure(object): self.historic = False self.owner = None self.season = 1 + self.autoplay = -1 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] } } @@ -182,6 +183,22 @@ class league_structure(object): 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 standings_embed(self): this_embed = Embed(color=Color.purple(), title=self.name) standings = {} @@ -191,21 +208,54 @@ class league_structure(object): this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False) for division in iter(self.league[subleague].keys()): this_embed.add_field(name="Division:", value=f"**{division}**", inline = False) - teams = self.league[subleague][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"],) + teams = self.division_standings(self.league[subleague][division], standings) - def sorter(team_in_list): - return (team_in_list[1], team_in_list[3]) - teams.sort(key=sorter, reverse=True) + 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 for this_team in teams: - this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} Diff: {this_team[3]}", inline = False) + if this_team[2] != 0 or this_team[1] != 0: + this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}", inline = False) + else: + this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}", inline = False) this_embed.set_footer(text=f"Standings as of day {self.day-1}") 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()): + this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False) + 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) + + 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: + this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}", inline = False) + else: + this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}", inline = False) + + this_embed.set_footer(text=f"Wildcard standings as of day {self.day-1}") + return this_embed + 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 @@ -330,6 +380,7 @@ def load_league_file(league_name): 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"] diff --git a/the_prestige.py b/the_prestige.py index c34fc97..21cc57b 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -562,7 +562,12 @@ class StartTournamentCommand(Command): if team == None: await msg.channel.send(f"We couldn't find {name}. Try again?") return - team_dic[team] = {"wins": 0} + add = True + for extant_team in team_dic.keys(): + if extant_team.name == team.name: + add = False + if add: + team_dic[team] = {"wins": 0} channel = msg.channel await msg.delete() @@ -754,26 +759,39 @@ class DebugLeagueDisplay(Command): class StartLeagueCommand(Command): name = "startleague" - template = "m;startleague [league name]" - description = """Optional flag: `--queue X` or `-q X` to play X number of series before stopping. -Plays a league with a given name, provided that league has been saved on the website.""" + template = "m;startleague [league name]\n[games per hour]" + description = """Optional flag for the first line: `--queue X` or `-q X` to play X number of series before stopping. +Plays a league with a given name, provided that league has been saved on the website. The games per hour sets how often the games will start. (e.g. GPH 2 will start games at X:00 and X:30)""" async def execute(self, msg, command): - league_name = command.split("-")[0].strip() + league_name = command.split("-")[0].split("\n")[0].strip() autoplay = None - try: + + try: if "--queue " in command: - autoplay = int(command.split("--queue ")[1]) + autoplay = int(command.split("--queue ")[1].split("\n")[0]) elif "-q " in command: - autoplay = int(command.split("-q ")[1]) + autoplay = int(command.split("-q ")[1].split("\n")[0]) if autoplay is not None and autoplay <= 0: raise ValueError elif autoplay is None: autoplay = -1 - except: + command = command.split("\n")[1] + except ValueError: await msg.channel.send("Sorry boss, the queue flag needs a natural number. Any whole number over 0 will do just fine.") return + except IndexError: + await msg.channel.send("We need a games per hour number in the second line.") + return + + try: + gph = int(command.strip()) + if gph < 1 or gph > 12: + raise ValueError + except ValueError: + await msg.channel.send("Chief, we need a games per hour number between 1 and 12. We think that's reasonable.") + return if league_exists(league_name): league = leagues.load_league_file(league_name) @@ -784,10 +802,50 @@ Plays a league with a given name, provided that league has been saved on the web if active_league.name == league.name: await msg.channel.send("That league is already running, boss. Patience is a virtue, you know.") return - await start_league_day(msg.channel, league, autoplay = autoplay) + league.autoplay = autoplay + league.games_per_hour = gph + await start_league_day(msg.channel, league) else: await msg.channel.send("Couldn't find that league, boss. Did you save it on the website?") +class LeagueDisplayCommand(Command): + name = "leaguestandings" + template = "m;leaguestandings [league name]" + description = "Displays the current standings for the given league." + + async def execute(self, msg, command): + if league_exists(command.strip()): + league = leagues.load_league_file(command.strip()) + await msg.channel.send(embed=league.standings_embed()) + else: + await msg.channel.send("Can't find that league, boss.") + +class LeagueWildcardCommand(Command): + name = "leaguewildcard" + template = "m;leaguewildcard [league name]" + description = "Displays the current wildcard race for the given league, if the league has wildcard slots." + + async def execute(self, msg, command): + if league_exists(command.strip()): + league = leagues.load_league_file(command.strip()) + if league.constraints["wild_cards"] > 0: + await msg.channel.send(embed=league.wildcard_embed()) + else: + await msg.channel.send("That league doesn't have wildcards, boss.") + else: + await msg.channel.send("Can't find that league, boss.") + +class LeaguePauseCommand(Command): + name = "pauseleague" + template = "m;pauseleague [league name]" + descripton = "Tells a currently running league to stop running automatically after the current series." + + async def execute(self, msg, command): + league_name = command.strip() + for active_league in active_leagues: + if active_league.name == league_name: + active_league.autoplay = 0 + await msg.channel.send(f"Loud and clear, chief. {league_name} will stop after this series is over.") commands = [ IntroduceCommand(), CountActiveGamesCommand(), @@ -809,6 +867,9 @@ commands = [ StartGameCommand(), StartTournamentCommand(), StartLeagueCommand(), + LeaguePauseCommand(), + LeagueDisplayCommand(), + LeagueWildcardCommand(), StartRandomGameCommand(), CreditCommand(), RomanCommand(), @@ -1152,7 +1213,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals try: for i in range(0, len(games_list)): game, key = games_list[i] - if game.over and main_controller.master_games_dic[key][1]["end_delay"] <= 8: + if game.over and ((key in main_controller.master_games_dic.keys() and main_controller.master_games_dic[key][1]["end_delay"] <= 8) or not key in main_controller.master_games_dic.keys()): if game.teams['home'].name not in wins_in_series.keys(): wins_in_series[game.teams["home"].name] = 0 if game.teams['away'].name not in wins_in_series.keys(): @@ -1406,7 +1467,7 @@ async def game_watcher(): this_array = gamesarray.copy() for i in range(0,len(this_array)): game, channel, user, key = this_array[i] - if game.over and main_controller.master_games_dic[key][1]["end_delay"] <= 8: + if game.over and ((key in main_controller.master_games_dic.keys() and main_controller.master_games_dic[key][1]["end_delay"] <= 8) or not key in main_controller.master_games_dic.keys()): final_embed = game_over_embed(game) if isinstance(user, str): await channel.send(f"A game started by {user} just ended.") @@ -1452,7 +1513,7 @@ def get_team_fuzzy_search(team_name): team = teams[0] return team -async def start_league_day(channel, league, autoplay = 1): +async def start_league_day(channel, league): current_games = [] games_to_start = league.schedule[str(league.day_to_series_num(league.day))] @@ -1490,12 +1551,12 @@ async def start_league_day(channel, league, autoplay = 1): await channel.send(f"The day {league.day} series of the {league.name} is starting now, at {config()['simmadome_url']+ext}") last = False - await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, autoplay, last) + await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, last) -async def league_day_watcher(channel, league, games_list, filter_url, autoplay, last = False): +async def league_day_watcher(channel, league, games_list, filter_url, last = False): league.active = True - autoplay -= 1 + league.autoplay -= 1 if league not in active_leagues: active_leagues.append(league) series_results = {} @@ -1503,49 +1564,50 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, while league.active: queued_games = [] while len(games_list) > 0: - #try: - for i in range(0, len(games_list)): - game, key = games_list[i] - if game.over and main_controller.master_games_dic[key][1]["end_delay"] <= 8: - if game.teams['home'].name not in series_results.keys(): - series_results[game.teams["home"].name] = {} - series_results[game.teams["home"].name]["wins"] = 0 - series_results[game.teams["home"].name]["losses"] = 0 - series_results[game.teams["home"].name]["run_diff"] = 0 - if game.teams['away'].name not in series_results.keys(): - series_results[game.teams["away"].name] = {} - series_results[game.teams["away"].name]["wins"] = 0 - series_results[game.teams["away"].name]["losses"] = 0 - series_results[game.teams["away"].name]["run_diff"] = 0 + try: + for i in range(0, len(games_list)): + game, key = games_list[i] + if game.over and ((key in main_controller.master_games_dic.keys() and main_controller.master_games_dic[key][1]["end_delay"] <= 8) or not key in main_controller.master_games_dic.keys()): + if game.teams['home'].name not in series_results.keys(): + series_results[game.teams["home"].name] = {} + series_results[game.teams["home"].name]["wins"] = 0 + series_results[game.teams["home"].name]["losses"] = 0 + series_results[game.teams["home"].name]["run_diff"] = 0 + if game.teams['away'].name not in series_results.keys(): + series_results[game.teams["away"].name] = {} + series_results[game.teams["away"].name]["wins"] = 0 + series_results[game.teams["away"].name]["losses"] = 0 + series_results[game.teams["away"].name]["run_diff"] = 0 - winner_name = game.teams['home'].name if game.teams['home'].score > game.teams['away'].score else game.teams['away'].name - loser_name = game.teams['away'].name if game.teams['home'].score > game.teams['away'].score else game.teams['home'].name - rd = int(math.fabs(game.teams['home'].score - game.teams['away'].score)) + winner_name = game.teams['home'].name if game.teams['home'].score > game.teams['away'].score else game.teams['away'].name + loser_name = game.teams['away'].name if game.teams['home'].score > game.teams['away'].score else game.teams['home'].name + rd = int(math.fabs(game.teams['home'].score - game.teams['away'].score)) - series_results[winner_name]["wins"] += 1 - series_results[winner_name]["run_diff"] += rd + series_results[winner_name]["wins"] += 1 + series_results[winner_name]["run_diff"] += rd - winner_dic = {"wins" : 1, "run_diff" : rd} + winner_dic = {"wins" : 1, "run_diff" : rd} - series_results[loser_name]["losses"] += 1 - series_results[loser_name]["run_diff"] -= rd + series_results[loser_name]["losses"] += 1 + series_results[loser_name]["run_diff"] -= rd - loser_dic = {"losses" : 1, "run_diff" : -rd} + loser_dic = {"losses" : 1, "run_diff" : -rd} - league.add_stats_from_game(game.get_team_specific_stats()) - league.update_standings({winner_name : winner_dic, loser_name : loser_dic}) - leagues.save_league(league) - final_embed = game_over_embed(game) - final_embed.add_field(name="Series score:", value=f"{series_results[game.teams['away'].name]['wins']} - {series_results[game.teams['home'].name]['wins']}") - await channel.send(f"A {league.name} game just ended!") - await channel.send(embed=final_embed) - if series_results[winner_name]["wins"] + series_results[winner_name]["losses"] < league.series_length: - queued_games.append(game) - games_list.pop(i) - break - #except: - #print("something went wrong in league_day_watcher") - await asyncio.sleep(1) + league.add_stats_from_game(game.get_team_specific_stats()) + league.update_standings({winner_name : winner_dic, loser_name : loser_dic}) + leagues.save_league(league) + final_embed = game_over_embed(game) + final_embed.add_field(name="Day:", value=league.day) + final_embed.add_field(name="Series score:", value=f"{series_results[game.teams['away'].name]['wins']} - {series_results[game.teams['home'].name]['wins']}") + await channel.send(f"A {league.name} game just ended!") + await channel.send(embed=final_embed) + if series_results[winner_name]["wins"] + series_results[winner_name]["losses"] < league.series_length: + queued_games.append(game) + games_list.pop(i) + break + except: + print("something went wrong in league_day_watcher") + await asyncio.sleep(2) league.day += 1 if len(queued_games) > 0: @@ -1555,8 +1617,16 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] for i in range(0, len(validminutes)): if now.minute > validminutes[i]: - if i <= len(validminutes)-2: - delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) else: delta = datetime.timedelta(minutes= (60 - now.minute)) @@ -1576,7 +1646,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, - if last or autoplay == 0: #if this series was the last of the season OR number of series to autoplay has been reached + if last or league.autoplay == 0: #if this series was the last of the season OR number of series to autoplay has been reached await channel.send(embed=league.standings_embed()) await channel.send(f"The {league.name} is no longer autoplaying.") leagues.save_league(league) @@ -1588,8 +1658,16 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] for i in range(0, len(validminutes)): if now.minute > validminutes[i]: - if i < len(validminutes)-2: - delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) else: delta = datetime.timedelta(minutes= (60 - now.minute)) @@ -1601,7 +1679,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, autoplay, await channel.send(f"""This {league.name} series is now complete! The next series will be starting in {int(wait_seconds/60)} minutes.""") await asyncio.sleep(wait_seconds) - await start_league_day(channel, league, autoplay) + await start_league_day(channel, league) async def continue_league_series(league, queue, games_list, series_results): for oldgame in queue: From 19072f21113fbee7b348d493355582213b90b62b Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 02:12:30 -0500 Subject: [PATCH 13/44] implemented tiebreakers and postseason tournament --- leagues.py | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ the_prestige.py | 34 +++++++++++++++++++++++--- 2 files changed, 96 insertions(+), 3 deletions(-) diff --git a/leagues.py b/leagues.py index 9356d45..14c0cdf 100644 --- a/leagues.py +++ b/leagues.py @@ -44,6 +44,41 @@ class league_structure(object): 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 = {} + division_leaders = [] + subleague_array = [] + wildcard_leaders = [] + for division in iter(self.league[subleague].keys()): + division_standings += self.division_standings(self.league[subleague][division], standings) + for division_team in division_standings: + if division_team.name != division_standings[self.constraints["division_leaders"]-1].name and standings[division_team.name]["wins"] == standings[division_standings[self.constraints["division_leaders"]-1].name]["wins"]: + matchups.append((division_team, division_standings[self.constraints["division_leaders"]-1]), 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) + for wildcard_team in wildcard_standings: + if wildcard_team.name != wildcard_standings[self.constraints["wild_cards"]-1].name and standings[wildcard_team.name]["wins"] == standings[wildcard_standings[self.constraints["wild_cards"]-1].name]["wins"]: + matchups.append((wildcard_team, wildcard_standings[self.constraints["wild_cards"]-1]), f"{subleague} Wildcard Tiebreaker") + + for this_team, wins, losses, diff, gb in divison_leaders + wildcard_leaders: + team_dic[this_team] = {"wins" : wins} + + for team_a, team_b, type in matchups: + tourney = tournament(f"{league.name} {type}",{team_a : {"wins" : 1}, team_b : {"wins" : 0}}, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour)) + tourney.build_bracket(by_wins = True) + 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()): @@ -256,6 +291,35 @@ class league_structure(object): 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 divison_leaders + wildcard_leaders: + team_dic[this_team] = {"wins" : wins} + + subleague_tournament = tournament(f"{self.name} {subleague} Championship Series", team_dic, 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) + 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 @@ -270,6 +334,7 @@ class tournament(object): self.round_delay = secs_between_rounds self.finals = False self.id = id + self.winner = None if id is None: self.id = random.randint(1111,9999) diff --git a/the_prestige.py b/the_prestige.py index 21cc57b..73d3170 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1255,6 +1255,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals if finals: #if this last round was finals embed = discord.Embed(color = discord.Color.dark_purple(), title = f"{winner_list[0]} win the {tourney.name} finals!") await channel.send(embed=embed) + tourney.winner = get_team_fuzzy_search(winner_list[0]) active_tournaments.pop(active_tournaments.index(tourney)) return @@ -1644,15 +1645,44 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal league.active = False + if last: #if last game of the season + embed = league.standings_embed() + embed.set_footer(text="Final Standings") + await channel.send(embed=embed) + + + tiebreakers = league.tiebreaker_required() + if tiebreakers != []: + await channel.send("Tiebreakers required!") + await asyncio.gather(*[start_tournament_round(tourney) for tourney in tiebreakers]) + for tourney in tiebreakers: + league.update_standings({tourney.winner.name : {"wins" : 1}}) + leagues.save_league(league) + + await channel.send("Setting up postseason...") + tourneys = league.champ_series() + await asyncio.gather(*[start_tournament_round(tourney) for tourney in tourneys]) + champs = {} + for tourney in tourneys: + for team in tourney.teams.keys(): + if team.name == tourney.winner.name: + champs[tourney.winner] = {"wins" : tourney.teams[team]["wins"]} + world_series = leagues.tournament(f"{league.name} Championship Series", champs, series_length=7, secs_between_games=int(3600/league.games_per_hour), secs_between_rounds=int(7200/league.games_per_hour)) + world_series.build_bracket(by_wins = True) + await start_tournament_round(channel, world_series) + return - if last or league.autoplay == 0: #if this series was the last of the season OR number of series to autoplay has been reached + + if league.autoplay == 0: #if number of series to autoplay has been reached await channel.send(embed=league.standings_embed()) await channel.send(f"The {league.name} is no longer autoplaying.") leagues.save_league(league) active_leagues.pop(active_leagues.index(league)) return + + now = datetime.datetime.now() validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] @@ -1704,6 +1734,4 @@ async def continue_league_series(league, queue, games_list, series_results): - - client.run(config()["token"]) From 8d6f6ab33a0b68680e99a065047a8e9923ae7fdc Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 02:23:44 -0500 Subject: [PATCH 14/44] direct start to postseason, partial series support --- the_prestige.py | 79 ++++++++++++++++++++++++++++++------------------- 1 file changed, 48 insertions(+), 31 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index 73d3170..bd98b32 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -804,7 +804,12 @@ Plays a league with a given name, provided that league has been saved on the web return league.autoplay = autoplay league.games_per_hour = gph - await start_league_day(msg.channel, league) + if str(league.day_to_series_num(league.day)) not in league.schedule.keys(): + await league_postseason(msg.channel, league) + elif league.day % league.series_length == 1: + await start_league_day(msg.channel, league) + else: + else: await msg.channel.send("Couldn't find that league, boss. Did you save it on the website?") @@ -1514,7 +1519,7 @@ def get_team_fuzzy_search(team_name): team = teams[0] return team -async def start_league_day(channel, league): +async def start_league_day(channel, league, partial = False): current_games = [] games_to_start = league.schedule[str(league.day_to_series_num(league.day))] @@ -1534,8 +1539,11 @@ async def start_league_day(channel, league): this_game, state_init = prepare_game(this_game) state_init["is_league"] = True - series_string = f"Series score:" - state_init["title"] = f"{series_string} 0 - 0" + if not partial: + series_string = "Series score:" + state_init["title"] = f"{series_string} 0 - 0" + else: + state_init["title"] = "Interrupted series!" discrim_string = league.name id = str(uuid4()) @@ -1545,17 +1553,21 @@ async def start_league_day(channel, league): ext = "?league=" + urllib.parse.quote_plus(league.name) if league.last_series_check(): #if finals - await channel.send(f"The final series of the {league.name} is starting now, at {config()['simmadome_url']+ext}") + await channel.send(f"The final series of the {league.name} regular season is starting now, at {config()['simmadome_url']+ext}") last = True else: await channel.send(f"The day {league.day} series of the {league.name} is starting now, at {config()['simmadome_url']+ext}") last = False - await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, last) + if partial: + missed_games = (league.day % league.series_length) - 2 + await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, last, missed = missed_games) + else: + await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, last) -async def league_day_watcher(channel, league, games_list, filter_url, last = False): +async def league_day_watcher(channel, league, games_list, filter_url, last = False, missed = 0): league.active = True league.autoplay -= 1 if league not in active_leagues: @@ -1602,7 +1614,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal final_embed.add_field(name="Series score:", value=f"{series_results[game.teams['away'].name]['wins']} - {series_results[game.teams['home'].name]['wins']}") await channel.send(f"A {league.name} game just ended!") await channel.send(embed=final_embed) - if series_results[winner_name]["wins"] + series_results[winner_name]["losses"] < league.series_length: + if series_results[winner_name]["wins"] + series_results[winner_name]["losses"] + missed < league.series_length: queued_games.append(game) games_list.pop(i) break @@ -1646,30 +1658,10 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal if last: #if last game of the season - embed = league.standings_embed() - embed.set_footer(text="Final Standings") - await channel.send(embed=embed) - + await league_postseason(channel, league) + + #need to reset league to new season here - tiebreakers = league.tiebreaker_required() - if tiebreakers != []: - await channel.send("Tiebreakers required!") - await asyncio.gather(*[start_tournament_round(tourney) for tourney in tiebreakers]) - for tourney in tiebreakers: - league.update_standings({tourney.winner.name : {"wins" : 1}}) - leagues.save_league(league) - - await channel.send("Setting up postseason...") - tourneys = league.champ_series() - await asyncio.gather(*[start_tournament_round(tourney) for tourney in tourneys]) - champs = {} - for tourney in tourneys: - for team in tourney.teams.keys(): - if team.name == tourney.winner.name: - champs[tourney.winner] = {"wins" : tourney.teams[team]["wins"]} - world_series = leagues.tournament(f"{league.name} Championship Series", champs, series_length=7, secs_between_games=int(3600/league.games_per_hour), secs_between_rounds=int(7200/league.games_per_hour)) - world_series.build_bracket(by_wins = True) - await start_tournament_round(channel, world_series) return @@ -1731,6 +1723,31 @@ async def continue_league_series(league, queue, games_list, series_results): return games_list +async def league_postseason(channel, league): + embed = league.standings_embed() + embed.set_footer(text="Final Standings") + await channel.send(embed=embed) + + + tiebreakers = league.tiebreaker_required() + if tiebreakers != []: + await channel.send("Tiebreakers required!") + await asyncio.gather(*[start_tournament_round(tourney) for tourney in tiebreakers]) + for tourney in tiebreakers: + league.update_standings({tourney.winner.name : {"wins" : 1}}) + leagues.save_league(league) + + await channel.send("Setting up postseason...") + tourneys = league.champ_series() + await asyncio.gather(*[start_tournament_round(tourney) for tourney in tourneys]) + champs = {} + for tourney in tourneys: + for team in tourney.teams.keys(): + if team.name == tourney.winner.name: + champs[tourney.winner] = {"wins" : tourney.teams[team]["wins"]} + world_series = leagues.tournament(f"{league.name} Championship Series", champs, series_length=7, secs_between_games=int(3600/league.games_per_hour), secs_between_rounds=int(7200/league.games_per_hour)) + world_series.build_bracket(by_wins = True) + await start_tournament_round(channel, world_series) From e77e406470b8436f87ae238c1670b29c389d32c3 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 03:18:41 -0500 Subject: [PATCH 15/44] adjusted tournaments to work on the same schedule system as leagues --- leagues.py | 28 ++++++----- the_prestige.py | 125 ++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 131 insertions(+), 22 deletions(-) diff --git a/leagues.py b/leagues.py index 14c0cdf..02761d5 100644 --- a/leagues.py +++ b/leagues.py @@ -52,30 +52,30 @@ class league_structure(object): standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff} for subleague in iter(self.league.keys()): - team_dic = {} - division_leaders = [] + 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) - for division_team in division_standings: - if division_team.name != division_standings[self.constraints["division_leaders"]-1].name and standings[division_team.name]["wins"] == standings[division_standings[self.constraints["division_leaders"]-1].name]["wins"]: - matchups.append((division_team, division_standings[self.constraints["division_leaders"]-1]), f"{division} Tiebreaker") + 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) - for wildcard_team in wildcard_standings: - if wildcard_team.name != wildcard_standings[self.constraints["wild_cards"]-1].name and standings[wildcard_team.name]["wins"] == standings[wildcard_standings[self.constraints["wild_cards"]-1].name]["wins"]: - matchups.append((wildcard_team, wildcard_standings[self.constraints["wild_cards"]-1]), f"{subleague} Wildcard Tiebreaker") - - for this_team, wins, losses, diff, gb in divison_leaders + wildcard_leaders: - team_dic[this_team] = {"wins" : wins} + 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"{league.name} {type}",{team_a : {"wins" : 1}, team_b : {"wins" : 0}}, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour)) + 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 @@ -310,11 +310,12 @@ class league_structure(object): 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 divison_leaders + wildcard_leaders: + 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} Championship Series", team_dic, 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 @@ -334,6 +335,7 @@ class tournament(object): self.round_delay = secs_between_rounds self.finals = False self.id = id + self.league = None self.winner = None if id is None: diff --git a/the_prestige.py b/the_prestige.py index bd98b32..01950de 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -809,7 +809,7 @@ Plays a league with a given name, provided that league has been saved on the web elif league.day % league.series_length == 1: await start_league_day(msg.channel, league) else: - + await start_league_day(msg.channel, league, partial = True) else: await msg.channel.send("Couldn't find that league, boss. Did you save it on the website?") @@ -1156,7 +1156,15 @@ async def start_tournament_round(channel, tourney, seeding = None): for pair in games_to_start: if pair[0] is not None and pair[1] is not None: - this_game = games.game(pair[0].prepare_for_save().finalize(), pair[1].prepare_for_save().finalize(), length = tourney.game_length) + team_a = get_team_fuzzy_search(pair[0].name) + team_b = get_team_fuzzy_search(pair[1].name) + + if tourney.league is not None: + team_a.set_pitcher(rotation_slot = tourney.league.day) + team_b.set_pitcher(rotation_slot = tourney.league.day) + league.day += 1 + + this_game = games.game(team_a.finalize(), team_b.finalize(), length = tourney.game_length) this_game, state_init = prepare_game(this_game) state_init["is_league"] = True @@ -1187,6 +1195,12 @@ async def continue_tournament_series(tourney, queue, games_list, wins_in_series) for oldgame in queue: away_team = games.get_team(oldgame.teams["away"].name) home_team = games.get_team(oldgame.teams["home"].name) + + if tourney.league is not None: + away_team.set_pitcher(rotation_slot = tourney.league.day) + home_team.set_pitcher(rotation_slot = tourney.league.day) + league.day += 1 + this_game = games.game(away_team.finalize(), home_team.finalize(), length = tourney.game_length) this_game, state_init = prepare_game(this_game) @@ -1250,8 +1264,32 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals if len(queued_games) > 0: - await channel.send(f"The next batch of games for {tourney.name} will start in {int(tourney.delay/60)} minutes.") - await asyncio.sleep(tourney.delay) + + if tourney.league is not None: + now = datetime.datetime.now() + validminutes = [int((60 * div)/tourney.league.games_per_hour) for div in range(0,tourney.league.games_per_hour)] + for i in range(0, len(validminutes)): + if now.minute > validminutes[i]: + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + else: + delta = datetime.timedelta(minutes= (60 - now.minute)) + + next_start = (now + delta).replace(microsecond=0) + wait_seconds = (next_start - now).seconds + await channel.send(f"The next batch of games for {tourney.name} will start in {math.ceil(wait_seconds/60)} minutes.") + await asyncio.sleep(wait_seconds) + else: + await channel.send(f"The next batch of games for {tourney.name} will start in {int(tourney.delay/60)} minutes.") + await asyncio.sleep(tourney.delay) await channel.send(f"{len(queued_games)} games for {tourney.name}, starting at {filter_url}") games_list = await continue_tournament_series(tourney, queued_games, games_list, wins_in_series) else: @@ -1269,11 +1307,37 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals winners_string = "" for game in tourney.bracket.get_bottom_row(): winners_string += f"{game[0].name}\n{game[1].name}\n" - await channel.send(f""" + + if tourney.league is not None: + now = datetime.datetime.now() + validminutes = [int((60 * div)/tourney.league.games_per_hour) for div in range(0,tourney.league.games_per_hour)] + for i in range(0, len(validminutes)): + if now.minute > validminutes[i]: + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + else: + delta = datetime.timedelta(minutes= (60 - now.minute)) + + next_start = (now + delta).replace(microsecond=0) + wait_seconds = (next_start - now).seconds + await channel.send(f"""This round of games for {tourney.name} is now complete! The next round will start in {math.ceil(wait_seconds/60)} minutes. +Advancing teams: +{winners_string}""") + await asyncio.sleep(wait_seconds) + else: + await channel.send(f""" This round of games for {tourney.name} is now complete! The next round will be starting in {int(tourney.round_delay/60)} minutes. Advancing teams: {winners_string}""") - await asyncio.sleep(tourney.round_delay) + await asyncio.sleep(tourney.round_delay) await start_tournament_round(channel, tourney) @@ -1658,6 +1722,27 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal if last: #if last game of the season + now = datetime.datetime.now() + validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] + for i in range(0, len(validminutes)): + if now.minute > validminutes[i]: + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + else: + delta = datetime.timedelta(minutes= (60 - now.minute)) + + next_start = (now + delta).replace(microsecond=0) + wait_seconds = (next_start - now).seconds + await channel.send(f"This {league.name} season is now over! The postseason (with any necessary tiebreakers) will be starting in {math.ceil(wait_seconds/60)} minutes.") + await asyncio.sleep(wait_seconds) await league_postseason(channel, league) #need to reset league to new season here @@ -1732,14 +1817,36 @@ async def league_postseason(channel, league): tiebreakers = league.tiebreaker_required() if tiebreakers != []: await channel.send("Tiebreakers required!") - await asyncio.gather(*[start_tournament_round(tourney) for tourney in tiebreakers]) + await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tiebreakers]) for tourney in tiebreakers: league.update_standings({tourney.winner.name : {"wins" : 1}}) leagues.save_league(league) + now = datetime.datetime.now() + + validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] + for i in range(0, len(validminutes)): + if now.minute > validminutes[i]: + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + else: + delta = datetime.timedelta(minutes= (60 - now.minute)) + + next_start = (now + delta).replace(microsecond=0) + wait_seconds = (next_start - now).seconds + await channel.send(f"Tiebreakers complete! Postseason starting in {math.ceil(wait_seconds/60)} minutes.") + await asyncio.sleep(wait_seconds) - await channel.send("Setting up postseason...") + tourneys = league.champ_series() - await asyncio.gather(*[start_tournament_round(tourney) for tourney in tourneys]) + await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tourneys]) champs = {} for tourney in tourneys: for team in tourney.teams.keys(): From 5eec52db627b9b092de3bccce46cf3f22d3259fa Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 03:22:26 -0500 Subject: [PATCH 16/44] made tournaments use rotations when leagues are assigned --- the_prestige.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/the_prestige.py b/the_prestige.py index 01950de..10ac6a2 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1854,6 +1854,29 @@ async def league_postseason(channel, league): champs[tourney.winner] = {"wins" : tourney.teams[team]["wins"]} world_series = leagues.tournament(f"{league.name} Championship Series", champs, series_length=7, secs_between_games=int(3600/league.games_per_hour), secs_between_rounds=int(7200/league.games_per_hour)) world_series.build_bracket(by_wins = True) + world_series.league = league + now = datetime.datetime.now() + + validminutes = [int((60 * div)/league.games_per_hour) for div in range(0,league.games_per_hour)] + for i in range(0, len(validminutes)): + if now.minute > validminutes[i]: + if i <= len(validminutes)-3: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (validminutes[i+2] - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + elif i <= len(validminutes)-2: + if validminutes[i+1] == now.minute: + delta = datetime.timedelta(minutes= (60 - now.minute)) + else: + delta = datetime.timedelta(minutes= (validminutes[i+1] - now.minute)) + else: + delta = datetime.timedelta(minutes= (60 - now.minute)) + + next_start = (now + delta).replace(microsecond=0) + wait_seconds = (next_start - now).seconds + await channel.send(f"The {league.name} Championship Series is starting in {math.ceil(wait_seconds/60)} minutes!") + await asyncio.sleep(wait_seconds) await start_tournament_round(channel, world_series) From af7112367db59f039e92cc5745d560fb694668e7 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 04:27:20 -0500 Subject: [PATCH 17/44] added m;leagueschedule --- leagues.py | 24 ++++++++++++++---------- the_prestige.py | 42 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/leagues.py b/leagues.py index 02761d5..20d38f2 100644 --- a/leagues.py +++ b/leagues.py @@ -233,6 +233,8 @@ class league_structure(object): teams.sort(key=sorter, reverse=True) return teams + def season_length(self): + return self.constraints["division_games"]*(len(random.choice(random.choice(league))-1)) + self.constraints["inter_div_games"] + self.constraints["inter_league_games"] def standings_embed(self): this_embed = Embed(color=Color.purple(), title=self.name) @@ -242,7 +244,6 @@ class league_structure(object): 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()): - this_embed.add_field(name="Division:", value=f"**{division}**", inline = False) teams = self.division_standings(self.league[subleague][division], standings) for index in range(0, len(teams)): @@ -251,14 +252,16 @@ class league_structure(object): 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: - this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}", inline = False) + 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: - this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}", inline = False) + teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n" - this_embed.set_footer(text=f"Standings as of day {self.day-1}") + 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): @@ -267,14 +270,13 @@ class league_structure(object): 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) 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] = "-" @@ -284,9 +286,11 @@ class league_structure(object): for this_team in teams: if this_team[2] != 0 or this_team[1] != 0: - this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}", inline = False) + 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: - this_embed.add_field(name=this_team[0].name, value=f"{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}", inline = False) + 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 @@ -313,7 +317,7 @@ class league_structure(object): 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} Championship Series", team_dic, secs_between_games=int(3600/self.games_per_hour), secs_between_rounds=int(7200/self.games_per_hour)) + subleague_tournament = tournament(f"{self.name} {subleague} Championship 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) diff --git a/the_prestige.py b/the_prestige.py index 10ac6a2..4ae551a 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -764,6 +764,10 @@ class StartLeagueCommand(Command): Plays a league with a given name, provided that league has been saved on the website. The games per hour sets how often the games will start. (e.g. GPH 2 will start games at X:00 and X:30)""" async def execute(self, msg, command): + if config()["game_freeze"]: + await msg.channel.send("Patch incoming. We're not allowing new games right now.") + return + league_name = command.split("-")[0].split("\n")[0].strip() autoplay = None @@ -851,6 +855,33 @@ class LeaguePauseCommand(Command): if active_league.name == league_name: active_league.autoplay = 0 await msg.channel.send(f"Loud and clear, chief. {league_name} will stop after this series is over.") + +class LeagueScheduleCommand(Command): + name = "leagueschedule" + template = "m;leagueschedule [league name]" + description = "Sends an embed with the given league's schedule for the next 4 series." + + async def execute(self, msg, command): + league_name = command.strip() + if league_exists(league_name): + league = leagues.load_league_file(league_name) + current_series = league.day_to_series_num(league.day) + if str(current_series+1) in league.schedule.keys(): + sched_embed = discord.Embed(title=f"{league.name}'s Schedule:") + days = [0,1,2,3] + for day in days: + if str(current_series+day) in league.schedule.keys(): + schedule_text = "" + for game in league.schedule[str(current_series+day)]: + schedule_text += f"**{game[0]}** @ **{game[1]}**\n" + sched_embed.add_field(name=f"Days {((current_series+day-1)*league.series_length) + 1} - {(current_series+day)*(league.series_length)}", value=schedule_text, inline = False) + await msg.channel.send(embed=sched_embed) + else: + await msg.channel.send("That league's already finished with this season, boss.") + else: + await msg.channel.send("We can't find that league. Typo?") + + commands = [ IntroduceCommand(), CountActiveGamesCommand(), @@ -875,6 +906,7 @@ commands = [ LeaguePauseCommand(), LeagueDisplayCommand(), LeagueWildcardCommand(), + LeagueScheduleCommand(), StartRandomGameCommand(), CreditCommand(), RomanCommand(), @@ -1162,7 +1194,6 @@ async def start_tournament_round(channel, tourney, seeding = None): if tourney.league is not None: team_a.set_pitcher(rotation_slot = tourney.league.day) team_b.set_pitcher(rotation_slot = tourney.league.day) - league.day += 1 this_game = games.game(team_a.finalize(), team_b.finalize(), length = tourney.game_length) this_game, state_init = prepare_game(this_game) @@ -1199,7 +1230,7 @@ async def continue_tournament_series(tourney, queue, games_list, wins_in_series) if tourney.league is not None: away_team.set_pitcher(rotation_slot = tourney.league.day) home_team.set_pitcher(rotation_slot = tourney.league.day) - league.day += 1 + this_game = games.game(away_team.finalize(), home_team.finalize(), length = tourney.game_length) this_game, state_init = prepare_game(this_game) @@ -1261,7 +1292,8 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals except: print("something went wrong in tourney_watcher") await asyncio.sleep(4) - + if tourney.league is not None: + tourney.league.day += 1 if len(queued_games) > 0: @@ -1751,9 +1783,11 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal - if league.autoplay == 0: #if number of series to autoplay has been reached + if league.autoplay == 0 or config()["game_freeze"]: #if number of series to autoplay has been reached await channel.send(embed=league.standings_embed()) await channel.send(f"The {league.name} is no longer autoplaying.") + if config()["game_freeze"]: + await channel.send("Patch incoming.") leagues.save_league(league) active_leagues.pop(active_leagues.index(league)) return From fc07efa7efdb0f2f3054d6ca564098fc65a5f9be Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 04:31:31 -0500 Subject: [PATCH 18/44] tidyed up wait times for tournament games --- the_prestige.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index 4ae551a..b6967b2 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1315,7 +1315,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals else: delta = datetime.timedelta(minutes= (60 - now.minute)) - next_start = (now + delta).replace(microsecond=0) + next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds await channel.send(f"The next batch of games for {tourney.name} will start in {math.ceil(wait_seconds/60)} minutes.") await asyncio.sleep(wait_seconds) @@ -1358,7 +1358,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals else: delta = datetime.timedelta(minutes= (60 - now.minute)) - next_start = (now + delta).replace(microsecond=0) + next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds await channel.send(f"""This round of games for {tourney.name} is now complete! The next round will start in {math.ceil(wait_seconds/60)} minutes. Advancing teams: @@ -1771,7 +1771,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal else: delta = datetime.timedelta(minutes= (60 - now.minute)) - next_start = (now + delta).replace(microsecond=0) + next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds await channel.send(f"This {league.name} season is now over! The postseason (with any necessary tiebreakers) will be starting in {math.ceil(wait_seconds/60)} minutes.") await asyncio.sleep(wait_seconds) @@ -1812,7 +1812,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal else: delta = datetime.timedelta(minutes= (60 - now.minute)) - next_start = (now + delta).replace(microsecond=0) + next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds leagues.save_league(league) @@ -1873,7 +1873,7 @@ async def league_postseason(channel, league): else: delta = datetime.timedelta(minutes= (60 - now.minute)) - next_start = (now + delta).replace(microsecond=0) + next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds await channel.send(f"Tiebreakers complete! Postseason starting in {math.ceil(wait_seconds/60)} minutes.") await asyncio.sleep(wait_seconds) @@ -1907,7 +1907,7 @@ async def league_postseason(channel, league): else: delta = datetime.timedelta(minutes= (60 - now.minute)) - next_start = (now + delta).replace(microsecond=0) + next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds await channel.send(f"The {league.name} Championship Series is starting in {math.ceil(wait_seconds/60)} minutes!") await asyncio.sleep(wait_seconds) From 016bc2ed24f701b424c1b3773fb94c3856b417f8 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:09:23 -0500 Subject: [PATCH 19/44] set only one tournament to increment league day --- leagues.py | 2 ++ the_prestige.py | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/leagues.py b/leagues.py index 20d38f2..298b8ab 100644 --- a/leagues.py +++ b/leagues.py @@ -322,6 +322,7 @@ class league_structure(object): subleague_tournament.league = self tournaments.append(subleague_tournament) + tournaments[0].increment = True return tournaments @@ -341,6 +342,7 @@ class tournament(object): self.id = id self.league = None self.winner = None + self.increment = False if id is None: self.id = random.randint(1111,9999) diff --git a/the_prestige.py b/the_prestige.py index b6967b2..10a3b67 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1292,7 +1292,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals except: print("something went wrong in tourney_watcher") await asyncio.sleep(4) - if tourney.league is not None: + if tourney.league is not None and tourney.league.increment: tourney.league.day += 1 if len(queued_games) > 0: @@ -1851,6 +1851,7 @@ async def league_postseason(channel, league): tiebreakers = league.tiebreaker_required() if tiebreakers != []: await channel.send("Tiebreakers required!") + tiebreakers[0].increment = True await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tiebreakers]) for tourney in tiebreakers: league.update_standings({tourney.winner.name : {"wins" : 1}}) @@ -1880,6 +1881,7 @@ async def league_postseason(channel, league): tourneys = league.champ_series() + tourneys[0].increment = true await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tourneys]) champs = {} for tourney in tourneys: From 3d2df59ca14773f2af0343cee45f751f282b0876 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:12:55 -0500 Subject: [PATCH 20/44] started recording season champions --- league_storage.py | 1 + leagues.py | 5 +++++ the_prestige.py | 1 + 3 files changed, 7 insertions(+) diff --git a/league_storage.py b/league_storage.py index ff1375f..b3edb4c 100644 --- a/league_storage.py +++ b/league_storage.py @@ -87,6 +87,7 @@ def save_league(league): "series_length" : league.series_length, "games_per_hour" : league.games_per_hour, "owner" : league.owner, + "champions" : league.champions, "historic" : league.historic } with open(os.path.join(data_dir, league_dir, league.name, f"{league.name}.state"), "w") as state_file: diff --git a/leagues.py b/leagues.py index 298b8ab..9a6d268 100644 --- a/leagues.py +++ b/leagues.py @@ -14,6 +14,7 @@ class league_structure(object): self.owner = None self.season = 1 self.autoplay = -1 + self.champions = {} 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] } } @@ -460,4 +461,8 @@ def load_league_file(league_name): 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.champions = state_dic["champions"] + except: + this_league.champions = {} return this_league \ No newline at end of file diff --git a/the_prestige.py b/the_prestige.py index 10a3b67..54286c2 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1914,6 +1914,7 @@ async def league_postseason(channel, league): await channel.send(f"The {league.name} Championship Series is starting in {math.ceil(wait_seconds/60)} minutes!") await asyncio.sleep(wait_seconds) await start_tournament_round(channel, world_series) + league.champions[str(league.season)] = world_series.winner.name From a1a45ca80546465f883d694883205ff50227ea29 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:34:17 -0500 Subject: [PATCH 21/44] fixed an f-string --- leagues.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/leagues.py b/leagues.py index 9a6d268..7caf630 100644 --- a/leagues.py +++ b/leagues.py @@ -262,7 +262,7 @@ class league_structure(object): 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()") + this_embed.set_footer(text=f"Standings as of day {self.day-1} / {self.season_length()}") return this_embed def wildcard_embed(self): From 9404ffd8fc0e06c00ed3adde9384f260fcc645e3 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:37:25 -0500 Subject: [PATCH 22/44] fixed season length --- leagues.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/leagues.py b/leagues.py index 7caf630..d30690c 100644 --- a/leagues.py +++ b/leagues.py @@ -235,7 +235,7 @@ class league_structure(object): return teams def season_length(self): - return self.constraints["division_games"]*(len(random.choice(random.choice(league))-1)) + self.constraints["inter_div_games"] + self.constraints["inter_league_games"] + return self.constraints["division_games"]*(len(random.choice(random.choice(self.league))-1)) + self.constraints["inter_div_games"] + self.constraints["inter_league_games"] def standings_embed(self): this_embed = Embed(color=Color.purple(), title=self.name) From 6c30ccb88afcd4eeaf2148828ca0ed5f0b4b25bd Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:44:59 -0500 Subject: [PATCH 23/44] fixed season length for real this time, started saving champs --- leagues.py | 4 ++-- the_prestige.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/leagues.py b/leagues.py index d30690c..307497e 100644 --- a/leagues.py +++ b/leagues.py @@ -235,8 +235,8 @@ class league_structure(object): return teams def season_length(self): - return self.constraints["division_games"]*(len(random.choice(random.choice(self.league))-1)) + self.constraints["inter_div_games"] + self.constraints["inter_league_games"] - + return int(list(self.schedule.keys())[-1]) * self.series_length + def standings_embed(self): this_embed = Embed(color=Color.purple(), title=self.name) standings = {} diff --git a/the_prestige.py b/the_prestige.py index 54286c2..50d64af 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1915,6 +1915,7 @@ async def league_postseason(channel, league): await asyncio.sleep(wait_seconds) await start_tournament_round(channel, world_series) league.champions[str(league.season)] = world_series.winner.name + leagues.save_league(league) From 92034c185ec23abd6ee6b68f32482146ad256c94 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:46:50 -0500 Subject: [PATCH 24/44] fixed incrementation --- the_prestige.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/the_prestige.py b/the_prestige.py index 50d64af..c778d3a 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1292,7 +1292,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals except: print("something went wrong in tourney_watcher") await asyncio.sleep(4) - if tourney.league is not None and tourney.league.increment: + if tourney.league is not None and tourney.increment: tourney.league.day += 1 if len(queued_games) > 0: From 363d58905ed9382952635b68669751f7368e6432 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 05:54:06 -0500 Subject: [PATCH 25/44] fixed titles on interrupted games --- the_prestige.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index c778d3a..e6560d9 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1748,7 +1748,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal leagues.save_league(league) await asyncio.sleep(wait_seconds) await channel.send(f"A {league.name} series is continuing now at {filter_url}") - games_list = await continue_league_series(league, queued_games, games_list, series_results) + games_list = await continue_league_series(league, queued_games, games_list, series_results, missed) else: league.active = False @@ -1822,7 +1822,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal await start_league_day(channel, league) -async def continue_league_series(league, queue, games_list, series_results): +async def continue_league_series(league, queue, games_list, series_results, missed): for oldgame in queue: away_team = games.get_team(oldgame.teams["away"].name) away_team.set_pitcher(rotation_slot=league.day) @@ -1833,7 +1833,12 @@ async def continue_league_series(league, queue, games_list, series_results): state_init["is_league"] = True series_string = f"Series score:" - state_init["title"] = f"{series_string} {series_results[away_team.name]['wins']} - {series_results[home_team.name]['wins']}" + + if missed <= 0: + series_string = "Series score:" + state_init["title"] = f"{series_string} {series_results[away_team.name]['wins']} - {series_results[home_team.name]['wins']}" + else: + state_init["title"] = "Interrupted series!" discrim_string = league.name id = str(uuid4()) @@ -1881,7 +1886,7 @@ async def league_postseason(channel, league): tourneys = league.champ_series() - tourneys[0].increment = true + tourneys[0].increment = True await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tourneys]) champs = {} for tourney in tourneys: From 26ddaf7e5ab121f9c9ac52f6654a08824894dfc2 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 06:00:51 -0500 Subject: [PATCH 26/44] adjusted some text in discord --- the_prestige.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index e6560d9..5c2adf4 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1317,7 +1317,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds - await channel.send(f"The next batch of games for {tourney.name} will start in {math.ceil(wait_seconds/60)} minutes.") + await channel.send(f"The next batch of games for the {tourney.name} will start in {math.ceil(wait_seconds/60)} minutes.") await asyncio.sleep(wait_seconds) else: await channel.send(f"The next batch of games for {tourney.name} will start in {int(tourney.delay/60)} minutes.") @@ -1360,7 +1360,7 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals next_start = (now + delta).replace(second=0, microsecond=0) wait_seconds = (next_start - now).seconds - await channel.send(f"""This round of games for {tourney.name} is now complete! The next round will start in {math.ceil(wait_seconds/60)} minutes. + await channel.send(f"""This round of games for the {tourney.name} is now complete! The next round will start in {math.ceil(wait_seconds/60)} minutes. Advancing teams: {winners_string}""") await asyncio.sleep(wait_seconds) From 80aaa086fbbc500c3660a8964395f1e54fd1af31 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 06:08:52 -0500 Subject: [PATCH 27/44] fixed threshold for missed games --- the_prestige.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/the_prestige.py b/the_prestige.py index 5c2adf4..1295815 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1657,7 +1657,7 @@ async def start_league_day(channel, league, partial = False): last = False if partial: - missed_games = (league.day % league.series_length) - 2 + missed_games = (league.day % league.series_length) - 1 await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, last, missed = missed_games) else: await league_day_watcher(channel, league, current_games, config()['simmadome_url']+ext, last) From 780ca4b3bfc4b4808d26eae64d60f2553f4386ae Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 06:18:29 -0500 Subject: [PATCH 28/44] changed some language to be more clear about what tournament rounds mean what --- leagues.py | 5 ++--- the_prestige.py | 16 ++++++++++------ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/leagues.py b/leagues.py index 307497e..20c8b07 100644 --- a/leagues.py +++ b/leagues.py @@ -318,12 +318,11 @@ class league_structure(object): 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} Championship 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 = 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) - tournaments[0].increment = True return tournaments @@ -343,7 +342,7 @@ class tournament(object): self.id = id self.league = None self.winner = None - self.increment = False + self.day = None if id is None: self.id = random.randint(1111,9999) diff --git a/the_prestige.py b/the_prestige.py index 1295815..3229aa4 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1192,8 +1192,10 @@ async def start_tournament_round(channel, tourney, seeding = None): team_b = get_team_fuzzy_search(pair[1].name) if tourney.league is not None: - team_a.set_pitcher(rotation_slot = tourney.league.day) - team_b.set_pitcher(rotation_slot = tourney.league.day) + if tourney.day is None: + tourney.day = tourney.league.day + team_a.set_pitcher(rotation_slot = tourney.day) + team_b.set_pitcher(rotation_slot = tourney.day) this_game = games.game(team_a.finalize(), team_b.finalize(), length = tourney.game_length) this_game, state_init = prepare_game(this_game) @@ -1228,6 +1230,8 @@ async def continue_tournament_series(tourney, queue, games_list, wins_in_series) home_team = games.get_team(oldgame.teams["home"].name) if tourney.league is not None: + if tourney.day is None: + tourney.day = tourney.league.day away_team.set_pitcher(rotation_slot = tourney.league.day) home_team.set_pitcher(rotation_slot = tourney.league.day) @@ -1292,8 +1296,8 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals except: print("something went wrong in tourney_watcher") await asyncio.sleep(4) - if tourney.league is not None and tourney.increment: - tourney.league.day += 1 + if tourney.league is not None: + tourney.day += 1 if len(queued_games) > 0: @@ -1329,6 +1333,8 @@ async def tourney_round_watcher(channel, tourney, games_list, filter_url, finals if finals: #if this last round was finals embed = discord.Embed(color = discord.Color.dark_purple(), title = f"{winner_list[0]} win the {tourney.name} finals!") + if tourney.day > tourney.league.day: + tourney.league.day = tourney.day await channel.send(embed=embed) tourney.winner = get_team_fuzzy_search(winner_list[0]) active_tournaments.pop(active_tournaments.index(tourney)) @@ -1856,7 +1862,6 @@ async def league_postseason(channel, league): tiebreakers = league.tiebreaker_required() if tiebreakers != []: await channel.send("Tiebreakers required!") - tiebreakers[0].increment = True await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tiebreakers]) for tourney in tiebreakers: league.update_standings({tourney.winner.name : {"wins" : 1}}) @@ -1886,7 +1891,6 @@ async def league_postseason(channel, league): tourneys = league.champ_series() - tourneys[0].increment = True await asyncio.gather(*[start_tournament_round(channel, tourney) for tourney in tourneys]) champs = {} for tourney in tourneys: From b2b790b3c933dea8807423b7b943ce2881eef2d5 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 06:21:25 -0500 Subject: [PATCH 29/44] fixed tourney days --- the_prestige.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index 3229aa4..b47dcbd 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1232,8 +1232,8 @@ async def continue_tournament_series(tourney, queue, games_list, wins_in_series) if tourney.league is not None: if tourney.day is None: tourney.day = tourney.league.day - away_team.set_pitcher(rotation_slot = tourney.league.day) - home_team.set_pitcher(rotation_slot = tourney.league.day) + away_team.set_pitcher(rotation_slot = tourney.day) + home_team.set_pitcher(rotation_slot = tourney.day) this_game = games.game(away_team.finalize(), home_team.finalize(), length = tourney.game_length) From bac252b0becc32e20ce7345c271e15c2aa4a248b Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 16:06:52 -0500 Subject: [PATCH 30/44] added league ownership commands --- the_prestige.py | 70 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index b47dcbd..77e3adb 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -806,14 +806,18 @@ Plays a league with a given name, provided that league has been saved on the web if active_league.name == league.name: await msg.channel.send("That league is already running, boss. Patience is a virtue, you know.") return - league.autoplay = autoplay - league.games_per_hour = gph - if str(league.day_to_series_num(league.day)) not in league.schedule.keys(): - await league_postseason(msg.channel, league) - elif league.day % league.series_length == 1: - await start_league_day(msg.channel, league) + if (league.owner is not None and msg.author.id in league.owner) or msg.author.id in config()["owners"]: + league.autoplay = autoplay + league.games_per_hour = gph + if str(league.day_to_series_num(league.day)) not in league.schedule.keys(): + await league_postseason(msg.channel, league) + elif league.day % league.series_length == 1: + await start_league_day(msg.channel, league) + else: + await start_league_day(msg.channel, league, partial = True) else: - await start_league_day(msg.channel, league, partial = True) + await msg.channel.send("You don't have permission to manage that league.") + return else: await msg.channel.send("Couldn't find that league, boss. Did you save it on the website?") @@ -853,9 +857,53 @@ class LeaguePauseCommand(Command): league_name = command.strip() for active_league in active_leagues: if active_league.name == league_name: - active_league.autoplay = 0 - await msg.channel.send(f"Loud and clear, chief. {league_name} will stop after this series is over.") + if (active_league.owner is not None and msg.author.id in active_league.owner) or msg.author.id in config()["owners"]: + active_league.autoplay = 0 + await msg.channel.send(f"Loud and clear, chief. {league_name} will stop after this series is over.") + return + else: + await msg.channel.send("You don't have permission to manage that league.") + return + await msg.channel.send("That league either doesn't exist or isn't running.") +class LeagueClaimCommand(Command): + name = "claimleague" + template = "m;claimleague [league name]" + description = "Claims an unclaimed league. Do this as soon as possible after creating the league, or it will remain unclaimed." + + async def execute(self, msg, command): + league_name = command.strip() + if league_exists(league_name): + league = leagues.load_league_file(league_name) + if league.owner is None: + league.owner = [msg.author.id] + leagues.save_league(league) + await msg.channel.send(f"The {league} commissioner is doing a great job. That's you, by the way.") + else: + await msg.channel.send("That league has already been claimed!") + await msg.channel.send("Can't find that league, boss.") + +class LeagueAddOwnersCommand(Command): + name = "addleagueowner" + template = "m;addleagueowner [league name]\n[user mentions]" + description = "Adds additional owners to a league." + + async def execute(self, msg, command): + league_name = command.split("\n")[0].strip() + if league_exists(league_name): + league = leagues.load_league_file(league_name) + if league.owner is not None and (msg.author.id in league.owner or msg.author.id in config()["owners"]): + for user in msg.mentions: + if user.id not in league.owner: + league.owner.append(user.id) + await msg.channel.send(f"The new {league} front office is now up and running.") + return + else: + await msg.channel.send(f"That league hasn't been claimed yet. Try m;claimleague first.") + return + else: + await msg.channel.send("Can't find that league, boss.") + class LeagueScheduleCommand(Command): name = "leagueschedule" template = "m;leagueschedule [league name]" @@ -901,13 +949,15 @@ commands = [ ShowAllTeamsCommand(), SearchTeamsCommand(), StartGameCommand(), + StartRandomGameCommand(), StartTournamentCommand(), + LeagueClaimCommand(), + LeagueAddOwnersCommand(), StartLeagueCommand(), LeaguePauseCommand(), LeagueDisplayCommand(), LeagueWildcardCommand(), LeagueScheduleCommand(), - StartRandomGameCommand(), CreditCommand(), RomanCommand(), HelpCommand(), From 6cdfa1bd5b883fc684d6a7da2abeb9f776f2c9ff Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 16:08:39 -0500 Subject: [PATCH 31/44] fixed handling on league claim --- the_prestige.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index 77e3adb..e9ca92c 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -878,10 +878,12 @@ class LeagueClaimCommand(Command): if league.owner is None: league.owner = [msg.author.id] leagues.save_league(league) - await msg.channel.send(f"The {league} commissioner is doing a great job. That's you, by the way.") + await msg.channel.send(f"The {league.name} commissioner is doing a great job. That's you, by the way.") + return else: await msg.channel.send("That league has already been claimed!") - await msg.channel.send("Can't find that league, boss.") + else: + await msg.channel.send("Can't find that league, boss.") class LeagueAddOwnersCommand(Command): name = "addleagueowner" From 53e67d484ab702ec4de1500dfce0db260665790f Mon Sep 17 00:00:00 2001 From: Genderdruid Date: Fri, 15 Jan 2021 13:13:29 -0800 Subject: [PATCH 32/44] Update README.md --- README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/README.md b/README.md index 4c251cd..e69f22e 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,40 @@ accepting pull requests, check the issues for to-dos. - 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 # + - 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 unless paused with the m;pauseleague command. you can use the --queue #/-q # flag to only play # series at a time before automatically pausing 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] + - displays the current standings for the specified league. + - 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. + ### other commands: - m;help [command] - 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. From 7bf35e656cb9f8a7293b7ce5db04cc496900432a Mon Sep 17 00:00:00 2001 From: Genderdruid Date: Fri, 15 Jan 2021 13:15:49 -0800 Subject: [PATCH 33/44] Update README.md --- README.md | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e69f22e..3273d30 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,6 @@ 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. use this command at the top of a list with entries separated by new lines: @@ -27,7 +26,6 @@ accepting pull requests, check the issues for to-dos. - 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: @@ -46,7 +44,6 @@ accepting pull requests, check the issues for to-dos. - 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 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. @@ -55,14 +52,6 @@ accepting pull requests, check the issues for to-dos. - m;showallteams - shows a paginated list of all teams available for games which can be scrolled through. -### 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 in a discord embed. - ### 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. @@ -90,7 +79,6 @@ accepting pull requests, check the issues for to-dos. - 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. @@ -114,6 +102,14 @@ accepting pull requests, check the issues for to-dos. - 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 in a discord embed. ### other commands: - m;help [command] From fa54536bfa9d9e3a579dfef571ba9706bd1ec770 Mon Sep 17 00:00:00 2001 From: Genderdruid Date: Fri, 15 Jan 2021 13:17:20 -0800 Subject: [PATCH 34/44] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3273d30..3e0edb6 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ blaseball, blaseball, is back! in an unofficial capacity. this project is completely unaffiliated with the game band. -we have custom players (generated by onomancer), 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! 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 From eead0c93099dda2ac6268426ce25aa0f980c12b1 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 16:24:00 -0500 Subject: [PATCH 35/44] finalized league ownership --- the_prestige.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index e9ca92c..838350b 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -894,14 +894,15 @@ class LeagueAddOwnersCommand(Command): league_name = command.split("\n")[0].strip() if league_exists(league_name): league = leagues.load_league_file(league_name) - if league.owner is not None and (msg.author.id in league.owner or msg.author.id in config()["owners"]): + if (league.owner is not None and msg.author.id in league.owner) or (league.owner is not None and msg.author.id in config()["owners"]): for user in msg.mentions: if user.id not in league.owner: league.owner.append(user.id) - await msg.channel.send(f"The new {league} front office is now up and running.") + leagues.save_league(league) + await msg.channel.send(f"The new {league.name} front office is now up and running.") return else: - await msg.channel.send(f"That league hasn't been claimed yet. Try m;claimleague first.") + await msg.channel.send(f"That league isn't yours, boss.") return else: await msg.channel.send("Can't find that league, boss.") From d96355c3f054021793d18aab012164ca74df4ee0 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 16:30:11 -0500 Subject: [PATCH 36/44] postseason pause flag --- the_prestige.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/the_prestige.py b/the_prestige.py index 838350b..e94c78c 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -760,7 +760,7 @@ class DebugLeagueDisplay(Command): class StartLeagueCommand(Command): name = "startleague" template = "m;startleague [league name]\n[games per hour]" - description = """Optional flag for the first line: `--queue X` or `-q X` to play X number of series before stopping. + description = """Optional flags for the first line: `--queue X` or `-q X` to play X number of series before stopping; `--noautopostseason` will pause the league before starting postseason. Plays a league with a given name, provided that league has been saved on the website. The games per hour sets how often the games will start. (e.g. GPH 2 will start games at X:00 and X:30)""" async def execute(self, msg, command): @@ -789,6 +789,8 @@ Plays a league with a given name, provided that league has been saved on the web await msg.channel.send("We need a games per hour number in the second line.") return + + try: gph = int(command.strip()) if gph < 1 or gph > 12: @@ -799,6 +801,9 @@ Plays a league with a given name, provided that league has been saved on the web if league_exists(league_name): league = leagues.load_league_file(league_name) + if "--noautopostseason" in command: + autoplay = int(list(league.schedule.keys())[-1]) - league.day_to_series_num(league.day) + 1 + if league.historic: await msg.channel.send("That league is done and dusted, chief. Sorry.") return From ab909d78412a2a0a1a89dd1ff28f0053e85a1469 Mon Sep 17 00:00:00 2001 From: Genderdruid Date: Fri, 15 Jan 2021 13:30:16 -0800 Subject: [PATCH 37/44] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3e0edb6..c4e7963 100644 --- a/README.md +++ b/README.md @@ -90,9 +90,11 @@ accepting pull requests, check the issues for to-dos. - 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 # + - 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 unless paused with the m;pauseleague command. you can use the --queue #/-q # flag to only play # series at a time before automatically pausing until you use this command again. + - 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): From 6ccd88a7ba51809bbddcaf7a27ace29c548714fd Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 16:32:18 -0500 Subject: [PATCH 38/44] Delete LICENSE.md --- LICENSE.md | 437 ----------------------------------------------------- 1 file changed, 437 deletions(-) delete mode 100644 LICENSE.md diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index d60efe4..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,437 +0,0 @@ -Attribution-NonCommercial-ShareAlike 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More_considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International -Public License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution-NonCommercial-ShareAlike 4.0 International Public License -("Public License"). To the extent this Public License may be -interpreted as a contract, You are granted the Licensed Rights in -consideration of Your acceptance of these terms and conditions, and the -Licensor grants You such rights in consideration of benefits the -Licensor receives from making the Licensed Material available under -these terms and conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. BY-NC-SA Compatible License means a license listed at - creativecommons.org/compatiblelicenses, approved by Creative - Commons as essentially the equivalent of this Public License. - - d. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - e. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - f. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - g. License Elements means the license attributes listed in the name - of a Creative Commons Public License. The License Elements of this - Public License are Attribution, NonCommercial, and ShareAlike. - - h. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - i. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - j. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - k. NonCommercial means not primarily intended for or directed towards - commercial advantage or monetary compensation. For purposes of - this Public License, the exchange of the Licensed Material for - other material subject to Copyright and Similar Rights by digital - file-sharing or similar means is NonCommercial provided there is - no payment of monetary compensation in connection with the - exchange. - - l. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - m. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - n. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part, for NonCommercial purposes only; and - - b. produce, reproduce, and Share Adapted Material for - NonCommercial purposes only. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. Additional offer from the Licensor -- Adapted Material. - Every recipient of Adapted Material from You - automatically receives an offer from the Licensor to - exercise the Licensed Rights in the Adapted Material - under the conditions of the Adapter's License You apply. - - c. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties, including when - the Licensed Material is used other than for NonCommercial - purposes. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - b. ShareAlike. - - In addition to the conditions in Section 3(a), if You Share - Adapted Material You produce, the following conditions also apply. - - 1. The Adapter's License You apply must be a Creative Commons - license with the same License Elements, this version or - later, or a BY-NC-SA Compatible License. - - 2. You must include the text of, or the URI or hyperlink to, the - Adapter's License You apply. You may satisfy this condition - in any reasonable manner based on the medium, means, and - context in which You Share Adapted Material. - - 3. You may not offer or impose any additional or different terms - or conditions on, or apply any Effective Technological - Measures to, Adapted Material that restrict exercise of the - rights granted under the Adapter's License You apply. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database for NonCommercial purposes - only; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material, - including for purposes of Section 3(b); and - - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - -======================================================================= - -Creative Commons is not a party to its public -licenses. Notwithstanding, Creative Commons may elect to apply one of -its public licenses to material it publishes and in those instances -will be considered the β€œLicensor.” The text of the Creative Commons -public licenses is dedicated to the public domain under the CC0 Public -Domain Dedication. Except for the limited purpose of indicating that -material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the -public licenses. - -Creative Commons may be contacted at creativecommons.org. From 7ab11dcebf599f4280a7872bad92063b0a9e42f1 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 16:32:44 -0500 Subject: [PATCH 39/44] Rename LICENSE to LICENSE.md --- LICENSE => LICENSE.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LICENSE => LICENSE.md (100%) diff --git a/LICENSE b/LICENSE.md similarity index 100% rename from LICENSE rename to LICENSE.md From 797e0da9312adb8f4a6237b90dd29e8513b6c1a4 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 20:15:52 -0500 Subject: [PATCH 40/44] past season standings with -s flag --- league_storage.py | 61 ++++++++++++++++++++++++++++++++++++++++++++--- leagues.py | 47 ++++++++++++++++++++++++++++++++---- the_prestige.py | 39 +++++++++++++++++++++++------- 3 files changed, 131 insertions(+), 16 deletions(-) diff --git a/league_storage.py b/league_storage.py index b3edb4c..1ea012a 100644 --- a/league_storage.py +++ b/league_storage.py @@ -21,6 +21,23 @@ def create_connection(league_name): 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"))) @@ -87,7 +104,7 @@ def save_league(league): "series_length" : league.series_length, "games_per_hour" : league.games_per_hour, "owner" : league.owner, - "champions" : league.champions, + "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: @@ -138,11 +155,49 @@ def get_standings(league_name): 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 in subfolder.name: - return True + 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 \ No newline at end of file diff --git a/leagues.py b/leagues.py index 20c8b07..a1d06e2 100644 --- a/leagues.py +++ b/leagues.py @@ -14,7 +14,7 @@ class league_structure(object): self.owner = None self.season = 1 self.autoplay = -1 - self.champions = {} + 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] } } @@ -32,6 +32,14 @@ class league_structure(object): 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) @@ -234,11 +242,42 @@ class league_structure(object): 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=self.name) + 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} @@ -461,7 +500,7 @@ def load_league_file(league_name): this_league.historic = state_dic["historic"] this_league.season = state_dic["season"] try: - this_league.champions = state_dic["champions"] + this_league.champion = state_dic["champion"] except: - this_league.champions = {} + this_league.champion = None return this_league \ No newline at end of file diff --git a/the_prestige.py b/the_prestige.py index e94c78c..9a2596f 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -1,7 +1,7 @@ import discord, json, math, os, roman, games, asyncio, random, main_controller, threading, time, urllib, leagues, datetime import database as db import onomancer as ono -from league_storage import league_exists +from league_storage import league_exists, season_save from the_draft import Draft, DRAFT_ROUNDS from flask import Flask from uuid import uuid4 @@ -753,9 +753,15 @@ class DebugLeagueDisplay(Command): name = "displaydebugleague" async def execute(self, msg, command): - if league_exists("test2"): - league = leagues.load_league_file("test2") - await msg.channel.send(embed=league.standings_embed()) + if league_exists("Midseries"): + league = leagues.load_league_file("Midseries") + league.champion = "Butts" + leagues.save_league(league) + season_save(league) + league.season_reset() + + await msg.channel.send(embed=league.past_standings(1)) + class StartLeagueCommand(Command): name = "startleague" @@ -829,12 +835,25 @@ Plays a league with a given name, provided that league has been saved on the web class LeagueDisplayCommand(Command): name = "leaguestandings" template = "m;leaguestandings [league name]" - description = "Displays the current standings for the given league." + description = "Displays the current standings for the given league. Use `--season X` or `-s X` to get standings from season X of that league." async def execute(self, msg, command): - if league_exists(command.strip()): - league = leagues.load_league_file(command.strip()) - await msg.channel.send(embed=league.standings_embed()) + if league_exists(command.split("-")[0].strip()): + league = leagues.load_league_file(command.split("-")[0].strip()) + + try: + if "--season " in command: + season_num = int(command.split("--season ")[1]) + await msg.channel.send(embed=league.past_standings(season_num)) + elif "-s " in command: + season_num = int(command.split("-s ")[1]) + await msg.channel.send(embed=league.past_standings(season_num)) + else: + await msg.channel.send(embed=league.standings_embed()) + except ValueError: + await msg.channel.send("Give us a proper number, boss.") + except TypeError: + await msg.channel.send("That season hasn't been played yet, chief.") else: await msg.channel.send("Can't find that league, boss.") @@ -1981,8 +2000,10 @@ async def league_postseason(channel, league): await channel.send(f"The {league.name} Championship Series is starting in {math.ceil(wait_seconds/60)} minutes!") await asyncio.sleep(wait_seconds) await start_tournament_round(channel, world_series) - league.champions[str(league.season)] = world_series.winner.name + league.champion = world_series.winner.name leagues.save_league(league) + season_save(league) + league.season_reset() From 62dbc6f53325f9ee6e21a8097c699286a82eb748 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 20:27:58 -0500 Subject: [PATCH 41/44] tidyed up instructions for draft command --- the_prestige.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index 9a2596f..7c17fb5 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -601,8 +601,8 @@ class DraftPlayerCommand(Command): class StartDraftCommand(Command): name = "startdraft" - template = "m;startdraft [mention] [teamname] [slogan]" - description = """Starts a draft with an arbitrary number of participants. Send this command at the top of the list with each mention, teamname, and slogan on a new line (shift+enter in discord). + template = "m;startdraft\n[mention]\n[teamname]\n[slogan]" + description = """Starts a draft with an arbitrary number of participants. Send this command at the top of the list with each mention, teamname, and slogan on their own lines (shift+enter in discord). - The draft will proceed in the order that participants were entered. - 20 players will be available for draft at a time, and the pool will refresh automatically when it becomes small. - Each participant will be asked to draft 12 hitters then finally one pitcher. @@ -817,7 +817,7 @@ Plays a league with a given name, provided that league has been saved on the web if active_league.name == league.name: await msg.channel.send("That league is already running, boss. Patience is a virtue, you know.") return - if (league.owner is not None and msg.author.id in league.owner) or msg.author.id in config()["owners"]: + if (league.owner is not None and msg.author.id in league.owner) or msg.author.id in config()["owners"] or league.owner is None: league.autoplay = autoplay league.games_per_hour = gph if str(league.day_to_series_num(league.day)) not in league.schedule.keys(): From 58797cf04ca1e5c764ea17bac56f716e43ea3211 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 22:00:46 -0500 Subject: [PATCH 42/44] fixed postseason pause feature --- the_prestige.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/the_prestige.py b/the_prestige.py index 7c17fb5..bfd0bb8 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -787,7 +787,6 @@ Plays a league with a given name, provided that league has been saved on the web raise ValueError elif autoplay is None: autoplay = -1 - command = command.split("\n")[1] except ValueError: await msg.channel.send("Sorry boss, the queue flag needs a natural number. Any whole number over 0 will do just fine.") return @@ -798,7 +797,7 @@ Plays a league with a given name, provided that league has been saved on the web try: - gph = int(command.strip()) + gph = int(command.split("\n")[1].strip()) if gph < 1 or gph > 12: raise ValueError except ValueError: @@ -1835,6 +1834,14 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal else: league.active = False + if league.autoplay == 0 or config()["game_freeze"]: #if number of series to autoplay has been reached + await channel.send(embed=league.standings_embed()) + await channel.send(f"The {league.name} is no longer autoplaying.") + if config()["game_freeze"]: + await channel.send("Patch incoming.") + leagues.save_league(league) + active_leagues.pop(active_leagues.index(league)) + return if last: #if last game of the season now = datetime.datetime.now() @@ -1866,14 +1873,7 @@ async def league_day_watcher(channel, league, games_list, filter_url, last = Fal - if league.autoplay == 0 or config()["game_freeze"]: #if number of series to autoplay has been reached - await channel.send(embed=league.standings_embed()) - await channel.send(f"The {league.name} is no longer autoplaying.") - if config()["game_freeze"]: - await channel.send("Patch incoming.") - leagues.save_league(league) - active_leagues.pop(active_leagues.index(league)) - return + From 7764e2ab32b45702e5664f9a4567e2d026b6e25f Mon Sep 17 00:00:00 2001 From: Sakimori Date: Fri, 15 Jan 2021 22:08:52 -0500 Subject: [PATCH 43/44] disabled turbo mode --- main_controller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main_controller.py b/main_controller.py index 8086dad..c4de4e7 100644 --- a/main_controller.py +++ b/main_controller.py @@ -206,4 +206,4 @@ def update_loop(): state["update_pause"] -= 1 socketio.emit("states_update", game_states) - time.sleep(1) \ No newline at end of file + time.sleep(8) \ No newline at end of file From df7a12e19a6d397b2a62e22b4d038ec4bb664c97 Mon Sep 17 00:00:00 2001 From: Sakimori Date: Sat, 16 Jan 2021 01:09:59 -0500 Subject: [PATCH 44/44] fixed idolize commands not being stripped --- .gitignore | 2 ++ simmadome/.eslintcache | 1 + the_prestige.py | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 simmadome/.eslintcache diff --git a/.gitignore b/.gitignore index 6b7e8e2..4708091 100644 --- a/.gitignore +++ b/.gitignore @@ -352,3 +352,5 @@ matteo.db-shm /matteo_env/Lib/site-packages/flask_socketio/__init__.py env +/data/leagues +/simmadome/build diff --git a/simmadome/.eslintcache b/simmadome/.eslintcache new file mode 100644 index 0000000..9f96e6b --- /dev/null +++ b/simmadome/.eslintcache @@ -0,0 +1 @@ +[{"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\index.tsx":"1","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\reportWebVitals.ts":"2","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\GamesPage.tsx":"3","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\GamePage.tsx":"4","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\GamesUtil.tsx":"5","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\Game.tsx":"6","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\CreateLeague.tsx":"7","M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\util.tsx":"8"},{"size":2425,"mtime":1610685584594,"results":"9","hashOfConfig":"10"},{"size":440,"mtime":1610521673158,"results":"11","hashOfConfig":"10"},{"size":4866,"mtime":1610685584593,"results":"12","hashOfConfig":"10"},{"size":1897,"mtime":1610685584589,"results":"13","hashOfConfig":"10"},{"size":1157,"mtime":1610685584594,"results":"14","hashOfConfig":"10"},{"size":3173,"mtime":1610583643836,"results":"15","hashOfConfig":"10"},{"size":17241,"mtime":1610685584587,"results":"16","hashOfConfig":"10"},{"size":1029,"mtime":1610685584594,"results":"17","hashOfConfig":"10"},{"filePath":"18","messages":"19","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1jg8ts7",{"filePath":"20","messages":"21","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"22"},{"filePath":"23","messages":"24","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"25","messages":"26","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"27","messages":"28","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"29","messages":"30","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"22"},{"filePath":"31","messages":"32","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"33","messages":"34","errorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\index.tsx",[],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\reportWebVitals.ts",[],["35","36"],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\GamesPage.tsx",[],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\GamePage.tsx",[],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\GamesUtil.tsx",[],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\Game.tsx",[],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\CreateLeague.tsx",[],"M:\\Documents\\Code\\matteo\\the-prestige\\simmadome\\src\\util.tsx",["37"],{"ruleId":"38","replacedBy":"39"},{"ruleId":"40","replacedBy":"41"},{"ruleId":"42","severity":1,"message":"43","line":1,"column":9,"nodeType":"44","messageId":"45","endLine":1,"endColumn":15},"no-native-reassign",["46"],"no-negated-in-lhs",["47"],"@typescript-eslint/no-unused-vars","'useRef' is defined but never used.","Identifier","unusedVar","no-global-assign","no-unsafe-negation"] \ No newline at end of file diff --git a/the_prestige.py b/the_prestige.py index 9df36cf..d43df0e 100644 --- a/the_prestige.py +++ b/the_prestige.py @@ -78,7 +78,7 @@ class IdolizeCommand(Command): else: meme = False - player_name = discord.utils.escape_mentions(command) + player_name = discord.utils.escape_mentions(command.strip()) if len(player_name) >= 70: await msg.channel.send("That name is too long. Please keep it below 70 characters, for my sake and yours.") return