diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b41050 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.swp +wwwcats +wwwcats.exe +wwwcats.log +TODO.txt diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b62f197 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# Detonating Cats + +A web-based clone of the popular _[Exploding Kittens](https://explodingkittens.com)_ card game. I wrote this +because I wanted to play the game online with my friends during the December 2020 coronavirus lockdown and +was dissatisfied with the existing clones of the game. + +## Features + +This is a pretty much feature-complete clone of the base game. The objective is to permit any play +which would be allowed by the rules in a real-life game. + +I have done my best to emulate the most important aspects of the game faithfully; while no computer +card game is ever 100% true to the experience of the real thing, this version attempts to preserve +many of the features of _Exploding Kittens_ which make the game dramatic, dynamic and fun. + +The game is fast and lightweight, and can be hosted on any server with no dependencies; all you need +is the game server binary and the corresponding static client bundle. + +## Caveats + + * I designed everything myself, including drawing the cards. I have no idea about user interface design, + so the whole thing feels a bit early-2000s. + * The game has not been well-tested. I made this for fun, and there are probably bugs. You've been warned! + * If you're interested in improving any aspect of the game, contributions are very welcome. Please open an + issue or pull request on GitHub! + +## Compilation + +To compile, you need a recent version of [Go](https://golang.org) – version 1.14 or newer is probably fine. +All the other dependencies are fetched automatically. + +After cloning the repository: +``` +$ go build +$ # Or, for a statically linked, stripped binary: +$ CGO_ENABLED=0 go build -ldflags "-s -w" +``` + +Just run the `wwwcats` binary to start the server, and `./wwwcats -h` for help with more options. + +## License + +Copyright (C) 2021 Lawrence Brown. + +"Exploding Kittens" is a trademark of Exploding Kittens Inc. + +The program's source code is released under the terms of the GNU Affero General Public License (version 3). +Please see the `LICENSE` file for more information. diff --git a/cards.go b/cards.go new file mode 100644 index 0000000..43361f0 --- /dev/null +++ b/cards.go @@ -0,0 +1,241 @@ +package main + +import ( + "math/rand" + "time" + "sort" +) + +type Deck struct { + // The end of the slice is the top of the deck + cards []string +} + +func newDeck() (d *Deck) { + d = new(Deck) + + // Add all the cards, EXCEPT those which should not be dealt to players + d.insertMultiple(map[string]int{ + "nope": 5, + "attack": 4, + "skip": 4, + "favour": 4, + "shuffle": 4, + "see3": 5, + "random1": 4, + "random2": 4, + "random3": 4, + "random4": 4, + "random5": 4, + }) + + d.shuffle() + + return +} + +func (d *Deck) addExtraCards(players int) { + d.insertMultiple(map[string]int{ + "exploding": players - 1, + "defuse": 6 - players, + }) + + d.shuffle() + + return +} + +func (d *Deck) insertOnTop(card string) { + d.cards = append(d.cards, card) +} + +func (d *Deck) insertMultiple(cards map[string]int) { + for card, number := range cards { + for i := 0; i < number; i++ { + d.insertOnTop(card) + } + } +} + +func (d *Deck) insertAtPos(pos int, card string) { + // the top of the deck is the end of the array + pos = len(d.cards) - (pos) + d.cards = append(d.cards, "") + copy(d.cards[pos+1:], d.cards[pos:]) + d.cards[pos] = card +} + +func (d *Deck) draw() (card string) { + // pop + card, d.cards = d.cards[len(d.cards)-1], d.cards[:len(d.cards)-1] + return +} + +func (d *Deck) peek(num int) (ret []string) { + from := len(d.cards) - num + if from < 0 { + from = 0 + } + + length := num + if len(d.cards) < num { + length = len(d.cards) + } + + ret = make([]string, length) + copy(ret, d.cards[from:]) + + // Reverse + for i := len(ret)/2 - 1; i >= 0; i-- { + opp := len(ret) - 1 - i + ret[i], ret[opp] = ret[opp], ret[i] + } + + return +} + +func (d *Deck) shuffle() { + rand.Seed(time.Now().UnixNano()) + rand.Shuffle(len(d.cards), func(i, j int) { + d.cards[i], d.cards[j] = d.cards[j], d.cards[i] + }) +} + +func (d *Deck) dealHand(playerCount int) (h *Hand) { + h = new(Hand) + + h.cards = []string{"defuse"} + + var cardCount int + if playerCount > 5 { + cardCount = 6 + } else { + cardCount = 7 + } + + for i := 0; i < cardCount; i++ { + h.cards = append(h.cards, d.draw()) + } + + return +} + +func (d *Deck) cardsLeft() int { + return len(d.cards) +} + +type Hand struct { + cards []string +} + +func (h *Hand) cardList() (list string) { + for _, card := range h.cards { + list = list + " " + card + } + + return +} + +func (h *Hand) getCard(num int) string { + return h.cards[num] +} + +func (h *Hand) addCard(card string) { + h.cards = append(h.cards, card) +} + +func (h *Hand) removeCard(num int) { + h.cards = append(h.cards[:num], h.cards[num+1:]...) +} + +func (h *Hand) removeByName(wanted string) { + for i, card := range h.cards { + if card == wanted { + h.cards = append(h.cards[:i], h.cards[i+1:]...) + return + } + } +} + +func (h *Hand) contains(wanted string) bool { + for _, card := range h.cards { + if card == wanted { + return true + } + } + return false +} + +func (h *Hand) containsMultiple(wanted string, num int) bool { + found := 0 + for _, card := range h.cards { + if card == wanted { + found += 1 + if found == num { + return true + } + } + } + return false +} + +func (h *Hand) getLength() int { + return len(h.cards) +} + +func (h *Hand) takeRandom() string { + rand.Seed(time.Now().UnixNano()) + cardNo := rand.Intn(len(h.cards)) + card := h.getCard(cardNo) + h.removeCard(cardNo) + return card +} + +func (h *Hand) sort() { + weights := map[string]int{ + "defuse": 10, + "nope": 20, + "skip": 30, + "attack": 40, + "see3": 50, + "shuffle": 60, + "favour": 70, + "random1": 80, + "random2": 90, + "random3": 100, + "random4": 110, + "random5": 120, + } + + sort.Slice(h.cards, func (a, b int) bool { + return weights[h.cards[a]] < weights[h.cards[b]] + }) +} + +type GameState struct { + // Used to save the game state before performing a NOPEable action + // needs to contain anything that can be reversed by a NOPE + deck Deck + currentPlayer int + attack bool +} + +func makeGameState(g *Game) *GameState { + // Copy everything + cards := make([]string, len(g.deck.cards)) + copy(cards, g.deck.cards) + + return &GameState{ + deck: Deck{ + cards: cards, + }, + currentPlayer: g.currentPlayer, + attack: g.attack, + } +} + +func (gs *GameState) restore(g *Game) { + g.deck = &gs.deck + g.currentPlayer = gs.currentPlayer + g.attack = gs.attack +} diff --git a/client.go b/client.go new file mode 100644 index 0000000..54fbecf --- /dev/null +++ b/client.go @@ -0,0 +1,184 @@ +package main + +import ( + "log" + "strconv" + "strings" + "time" + + "runtime/debug" + + "github.com/gorilla/websocket" +) + +const ( + // Timeout for writing to a client + writeWait = 10 * time.Second + + // Timeout for receiving a 'pong' from the client + pongWait = 15 * time.Second + + // How often should we ping? Must be less than pongWait + pingPeriod = (pongWait * 9) / 10 + + maxMessageSize = 512 +) + +type Client struct { + // Websocket connection object + conn *websocket.Conn + + // Buffer for outgoing messages + send chan []byte + + name string + lobby *Lobby +} + +func (c *Client) readPump(lobbies map[string]*Lobby) { + // Sets up a client, reads incoming messages and sends them to the right place + // + // This is called as a goroutine for each client, and this function + // is the only function allowed to read from the client. + + defer func() { + // Clean up + c.conn.Close() + if c.lobby != nil { + c.lobby.unregister <- c + } + + if r := recover(); r != nil { + c.dieGracefully(r) + } + }() + + c.conn.SetReadLimit(maxMessageSize) + c.conn.SetReadDeadline(time.Now().Add(pongWait)) + c.conn.SetPongHandler(func(string) error { + c.conn.SetReadDeadline(time.Now().Add(pongWait)) + return nil + }) + + for { + + // Read the incoming messages + + _, bytes, err := c.conn.ReadMessage() + if err != nil { + // The connection is dead + if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { + log.Printf("%s !!! Connection closed (%v)", c.name, err) + } + break + } + + message := string(bytes) + + // Check for badly-formed messages which could do something strange + if strings.Contains(message, "\n") || strings.Contains(message, "\r") { + continue + } + + log.Printf("%s >>> %s", c.name, message) + + // If this client is in a lobby, let the lobby handle the message + + if c.lobby != nil { + c.lobby.readFromClient(c, message) + continue + } + + // The client is not currently in a lobby; check if they're trying to join + + fields := strings.Fields(message) + + if len(fields) == 3 && fields[0] == "join_lobby" { + lobby_name := fields[1] + player_name := fields[2] + + // Length is already limited by SetReadLimit, so we're not worried + + c.joinToLobby(lobby_name, player_name, lobbies) + } + } +} + +func (c *Client) writePump() { + // Counterpart to readPump + // Massively adapted from the gorilla websocket docs + + ticker := time.NewTicker(pingPeriod) + + defer func() { + ticker.Stop() + c.conn.Close() + + if r := recover(); r != nil { + c.dieGracefully(r) + } + }() + + // Send the server version on connect + c.sendMsg("version "+strconv.Itoa(REVISION)) + + for { + select { + case message, ok := <-c.send: + c.conn.SetWriteDeadline(time.Now().Add(writeWait)) + + if !ok { + log.Printf("%s !!! Write channel closed", c.name) + + // Close the channel + // I have no idea how this actually works + c.conn.WriteMessage(websocket.CloseMessage, []byte{}) + return + } + + w, err := c.conn.NextWriter(websocket.TextMessage) + if err != nil { + log.Printf("%s !!! Disconnected on write (%v)", c.name, err) + return + } + w.Write(message) + + /* + // Finish writing whatever is left + n := len(c.send) + for i := 0; i < n; i++ { + w.Write([]byte("\r\n")) + w.Write(<-c.send) + } + */ + + if err := w.Close(); err != nil { + log.Printf("%s !!! Couldn't close write (%v)", c.name, err) + return + } + + case <-ticker.C: + c.conn.SetWriteDeadline(time.Now().Add(writeWait)) + if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { + log.Printf("%s !!! Ping timeout (%v)", c.name, err) + return + } + } + } +} + +func (c *Client) sendMsg(message string) { + log.Printf("%s <<< %s", c.name, message) + + select { + case c.send <- []byte(message): + default: + log.Fatal("Failed to write to client", c.name) + } +} + +func (c *Client) dieGracefully(r interface {}) { + // Terminates a panicking client to avoid crashing the server + log.Printf("!!! PANIC in client %s: %v !!!", c.name, r) + debug.PrintStack() +} diff --git a/game.go b/game.go new file mode 100644 index 0000000..690d863 --- /dev/null +++ b/game.go @@ -0,0 +1,741 @@ +package main + +import ( + "log" + "math/rand" + "strconv" + "strings" + "time" +) + +type Game struct { + // The corresponding Lobby object, to allow communication + // with clients + lobby *Lobby + + // It's easier if we index the spectators, so we use a map + // Only synced with the client during netburst + spectators map[*Client]bool + + // We need a strict order for players, so we use a slice + // The player list is order-sensitive, so we re-sync it + // with the client every time it's updated. + players []*Client + currentPlayer int + + // Various game-related variables + started bool + defusing bool + attack bool + favouring *Client // Who is asking for a favour? + favoured *Client // Who is being asked for a favour? + favourType int // !! not reset !! + // 1 - favour, 2 - random, 3 - steal + + deck *Deck + hands map[*Client]*Hand + + // We store one action's worth of 'history' in case of a nope + history *GameState +} + +func newGame(lobby *Lobby) *Game { + return &Game{ + lobby: lobby, + spectators: make(map[*Client]bool), + hands: make(map[*Client]*Hand), + currentPlayer: -1, + } +} + +func (g *Game) addPlayer(client *Client) { + // Adds a player to the spectators + // /!\ This function expects the caller to have already obtained a lock on + // g.lobby.clients - not doing this leads to a race condition + g.spectators[client] = true + g.lobby.sendBcastRaw("joins " + client.name) + g.netburst(client) +} + +func (g *Game) removePlayer(client *Client) { + _, ok := g.spectators[client] + if !ok { + // First downgrade the player to spectator + g.downgradePlayer(client) + } + + delete(g.spectators, client) + g.lobby.sendBcast("parts " + client.name) +} + +func (g *Game) playerNumber(client *Client) (num int) { + // Finds the number of a player in the players slice + // Mostly useful for removing players + num = -1 + for i, _ := range g.players { + if g.players[i] == client { + num = i + break + } + } + return +} + +func (g *Game) playerByName(name string) (player *Client) { + for _, thisPlayer := range g.players { + if thisPlayer.name == name { + player = thisPlayer + break + } + } + return +} + +func (g *Game) upgradePlayer(client *Client) { + // Move a player from the spectators into the players + delete(g.spectators, client) + g.players = append(g.players, client) + + g.lobby.sendBcast("upgrades " + client.name) + g.lobby.sendBcast("players" + g.playerList()) + + // Display a message to tell the client they are playing + client.sendMsg("message playing") +} + +func (g *Game) downgradePlayer(client *Client) { + currentlyPlaying := false + if g.playerNumber(client) == g.currentPlayer { + currentlyPlaying = true + } + + clientToRemove := g.playerNumber(client) + g.players = append(g.players[:clientToRemove], g.players[clientToRemove+1:]...) + g.spectators[client] = true + delete(g.hands, client) + + g.lobby.sendBcast("downgrades " + client.name) + g.lobby.sendBcast("players" + g.playerList()) + + if !g.started { + // Display a message to tell the client they are spectating + client.sendMsg("message spectating") + return + } + + // Gracefully remove the player from the game in progress + client.sendMsg("message spectating_exploded") + + // Erase their hand + client.sendMsg("hand") + + if len(g.players) == 1 { + go g.wins(g.players[0]) + return + } + + if g.favouring == client { + g.favoured.sendMsg("q_cancel") + g.favouring = nil + g.favoured = nil + } + if g.favoured == client && g.favourType == 1 { + // The favour is cancelled + g.lobby.sendBcast("bcast favour_cancel") + g.favouring.sendMsg("unlock") + g.favouring = nil + g.favoured = nil + } + // for favourType 2, it is instant - this can't happen + // for favourType 3, we are waiting on a response from the player ASKING + // (so we can deal with it in answersQuestion) + + // If they are currently playing, advance to the next player + if currentlyPlaying && len(g.players) > 0 { + g.nextTurn() + } +} + +func (g *Game) wins(winner *Client) { + g.lobby.sendBcast("wins " + winner.name) + + // This function runs a separate goroutine, so it's safe to sleep + time.Sleep(5 * time.Second) + + // Destroy the game and create a new one + g.lobby.sendBcast("hand") + g.lobby.sendBcast("draw_pile no") + g.lobby.sendBcast("no_discard") + g.lobby.sendBcast("bcast new_game") + + g.lobby.clientsMu.Lock() + defer g.lobby.clientsMu.Unlock() + + g.lobby.currentGame = newGame(g.lobby) + for client := range g.lobby.clients { + g.lobby.currentGame.addPlayer(client) + // We add a very short delay to allow each joining client to be processed separately + time.Sleep(50 * time.Millisecond) + } + + // The GC should now be able to collect this old game object, I think +} + +func (g *Game) netburst(client *Client) { + // Communicates the current game state to a newly joining client + client.sendMsg("spectators" + g.spectatorList()) + client.sendMsg("players" + g.playerList()) + + // Display a message to tell the client they are spectating + if !g.started { + client.sendMsg("message spectating") + return + } + + // allow the client to spectate a game-in-progress + client.sendMsg("message spectating_started") + if g.deck.cardsLeft() > 0 { + client.sendMsg("draw_pile yes") + } +} + +func (g *Game) spectatorList() (list string) { + for spec := range g.spectators { + list = list + " " + spec.name + } + return +} + +func (g *Game) playerList() (list string) { + for _, player := range g.players { + list = list + " " + player.name + } + return +} + +func (g *Game) readFromClient(c *Client, msg string) { + fields := strings.Fields(msg) + + switch fields[0] { + case "join": + // Joining the game (from spectators) + + if g.started { + // You can't join an active game + break + } + + _, ok := g.spectators[c] + if !ok { + // Player is not a spectator! + break + } + + g.upgradePlayer(c) + + case "leave": + // Leaving the game (back to spectators) + + _, ok := g.spectators[c] + if ok { + // Player is a spectator! + break + } + + g.downgradePlayer(c) + + case "start": + if g.started { + break + } + + if len(g.players) < 2 { + c.sendMsg("bcast min_players") + break + } + + if len(g.players) > 6 { + g.lobby.sendBcast("bcast max_players") + break + } + + if len(g.players) == 6 { + // Warning message + g.lobby.sendBcast("bcast high_players") + } + + g.start() + + case "draw": + _, ok := g.spectators[c] + if ok { + break + } + + if g.currentPlayer >= len(g.players) { + log.Println("Player out of range") + break + } + + if g.deck.cardsLeft() < 1 { + c.sendMsg("err illegal_move") + break + } + + if g.players[g.currentPlayer].name != c.name { + c.sendMsg("err illegal_move") + break + } + + if g.defusing { + log.Println("Defusing") + break + } + + g.drawCard(c) + + case "play": + _, ok := g.spectators[c] + if ok { + break + } + + if len(fields) != 2 { + break + } + + if g.currentPlayer >= len(g.players) { + log.Println("Player out of range") + break + } + + if g.favouring != nil { + // There is a case where it would be legal to play + // NOPE here - TODO + break + } + + card, err := strconv.Atoi(fields[1]) + if err != nil { + c.sendMsg("err illegal_move") + break + } + + if card >= g.hands[c].getLength() { + c.sendMsg("err illegal_move") + break + } + + cardText := g.hands[c].getCard(card) + + if g.defusing && cardText != "defuse" { + log.Println("Defusing") + break + } + + if cardText != "nope" && g.players[g.currentPlayer].name != c.name { + c.sendMsg("err illegal_move") + break + } + + g.favouring = nil + g.favoured = nil + g.hands[c].removeCard(card) + c.sendMsg("hand" + g.hands[c].cardList()) + g.playsCard(c, cardText) + + case "play_multiple": + _, ok := g.spectators[c] + if ok { + break + } + + if len(fields) != 3 { + break + } + + if g.currentPlayer >= len(g.players) { + break + } + + if g.favouring != nil { + c.sendMsg("err illegal_move") + break + } + + if g.defusing { + break + } + + num, err := strconv.Atoi(fields[1]) + if err != nil || num > 3 || num < 2 { + c.sendMsg("err illegal_move") + break + } + + if !g.hands[c].containsMultiple(fields[2], num) { + c.sendMsg("err illegal_move") + break + } + + g.favouring = nil + g.favoured = nil + for i := 0; i < num; i++ { + g.hands[c].removeByName(fields[2]) + } + c.sendMsg("hand" + g.hands[c].cardList()) + g.playsCombo(c, fields[2], num) + + case "a": + if len(fields) != 3 { + if len(fields) == 2 { + c.sendMsg("q "+fields[1]) + } + break + } + + g.answersQuestion(c, fields[1], fields[2]) + + case "sort": + _, ok := g.spectators[c] + if ok { + break + } + if !g.started { + break + } + g.hands[c].sort() + c.sendMsg("hand" + g.hands[c].cardList()) + + default: + log.Println("Uncaught message from", c.name+":", msg) + } // End switch +} + +func (g *Game) drawCard(c *Client) { + card := g.deck.draw() + g.history = nil + g.favouring = nil + g.favoured = nil + + g.lobby.sendBcast("cards_left "+strconv.Itoa(g.deck.cardsLeft())) + + if card == "exploding" { + g.lobby.sendBcast("exploded " + c.name) + + if !g.hands[c].contains("defuse") { + g.downgradePlayer(c) + return + } + + g.defusing = true + c.sendMsg("defusing") + + g.nextTurn() + return + } + + g.hands[c].addCard(card) + c.sendMsg("hand" + g.hands[c].cardList()) + // Tell the player what card they drew + c.sendMsg("drew " + card) + // Tell everyone else that a mystery card was drawn + g.lobby.sendComplexBcast("drew_other "+c.name, map[*Client]bool{c: true}) + + g.incrementTurn() + g.nextTurn() +} + +func (g *Game) playsCard(player *Client, card string) { + g.lobby.sendBcast("played " + player.name + " " + card) + + // Every case here should do something with g.history + // - either make a backup, or clear it so that we can't + // NOPE too far back into history + switch card { + case "defuse": + if !g.defusing { + return + } + player.sendMsg("q defuse_pos") + case "favour": + g.favouring = player + g.favourType = 1 + player.sendMsg("q favour_who") + case "shuffle": + g.history = makeGameState(g) + g.deck.shuffle() + case "nope": + if g.history == nil { + g.lobby.sendBcast("bcast no_nope") + return + } + // Back up the game state before restoring the old one + // - that way, you can NOPE a NOPE + history := makeGameState(g) + g.history.restore(g) + g.history = history + g.nextTurn() + case "skip": + g.history = makeGameState(g) + g.incrementTurn() + g.nextTurn() + case "attack": + g.history = makeGameState(g) + if g.attack { + // player is on the first turn of an attack + g.attack = false + } else { + g.currentPlayer++ + g.attack = true + } + g.nextTurn() + case "see3": + cards := g.deck.peek(3) + player.sendMsg("seen " + strings.Join(cards, " ")) + g.history = nil + default: + log.Println("unhandled card: ", card) + } +} + +func (g *Game) playsCombo(player *Client, card string, num int) { + g.lobby.sendBcast("played_multiple " + player.name + " " + strconv.Itoa(num) + " " + card) + + g.history = nil // TODO + + if num == 2 { + // 2 of a kind - random card + g.favouring = player + g.favourType = 2 + player.sendMsg("q random_who") + } else if num == 3 { + // 3 of a kind - 'stealing' a card + g.favouring = player + g.favourType = 3 + player.sendMsg("q steal_who") + } else { + log.Fatal("what the chuff??") + } +} + +func (g *Game) answersQuestion(player *Client, question string, answer string) { + switch question { + case "defuse_pos": + if !g.defusing { + break + } + + if g.players[g.currentPlayer] != player { + break + } + + pos, err := strconv.Atoi(answer) + if err != nil { + player.sendMsg("q " + question) + break + } + + if pos > g.deck.cardsLeft() { + player.sendMsg("q " + question) + break + } + + g.deck.insertAtPos(pos, "exploding") + g.defusing = false + g.lobby.sendBcast("cards_left "+strconv.Itoa(g.deck.cardsLeft())) + g.incrementTurn() + g.nextTurn() + case "favour_who": + if g.favouring != player { + break + } + + target := g.playerByName(answer) + if target == nil || target == player { + player.sendMsg("q " + question) + break + } + + g.favoured = target + g.lobby.sendComplexBcast("favoured "+player.name+" "+target.name, map[*Client]bool{target: true}) + target.sendMsg("q favour_what " + player.name) + player.sendMsg("lock") // block further play until the transaction completes + case "random_who": + if g.favouring != player { + break + } + + target := g.playerByName(answer) + if target == nil || target == player { + player.sendMsg("q " + question) + break + } + + // removes the card from the target's hand + + // what if they have no cards? + if g.hands[target].getLength() == 0 { + g.lobby.sendBcast("random_n "+player.name+" "+target.name) + g.favouring = nil + g.favoured = nil + break + } + + card := g.hands[target].takeRandom() + + g.lobby.sendComplexBcast("randomed "+player.name+" "+target.name, + map[*Client]bool{target: true, player: true}) + target.sendMsg("random_gave "+player.name+" "+card) + player.sendMsg("random_recv "+target.name+" "+card) + + g.hands[player].addCard(card) + player.sendMsg("hand" + g.hands[player].cardList()) + target.sendMsg("hand" + g.hands[target].cardList()) + g.favouring = nil + g.favoured = nil + case "steal_who": + if g.favouring != player { + break + } + + target := g.playerByName(answer) + if target == nil || target == player { + player.sendMsg("q " + question) + break + } + + g.favoured = target + player.sendMsg("q steal_what") + case "favour_what": + if g.favoured != player { + player.sendMsg("err illegal_move") + break + } + + card, err := strconv.Atoi(answer) + if err != nil { + player.sendMsg("err illegal_move") + break + } + + if card >= g.hands[player].getLength() { + player.sendMsg("err illegal_move") + break + } + + cardText := g.hands[player].getCard(card) + + // TODO: prevent favouring a nope + // this is harder than it seems and will require some changes in the game's logic... + + g.hands[player].removeCard(card) + player.sendMsg("hand" + g.hands[player].cardList()) + + g.hands[g.favouring].addCard(cardText) + g.favouring.sendMsg("hand" + g.hands[g.favouring].cardList()) + + // The favour transaction is complete + g.favouring.sendMsg("unlock") + g.favouring.sendMsg("favour_recv " + g.favoured.name + " " + cardText) + g.favoured.sendMsg("favour_gave " + g.favouring.name + " " + cardText) + g.lobby.sendComplexBcast("favour_complete "+g.favouring.name+" "+g.favoured.name, + map[*Client]bool{g.favoured: true, g.favouring: true}) + g.favouring = nil + g.favoured = nil + case "steal_what": + if g.favouring != player || g.favoured == nil { + break + } + + if g.playerNumber(g.favoured) == -1 { + // The player being asked has left :( + player.sendMsg("q steal_who") + break + } + + if !g.hands[g.favoured].contains(answer) { + g.lobby.sendBcast("steal_n "+g.favouring.name+" "+g.favoured.name+" "+answer) + } else { + g.hands[g.favoured].removeByName(answer) + g.favoured.sendMsg("hand" + g.hands[g.favoured].cardList()) + + g.hands[player].addCard(answer) + player.sendMsg("hand" + g.hands[g.favouring].cardList()) + + g.lobby.sendBcast("steal_y "+g.favouring.name+" "+g.favoured.name+" "+answer) + } + + g.favouring = nil + g.favoured = nil + default: + log.Println("unexpected Q/A: ", question, answer) + } +} + +func (g *Game) incrementTurn() { + // Changes the turn counter to the next player + // (or not, if an attack has been played) + + if g.attack { + g.attack = false + return + } + + g.currentPlayer++ + + return +} + +func (g *Game) nextTurn() { + // Begins the next turn + // NB. this doesn't change currentPlayer + + if g.currentPlayer >= len(g.players) { + g.currentPlayer = 0 + } + + g.lobby.sendBcast("now_playing " + g.players[g.currentPlayer].name) + if g.deck.cardsLeft() == 0 { + g.lobby.sendBcast("draw_pile no") + } else { + g.lobby.sendBcast("draw_pile yes") + } +} + +func (g *Game) start() { + // Starts the game + + g.started = true + + g.lobby.sendBcast("clear_message") + g.lobby.sendBcast("bcast starting") + + // Shuffle the player list and re-send it + rand.Seed(time.Now().UnixNano()) // Hard enough to predict; should be fine + rand.Shuffle(len(g.players), func(i, j int) { + g.players[i], g.players[j] = g.players[j], g.players[i] + }) + g.currentPlayer = 0 + g.lobby.sendBcast("players" + g.playerList()) + g.lobby.sendBcast("now_playing " + g.players[g.currentPlayer].name) + + // Generate the deck + g.deck = newDeck() + + // Give each player a hand + for _, player := range g.players { + // Pass the number of players so the deal method knows how many cards to deal + g.hands[player] = g.deck.dealHand(len(g.players)) + } + + // Shuffle in extra cards + g.deck.addExtraCards(len(g.players)) + + // Sync the cards to the client + for _, player := range g.players { + player.sendMsg("hand" + g.hands[player].cardList()) + } + g.lobby.sendBcast("draw_pile yes") + g.lobby.sendBcast("cards_left "+strconv.Itoa(g.deck.cardsLeft())) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..854c7a9 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/albino/wwwcats + +go 1.14 + +require github.com/gorilla/websocket v1.4.2 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..85efffd --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= diff --git a/lobby.go b/lobby.go new file mode 100644 index 0000000..47de09d --- /dev/null +++ b/lobby.go @@ -0,0 +1,177 @@ +package main + +import ( + "log" + "strings" + "sync" + + "runtime/debug" +) + +type Lobby struct { + name string + + // Client management + + // We need a lock for clients, because although the map is never written concurrently, + // it can be updated while a send operation is taking place, resulting in a race + // condition -> send on closed channel + // The reason for doing all this is so that we can make synchronous writes to the send + // channel of clients, in order to send events in the order they occur. + // Therefore: need to gain a lock when changing OR sending to clients! + + clients map[*Client]bool + clientsMu sync.Mutex + register chan *Client + unregister chan *Client + + currentGame *Game +} + +func newLobby(name string) (lobby *Lobby) { + lobby = &Lobby{ + name: name, + clients: make(map[*Client]bool), + + // We make channels with a small buffer, in case we need to + // write to them from their own goroutine for convenience + + register: make(chan *Client, 64), + unregister: make(chan *Client, 64), + } + lobby.currentGame = newGame(lobby) + return +} + +func (l *Lobby) run(lobbies map[string]*Lobby) { + // Goroutine to deal with all the tasks of the lobby + + defer func() { + if r := recover(); r != nil { + // Recover a panicking lobby to avoid crashing the whole server + for client := range l.clients { + l.destroyClient(client) + } + + delete(lobbies, l.name) + + log.Printf("!!! PANIC in lobby %s: %v !!!", l.name, r) + debug.PrintStack() + } + }() + + for { + select { + + case client := <-l.register: + l.clients[client] = true + + // Sync the join to the game object + l.clientsMu.Lock() + l.currentGame.addPlayer(client) + l.clientsMu.Unlock() + + case client := <-l.unregister: + // Announce and sync + // We need to do this before we close the channel + l.currentGame.removePlayer(client) + + if _, ok := l.clients[client]; ok { + l.destroyClient(client) + } + + if len(l.clients) == 0 { + // The lobby is finished + delete(lobbies, l.name) + return + } + + } + } +} + +func (c *Client) joinToLobby(lobby_name string, player_name string, lobbies map[string]*Lobby) { + var lobby *Lobby + + if lobbies[lobby_name] == nil { + // Create the lobby, and start its goroutine + lobby = newLobby(lobby_name) + lobbies[lobby_name] = lobby + go lobby.run(lobbies) + } else { + lobby = lobbies[lobby_name] + } + + // Avoid nickname collisions + for connected_client := range lobbies[lobby_name].clients { + if connected_client.name == player_name { + select { + case c.send <- []byte("err username_exists"): + default: + close(c.send) + } + // Nobody is getting joined to the lobby today + return + } + } + + c.name = player_name + + lobby.register <- c + c.lobby = lobby +} + +func (l *Lobby) readFromClient(c *Client, msg string) { + fields := strings.Fields(msg) + + if len(fields) < 1 { + return + } + + // Lobby-wide commands + + if fields[0] == "chat" { + l.sendBcast("chat " + c.name + " " + msg[5:]) + return + } + + // Nothing to be done here, hand the message off to the game object + l.currentGame.readFromClient(c, msg) +} + +func (l *Lobby) sendBcast(msg string) { + l.clientsMu.Lock() + defer l.clientsMu.Unlock() + + l.sendBcastRaw(msg) +} + +func (l *Lobby) sendBcastRaw(msg string) { + for client := range l.clients { + client.sendMsg(msg) + } +} + +func (l *Lobby) sendComplexBcast(text string, except map[*Client]bool) { + l.clientsMu.Lock() + defer l.clientsMu.Unlock() + + for client := range l.clients { + _, ok := except[client] + if ok { + continue + } + + client.sendMsg(text) + } +} + +func (l *Lobby) destroyClient(client *Client) { + l.clientsMu.Lock() + defer l.clientsMu.Unlock() + + client.conn.Close() + delete(l.clients, client) + close(client.send) + log.Printf("DELETING %s", client.name) +} diff --git a/public_html/about.html b/public_html/about.html new file mode 100644 index 0000000..e6a5cbb --- /dev/null +++ b/public_html/about.html @@ -0,0 +1,44 @@ + + + + + About Detonating Cats + + + +

About Detonating Cats

+

+ Detonating Cats is a web-based clone of the popular + Exploding Kittens card game, written by Lawrence Brown to + stave off boredom during the coronavirus lockdown of December 2020. +

+

+ The game's art and code are original, although the concept and Exploding Kittens trademark are + property of Exploding Kittens Inc. Please don't sue me. +

+

+ The game is licensed under the GNU AGPLv3 license, which grants you the freedom to run, modify and + share it, as long as you continue to provide the source code of your copy under the same (or + compatible) license. For details and the full license text, please see the LICENSE + document distributed alongside this program. +

+

+ The source code, including full instructions for compiling and running the game on your own computer, + is available on GitHub: albino/wwwcats. +

+ + diff --git a/public_html/assets/atomic.ogg b/public_html/assets/atomic.ogg new file mode 100644 index 0000000..18d48b3 --- /dev/null +++ b/public_html/assets/atomic.ogg Binary files differ diff --git a/public_html/assets/card_attack.png b/public_html/assets/card_attack.png new file mode 100644 index 0000000..d98e18f --- /dev/null +++ b/public_html/assets/card_attack.png Binary files differ diff --git a/public_html/assets/card_back.png b/public_html/assets/card_back.png new file mode 100644 index 0000000..e673225 --- /dev/null +++ b/public_html/assets/card_back.png Binary files differ diff --git a/public_html/assets/card_defuse.png b/public_html/assets/card_defuse.png new file mode 100644 index 0000000..a9f4398 --- /dev/null +++ b/public_html/assets/card_defuse.png Binary files differ diff --git a/public_html/assets/card_exploding.png b/public_html/assets/card_exploding.png new file mode 100644 index 0000000..ada1d9d --- /dev/null +++ b/public_html/assets/card_exploding.png Binary files differ diff --git a/public_html/assets/card_favour.png b/public_html/assets/card_favour.png new file mode 100644 index 0000000..593409c --- /dev/null +++ b/public_html/assets/card_favour.png Binary files differ diff --git a/public_html/assets/card_nope.png b/public_html/assets/card_nope.png new file mode 100644 index 0000000..7e66287 --- /dev/null +++ b/public_html/assets/card_nope.png Binary files differ diff --git a/public_html/assets/card_random1.png b/public_html/assets/card_random1.png new file mode 100644 index 0000000..e46b8fc --- /dev/null +++ b/public_html/assets/card_random1.png Binary files differ diff --git a/public_html/assets/card_random2.png b/public_html/assets/card_random2.png new file mode 100644 index 0000000..dfca2f2 --- /dev/null +++ b/public_html/assets/card_random2.png Binary files differ diff --git a/public_html/assets/card_random3.png b/public_html/assets/card_random3.png new file mode 100644 index 0000000..7fc162b --- /dev/null +++ b/public_html/assets/card_random3.png Binary files differ diff --git a/public_html/assets/card_random4.png b/public_html/assets/card_random4.png new file mode 100644 index 0000000..cc16d50 --- /dev/null +++ b/public_html/assets/card_random4.png Binary files differ diff --git a/public_html/assets/card_random5.png b/public_html/assets/card_random5.png new file mode 100644 index 0000000..693afe4 --- /dev/null +++ b/public_html/assets/card_random5.png Binary files differ diff --git a/public_html/assets/card_see3.png b/public_html/assets/card_see3.png new file mode 100644 index 0000000..e7c4c05 --- /dev/null +++ b/public_html/assets/card_see3.png Binary files differ diff --git a/public_html/assets/card_shuffle.png b/public_html/assets/card_shuffle.png new file mode 100644 index 0000000..f139839 --- /dev/null +++ b/public_html/assets/card_shuffle.png Binary files differ diff --git a/public_html/assets/card_skip.png b/public_html/assets/card_skip.png new file mode 100644 index 0000000..32584a0 --- /dev/null +++ b/public_html/assets/card_skip.png Binary files differ diff --git a/public_html/assets/wood.jpg b/public_html/assets/wood.jpg new file mode 100644 index 0000000..6d62a51 --- /dev/null +++ b/public_html/assets/wood.jpg Binary files differ diff --git a/public_html/changelog.html b/public_html/changelog.html new file mode 100644 index 0000000..2ddb065 --- /dev/null +++ b/public_html/changelog.html @@ -0,0 +1,33 @@ + + + + + Changelog + + + +

+ 2020-01-25: Added a 'your turn' notification. +

+

+ 2020-01-22: You can no longer NOPE a Detonating Cat. You no longer get kicked out of the game + when trying to steal a card from someone. Tried to stop the server crashing all the time. +

+

+ 2020-01-19: Added a point-and-click player/card chooser. +

+

+ 2020-01-18: The game client now checks that the correct version is running. Added a new + logging system to help identify bugs in future. +

+

+ 2020-01-17: Bug fixes: the game no longer crashes when you fail to answer a question, try + to NOPE a Favour card, or ask someone with an empty hand for a random card. Networking changes so + that messages (usually) appear in the right order. +

+

+ 2020-01-06: Welcome to Detonating Cats (beta)! The game is just about playable + but still very much a work in progress. Feedback is welcome. +

+ + diff --git a/public_html/game.js b/public_html/game.js new file mode 100644 index 0000000..efa3f09 --- /dev/null +++ b/public_html/game.js @@ -0,0 +1,576 @@ +var GameState = function() { + // Websocket handle + + this.conn = null; + + this.started = false; + this.defusing = false; + this.ourTurn = false; + this.locked = false; + this.favouring = false; + this.combo = 1; + + // Player and lobby name + + this.name = ""; + this.lobby = ""; + + this.nowPlaying = ""; + this.players = []; + + // Assets + + this.assets = {}; + + this.loadAsset = function(url, el) { + this.assets[url] = el; + } + + this.resetButtons = function() { + let buttons = $(".combo-btn").toArray(); + buttons.forEach(function(btn) { + $(btn).removeClass("active"); + }); + this.combo = 1; + } + + this.start = function() { + // Run the game! + // Doesn't actually _start_ the game, but rather starts the game client + + $("#player-name").text(this.name); + $("#lobby-name").text(this.lobby); + + // Scroll wheel hack - allows the user to scroll the card deck horizontally + $("#card-deck").mousewheel(function(ev, delta) { + this.scrollLeft -= (delta * 30); + ev.preventDefault(); + }); + + // Send the contents of the chat box when enter is pressed + // feat. a stupid scope hack + (function (gameState) { + $("#chat-message").keydown( function(ev) { + if (ev.key === "Enter") { + if ($( this ).val().startsWith("/")) { + // Send as a command + let msg = $( this ).val().substring(1); + gameState.send(msg); + } else { + // Send as a message + let msg = $( this ).val(); + gameState.send("chat " + msg); + } + + // Clear the box + $( this ).val(""); + } + }); + })(this); + + // Draw a card + (function(gameState) { + $("#draw-pile").on('click', function() { + if (gameState.ourTurn) { + gameState.send("draw"); + } + }); + })(this); + + // 2x and 3x buttons + (function(gameState) { + let buttons = $(".combo-btn").toArray(); + buttons.forEach(function(btn) { + $(btn).on("click", function() { + // deactive all the buttons, except this one + buttons.forEach(function(b) { + if (b != btn) { + $(b).removeClass("active"); + } + }); + $(this).toggleClass("active"); + + if ($(this).hasClass("active")) { + gameState.combo = $(this).attr("id") == "2x-button" ? 2 : 3; + } else { + gameState.combo = 0; + } + }); + }); + })(this); + + // Sort button + (function(gameState) { + $("#sort-button").on("click", function() { + gameState.send("sort"); + }); + })(this); + + // Mute button + (function(gameState) { + $("#mute-button").on("click", function() { + if (gameState.assets["atomic.ogg"].muted) { + gameState.assets["atomic.ogg"].muted = false; + $("#mute-button").text("Mute sound"); + } else { + gameState.assets["atomic.ogg"].muted = true; + $("#mute-button").text("Unmute sound"); + } + }); + })(this); + + (function(gameState) { + window.onbeforeunload = function () { + if (gameState.conn.readyState !== WebSocket.CLOSED) { + gameState.conn.onclose = null; + return ""; // Display confirmation message + } + }; + })(this); + + this.console("Welcome to Detonating Cats!"); + + // We're ready to bring the game board into view + $("body").css("background-color", "black"); + $("#welcome").toggleClass("reveal"); + $("#game-view").toggleClass("reveal"); + + this.started = true; + } + + this.console = function(msg) { + $("#game-log").append(msg+"
"); + + // Scroll to bottom + $("#game-log").scrollTop($("#game-log")[0].scrollHeight); + } + + this.drawPlayerList = function() { + $("#player-list").empty(); + this.players.forEach(x => $("#player-list").append("
  • "+x+"
  • ")); + + (function(gameState) { + $("#player-list > li").each( function() { + if ($( this ).html() == gameState.nowPlaying) { + $( this ).append(" *"); + } + } ); + })(this); + } + + this.readFromServer = function(ev) { + var parts = ev.data.split(" "); + + // TODO: cleanup and refactor + + if (parts[0] == "err") { + alert(strings[parts[1]]); + this.conn.close(); + this.conn = null; + return; + } + if (parts[0] == "version" && parts[1] != REVISION) { + alert(strings["bad_version"]); + this.conn.close(); + this.conn = null; + return; + } + + if (parts[0] == "joins" && parts[1] == this.name) { + // We're in! + if (!this.started) { + this.start(); + } + return; + } + + if (parts[0] == "spectators") { + // Update spectators list + $("#spectator-list").empty(); + + for (var i=1; i < parts.length; i++) { + let encoded = entities(parts[i]); + $("#spectator-list").append("
  • "+encoded+"
  • "); + } + + return; + } + + if (parts[0] == "players") { + // Update players list + this.players = parts.slice(1).map(x => entities(x)); + this.drawPlayerList(); + + return; + } + + if (parts[0] == "joins") { + // Announce in console + let encoded = entities(parts[1]); + this.console(""+encoded+" joined as a spectator."); + + // Update spectators list + $("#spectator-list").append("
  • "+encoded+"
  • "); + + return; + } + + if (parts[0] == "parts") { + // Announce in console + let encoded = entities(parts[1]); + this.console(""+encoded+" left the game."); + + // Update spectators list if appropriate + $("#spectator-list > li").each( function() { + if ($( this ).html() == encoded) { + $( this ).remove(); + } + } ); + + return; + } + + if (parts[0] == "upgrades") { + // Announce in console + let encoded = entities(parts[1]); + this.console(""+encoded+" is now playing."); + + // Update spectators list + $("#spectator-list > li").each( function() { + if ($( this ).html() == encoded) { + $( this ).remove(); + } + } ); + + // Server will send players list separately, no worries + + return; + } + + if (parts[0] == "downgrades") { + // Announce in console + let encoded = entities(parts[1]); + this.console(""+encoded+" is now spectating."); + + // Update spectators list + $("#spectator-list").append("
  • "+encoded+"
  • "); + + // Server will send players list separately, no worries + + return; + } + + if (parts[0] == "chat") { + let encodedName = entities(parts[1]); + let encodedMsg = entities(ev.data.substring(parts[1].length + 5)); + this.console(encodedName+": "+encodedMsg); + + return; + } + + if (parts[0] == "message") { + // This refers to the 'message' container in the middle of the board + // that can be used to display useful game info + let msg = strings["message_"+ev.data.substring(8)]; + $("#message").html(msg); + $("#message-container").removeClass("reveal"); + + return; + } + + if (parts[0] == "clear_message") { + $("#message").html(""); + $("#message-container").addClass("reveal"); + + return; + } + + if (parts[0] == "bcast") { + let msg = strings["bcast_"+ev.data.substring(6)]; + this.console(msg); + + return; + } + + if (parts[0] == "hand") { + $("#card-deck").empty(); + + for (var i=1; i < parts.length; i++) { + var card = $(""); + + (function (gameState, cardNo, cardName) { + card.on("click", function() { + if (gameState.locked) { + return; + } + + if (gameState.favouring) { + // Favour NOPE-logic is handled server-side :) + gameState.send("a favour_what "+cardNo.toString()); + gameState.favouring = false; + return; + } + + if (gameState.combo > 1) { + // Do we have enough cards? + let cards = 0; + for (var j=1; j < parts.length; j++) { + if (parts[j] == cardName) { + cards++; + if (cards == gameState.combo) { + break; + } + } + } + if (cards < gameState.combo) { + gameState.console("You don't have enough " + strings["card_"+cardName] + + " cards to do that!"); + return; + } + + if (gameState.ourTurn) { + gameState.send("play_multiple "+gameState.combo.toString()+" "+ + cardName); + gameState.resetButtons(); + return; + } + } + + if ((gameState.ourTurn || cardName === "nope") && !cardName.startsWith("random") + && ( (!gameState.defusing && cardName !== "defuse") + || (gameState.defusing && cardName === "defuse") )) { + gameState.send("play "+cardNo.toString()); + gameState.defusing = false; + } + }); + })(this, i-1, parts[i]); + + $("#card-deck").append(card); + } + + return; + } + + if (ev.data == "draw_pile yes") { + $("#draw-pile").html(""); + $("#draw-pile-counter").removeClass("reveal"); + return; + } + if (ev.data == "draw_pile no") { + $("#draw-pile").html(""); + $("#draw-pile-counter").addClass("reveal"); + return; + } + if (parts[0] == "cards_left") { + $("#remaining-card-count").text(parts[1]); + return; + } + + if (parts[0] == "now_playing") { + this.nowPlaying = entities(parts[1]); + this.console("It is "+this.nowPlaying+"'s turn."); + + this.drawPlayerList(); + + // cmp with raw data because name isn't stored encoded + if (parts[1] == this.name) { + this.ourTurn = true; + this.assets["atomic.ogg"].play(); + document.title = strings["title_alert"]; + } else { + this.ourTurn = false; + document.title = strings["title_normal"]; // a bit fragile, needs to be same as + } + + return; + } + + if (parts[0] == "drew") { + this.console("You drew <span style='color:orange'>"+strings["card_"+parts[1]]+".</span>"); + + // Animation + cardHUD(parts[1], 2000); + + return; + } + if (parts[0] == "drew_other") { + let encoded = entities(parts[1]); + this.console("<span style='color:#ccc'>"+encoded+" drew a card.</span>"); + + // Animation + $("#draw-pile-animation").html("<img src='assets/card_back.png' class='card' />"); + animate("#draw-pile-animation", "right", 125, -150, -15, "px"); + + return; + } + + if (parts[0] == "exploded") { + let encoded = entities(parts[1]); + this.console("<span style='color:purple'>"+encoded+" drew a Detonating Cat!</span>"); + + cardHUD("exploding", 1000); + + return; + } + + if (parts[0] == "wins") { + this.ourTurn = false; + let encoded = entities(parts[1]); + this.console("<span style='color:deepskyblue'>"+encoded+" won!</span>"); + this.nowPlaying = ""; + return; + } + + if (parts[0] == "defusing") { + this.console(strings["must_defuse"]); + this.defusing = true; + return; + } + + if (parts[0] == "played") { + let encoded = entities(parts[1]); + this.console(encoded+" played "+strings["card_"+parts[2]]+"."); + + $("#discard-pile").html("<img class='card' src='assets/card_"+parts[2]+".png' />"); + + if (parts[2] != "see3") { + cardHUD(parts[2], 1000); + } + + return; + } + + if (parts[0] == "played_multiple") { + let encoded = entities(parts[1]); + this.console(encoded+" played "+parts[2]+"x "+strings["card_"+parts[3]]+"."); + + $("#discard-pile").html("<img class='card' src='assets/card_"+parts[3]+".png' />"); + + if (parts[2] == 2) { + cardHUD3([parts[3], parts[3]], 1000); + } else { + cardHUD3([parts[3], parts[3], parts[3]], 1000); + } + + return; + } + + if (parts[0] == "no_discard") { + $("#discard-pile").html(""); + return; + } + + if (parts[0] == "q") { + if (parts[1] == "favour_what") { + this.favouring = true; + let perpetrator = entities(parts[2]); + this.console("<span style='color:deepskyblue'>" + perpetrator + + " is asking you for a favour.</span>"); + } else if (parts[1] == "favour_who" || parts[1] == "random_who" || parts[1] == "steal_who") { + (function (gameState) { + modalChoice(function(player) { + gameState.send("a "+parts[1]+" "+player); + }, strings["question_"+parts[1]], gameState.players, entities(gameState.name), null); + })(this); + } else if (parts[1] == "steal_what") { + (function (gameState) { + modalChoice(function(card) { + gameState.send("a "+parts[1]+" "+card); + }, strings["question_"+parts[1]], cards, null, x => strings["card_"+x]); + })(this); + } else { + ans = prompt(strings["question_"+parts[1]]); + this.send("a "+parts[1]+" "+ans); + } + + return; + } + if (parts[0] == "q_cancel") { + this.favouring = false; + } + + if (parts[0] == "seen") { + cardHUD3(parts.slice(1), 2000); + this.console("You saw "+strings["card_"+parts[1]]+", "+strings["card_"+parts[2]]+" and "+ + strings["card_"+parts[3]]+"."); + return; + } + + if (parts[0] == "favoured" || parts[0] == "favour_complete") { + let perpetrator = entities(parts[1]); + let victim = entities(parts[2]); + if (parts[0] == "favoured") { + this.console(perpetrator+" is asking "+victim+" for a favour."); + } else { + this.console(victim+" gave "+perpetrator+" a favour."); + } + return; + } + if (parts[0] == "favour_recv" || parts[0] == "favour_gave") { + let remotePlayer = entities(parts[1]); + let card = strings["card_"+parts[2]]; + if (parts[0] == "favour_recv") { + this.console(remotePlayer + " gave you <span style='color:orange'>" + card + "</span>."); + cardHUD(parts[2], 2000); + } else { + this.console("You gave " + remotePlayer + " <span style='color:orange'>" + card + "</span>."); + } + return; + } + + if (parts[0] == "randomed" || parts[0] == "random_n") { + let perpetrator = entities(parts[1]); + let victim = entities(parts[2]); + if (parts[0] == "randomed") { + this.console(perpetrator+" took a random card from "+victim+"."); + } else { + this.console(perpetrator+" asked "+victim+ + " for a random card, but they had nothing to give away!"); + } + + return; + } + if (parts[0] == "random_recv" || parts[0] == "random_gave") { + let remotePlayer = entities(parts[1]); + let card = strings["card_"+parts[2]]; + if (parts[0] == "random_recv") { + this.console("You randomly took <span style='color:orange'>"+card+"</span> from "+ + remotePlayer+"."); + } else { + this.console(remotePlayer+" randomly took <span style='color:orange'>"+card+ + "</span> from you."); + } + cardHUD(parts[2], 2000); + return; + } + + if (parts[0] == "steal_n" || parts[0] == "steal_y") { + let perpetrator = entities(parts[1]); + let victim = entities(parts[2]); + if (parts[0] == "steal_y") { + this.console(perpetrator+" stole <span style='color:orange'>"+ + strings["card_"+parts[3]]+"</span> from "+victim+"!"); + cardHUD(parts[3], 2000); + } else { + this.console(perpetrator+" asked "+victim+" for <span style='color:orange'>" + +strings["card_"+parts[3]]+"</span>, but ended up empty-handed!"); + } + return; + } + + if (parts[0] == "lock") { + this.locked = true; + return; + } + if (parts[0] == "unlock") { + this.locked = false; + return; + } + + console.warn("WARN: received unknown data from server: "+ev.data); + } + + this.send = function(msg) { + this.conn.send(msg); + } +} diff --git a/public_html/index.html b/public_html/index.html new file mode 100644 index 0000000..46371b7 --- /dev/null +++ b/public_html/index.html @@ -0,0 +1,120 @@ +<!DOCTYPE HTML> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>Detonating Cats + + + + + + + + +
    +

    Loading assets, please wait.

    +

    0 assets loaded.

    +

    (If this takes too long, try force-reloading with Ctrl+F5...)

    +
    + +
    + + + + + + +
    +

    Welcome to DETONATING CATS (beta)

    + + + + + + + + + +
    + +
    +

    Changelog

    + +
    +

    Privacy notice: game and chat messages may be logged to help with debugging. + These logs will not be shared. Your IP address and browser fingerprint are never logged.

    +
    +
    + +
    +
    +
    + + DETONATING CATS (info) + + + @ + +
    + +
    +
    +
    + +
    + + Cards left: + + + +
    + +
    + +
    +
    + +
    +
    +
    +
    + + +
    + +
    + + + + +
    + + +
    + + + + + + + + + + diff --git a/public_html/init.js b/public_html/init.js new file mode 100644 index 0000000..3a6f0b3 --- /dev/null +++ b/public_html/init.js @@ -0,0 +1,132 @@ +var REVISION = "9"; + +(function () { + + // Everything that runs as soon as the page loads; sets up the page and handles the + // connection to the server. + + var gameState = new GameState(); + + $( document ).ready(function () { + // Set up the game + + // Check that the JS and HTML have matching versions + // (caching is weird) + var htmlRev = $("#REVISION").val(); + if (htmlRev != REVISION) { + setTimeout(function() { + location.reload(); + }, 1500); + return; + } + + // Create the changelog iframe + // We use this roundabout method to make sure the changelog is always + // re-downloaded every time REVISION changes + var changelog = document.createElement("iframe"); + changelog.setAttribute("src", "changelog.html?rev="+REVISION); + changelog.id = "changelog"; + document.getElementById("changelog-container").appendChild(changelog); + + // Load assets + var assets = [ + "wood.jpg", + "card_back.png", + "card_defuse.png", + "card_exploding.png", + "card_nope.png", + "card_skip.png", + "card_attack.png", + "card_see3.png", + "card_favour.png", + "card_shuffle.png", + "card_random1.png", + "card_random2.png", + "card_random3.png", + "card_random4.png", + "card_random5.png", + "atomic.ogg" + ]; + var promises = []; + var assetsLoaded = 0; + + for (var i = 0; i < assets.length; i++) { + (function(url, promise) { + let ext = url.split(".").pop(); + var el; + if (ext == "jpg" || ext == "png") { + el = new Image(); + } else { + el = new Audio(); + } + + el.onload = function() { + // Increment the loading counter to convince the user we're doing something + assetsLoaded += 1; + document.getElementById("loading-assets").innerHTML = assetsLoaded; + + promise.resolve(); + }; + if (ext == "ogg") { + el.oncanplaythrough = el.onload; + } + + el.src = "assets/"+url; + + gameState.loadAsset(url, el); + })(assets[i], promises[i] = $.Deferred()); + } + + // Once all the promises have resolved (all assets loaded), call the function to + // display the welcome page. + $.when.apply($, promises).done(welcomePage); + }); + + function welcomePage() { + // Transition loading screen -> welcome page + + $("#welcome-join").bind("click touchstart", joinGame); + + $("#loading").toggleClass("reveal"); + $("#welcome").toggleClass("reveal"); + } + + function joinGame() { + // Communicate with the server, make sure we join the game ok, render the board + + if (gameState.conn != null) { + alert(strings["already_connecting"]); + return; + } + + gameState.lobby = $("#welcome-lobby").val() || $("#welcome-lobby").attr("placeholder"); + gameState.name = $("#welcome-username").val() || $("#welcome-username").attr("placeholder"); + + if (gameState.name.includes(" ")) { + alert(strings["one_word"]); + return; + } + if (gameState.lobby.includes(" ")) { + alert(strings["lobby_one_word"]); + return; + } + + gameState.conn = new WebSocket("ws://" + location.host + "/ws"); + + gameState.conn.onopen = function () { + gameState.conn.send("join_lobby " + gameState.lobby + " " + gameState.name); + } + + gameState.conn.onclose = function () { + alert(strings["conn_closed"]); + location.reload(); + }; + + gameState.conn.onmessage = function(ev) { + // We wrap this in an anonymous function so that 'this' + // will refer to the GameState object and not the WebSocket + // (I don't have a clue how javascript OOP works) + gameState.readFromServer(ev); + }; + } +})(); diff --git a/public_html/strings.js b/public_html/strings.js new file mode 100644 index 0000000..55fb7e2 --- /dev/null +++ b/public_html/strings.js @@ -0,0 +1,57 @@ +var strings = { + "card_attack": "Attack", + "card_defuse": "Defuse", + "card_exploding": "Detonating Cat!", + "card_favour": "Favour", + "card_nope": "Nope!", + "card_random1": "BEANS Cat", + "card_random2": "CHUFFing Cat", + "card_random3": "Fridge Cat", + "card_random4": "Tacky Yack Cat", + "card_random5": "Bin Guitar Cat", + "card_see3": "See the Future (x3)", + "card_shuffle": "Shuffle", + "card_skip": "Skip", + "username_exists": "That username has already been taken. Please try and be more original.", + "already_connecting": "There is already an active connection. Please reload the page if this problem persists.", + "one_word": "Your name should be one word.", + "lobby_one_word": "Lobby names can only be one word.", + "illegal_move": "Sorry, but the server has disconnected you for moving improperly. This is either a bug or you are trying to cheat.", + "message_spectating": "You are currently spectating; to join, type /join.", + "message_spectating_started": "You are spectating and can join once this round has finished.", + "message_spectating_exploded": "You are out for this round.", + "message_playing": "Type /start to start the game, or /leave to spectate.", + "bcast_starting": "The game is starting!", + "bcast_new_game": "A new game has started.", + "bcast_no_nope": "Nope! There is nothing to Nope!", + "bcast_favour_cancel": "The favour was cancelled.", + "bcast_min_players": "There must be at least 2 players in a game.", + "bcast_max_players": "There cannot be more than 6 players in a game.", + "bcast_high_players": "You are playing with 6 players - the game will still work, but be aware that this is more than intended!", + "must_defuse": "You must defuse the Detonating Cat.", + "question_defuse_pos": "Where should the Detonating Cat be placed in the deck? (0 = on top)", + "question_favour_who": "Who do you want to ask for a favour?", + "question_random_who": "Who would you like to ask for a random card?", + "question_steal_who": "Who would you like to steal a card from?", + "question_steal_what": "Which card would you like to steal?", + "conn_closed": "The connection to the server was lost.", + "bad_version": "The game server is running a different version of the game. If this problem persists, please try hard-reloading the page by pressing Ctrl+F5 or clearing your browser cache.", + "title_normal": "Detonating Cats", + "title_alert": "* YOUR TURN! * (Detonating Cats)" +}; + +var cards = [ + "attack", + "defuse", + "exploding", + "favour", + "nope", + "random1", + "random2", + "random3", + "random4", + "random5", + "see3", + "shuffle", + "skip" +]; diff --git a/public_html/style.css b/public_html/style.css new file mode 100644 index 0000000..5ccc360 --- /dev/null +++ b/public_html/style.css @@ -0,0 +1,295 @@ +* { + margin: 0; + font-family: sans-serif; +} + +.reveal { + display: none; +} + +div#loading, div#welcome { + margin: 10px; +} +div#welcome > p { + margin-bottom: 10px; +} +div#welcome > table { + max-width: 800px; +} +td.welcome-pane { + padding: 20px; + height: 300px; +} +td.welcome-pane > h1 { + font-size: 20px; + margin-bottom: 10px; +} +table#login-form { + margin-bottom: 10px; +} +tr#privacy { + font-size: 10px; + text-decoration: italic; + color: #333; +} + +iframe#changelog { + height: 100% +} +body.changelog { + padding: 10px; +} +p.changelog-entry { + line-height: 1.6; + margin-bottom: 1em; +} +p.changelog-entry:last-of-type { + margin-bottom: 0; +} + +div#game-view { + height: 100%; + width: 100%; + position: absolute; +} + +div#board { + background-image: url("assets/wood.jpg"); + width: 800px; + height: 800px; + border: 1px solid #9c3500; + position: absolute; + top: 20px; + left: 20px; +} + +.shade { + background-color: rgba(0, 0, 0, 0.5); + padding: 2px; + color: #ccc; +} +.shade a{ + color: inherit; + text-decoration: none; +} +.shade a:hover { + text-decoration: underline; +} + +span.left-text { + float: left; +} +span.right-text { + float: right; +} + +div#message-container { + position: absolute; + top: 450px; + width: 800px; + text-align: center; +} +span#message { + background-color: rgba(0, 0, 0, 0.5); + padding: 5px; + color: white; + font-size: 30px; + margin-left: auto; + margin-right: auto; +} + +.card { + height: 250px; + border-radius: 10px; + border: 5px solid white; +} + +#discard-pile, #draw-pile, #draw-pile-animation { + position: absolute; + top: 150px; + transition: 0.3s top, 0.3s left, 0.3s right; +} +#discard-pile { + left: 125px; +} +#discard-pile:hover { + left: 120px; +} +#draw-pile { + right: 125px; +} +#draw-pile:hover { + right: 120px; +} +#draw-pile .card:hover, #discard-pile .card:hover { + height: 260px; +} +#draw-pile .card, #discard-pile .card, #draw-pile-animation .card { + transition: 0.3s height; + display: block; /* To prevent trailing whitespace */ +} +#draw-pile:hover, #discard-pile:hover { + top: 145px; +} + +#draw-pile-animation { + transition: none; +} + +#card-deck { + overflow: auto; + white-space: nowrap; + background-color: rgba(255, 255, 255, 0); + position: absolute; + bottom: 0px; + width: 100%; +} +#card-deck .card { + height: 150px; + border-radius: 7px; + border: 3px solid white; + transition: 0.3s height; + margin-right: 5px; +} +#card-deck .card:hover { + height: 250px; + border-radius: 10px; + border: 5px solid white; +} + +span#draw-pile-counter { + position: absolute; + top: 415px; + right: 115px; + width: 185px; + color: white; + text-shadow: 1px 1px 1px #222; +} + +div#sidebar { + position: absolute; + top: 20px; + left: 840px; + color: white; + width: 250px; + height: 800px; + display: flex; + flex-direction: column; + background-color: black; + z-index: 1; +} + +div.sidebar-box { + padding: 5px; + border: 1px solid white; + margin-bottom: 10px; +} +div.sidebar-box:last-child { + margin-bottom: 0; +} + +div#game-log { + overflow: auto; + flex: 1; + flex-direction: column; + overflow: auto; +} +div#game-log-container { + flex: 1; + display: flex; + flex-direction: column; + min-height: min-content; + overflow: auto; +} + +div#chat-container { + display: flex; + flex-direction: row; +} +input#chat-message { + flex: 1 1 auto; +} + +div.card-hud { + z-index: 1; + background-color: rgba(0, 0, 0, 0.5); + opacity: 0; + transition: 0.5s opacity; + padding-top: 200px; + height: 600px; + width: 800px; + position: absolute; +} +div#card-hud > img.card { + margin: auto; + height: 400px; + display: block; +} +div#card-hud-3-wrapper { + padding-top: 242px; + height: 558px; +} +div#card-hud-3 { + text-align: center; +} +div#card-hud-3 > img.card { + display: inline-block; + height: 300px; + margin-right: 20px; +} +div#card-hud-3 > img.card:last-child { + margin-right: 0; +} + +div.modal-hud { + z-index: 1; + background-color: rgba(0, 0, 0, 0.5); + opacity: 0; + transition: 0.5s opacity; + height: 600px; + padding-top: 200px; + width: 800px; + position: absolute; +} +div.modal { + background-color: white; + color: #333; + width: 360px; + height: 360px; + overflow: auto; + margin-left: auto; + margin-right: auto; + border: 2px solid #777; + padding: 20px; + border-radius: 10px; +} +ul.modal-options { + margin-top: 10px; + padding-left: 0; +} +ul.modal-options li { + list-style: none; + padding: 10px; + background-color: #a8d9ff; + margin-left: auto; + margin-right: auto; + width: 200px; + border: 2px solid #0090ff; + margin-bottom: 10px; + cursor: pointer; +} +ul.modal-options li:hover { + background-color: #45aeff; +} + +div#buttons-container { + position: absolute; + top: 830px; + left: 20px; +} +button.combo-btn.active::before { + content: "[[ "; +} +button.combo-btn.active::after { + content: " ]]"; +} diff --git a/public_html/util.js b/public_html/util.js new file mode 100644 index 0000000..f5ef0d2 --- /dev/null +++ b/public_html/util.js @@ -0,0 +1,118 @@ +// Utility functions + +function entities(str) { + // jQuery hack, I don't know how this works either + return $("
    ").text(str).html(); +} + +function animate(element, property, vInitial, vFinal, incr, unit) { + // Animate a CSS property + + $(element).removeClass("reveal"); + $(element).css(property, vInitial); + var vCurrent = vInitial; + + var id = setInterval(frame, 15); + function frame() { + let hasFinished = false; + if (vInitial < vFinal) { + hasFinished = vCurrent >= vFinal; + } else { + hasFinished = vCurrent <= vFinal; + } + + if (hasFinished) { + clearInterval(id); + $(element).addClass("reveal"); + $(element).css(property, vInitial.toString() + unit); + return; + } + + vCurrent += incr; + $(element).css(property, vCurrent.toString() + unit); + } +} + +function cardHUD(card, time) { + $("#card-hud").html(""); + $("#card-hud").removeClass("reveal"); + // The opacity property needs a delay or the animation doesn't work + // no idea why, better not to ask + setTimeout(function() { + $("#card-hud").css("opacity", "1"); + }, 100); + + setTimeout(function() { + $("#card-hud").css("opacity", "0"); + + setTimeout(function() { + $("#card-hud").empty(); + $("#card-hud").addClass("reveal"); + }, 500); + }, time); +} + +function cardHUD3(cards, time) { + cards.forEach(function(card) { + $("#card-hud-3").append(""); + }); + $("#card-hud-3-wrapper").removeClass("reveal"); + + setTimeout(function() { + $("#card-hud-3-wrapper").css("opacity", "1"); + }, 100); + + setTimeout(function() { + $("#card-hud-3-wrapper").css("opacity", "0"); + + setTimeout(function() { + $("#card-hud-3").empty(); + $("#card-hud-3-wrapper").addClass("reveal"); + }, 500); + }, time); +} + +function modalChoice(cb, question, options, exclude, transform) { + // NO anti-xss + + let modalHud = document.createElement("DIV"); + $(modalHud).addClass("modal-hud"); + let modal = document.createElement("DIV"); + $(modal).addClass("modal"); + $(modal).html(""+question+""); + + let modalOptions = document.createElement("UL"); + $(modalOptions).addClass("modal-options"); + + options.forEach(function (opt) { + if (opt === exclude) { + return; + } + + let button = document.createElement("LI"); + + if (transform) { + button.innerHTML = transform(opt); + } else { + button.innerHTML = opt; + } + + button.addEventListener("click", function() { + cb(opt); + + $(modalHud).css("opacity", "0"); + setTimeout(function() { + document.getElementById("modal-container").removeChild(modalHud); + }, 500); + }, false); + modalOptions.appendChild(button); + }); + + modal.appendChild(modalOptions); + modalHud.appendChild(modal); + document.getElementById("modal-container").appendChild(modalHud); + + setTimeout(function() { + $(modalHud).css("opacity", "1"); + }, 100); +} diff --git a/tools/release.sh b/tools/release.sh new file mode 100755 index 0000000..f25d98d --- /dev/null +++ b/tools/release.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# We store the current revision number in a few of the game's source files, +# so that on startup, the client can check that everything is correct +# (web caching is flaky) +# This script updates all of those files at once (HACK) + +# We can safely get the revision number from wwwcats.go this way +# because it won't compile if there is more than one 'var REVISION' + +if [ ! -f wwwcats.go ]; then + echo "Can't find source files" + exit -1 +fi + +VERSION=$(egrep "^var REVISION = " wwwcats.go | rev | cut -d' ' -f 1 | rev) +NEW_VERSION=$((VERSION+1)) + +sed -i "s/var REVISION = $VERSION/var REVISION = $NEW_VERSION/" wwwcats.go +sed -i "s/var REVISION = \"$VERSION\";/var REVISION = \"$NEW_VERSION\";/" public_html/init.js +sed -i "s/id=\"REVISION\" value=\"$VERSION\"/id=\"REVISION\" value=\"$NEW_VERSION\"/" public_html/index.html + +echo "Updated to version $NEW_VERSION" diff --git a/wwwcats.go b/wwwcats.go new file mode 100644 index 0000000..858dcf1 --- /dev/null +++ b/wwwcats.go @@ -0,0 +1,54 @@ +package main + +import ( + "flag" + "log" + "net/http" + + "github.com/gorilla/websocket" +) + +var addr = flag.String("l", ":8080", "http service address") + +var REVISION = 9 + +func main() { + flag.Parse() + + // Create a global list of lobbies + lobbies := make(map[string]*Lobby) + + // Serve the client-side software + fs := http.FileServer(http.Dir("public_html")) + http.Handle("/", fs) + + // Handle incoming websocket connections + http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { + handleConnections(w, r, lobbies) + }) + + // Start the server + log.Println("Now listening on", *addr) + log.Fatal(http.ListenAndServe(*addr, nil)) +} + +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +// Upgrade incoming connections to websockets +func handleConnections(w http.ResponseWriter, r *http.Request, lobbies map[string]*Lobby) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log.Println(err) + return + } + + // Instantiate the new client object + client := &Client{conn: conn, send: make(chan []byte, 256)} + + // Hand the client off to these goroutines which will handle all i/o + go client.readPump(lobbies) + go client.writePump() +}