Repository: Igoorx/PyRoyale
Branch: master
Commit: 2f790e7862a6
Files: 15
Total size: 93.6 KB
Directory structure:
gitextract_7g6cwxka/
├── .gitignore
├── LICENSE
├── Pipfile
├── README.md
├── TUTORIAL.md
├── Tests/
│ ├── .gitignore
│ └── captcha_test.py
├── buffer.py
├── datastore.py
├── levelSchema.json
├── match.py
├── player.py
├── requirements.txt
├── server.cfg.example
└── server.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# local files
blocked.json
server.cfg
server.dat
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: Pipfile
================================================
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
twisted = "*"
autobahn = "*"
emoji = "*"
configparser = "*"
jsonschema = "*"
[requires]
python_version = "3.7"
================================================
FILE: README.md
================================================
# THIS REPOSITORY IS NOW BEING MAINTAINED AT [A NEW LOCATION, CLICK HERE.](https://github.com/mroyale/mroyale-server)
# PyRoyale
A open-source server emulator for Mario Royale browser game.

I really liked the idea of this addictive game and, as I already imagined that it would fall for a DMCA, I did a server emulator for it. This server's purpose is to allow playing with friends, but you're free to do anything you want with it.
You can discuss about the game and this emulator in [our discord](https://discord.gg/RqszZY6).
## Binaries
If you are on Windows and don't want to install python to run this server, you can use the latest binary released in the [releases page](https://github.com/Igoorx/PyRoyale/releases).
## Dependencies
This project uses Python <b>3.7</b> and the following dependencies:
- twisted
- autobahn
- emoji
- configparser
- jsonschema
- discord_webhook **(OPTIONAL)**
- captcha **(OPTIONAL)**
- argon2 **(OPTIONAL)**
<b>If you are on Windows, the module <u>pypiwin32</u> may also be required.</b>
## Tutorial
See [TUTORIAL.md](https://github.com/Igoorx/PyRoyale/blob/master/TUTORIAL.md) for more information about how to setup your own Mario Royale server.
================================================
FILE: TUTORIAL.md
================================================
# How to setup the Mario Royale server emulator
This setup guide will only cover Windows and Linux. However, the emulator should work on every system with Python.
This guide will not teach you how to do port forwarding.
## Windows
There's two options, either you download the binary from [the releases page](https://github.com/Igoorx/PyRoyale/releases) or you install python and setit up.
In this guide, we will go with the first option.
### 1 - Get the server to run
Download the "server.zip" from [releases page](https://github.com/Igoorx/PyRoyale/releases) and extract it somewhere on your PC. After that, go to the extracted folder and run `server.exe`

If a firewall window pops up, just click `Allow`.
### 2 - Get the website to run
You will need to download the website, but i can't share it here for a few reasons. You can get help to find it on [our discord](https://discord.gg/RqszZY6). After downloading the website, it will be compressed. Just extract it somewhere and go to the extracted folder. Run the `VerySimpleWebServer.exe` as admin.
- If you want you can use another webserver like apache or nginx, but you will need to know how to setup these webservers in order to make the game work properly.

#### 2.1 - Setup game JS
You will need also to setup the game JS. In VerySimpleWebServer's folder, follow this path: `www\royale\js`, then open the `game.min.js` in a Text Editor of your choice.

After opening it, search (CTRL+F) for the text `WS open event has unexpected result.`. You will end up on this line:

On this chunk of code you will find the text `infernoplus.com` or `77.68.80.27`. Replace it to `127.0.0.1:9000`

### 3 - Profit
If you did everything right, the game should be working now. Just access the url [http://127.0.0.1:8080/royale/index.html](http://127.0.0.1:8080/royale/index.html) on your browser.

## Linux
On Linux there's only one option, and that's to set up everything from the base.
### 1 - Get python and git
Use your OS package manager to install `git` and `python3.7`. On Debian or Ubuntu you can use apt-get:
`sudo apt-get install git`
`sudo apt-get install python3.7`
### 2 - Download this repository, install it's dependencies and run the server
To download this repository, open the command prompt on any path and run this command:
`git clone https://github.com/Igoorx/PyRoyale.git`
The server will be on the `./PyRoyale` path, so just execute `cd PyRoyale`.
After that, run this command to install the dependencies:
`sudo python3.7 -m pip install -r requirements.txt`
- If you get the error code 1, run the command `sudo apt-get build-essential python3.7-dev`and try again.
Now just run the command `python3.7 server.py </dev/null &>/dev/null &` to start the server.
### 3 - Get the website to run
To get the website running, you will need `nginx`. Download it with your OS package manager, on Debian or Ubuntu you can, again, use apt-get:
`sudo apt-get install nginx`
After the install has completed, open the file `/etc/nginx/sites-available/default` in a Text Editor of your choice. (I recommend VIM)
Find the text `location / {` and above it write the following:
```
location ^~ /royale {
if (-e $request_filename.json){
rewrite ^/(.*)$ /$1.json;
}
}
```

Now, save the file. In order to apply the changes, restart the nginx service. You can use this command too:
`sudo /etc/init.d/nginx restart`
### 4 - Setup the website
You will need to download the website, but I can't share it here for a few reasons. You can get help to find it on [our discord](https://discord.gg/RqszZY6). After downloading the website, it will be compressed. Extract it somewhere then go to the extracted directory.
In the extracted directory, open the file `www/royale/js/game.min.js` in a Text Editor of your choice (Again, i recommend VIM) and search for `/ws`

On this chunk of code, you will find the text `infernoplus.com` or `77.68.80.27`. Replace it to `127.0.0.1:9000`, and save the file.
Now just run the following command to move the website files to the nginx root.
`sudo mv www/royale /var/www/html/royale`
### 5 - Profit
If you did everything right, the game should be working now. Open the url [http://127.0.0.1/royale/index.html](http://127.0.0.1/royale/index.html) in your browser.
================================================
FILE: Tests/.gitignore
================================================
*.png
*.wav
================================================
FILE: Tests/captcha_test.py
================================================
'''
Created on Aug 23, 2018
@author: zhaosong
'''
from captcha.image import ImageCaptcha
from captcha.audio import AudioCaptcha
import random
from io import BytesIO
# The number list, lower case character list and upper case character list are used to generate captcha text.
number_list = ['0','1','2','3','4','5','6','7','8','9']
alphabet_lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
alphabet_uppercase = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
# This function will create a random captcha string text based on above three list.
# The input parameter is the captcha text length.
def create_random_captcha_text(captcha_string_size=5):
captcha_string_list = []
base_char = alphabet_lowercase + alphabet_uppercase + number_list
for i in range(captcha_string_size):
# Select one character randomly.
char = random.choice(base_char)
# Append the character to the list.
captcha_string_list.append(char)
captcha_string = ''
# Change the character list to string.
for item in captcha_string_list:
captcha_string += str(item)
return captcha_string
# This function will create a fully digital captcha string text.
def create_random_digital_text(captcha_string_size=5):
captcha_string_list = []
# Loop in the number list and return a digital captcha string list
for i in range(captcha_string_size):
char = random.choice(number_list)
captcha_string_list.append(char)
captcha_string = ''
# Convert the digital list to string.
for item in captcha_string_list:
captcha_string += str(item)
return captcha_string
# Create an image captcha with special text.
def create_image_captcha(captcha_text):
image_captcha = ImageCaptcha()
# Create the captcha image.
image = image_captcha.generate_image(captcha_text)
# Add noise curve for the image.
# image_captcha.create_noise_curve(image, image.getcolors())
# Add noise dots for the image.
# image_captcha.create_noise_dots(image, image.getcolors())
# Save the image to a png file.
image_file = "./captcha_"+captcha_text + ".png"
imgByteArr = BytesIO()
image.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
open("test.png", "wb").write(imgByteArr)
#image_captcha.write(captcha_text, image_file)
print(image_file + " has been created.")
# Create an audio captcha file.
def create_audio_captcha():
# Create the audio captcha with the specified voice wav file library folder.
# Each captcha char should has it's own directory under the specified folder ( such as ./voices),
# for example ./voices/a/a.wav will be played when the character is a.
# If you do not specify your own voice file library folder, the default built-in voice library which has only digital voice file will be used.
# audio_captcha = AudioCaptcha(voicedir='./voices')
# Create an audio captcha which use digital voice file only.
audio_captcha = AudioCaptcha()
# Because we use the default module voice library, so we can only generate digital text voice.
captcha_text = create_random_digital_text()
# Generate the audio captcha file.
audio_data = audio_captcha.generate(captcha_text)
# Save the autiod captcha file.
audio_file = "./captcha_"+captcha_text+'.wav'
audio_captcha.write(captcha_text, audio_file)
print(audio_file + " has been created.")
if __name__ == '__main__':
# Create random text.
captcha_text = create_random_captcha_text()
# Create image captcha.
create_image_captcha(captcha_text)
# Create audio captcha.
create_audio_captcha()
================================================
FILE: buffer.py
================================================
import struct
class Buffer:
def __init__(self, data=None):
self.buffer = data if data is not None else bytearray()
def write(self, data):
self.buffer += data
return self
def read(self, length=1):
data = self.buffer[:length]
del self.buffer[:length]
return data
def writeInt8(self, data):
self.write(bytes([data & 0xFF]))
return self
def readInt8(self):
return self.buffer.pop(0)
def writeInt16(self, data):
self.write(bytes([(data >> 8) & 0xFF, (data >> 0) & 0xFF]))
return self
def readInt16(self):
return self.readInt8() << 8 | self.readInt8() << 0
def writeInt24(self, data):
self.write(bytes([(data >> 16) & 0xFF, (data >> 8) & 0xFF, (data >> 0) & 0xFF]))
return self
def readInt24(self):
return self.readInt8() << 16 | self.readInt8() << 8 | self.readInt8() << 0
def writeInt32(self, data):
self.write(bytes([(data >> 24) & 0xFF, (data >> 16) & 0xFF, (data >> 8) & 0xFF, (data >> 0) & 0xFF]))
return self
def readInt32(self):
return self.readInt8() << 24 | self.readInt8() << 16 | self.readInt8() << 8 | self.readInt8() << 0
def writeBool(self, data):
self.write(bytes([1 if data else 0]))
return self
def readBool(self):
return self.buffer.pop(0) == 1
def readFloat(self):
data = struct.unpack("!f", self.read(4))[0]
return data
def writeFloat(self, data):
self.write(struct.pack("!f", data))
return self
def readShor2(self):
data = struct.unpack("<hh", self.read(4)[::-1])
return data
def writeShor2(self, _1, _2):
self.write(struct.pack("<hh", int(_1), int(_2))[::-1])
return self
def readVec2(self):
data = struct.unpack("!ff", self.read(8))
return data
def writeVec2(self, _1, _2):
self.write(struct.pack("!ff", _1, _2))
return self
def writeString(self, data):
self.writeInt16(len(data))
self.write(data)
return self
def readString(self):
return self.read(self.readInt16())
def writeBuffer(self, buffer):
self.buffer += buffer
return self
def length(self):
return len(self.buffer)
def getLength(self):
return self.length()
def available(self):
return self.length() > 0
def toString(self):
return self.buffer.decode('utf-8')
def toBytes(self):
return bytes(self.buffer)
def clear(self):
self.buffer = ""
================================================
FILE: datastore.py
================================================
import os
import hashlib
try:
import argon2
A2_IMPORT = True
except:
# Maybe we can switch to a built-in passwordHasher?
print("Can't import argon2-cffi, accounts functioning will be disabled.")
A2_IMPORT = False
import pickle
import secrets
accounts = {}
session = {}
if A2_IMPORT:
ph = argon2.PasswordHasher()
else:
ph = None
def loadState():
global accounts
try:
if os.path.exists("server.dat"):
with open("server.dat", "rb") as f:
accounts = pickle.load(f)
except Exception as e:
print(e)
def persistState():
with open("server.dat", "wb") as f:
pickle.dump(accounts, f)
def register(username, password):
if ph is None:
return False, "account system disabled"
if len(username) < 3:
return False, "username too short"
if len(username) > 20:
return False, "username too long"
if len(password) < 8:
return False, "password too short"
if len(password) > 120:
return False, "password too long"
if username in accounts:
return False, "account already registered"
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = ph.hash(password.encode('utf-8')+salt)
acc = { "salt": salt,
"pwdhash": pwdhash,
"nickname": username,
"skin": 0,
"squad": "" }
accounts[username] = acc
persistState()
acc2 = acc.copy()
del acc2["salt"]
del acc2["pwdhash"]
token = secrets.token_urlsafe(32)
session[token] = username
acc2["session"] = token
return True, acc2
def login(username, password):
if ph is None:
return False, "account system disabled"
invalidMsg = "invalid user name or password"
if len(username) < 3:
return False, invalidMsg
if len(username) > 20:
return False, invalidMsg
if len(password) < 8:
return False, invalidMsg
if len(password) > 120:
return False, invalidMsg
if username not in accounts:
return False, invalidMsg
acc = accounts[username]
try:
ph.verify(acc["pwdhash"], password.encode('utf-8')+acc["salt"])
except:
return False, invalidMsg
acc2 = acc.copy()
del acc2["salt"]
del acc2["pwdhash"]
token = secrets.token_urlsafe(32)
session[token] = username
acc2["session"] = token
return True, acc2
def resumeSession(token):
if token not in session:
return False, "session expired, please log in"
username = session[token]
if username not in accounts:
return False, "invalid user name or password"
acc = accounts[username]
acc2 = acc.copy()
del acc2["salt"]
del acc2["pwdhash"]
acc2["username"] = username
acc2["session"] = token
return True, acc2
def updateAccount(username, data):
if username not in accounts:
return
acc = accounts[username]
if "nickname" in data:
acc["nickname"] = data["nickname"]
if "squad" in data:
acc["squad"] = data["squad"]
if "skin" in data:
acc["skin"] = data["skin"]
persistState()
def logout(token):
if token in session:
del session[token]
loadState()
================================================
FILE: levelSchema.json
================================================
{ "type" : "object",
"properties" : {
"type" : {"type" : "string", "pattern" : "^game$"},
"resource" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"id" : {"type":"string", "minLength" : 1},
"src" : {"type":"string", "minLength" : 1}
},
"required" : ["id", "src"]
}
},
"initial" : { "type" : "integer" },
"world" : {
"type" : "array",
"minItems" : 1,
"items" : {
"type" : "object",
"properties" : {
"id" : { "type" : "integer" },
"name" : { "type" : "string", "minLength" : 1},
"initial" : { "type" : "integer" },
"zone" : {
"type" : "array",
"minItems" : 1,
"items" : {
"type": "object",
"properties" : {
"id" : { "type" : "integer" },
"initial" : { "type" : "integer" },
"color" : { "type" : "string", "pattern" : "#[0-9a-fA-F]{6}" },
"music" : { "type" : "string", "minLength" : 1},
"data" : {
"type" : "array",
"minItems" : 1,
"items" : {
"type" : "array",
"minItems" : 1,
"items" : {"type" : "integer"}
}
},
"obj" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"type" : {"type" : "integer"},
"pos" : {"type" : "integer"},
"param" : {"type" : "array"}
},
"required" : ["type", "pos", "param"]
}
},
"warp" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"id" : {"type" : "integer"},
"pos" : {"type" : "integer"},
"data" : {"type" : "integer"}
},
"required" : ["id", "pos", "data"]
}
}
},
"required" : ["id", "initial", "color", "music", "data", "obj", "warp"]
}
}
},
"required": ["id", "name", "initial", "zone"]
}
}
},
"required": ["type", "resource", "initial", "world"]
}
================================================
FILE: match.py
================================================
from twisted.internet import reactor
from buffer import Buffer
import os
import json
import random
import jsonschema
levelJsonSchema = json.loads(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "levelSchema.json"), "r").read())
class Match(object):
def __init__(self, server, roomName, private):
self.server = server
self.forceLevel = ""
self.customLevelData = ""
self.world = "lobby"
self.roomName = roomName
self.closed = False
self.private = private
self.playing = False
self.autoStartTimer = None
self.startTimer = int()
self.votes = int()
self.winners = int()
self.lastId = -1
self.players = list()
self.goldFlowerTaken = bool()
def getNextPlayerId(self):
self.lastId += 1
return self.lastId
def addPlayer(self, player):
self.players.append(player)
return self.getNextPlayerId()
def removePlayer(self, player):
if player not in self.players:
return
self.players.remove(player)
if len(self.players) == 0:
try:
self.autoStartTimer.cancel()
except:
pass
self.server.removeMatch(self)
return
if not player.dead and not player.win: # Don't kill podium players
self.broadBin(0x11, Buffer().writeInt16(player.id)) # KILL_PLAYER_OBJECT
self.broadPlayerList()
if player.voted:
self.votes -= 1
elif self.server.enableVoteStart and not self.playing and self.votes >= len(self.players) * self.server.voteRateToStart:
self.start()
def getPlayer(self, pid):
for player in self.players:
if player.id == pid:
return player
return None
def getWinners(self):
self.winners += 1
return self.winners
def broadJSON(self, j):
for player in self.players:
if not player.loaded:
continue
player.sendJSON(j)
def broadBin(self, code, buff, ignore = None):
buff = buff.toBytes() if isinstance(buff, Buffer) else buff
for player in self.players:
if not player.loaded or (ignore is not None and player.id == ignore):
continue
player.sendBin(code, buff)
def broadLoadWorld(self):
for player in self.players:
player.loadWorld(self.world, self.customLevelData)
def broadStartTimer(self, time):
self.startTimer = time * 30
for player in self.players:
if not player.loaded:
continue
player.setStartTimer(self.startTimer)
if time > 0:
reactor.callLater(1, self.broadStartTimer, time - 1)
else:
self.closed = True
def broadPlayerList(self):
if self.closed:
return # Don't broad player list when in main game
data = {"packets": [
{"players": self.getPlayersData(),
"type": "g12"}
], "type": "s01"}
for player in self.players:
if not player.loaded:
continue
player.sendJSON(data)
def getPlayersData(self):
playersData = []
for player in self.players:
# We need to include even not loaded players as the remaining player count
# only updates on the start timer screen
playersData.append(player.getSimpleData())
return playersData
def broadPlayerUpdate(self, player, pktData):
data = Buffer().writeInt16(player.id).write(pktData).toBytes()
for p in self.players:
if not p.loaded or p.id == player.id:
continue
if not p.win and (p.level != player.level or p.zone != player.zone):
continue
p.sendBin(0x12, data)
def onPlayerEnter(self, player):
pass
def onPlayerReady(self, player):
if (not self.private or self.roomName != "") and not self.playing: # Ensure that the game starts even with fewer players
if self.autoStartTimer is not None:
try:
self.autoStartTimer.reset(self.server.autoStartTime)
except:
pass
else:
self.autoStartTimer = reactor.callLater(self.server.autoStartTime, self.start, True)
if self.world == "lobby" and self.goldFlowerTaken:
self.broadBin(0x20, Buffer().writeInt16(-1).writeInt8(0).writeInt8(0).writeInt32(458761).writeInt8(0))
if self.world == "lobby" or not player.lobbier or self.closed:
for p in self.players:
if not p.loaded or p == player:
continue
player.sendBin(0x10, p.serializePlayerObject())
if self.startTimer != 0 or self.closed:
player.setStartTimer(self.startTimer)
self.broadPlayerList()
if not self.playing:
if len(self.players) >= self.server.playerCap:
self.start(True)
# This is needed because if the votes is sufficient to start but there isn't sufficient players,
# when someone enters the game, it can make it possible to start the game.
elif self.server.enableVoteStart and self.votes >= len(self.players) * self.server.voteRateToStart:
self.start()
def onPlayerWarp(self, player, level, zone):
for p in self.players:
if not p.loaded or p.lastUpdatePkt is None or p.id == player.id:
continue
# Tell fellows that the player warped
if p.level == player.level and p.zone == player.zone:
p.sendBin(0x12, Buffer().writeInt16(player.id).writeInt8(level).writeInt8(zone).write(player.lastUpdatePkt[2:]))
continue
elif p.level != level or p.zone != zone:
continue
player.sendBin(0x12, Buffer().writeInt16(p.id).write(p.lastUpdatePkt))
def voteStart(self):
self.votes += 1
if self.server.enableVoteStart and not self.playing and self.votes >= len(self.players) * self.server.voteRateToStart:
self.start()
def start(self, forced = False):
if self.playing or (not forced and len(self.players) < (1 if self.private and self.roomName == "" else self.server.playerMin)): # We need at-least 10 players to start
return
self.playing = True
try:
self.autoStartTimer.cancel()
except:
pass
self.world = self.forceLevel if self.forceLevel != "" else self.server.getRandomWorld()
if not self.private:
reactor.callLater(3, self.broadLoadWorld)
reactor.callLater(4, self.broadStartTimer, self.server.startTimer)
else:
self.broadLoadWorld()
reactor.callLater(1, self.broadStartTimer, self.server.startTimer)
def validateCustomLevel(self, level):
lk = json.loads(level)
jsonschema.validate(instance=lk, schema=levelJsonSchema)
def selectLevel(self, level):
if level == "" or level in self.server.worlds:
self.forceLevel = level
self.broadLevelSelect()
def broadLevelSelect(self):
data = {"type":"gsl", "name":self.forceLevel, "status":"update", "message":""}
for player in self.players:
player.sendJSON(data)
def selectCustomLevel(self, level):
self.validateCustomLevel(level)
self.forceLevel = "custom"
self.customLevelData = level
self.broadLevelSelect()
================================================
FILE: player.py
================================================
import re
import emoji
from twisted.internet import reactor
from buffer import Buffer
try:
from discord_webhook import DiscordEmbed
except Exception as e:
pass
class Player(object):
def __init__(self, client, name, team, match, skin):
self.client = client
self.server = client.server
self.match = match
self.skin = skin
self.name = ' '.join(emoji.emojize(re.sub(r"[^\x00-\x7F]+", "", emoji.demojize(name)).strip())[:20].split()).upper()
self.team = team
if len(self.team) > 0 and self.server.checkCurse(self.name):
self.name = str()
if len(self.name) == 0:
self.name = self.server.defaultName
self.pendingWorld = None
self.level = int()
self.zone = int()
self.posX = int()
self.posY = int()
self.dead = True
self.win = bool()
self.voted = bool()
self.loaded = bool()
self.lobbier = bool()
self.lastUpdatePkt = None
self.trustCount = int()
self.lastX = int()
self.lastXOk = True
self.id = match.addPlayer(self)
def sendJSON(self, j):
self.client.sendJSON(j)
def sendBin(self, code, b):
self.client.sendBin(code, b)
def getSimpleData(self):
return {"id": self.id, "name": self.name, "team": self.team}
def serializePlayerObject(self):
return Buffer().writeInt16(self.id).writeInt8(self.level).writeInt8(self.zone).writeShor2(self.posX, self.posY).writeInt16(self.skin).toBytes()
def loadWorld(self, worldName, levelData):
self.dead = True
self.loaded = False
self.pendingWorld = worldName
msg = {"game": worldName, "type": "g01"}
if worldName == "custom":
msg["levelData"] = levelData
self.sendJSON({"packets": [msg], "type": "s01"})
self.client.startDCTimer(15)
def setStartTimer(self, time):
self.sendJSON({"packets": [
{"time": time, "type": "g13"}
], "type": "s01"})
def onEnterIngame(self):
if not self.dead:
return
if self.match.world == "lobby":
self.lobbier = True
self.match.onPlayerEnter(self)
self.loadWorld(self.match.world, self.match.customLevelData)
def onLoadComplete(self):
if self.loaded or self.pendingWorld is None:
return
self.client.stopDCTimer()
self.level = 0
self.zone = 0
self.posX = 35
self.posY = 3
self.win = False
self.dead = False
self.loaded = True
self.pendingWorld = None
self.lastXOk = True
self.sendBin(0x02, Buffer().writeInt16(self.id).writeInt16(self.skin)) # ASSIGN_PID
self.match.onPlayerReady(self)
def handlePkt(self, code, b, pktData):
if code == 0x10: # CREATE_PLAYER_OBJECT
level, zone, pos = b.readInt8(), b.readInt8(), b.readShor2()
self.level = level
self.zone = zone
self.dead = False
self.client.stopDCTimer()
self.match.broadBin(0x10, Buffer().writeInt16(self.id).write(pktData).writeInt16(self.skin))
elif code == 0x11: # KILL_PLAYER_OBJECT
if self.dead or self.win:
return
self.dead = True
self.client.startDCTimer(60)
self.match.broadBin(0x11, Buffer().writeInt16(self.id))
elif code == 0x12: # UPDATE_PLAYER_OBJECT
if self.dead or self.lastUpdatePkt == pktData:
return
level, zone, pos, sprite, reverse = b.readInt8(), b.readInt8(), b.readVec2(), b.readInt8(), b.readBool()
if self.level != level or self.zone != zone:
self.match.onPlayerWarp(self, level, zone)
self.level = level
self.zone = zone
self.posX = pos[0]
self.posY = pos[1]
self.lastUpdatePkt = pktData
if sprite > 5 and self.match.world == "lobby" and zone == 0:
self.client.block(0x1)
return
self.match.broadPlayerUpdate(self, pktData)
elif code == 0x13: # PLAYER_OBJECT_EVENT
if self.dead or self.win:
return
type = b.readInt8()
if self.match.world == "lobby":
self.client.block(0x2)
return
self.match.broadBin(0x13, Buffer().writeInt16(self.id).write(pktData))
elif code == 0x17:
killer = b.readInt16()
if self.id == killer:
return
killer = self.match.getPlayer(killer)
if killer is None:
return
killer.sendBin(0x17, Buffer().writeInt16(self.id).write(pktData))
elif code == 0x18: # PLAYER_RESULT_REQUEST
if self.dead or self.win:
return
self.win = True
self.client.startDCTimer(120)
pos = self.match.getWinners()
try:
# Maybe this should be assynchronous?
if self.server.discordWebhook is not None and pos == 1 and not self.match.private:
name = self.name
# We already filter players that have a squad so...
if len(self.team) == 0 and self.server.checkCurse(self.name):
name = "[ censored ]"
embed = DiscordEmbed(description='**%s** has achieved **#1** victory royale!' % name, color=0xffff00)
self.server.discordWebhook.add_embed(embed)
self.server.discordWebhook.execute()
self.server.discordWebhook.remove_embed(0)
except:
pass
# Make sure that everyone knows that the player is at the axe
self.match.broadPlayerUpdate(self, self.lastUpdatePkt)
self.match.broadBin(0x18, Buffer().writeInt16(self.id).writeInt8(pos).writeInt8(0))
elif code == 0x19:
self.trustCount += 1
if self.trustCount > 8:
self.client.block(0x3)
elif code == 0x20: # OBJECT_EVENT_TRIGGER
if self.dead:
return
level, zone, oid, type = b.readInt8(), b.readInt8(), b.readInt32(), b.readInt8()
if self.match.world == "lobby" and oid == 458761:
self.match.goldFlowerTaken = True
self.match.broadBin(0x20, Buffer().writeInt16(self.id).write(pktData))
elif code == 0x30: # TILE_EVENT_TRIGGER
if self.dead:
return
level, zone, pos, type = b.readInt8(), b.readInt8(), b.readShor2(), b.readInt8()
self.match.broadBin(0x30, Buffer().writeInt16(self.id).write(pktData))
================================================
FILE: requirements.txt
================================================
################################################################################
# This requirements file has been automatically generated from `Pipfile` with
# `pipenv-to-requirements`
#
#
# This has been done to maintain backward compatibility with tools and services
# that do not support `Pipfile` yet.
#
# Do NOT edit it directly, use `pipenv install [-d]` to modify `Pipfile` and
# `Pipfile.lock` and then regenerate `requirements*.txt`.
################################################################################
autobahn
configparser
emoji
jsonschema
twisted
================================================
FILE: server.cfg.example
================================================
[Server]
# The port on which the server will listen, if you don't know what it is, do not change it
ListenPort: 9000
# The moderator's code, this is useless until version 2.1.3
MCode:
# The path to the file "status.json"
StatusPath:
# The name that will be set for unnamed players
DefaultName: MARIO
# The squad that will be set for players without squad
DefaultTeam:
# Maximum of simultaneous connections per IP Address
MaxSimulIP: 3
# Discord Webhook Url for Discord functioning (see more: https://support.discordapp.com/hc/en-us/articles/228383668)
DiscordWebhookUrl:
[Match]
# Minimum of players to a match start by votes
PlayerMin: 2
# Maximum of players in a match
PlayerCap: 75
# The time until the match starts if no more players enter the match. (Disabled in solo private lobbies)
AutoStartTime: 30
# The match start timer, it is recommended to be at least 5 to allow the players to load the world.
StartTimer: 7
# Whether the votes can start the match or not (1 = yes, 0 = no)
EnableVoteStart: 1
# The rate of Votes/Players needed to the match start
VoteRateToStart: 0.85
# Whether players can enter the match while the start timer is running (1 = yes, 0 = no)
AllowLateEnter: 1
# The game's worlds, if you don't know what you're doing, do not change it
Worlds: world-1,world-2,world-3,world-5,world-6,world-l1,world-p
================================================
FILE: server.py
================================================
import os
import sys
import datastore
if sys.version_info.major != 3:
sys.stderr.write("You need python 3.7 or later to run this script\n")
if os.name == 'nt': # Enforce that the window opens in windows
print("Press ENTER to exit")
input()
exit(1)
from twisted.python import log
log.startLogging(sys.stdout)
from autobahn.twisted import install_reactor
# we use an Autobahn utility to import the "best" available Twisted reactor
reactor = install_reactor(verbose=False,
require_optimal_reactor=False)
try:
from discord_webhook import DiscordWebhook
DWH_IMPORT = True
except Exception as e:
print("Can't import discord_webhook, discord functioning will be disabled.")
DWH_IMPORT = False
try:
from captcha.image import ImageCaptcha
CP_IMPORT = True
except:
print("Can't import captcha, captcha functioning will be disabled.")
CP_IMPORT = False
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet.protocol import Factory
import json
import string
import random
import base64
import hashlib
import traceback
import configparser
from io import BytesIO
from buffer import Buffer
from player import Player
from match import Match
NUM_SKINS = 33 #temporary until shop is implemented
class MyServerProtocol(WebSocketServerProtocol):
def __init__(self, server):
WebSocketServerProtocol.__init__(self)
self.server = server
self.address = str()
self.recv = bytearray()
self.pendingStat = None
self.stat = str()
self.username = str();
self.session = str();
self.player = None
self.blocked = bool()
self.dcTimer = None
self.maxConLifeTimer = None
def startDCTimer(self, time):
self.stopDCTimer()
self.dcTimer = reactor.callLater(time, self.sendClose)
def stopDCTimer(self):
try:
self.dcTimer.cancel()
except:
pass
def onConnect(self, request):
#print("Client connecting: {0}".format(request.peer))
if "x-real-ip" in request.headers:
self.address = request.headers["x-real-ip"]
def onOpen(self):
#print("WebSocket connection open.")
if not self.address:
self.address = self.transport.getPeer().host
# A connection can only be alive for 20 minutes
self.maxConLifeTimer = reactor.callLater(20 * 60, self.sendClose)
self.startDCTimer(25)
self.setState("l")
def onClose(self, wasClean, code, reason):
#print("WebSocket connection closed: {0}".format(reason))
try:
self.maxConLifeTimer.cancel()
except:
pass
self.stopDCTimer()
if self.address in self.server.captchas:
del self.server.captchas[self.address]
if self.username != "" and self.username in self.server.authd:
self.server.authd.remove(self.username)
if self.stat == "g" and self.player != None:
self.server.players.remove(self.player)
self.player.match.removePlayer(self.player)
self.player.match = None
self.player = None
self.pendingStat = None
self.stat = str()
def onMessage(self, payload, isBinary):
if len(payload) == 0:
return
self.server.in_messages += 1
try:
if isBinary:
self.recv += payload
while len(self.recv) > 0:
if not self.onBinaryMessage():
break
else:
self.onTextMessage(payload.decode('utf8'))
except Exception as e:
traceback.print_exc()
self.sendClose()
self.recv.clear()
return
def sendJSON(self, j):
self.server.out_messages += 1
#print("sendJSON: "+str(j))
self.sendMessage(json.dumps(j).encode('utf-8'), False)
def sendBin(self, code, buff):
self.server.out_messages += 1
msg=Buffer().writeInt8(code).write(buff.toBytes() if isinstance(buff, Buffer) else buff).toBytes()
#print("sendBin: "+str(code)+" "+str(msg))
self.sendMessage(msg, True)
def loginSuccess(self):
self.sendJSON({"packets": [
{"name": self.player.name, "team": self.player.team, "type": "l01", "skin": self.player.skin}
], "type": "s01"})
def setState(self, state):
self.stat = self.pendingStat = state
self.sendJSON({"packets": [
{"state": state, "type": "s00"}
], "type": "s01"})
def exception(self, message):
self.sendJSON({"packets": [
{"message": message, "type": "x00"}
], "type": "s01"})
def block(self, reason):
if self.blocked or len(self.player.match.players) == 1:
return
print("Player blocked: {0}".format(self.player.name))
self.blocked = True
if not self.player.dead:
self.player.match.broadBin(0x11, Buffer().writeInt16(self.player.id), self.player.id) # KILL_PLAYER_OBJECT
self.server.blockAddress(self.address, self.player.name, reason)
def onTextMessage(self, payload):
#print("Text message received: {0}".format(payload))
packet = json.loads(payload)
type = packet["type"]
if self.stat == "l":
if type == "l00": # Input state ready
if self.player is not None or self.pendingStat is None:
self.sendClose()
return
self.pendingStat = None
self.stopDCTimer()
if self.address != "127.0.0.1" and self.server.getPlayerCountByAddress(self.address) >= self.server.maxSimulIP:
self.exception("Too many connections")
self.sendClose()
return
for b in self.server.blocked:
if b[0] == self.address:
self.blocked = True
self.setState("g") # Ingame
return
name = packet["name"]
team = packet["team"][:3].strip().upper()
priv = packet["private"]
skin = int(packet["skin"]) if "skin" in packet else 0
self.player = Player(self,
name if self.username != "" else ("*"+name),
team if team != "" else self.server.defaultTeam,
self.server.getMatch(team, priv if "private" in packet else False),
skin if skin in range(NUM_SKINS) else 0)
self.loginSuccess()
self.server.players.append(self.player)
self.setState("g") # Ingame
elif type == "llg": #login
if self.username != "" or self.player is not None or self.pendingStat is None:
self.sendClose()
return
self.stopDCTimer()
username = packet["username"].upper()
if self.address in self.server.loginBlocked:
self.sendJSON({"type": "llg", "status": False, "msg": "max login tries reached.\ntry again in one minute."})
return
elif username in self.server.authd:
self.sendJSON({"type": "llg", "status": False, "msg": "account already in use"})
return
status, msg = datastore.login(username, packet["password"])
if status:
self.username = username
self.session = msg["session"]
self.server.authd.append(self.username)
else:
if self.address not in self.server.maxLoginTries:
self.server.maxLoginTries[self.address] = 1
else:
self.server.maxLoginTries[self.address] += 1
if self.server.maxLoginTries[self.address] >= 4:
del self.server.maxLoginTries[self.address]
self.server.loginBlocked.append(self.address)
reactor.callLater(60, self.server.loginBlocked.remove, self.address)
self.sendJSON({"type": "llg", "status": status, "msg": msg})
elif type == "llo": #logout
if self.username == "" or self.player is not None or self.pendingStat is None:
self.sendClose()
return
datastore.logout(self.session)
self.sendJSON({"type": "llo"})
elif type == "lrg": #register
if self.username != "" or self.address not in self.server.captchas or self.player is not None or self.pendingStat is None:
self.sendClose()
return
self.stopDCTimer()
username = packet["username"].upper()
if CP_IMPORT and len(packet["captcha"]) != 5:
status, msg = False, "invalid captcha"
elif CP_IMPORT and packet["captcha"].upper() != self.server.captchas[self.address]:
status, msg = False, "incorrect captcha"
elif self.server.checkCurse(username):
status, msg = False, "please choose a different username"
else:
status, msg = datastore.register(username, packet["password"])
if status:
del self.server.captchas[self.address]
self.username = username
self.session = msg["session"]
self.server.authd.append(self.username)
self.sendJSON({"type": "lrg", "status": status, "msg": msg})
elif type == "lrc": #request captcha
if self.username != "" or self.player is not None or self.pendingStat is None:
self.sendClose()
return
if not CP_IMPORT:
self.server.captchas[self.address] = ""
self.sendJSON({"type": "lrc", "data": ""})
return
self.stopDCTimer()
cp = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(5))
self.server.captchas[self.address] = cp
imageCaptcha = ImageCaptcha()
image = imageCaptcha.generate_image(cp)
imgByteArr = BytesIO()
image.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
self.sendJSON({"type": "lrc", "data": base64.b64encode(imgByteArr).decode("utf-8")})
elif type == "lrs": #resume session
if self.username != "" or self.player is not None or self.pendingStat is None:
self.sendClose()
return
self.stopDCTimer()
status, msg = datastore.resumeSession(packet["session"])
if status:
if msg["username"] in self.server.authd:
self.sendJSON({"type": "lrs", "status": False, "msg": "account already in use"})
return
self.username = msg["username"]
self.session = msg["session"]
self.server.authd.append(self.username)
self.sendJSON({"type": "lrs", "status": status, "msg": msg})
elif type == "lpr": #update profile
if self.username == "" or self.player is not None or self.pendingStat is None:
self.sendClose()
return
datastore.updateAccount(self.username, packet)
elif self.stat == "g":
if type == "g00": # Ingame state ready
if self.player is None or self.pendingStat is None:
if self.blocked:
self.sendJSON({"packets": [{"game": "jail", "type": "g01"}], "type": "s01"})
return
self.sendClose()
return
self.pendingStat = None
self.player.onEnterIngame()
elif type == "g03": # World load completed
if self.player is None:
if self.blocked:
self.sendBin(0x02, Buffer().writeInt16(0).writeInt16(0))
self.startDCTimer(15)
return
self.sendClose()
return
self.player.onLoadComplete()
elif type == "g50": # Vote to start
if self.player is None or self.player.voted or self.player.match.playing:
return
self.player.voted = True
self.player.match.voteStart()
elif type == "g51": # (SPECIAL) Force start
if self.server.mcode and self.server.mcode in packet["code"]:
self.player.match.start(True)
elif type == "gsl": # Level select
if self.player is None or self.player.team != "" or not self.player.match.private:
return
levelName = packet["name"]
if levelName == "custom":
try:
self.player.match.selectCustomLevel(packet["data"])
except Exception as e:
estr = str(e)
estr = "\n".join(estr.split("\n")[:10])
self.sendJSON({"type":"gsl","name":levelName,"status":"error","message":estr})
return
self.sendJSON({"type":"gsl","name":levelName,"status":"success","message":""})
else:
self.player.match.selectLevel(levelName)
def onBinaryMessage(self):
pktLenDict = { 0x10: 6, 0x11: 0, 0x12: 12, 0x13: 1, 0x17: 2, 0x18: 4, 0x19: 0, 0x20: 7, 0x30: 7 }
code = self.recv[0]
if code not in pktLenDict:
#print("Unknown binary message received: {1} = {0}".format(repr(self.recv[1:]), hex(code)))
self.recv.clear()
return False
pktLen = pktLenDict[code] + 1
if len(self.recv) < pktLen:
return False
b = Buffer(self.recv[1:pktLen])
del self.recv[:pktLen]
if self.player is None or not self.player.loaded or self.blocked or (not self.player.match.closed and self.player.match.playing):
self.recv.clear()
return False
self.player.handlePkt(code, b, b.toBytes())
return True
class MyServerFactory(WebSocketServerFactory):
def __init__(self, url):
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"server.cfg"), "r") as f:
self.configHash = hashlib.md5(f.read().encode('utf-8')).hexdigest()
self.readConfig(self.configHash)
except Exception as e:
sys.stderr.write("The file \"server.cfg\" does not exist or is invalid, consider renaming \"server.cfg.example\" to \"server.cfg\".\n")
sys.stderr.write(str(e)+"\n")
if os.name == 'nt': # Enforce that the window opens in windows
print("Press ENTER to exit")
input()
exit(1)
WebSocketServerFactory.__init__(self, url.format(self.listenPort))
self.players = list()
self.matches = list()
self.curse = list()
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"words.json"), "r") as f:
self.curse = json.loads(f.read())
except:
pass
self.blocked = list()
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"blocked.json"), "r") as f:
self.blocked = json.loads(f.read())
except:
pass
if DWH_IMPORT:
self.discordWebhook = DiscordWebhook(url=self.discordWebhookUrl)
else:
self.discordWebhook = None
self.randomWorldList = list()
self.maxLoginTries = {}
self.loginBlocked = []
self.captchas = {}
self.authd = []
self.in_messages = 0
self.out_messages = 0
reactor.callLater(5, self.generalUpdate)
def readConfig(self, cfgHash):
self.configHash = cfgHash
config = configparser.ConfigParser()
config.read('server.cfg')
self.listenPort = config.getint('Server', 'ListenPort')
self.mcode = config.get('Server', 'MCode').strip()
self.statusPath = config.get('Server', 'StatusPath').strip()
self.defaultName = config.get('Server', 'DefaultName').strip()
self.defaultTeam = config.get('Server', 'DefaultTeam').strip()
self.maxSimulIP = config.getint('Server', 'MaxSimulIP')
self.discordWebhookUrl = config.get('Server', 'DiscordWebhookUrl').strip()
self.playerMin = config.getint('Match', 'PlayerMin')
try:
oldCap = self.playerCap
except:
oldCap = 0
self.playerCap = config.getint('Match', 'PlayerCap')
if self.playerCap < oldCap:
try:
for match in self.matches:
if len(match.players) >= self.playerCap:
match.start()
except:
print("Couldn't start matches after player cap change...")
self.autoStartTime = config.getint('Match', 'AutoStartTime')
self.startTimer = config.getint('Match', 'StartTimer')
self.enableVoteStart = config.getboolean('Match', 'EnableVoteStart')
self.voteRateToStart = config.getfloat('Match', 'VoteRateToStart')
self.allowLateEnter = config.getboolean('Match', 'AllowLateEnter')
self.worlds = config.get('Match', 'Worlds').strip().split(',')
def generalUpdate(self):
playerCount = len(self.players)
print("pc: {0}, mc: {1}, in: {2}, out: {3}".format(playerCount, len(self.matches), self.in_messages, self.out_messages))
self.in_messages = 0
self.out_messages = 0
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"server.cfg"), "r") as f:
cfgHash = hashlib.md5(f.read().encode('utf-8')).hexdigest()
if cfgHash != self.configHash:
self.readConfig(cfgHash)
print("Configuration reloaded.")
except:
print("Failed to reload configuration.")
# Just to keep self.blocked synchronized with blocked.json
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"blocked.json"), "r") as f:
self.blocked = json.loads(f.read())
except:
pass
if self.statusPath:
try:
with open(self.statusPath, "w") as f:
f.write('{"active":' + str(playerCount) + '}')
except:
pass
reactor.callLater(5, self.generalUpdate)
def getRandomWorld(self):
if len(self.worlds) == 0:
return None
if len(self.randomWorldList) > 0:
selected = random.choice(self.randomWorldList)
self.randomWorldList.remove(selected)
return selected
self.randomWorldList = list(self.worlds) # Make a copy
return self.getRandomWorld()
# Maybe this should be in a util class?
def leet2(self, word):
REPLACE = { str(index): str(letter) for index, letter in enumerate('oizeasgtb') }
letters = [ REPLACE.get(l, l) for l in word.lower() ]
return ''.join(letters)
def checkCurse(self, str):
if self.checkCheckCurse(str):
return True
str = self.leet2(str)
if self.checkCheckCurse(str):
return True
str = str.replace("|", "i").replace("$", "s").replace("@", "a").replace("&", "e")
str = ''.join(e for e in str if e.isalnum())
if self.checkCheckCurse(str):
return True
return False
def checkCheckCurse(self, str):
if len(str) <= 3:
return False
str = str.lower()
for w in self.curse:
if len(w) <= 3:
continue
if w in str:
return True
return False
def blockAddress(self, address, playerName, reason):
if not address in self.blocked:
self.blocked.append([address, playerName, reason])
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"blocked.json"), "w") as f:
f.write(json.dumps(self.blocked))
except:
pass
def getPlayerCountByAddress(self, address):
count = 0
for player in self.players:
if player.client.address == address:
count += 1
return count
def buildProtocol(self, addr):
protocol = MyServerProtocol(self)
protocol.factory = self
return protocol
def getMatch(self, roomName, private):
if private and roomName == "":
return Match(self, roomName, private)
fmatch = None
for match in self.matches:
if not match.closed and len(match.players) < self.playerCap and private == match.private and (not private or match.roomName == roomName):
if not self.allowLateEnter and match.playing:
continue
fmatch = match
break
if fmatch == None:
fmatch = Match(self, roomName, private)
self.matches.append(fmatch)
return fmatch
def removeMatch(self, match):
if match in self.matches:
self.matches.remove(match)
if __name__ == '__main__':
factory = MyServerFactory(u"ws://127.0.0.1:{0}/royale/ws")
# factory.setProtocolOptions(maxConnections=2)
reactor.listenTCP(factory.listenPort, factory)
reactor.run()
gitextract_7g6cwxka/ ├── .gitignore ├── LICENSE ├── Pipfile ├── README.md ├── TUTORIAL.md ├── Tests/ │ ├── .gitignore │ └── captcha_test.py ├── buffer.py ├── datastore.py ├── levelSchema.json ├── match.py ├── player.py ├── requirements.txt ├── server.cfg.example └── server.py
SYMBOL INDEX (103 symbols across 6 files)
FILE: Tests/captcha_test.py
function create_random_captcha_text (line 20) | def create_random_captcha_text(captcha_string_size=5):
function create_random_digital_text (line 43) | def create_random_digital_text(captcha_string_size=5):
function create_image_captcha (line 60) | def create_image_captcha(captcha_text):
function create_audio_captcha (line 82) | def create_audio_captcha():
FILE: buffer.py
class Buffer (line 3) | class Buffer:
method __init__ (line 4) | def __init__(self, data=None):
method write (line 7) | def write(self, data):
method read (line 11) | def read(self, length=1):
method writeInt8 (line 16) | def writeInt8(self, data):
method readInt8 (line 20) | def readInt8(self):
method writeInt16 (line 23) | def writeInt16(self, data):
method readInt16 (line 27) | def readInt16(self):
method writeInt24 (line 30) | def writeInt24(self, data):
method readInt24 (line 34) | def readInt24(self):
method writeInt32 (line 37) | def writeInt32(self, data):
method readInt32 (line 41) | def readInt32(self):
method writeBool (line 44) | def writeBool(self, data):
method readBool (line 48) | def readBool(self):
method readFloat (line 51) | def readFloat(self):
method writeFloat (line 55) | def writeFloat(self, data):
method readShor2 (line 59) | def readShor2(self):
method writeShor2 (line 63) | def writeShor2(self, _1, _2):
method readVec2 (line 67) | def readVec2(self):
method writeVec2 (line 71) | def writeVec2(self, _1, _2):
method writeString (line 75) | def writeString(self, data):
method readString (line 80) | def readString(self):
method writeBuffer (line 83) | def writeBuffer(self, buffer):
method length (line 87) | def length(self):
method getLength (line 90) | def getLength(self):
method available (line 93) | def available(self):
method toString (line 96) | def toString(self):
method toBytes (line 99) | def toBytes(self):
method clear (line 102) | def clear(self):
FILE: datastore.py
function loadState (line 21) | def loadState():
function persistState (line 30) | def persistState():
function register (line 34) | def register(username, password):
function login (line 68) | def login(username, password):
function resumeSession (line 99) | def resumeSession(token):
function updateAccount (line 116) | def updateAccount(username, data):
function logout (line 129) | def logout(token):
FILE: match.py
class Match (line 10) | class Match(object):
method __init__ (line 11) | def __init__(self, server, roomName, private):
method getNextPlayerId (line 30) | def getNextPlayerId(self):
method addPlayer (line 34) | def addPlayer(self, player):
method removePlayer (line 38) | def removePlayer(self, player):
method getPlayer (line 61) | def getPlayer(self, pid):
method getWinners (line 67) | def getWinners(self):
method broadJSON (line 71) | def broadJSON(self, j):
method broadBin (line 77) | def broadBin(self, code, buff, ignore = None):
method broadLoadWorld (line 84) | def broadLoadWorld(self):
method broadStartTimer (line 88) | def broadStartTimer(self, time):
method broadPlayerList (line 100) | def broadPlayerList(self):
method getPlayersData (line 112) | def getPlayersData(self):
method broadPlayerUpdate (line 120) | def broadPlayerUpdate(self, player, pktData):
method onPlayerEnter (line 129) | def onPlayerEnter(self, player):
method onPlayerReady (line 132) | def onPlayerReady(self, player):
method onPlayerWarp (line 162) | def onPlayerWarp(self, player, level, zone):
method voteStart (line 174) | def voteStart(self):
method start (line 179) | def start(self, forced = False):
method validateCustomLevel (line 198) | def validateCustomLevel(self, level):
method selectLevel (line 202) | def selectLevel(self, level):
method broadLevelSelect (line 207) | def broadLevelSelect(self):
method selectCustomLevel (line 212) | def selectCustomLevel(self, level):
FILE: player.py
class Player (line 11) | class Player(object):
method __init__ (line 12) | def __init__(self, client, name, team, match, skin):
method sendJSON (line 42) | def sendJSON(self, j):
method sendBin (line 45) | def sendBin(self, code, b):
method getSimpleData (line 48) | def getSimpleData(self):
method serializePlayerObject (line 51) | def serializePlayerObject(self):
method loadWorld (line 54) | def loadWorld(self, worldName, levelData):
method setStartTimer (line 64) | def setStartTimer(self, time):
method onEnterIngame (line 69) | def onEnterIngame(self):
method onLoadComplete (line 79) | def onLoadComplete(self):
method handlePkt (line 99) | def handlePkt(self, code, b, pktData):
FILE: server.py
class MyServerProtocol (line 50) | class MyServerProtocol(WebSocketServerProtocol):
method __init__ (line 51) | def __init__(self, server):
method startDCTimer (line 68) | def startDCTimer(self, time):
method stopDCTimer (line 72) | def stopDCTimer(self):
method onConnect (line 78) | def onConnect(self, request):
method onOpen (line 84) | def onOpen(self):
method onClose (line 96) | def onClose(self, wasClean, code, reason):
method onMessage (line 119) | def onMessage(self, payload, isBinary):
method sendJSON (line 139) | def sendJSON(self, j):
method sendBin (line 144) | def sendBin(self, code, buff):
method loginSuccess (line 150) | def loginSuccess(self):
method setState (line 155) | def setState(self, state):
method exception (line 161) | def exception(self, message):
method block (line 166) | def block(self, reason):
method onTextMessage (line 175) | def onTextMessage(self, payload):
method onBinaryMessage (line 373) | def onBinaryMessage(self):
class MyServerFactory (line 396) | class MyServerFactory(WebSocketServerFactory):
method __init__ (line 397) | def __init__(self, url):
method readConfig (line 449) | def readConfig(self, cfgHash):
method generalUpdate (line 482) | def generalUpdate(self):
method getRandomWorld (line 516) | def getRandomWorld(self):
method leet2 (line 529) | def leet2(self, word):
method checkCurse (line 534) | def checkCurse(self, str):
method checkCheckCurse (line 546) | def checkCheckCurse(self, str):
method blockAddress (line 557) | def blockAddress(self, address, playerName, reason):
method getPlayerCountByAddress (line 567) | def getPlayerCountByAddress(self, address):
method buildProtocol (line 574) | def buildProtocol(self, addr):
method getMatch (line 579) | def getMatch(self, roomName, private):
method removeMatch (line 597) | def removeMatch(self, match):
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (100K chars).
[
{
"path": ".gitignore",
"chars": 1252,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "Pipfile",
"chars": 215,
"preview": "[[source]]\nname = \"pypi\"\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\n\n[dev-packages]\n\n[packages]\ntwisted = \"*\"\naut"
},
{
"path": "README.md",
"chars": 1241,
"preview": "# THIS REPOSITORY IS NOW BEING MAINTAINED AT [A NEW LOCATION, CLICK HERE.](https://github.com/mroyale/mroyale-server)\n\n#"
},
{
"path": "TUTORIAL.md",
"chars": 4662,
"preview": "# How to setup the Mario Royale server emulator\n\nThis setup guide will only cover Windows and Linux. However, the emulat"
},
{
"path": "Tests/.gitignore",
"chars": 11,
"preview": "*.png\n*.wav"
},
{
"path": "Tests/captcha_test.py",
"chars": 3819,
"preview": "'''\nCreated on Aug 23, 2018\n@author: zhaosong\n'''\n\nfrom captcha.image import ImageCaptcha\nfrom captcha.audio import Audi"
},
{
"path": "buffer.py",
"chars": 2793,
"preview": "import struct\r\n\r\nclass Buffer:\r\n def __init__(self, data=None):\r\n self.buffer = data if data is not None else "
},
{
"path": "datastore.py",
"chars": 3295,
"preview": "import os\nimport hashlib\ntry:\n import argon2\n A2_IMPORT = True\nexcept:\n # Maybe we can switch to a built-in pas"
},
{
"path": "levelSchema.json",
"chars": 3251,
"preview": "{ \"type\" : \"object\",\n \"properties\" : {\n \"type\" : {\"type\" : \"string\", \"pattern\" : \"^game$\"},\n \"resource\" : {\n "
},
{
"path": "match.py",
"chars": 7983,
"preview": "from twisted.internet import reactor\r\nfrom buffer import Buffer\r\nimport os\r\nimport json\r\nimport random\r\nimport jsonschem"
},
{
"path": "player.py",
"chars": 7261,
"preview": "import re\r\nimport emoji\r\nfrom twisted.internet import reactor\r\nfrom buffer import Buffer\r\n\r\ntry:\r\n from discord_webho"
},
{
"path": "requirements.txt",
"chars": 573,
"preview": "################################################################################\n# This requirements file has been autom"
},
{
"path": "server.cfg.example",
"chars": 1347,
"preview": "[Server]\n# The port on which the server will listen, if you don't know what it is, do not change it\nListenPort: 9000\n\n# "
},
{
"path": "server.py",
"chars": 22968,
"preview": "import os\nimport sys\nimport datastore\n\nif sys.version_info.major != 3:\n sys.stderr.write(\"You need python 3.7 or late"
}
]
About this extraction
This page contains the full source code of the Igoorx/PyRoyale GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (93.6 KB), approximately 21.5k tokens, and a symbol index with 103 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.